diff --git a/apps/api/scripts/seed.ts b/apps/api/scripts/seed.ts index f4c2c8c..56dcde5 100644 --- a/apps/api/scripts/seed.ts +++ b/apps/api/scripts/seed.ts @@ -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) } }); diff --git a/apps/api/sql/site.sql b/apps/api/sql/site.sql index 1363299..920f186 100644 --- a/apps/api/sql/site.sql +++ b/apps/api/sql/site.sql @@ -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) +); diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 48b2625..408fcbf 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -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'; @@ -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 }); diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 2c4ee60..46bc065 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -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'; @@ -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 { + 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(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(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 { 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) })); diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 3c0c8d2..b079b59 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -124,6 +124,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited { setSiteId(id); setPlatformView(false); }; + const [dashMember, setDashMember] = useState(null); const pickTab = (k: Tab) => { setTab(k); setPlatformView(false); }; const [site, setSite] = useState(null); const [stats, setStats] = useState(null); @@ -191,7 +192,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited WhatBox platform - + { pickSite(id); setTab('overview'); }} /> ) : (<> @@ -202,7 +203,8 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited {!site || !siteId ? : ( <> - {tab === 'overview' ? <> setTab('moderation')} /> : null} + {tab === 'overview' ? <> setTab('moderation')} onOpenMember={setDashMember} memberOpen={!!dashMember} /> + setDashMember(null)} /> : null} {tab === 'moderation' ? : null} {tab === 'members' ? : null} {tab === 'email' ? : null} diff --git a/apps/member/src/ui/Dashboard.tsx b/apps/member/src/ui/Dashboard.tsx index ed3de78..a580b13 100644 --- a/apps/member/src/ui/Dashboard.tsx +++ b/apps/member/src/ui/Dashboard.tsx @@ -1,10 +1,10 @@ // KPI dashboard for Owner Admin (one site) and Platform Admin (every site added up). // Numbers come from each site's own database; traffic is WhatBox's own cookieless count of the public pages. -import { ApiError, type AdminApi, type KpiDay, type KpiMetric, type NetworkDashboard, type SiteDashboard } from '@whatbox/core'; +import { addDays, ApiError, type AdminApi, type KpiDay, type KpiDetail, type KpiMetric, type NetworkDashboard, type SiteDashboard } from '@whatbox/core'; import { useEffect, useState, type ReactNode } from 'react'; -import { Pressable, View } from 'react-native'; +import { Modal, Pressable, ScrollView, View } from 'react-native'; import Svg, { Line, Path } from 'react-native-svg'; -import { Card, ErrorText, H, Loading, Notice, Segmented, Txt, useTheme } from './kit'; +import { Avatar, Badge, Btn, Card, ErrorText, H, Icon, Loading, Notice, PhotoTile, Segmented, Txt, useTheme, useWide } from './kit'; type Days = '7' | '30' | '90'; const PERIODS: { value: Days; label: string }[] = [{ value: '7', label: '7 days' }, { value: '30', label: '30 days' }, { value: '90', label: '90 days' }]; @@ -36,39 +36,51 @@ function usePeriod(load: (days: number) => Promise, deps: unknown[]) { return { days, setDays, data, error }; } -export function SiteDashboardView({ api, siteId, onModeration }: { api: AdminApi; siteId: string; onModeration?: () => void }) { +type Pick = { metric: KpiMetric; from: string; to: string }; + +// memberOpen: the admin has a member's profile open on top, so the details sheet steps aside until it closes. +export function SiteDashboardView({ api, siteId, onModeration, onOpenMember, memberOpen }: { + api: AdminApi; siteId: string; onModeration?: () => void; onOpenMember?: (memberId: string) => void; memberOpen?: boolean; +}) { const { days, setDays, data, error } = usePeriod((d) => api.dashboard(siteId, d), [api, siteId]); + const [pick, setPick] = useState(null); + useEffect(() => { setPick(null); }, [siteId]); + const open = (metric: KpiMetric, from?: string, to?: string) => data && setPick({ metric, from: from ?? data.from, to: to ?? from ?? data.to }); return (
{error ? : !data ? : ( <> {data.error ? {data.error} : null} - + open(m, m === 'active' ? addDays(data.to, -29) : undefined, m === 'active' ? data.to : undefined)} /> {data.imported.total ? : null} - + open(m, day)} onAll={(m) => open(m)} /> ({ label: p.path, value: p.views }))} /> ({ label: r.host || 'Direct or unknown', value: r.views }))} /> +