Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/scripts/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { PgControlRepo, PgSiteRepo, siteDbName } from '../src/pg-repo';
for (const site of seedSites(now)) {
await control.saveSite(site);
const db = pool(siteDbName(site.slug));
await db.query('TRUNCATE members, photos, private_access, likes, passes, favorites, views, blocks, messages, contact_optins, reports, moderation, pages, events, event_rsvps, challenges, sessions, subscriptions, webhook_events, member_days, daily_counts, traffic_salts, traffic_visitors, traffic_daily, traffic_pages, traffic_referrers CASCADE');
await db.query('TRUNCATE members, photos, private_access, likes, passes, favorites, views, blocks, messages, contact_optins, reports, moderation, pages, events, event_rsvps, challenges, sessions, subscriptions, webhook_events, member_days, member_sign_ins, daily_counts, traffic_salts, traffic_visitors, traffic_daily, traffic_pages, traffic_referrers CASCADE');
const repo = new PgSiteRepo(db);
const crypto = new SiteCrypto(keys, site.id);
const s = seedSite(site, now, { demoMemberHash: { emailHash: await crypto.lookupHash(DEMO_MEMBER_EMAIL), emailEnc: await crypto.encrypt(DEMO_MEMBER_EMAIL) } });
Expand Down
8 changes: 8 additions & 0 deletions apps/api/sql/site.sql
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,11 @@ CREATE TABLE IF NOT EXISTS credentials (
doc jsonb NOT NULL
);
CREATE INDEX IF NOT EXISTS credentials_member_idx ON credentials (member_id);

-- Who signed in on which day (for the dashboard's sign-ins drill-down). Admin only.
CREATE TABLE IF NOT EXISTS member_sign_ins (
day date NOT NULL,
member_id text NOT NULL REFERENCES members(id) ON DELETE CASCADE,
n integer NOT NULL DEFAULT 1,
PRIMARY KEY (day, member_id)
);
6 changes: 5 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import { FileInterceptor } from '@nestjs/platform-express';
import { normalizeImage } from './photos';
import { safeReturnUrl } from './payments';
import { type ActivityKind, type Campaign, type MemberStatus, type ClientPlatform, type ContentPage, type ModerationDecision, type PhotoKind, type SuspendReason, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core';
import { type ActivityKind, type Campaign, type MemberStatus, type ClientPlatform, type ContentPage, type KpiMetric, type ModerationDecision, type PhotoKind, type SuspendReason, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core';
import type { Request, Response } from 'express';

export const PLATFORM = 'PLATFORM';
Expand Down Expand Up @@ -273,6 +273,10 @@ export class AdminController {
return this.p.adminDashboard(await this.admin(a), s, Number(d));
}
// Every site the admin may see (all for WhatBox, their own for an owner).
@Get('sites/:site/dashboard/detail') async dashboardDetail(@Headers('authorization') a: string, @Param('site') s: string,
@Query('metric') m: string, @Query('from') from: string, @Query('to') to?: string) {
return this.p.adminKpiDetail(await this.admin(a), s, m as KpiMetric, String(from ?? ''), to || undefined);
}
@Get('dashboard') async dashboardAll(@Headers('authorization') a: string, @Query('days') d?: string) { return this.p.adminDashboardAll(await this.admin(a), Number(d)); }
@Get('sites/:site/moderation') async mod(@Headers('authorization') a: string, @Param('site') s: string, @Query('status') st = 'pending', @Query('kind') kind?: string, @Query('confidence') confidence?: string) {
return this.p.adminModeration(await this.admin(a), s, st as any, { kind: kind || undefined, confidence: confidence || undefined });
Expand Down
52 changes: 51 additions & 1 deletion apps/api/src/pg-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import type {
Campaign, MailKind, MailLogEntry, MailSend, MailSendStatus, MemberStatus,
AdminChallenge, AdminSession, AdminUser, Block, MemberCredential, EventRsvp, SiteEvent, ContactOptIn, ContentPage, ControlRepo, Favorite, Like, Pass, Member, MemberQuery, MemberSession,
Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View,
Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, KpiDetailRaw, KpiMetric, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View,
} from '@whatbox/core';
import type { Pool } from 'pg';
import { NETWORK_KEEP_DAYS } from '@whatbox/core';
Expand Down Expand Up @@ -499,6 +499,56 @@ export class PgSiteRepo implements SiteRepo {
await this.db.query('INSERT INTO traffic_pages (day, path, views) VALUES ($1,$2,1) ON CONFLICT (day, path) DO UPDATE SET views = traffic_pages.views + 1', [h.day, h.path]);
await this.db.query('INSERT INTO traffic_referrers (day, host, views) VALUES ($1,$2,1) ON CONFLICT (day, host) DO UPDATE SET views = traffic_referrers.views + 1', [h.day, h.refHost]);
}
async noteSignIn(memberId: string, day: string) {
await this.db.query('INSERT INTO member_sign_ins (day, member_id, n) VALUES ($1,$2,1) ON CONFLICT (day, member_id) DO UPDATE SET n = member_sign_ins.n + 1', [day, memberId]);
}
async kpiDetail(metric: KpiMetric, fromDay: string, toDay: string, limit: number): Promise<KpiDetailRaw> {
const lo = fromDay + 'T00:00:00.000Z', hi = new Date(Date.parse(toDay + 'T00:00:00Z') + 86_400_000).toISOString();
const q = async (sql: string, args: unknown[]) => (await this.db.query(sql, args)).rows as any[];
const iso2 = (v: Date | string) => new Date(v).toISOString();
const people = async (table: 'member_days' | 'member_sign_ins', nExpr: string) => {
const [c] = await q(`SELECT count(DISTINCT member_id) AS n FROM ${table} WHERE day BETWEEN $1 AND $2`, [fromDay, toDay]);
const rows = await q(`SELECT member_id, max(day)::text AS day, sum(${nExpr})::int AS n FROM ${table} WHERE day BETWEEN $1 AND $2
GROUP BY member_id ORDER BY 3 DESC, 2 DESC, 1 LIMIT $3`, [fromDay, toDay, limit]);
return { total: Number(c.n), people: rows.map((r) => ({ id: r.member_id, at: r.day + 'T12:00:00.000Z', n: Number(r.n) })) };
};
switch (metric) {
case 'signups': {
const where = "NOT (doc ? 'imported') AND created_at >= $1 AND created_at < $2";
const [c] = await q(`SELECT count(*) AS n FROM members WHERE ${where}`, [lo, hi]);
const rows = await q(`SELECT id, created_at FROM members WHERE ${where} ORDER BY created_at DESC LIMIT $3`, [lo, hi, limit]);
return { total: Number(c.n), people: rows.map((r) => ({ id: r.id, at: iso2(r.created_at), n: 1 })) };
}
case 'active': return people('member_days', '1');
case 'signIns': return people('member_sign_ins', 'n');
case 'messages': {
const where = "id NOT LIKE 'msg\\_imp\\_%' AND at >= $1 AND at < $2";
const [c] = await q(`SELECT count(*) AS n FROM messages WHERE ${where}`, [lo, hi]);
const rows = await q(`SELECT from_id, to_id, count(*)::int AS n, sum(held::int)::int AS held,
sum((jsonb_array_length(COALESCE(doc->'flags', '[]'::jsonb)) > 0)::int)::int AS flagged, max(at) AS last_at
FROM messages WHERE ${where} GROUP BY 1, 2 ORDER BY 3 DESC, 6 DESC LIMIT $3`, [lo, hi, limit]);
return { total: Number(c.n), messagePairs: rows.map((r) => ({ fromId: r.from_id, toId: r.to_id, n: r.n, held: r.held, flagged: r.flagged, lastAt: iso2(r.last_at) })) };
}
case 'photos': {
const where = "id NOT LIKE 'ph\\_imp\\_%' AND (doc->>'createdAt')::timestamptz >= $1 AND (doc->>'createdAt')::timestamptz < $2";
const [c] = await q(`SELECT count(*) AS n FROM photos WHERE ${where}`, [lo, hi]);
const rows = await q(`SELECT doc FROM photos WHERE ${where} ORDER BY (doc->>'createdAt')::timestamptz DESC LIMIT $3`, [lo, hi, limit]);
return { total: Number(c.n), photos: docs<Photo>(rows) };
}
case 'moderation': {
const where = "id NOT LIKE 'mod\\_imp\\_%' AND created_at >= $1 AND created_at < $2";
const [c] = await q(`SELECT count(*) AS n FROM moderation WHERE ${where}`, [lo, hi]);
const rows = await q(`SELECT doc FROM moderation WHERE ${where} ORDER BY created_at DESC LIMIT $3`, [lo, hi, limit]);
return { total: Number(c.n), moderation: docs<ModerationItem>(rows) };
}
default: {
const [t] = await q('SELECT COALESCE(sum(views),0)::int AS views, COALESCE(sum(visitors),0)::int AS visitors, COALESCE(sum(visits),0)::int AS visits FROM traffic_daily WHERE day BETWEEN $1 AND $2', [fromDay, toDay]);
const pages = await q('SELECT path, sum(views)::int AS views FROM traffic_pages WHERE day BETWEEN $1 AND $2 GROUP BY path ORDER BY 2 DESC, 1 LIMIT $3', [fromDay, toDay, limit]);
const refs = await q('SELECT host, sum(views)::int AS views FROM traffic_referrers WHERE day BETWEEN $1 AND $2 GROUP BY host ORDER BY 2 DESC, 1 LIMIT $3', [fromDay, toDay, limit]);
return { total: t.views, traffic: { views: t.views, visitors: t.visitors, visits: t.visits, pages: pages.map((r) => ({ path: r.path, views: r.views })), referrers: refs.map((r) => ({ host: r.host, views: r.views })) } };
}
}
}
async kpis(since: string, topSince: string, nowIso: string): Promise<SiteKpiRaw> {
const q = async (sql: string, args: unknown[] = [since]) => (await this.db.query(sql, args)).rows;
const days = (rows: any[]) => rows.map((r) => ({ day: r.day as string, n: Number(r.n) }));
Expand Down
6 changes: 4 additions & 2 deletions apps/member/src/app/admin/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited<Retu
const isPlatform = me.admin.role === 'platform';
const [platformView, setPlatformView] = useState(isPlatform);
const pickSite = (id: string) => { setSiteId(id); setPlatformView(false); };
const [dashMember, setDashMember] = useState<string | null>(null);
const pickTab = (k: Tab) => { setTab(k); setPlatformView(false); };
const [site, setSite] = useState<Site | null>(null);
const [stats, setStats] = useState<SiteStats | null>(null);
Expand Down Expand Up @@ -191,7 +192,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited<Retu
{platformView ? (
<>
<H size={28}>WhatBox platform</H>
<NetworkDashboardView api={api} title="All sites at a glance" />
<NetworkDashboardView api={api} title="All sites at a glance" onPickSite={(id) => { pickSite(id); setTab('overview'); }} />
<PlatformPanel api={api} onSitesChanged={reload} />
</>
) : (<>
Expand All @@ -202,7 +203,8 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited<Retu
</View>
{!site || !siteId ? <Loading /> : (
<>
{tab === 'overview' ? <><SiteDashboardView api={api} siteId={siteId} onModeration={() => setTab('moderation')} /><Overview stats={stats} site={site} go={setTab} /><AuditList api={api} siteId={siteId} refreshKey={site} /></> : null}
{tab === 'overview' ? <><SiteDashboardView api={api} siteId={siteId} onModeration={() => setTab('moderation')} onOpenMember={setDashMember} memberOpen={!!dashMember} />
<MemberProfilePanel api={api} siteId={siteId} memberId={dashMember} onClose={() => setDashMember(null)} /><Overview stats={stats} site={site} go={setTab} /><AuditList api={api} siteId={siteId} refreshKey={site} /></> : null}
{tab === 'moderation' ? <Moderation api={api} siteId={siteId} niche={!!site.settings.niche} onChange={reloadStats} /> : null}
{tab === 'members' ? <Members api={api} siteId={siteId} /> : null}
{tab === 'email' ? <EmailMembers api={api} site={site} go={setTab} /> : null}
Expand Down
Loading
Loading