From c4d7a3bdad9a94040487705ab809c9b3d3820d1e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 01:48:23 +0000 Subject: [PATCH 1/2] Admin KPI dashboard: cookieless traffic, sign-ups, active members, messages, photos, moderation; optional Google tags per site - Owner Admin: Dashboard tab per site (7/30/90 days, vs previous period, top pages, referrers) - Platform Admin: all sites added up plus a by-site table; owners only ever see their own sites - Public page views counted by WhatBox itself: no cookies, daily-salted visitor hash deleted after 2 days, counts stored in each site's own database - New sign-ups leave imported members out; imports shown separately with how many have signed in since - Site settings: Google Analytics 4 / Google Ads IDs, off by default, public pages only, after cookie consent; ad personalization off on sensitive and adult sites Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvNtJhdMZrRQNLxjVYY --- apps/api/scripts/seed.ts | 5 +- apps/api/sql/site.sql | 52 +++++ apps/api/src/app.ts | 5 + apps/api/src/main.ts | 23 ++- apps/api/src/pg-repo.ts | 71 ++++++- apps/member/src/app/admin/index.tsx | 60 ++++-- apps/member/src/lib/backend.ts | 1 + apps/member/src/ui/Dashboard.tsx | 283 +++++++++++++++++++++++++++ apps/web/app/globals.css | 5 + apps/web/app/layout.tsx | 2 + apps/web/app/measure.tsx | 90 +++++++++ packages/core/src/analytics.ts | 147 ++++++++++++++ packages/core/src/api.ts | 8 +- packages/core/src/demo-analytics.ts | 42 ++++ packages/core/src/http-client.ts | 2 + packages/core/src/index.ts | 2 + packages/core/src/memory-platform.ts | 6 +- packages/core/src/memory-repo.ts | 93 ++++++++- packages/core/src/repo.ts | 12 +- packages/core/src/services.ts | 71 ++++++- packages/core/src/types.ts | 77 ++++++++ packages/core/test/dashboard.test.ts | 114 +++++++++++ 22 files changed, 1142 insertions(+), 29 deletions(-) create mode 100644 apps/member/src/ui/Dashboard.tsx create mode 100644 apps/web/app/measure.tsx create mode 100644 packages/core/src/analytics.ts create mode 100644 packages/core/src/demo-analytics.ts create mode 100644 packages/core/test/dashboard.test.ts diff --git a/apps/api/scripts/seed.ts b/apps/api/scripts/seed.ts index f1bba80..f4c2c8c 100644 --- a/apps/api/scripts/seed.ts +++ b/apps/api/scripts/seed.ts @@ -2,7 +2,7 @@ // It wipes and reloads the demo sites' member data, so run it only on purpose. // In Azure dev it runs as the `seed` job (ALLOW_DEMO_SEED=true); prod has no seed job. // SEED_ADMIN_EMAIL, if set, adds that person as a Platform Admin so they can sign in for real. -import { DEMO_MEMBER_EMAIL, seedAdmins, seedSite, seedSites, SiteCrypto } from '@whatbox/core'; +import { DEMO_MEMBER_EMAIL, seedAdmins, seedDemoAnalytics, seedSite, seedSites, SiteCrypto } from '@whatbox/core'; import { closePools, keyProvider, pool } from '../src/db'; import { config } from '../src/config'; import { PgControlRepo, PgSiteRepo, siteDbName } from '../src/pg-repo'; @@ -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 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, 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) } }); @@ -36,6 +36,7 @@ import { PgControlRepo, PgSiteRepo, siteDbName } from '../src/pg-repo'; for (const p of s.pages) await repo.savePage(p); for (const e of s.events) await repo.saveEvent(e); for (const r of s.rsvps) await repo.setRsvp(r); + await seedDemoAnalytics(repo, site, now, s.members.map((m) => m.id)); console.log(`seeded ${site.slug}: ${s.members.length} members`); } await closePools(); diff --git a/apps/api/sql/site.sql b/apps/api/sql/site.sql index 309a4c7..493ca0c 100644 --- a/apps/api/sql/site.sql +++ b/apps/api/sql/site.sql @@ -185,3 +185,55 @@ CREATE TABLE IF NOT EXISTS webhook_events ( at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (provider, event_id) ); + +-- Admin dashboard counters. Counts only: no IP addresses, no cookies, nothing shared with other sites. +-- One row per member per day they used the site (daily / weekly / monthly active members). +CREATE TABLE IF NOT EXISTS member_days ( + day date NOT NULL, + member_id text NOT NULL REFERENCES members(id) ON DELETE CASCADE, + PRIMARY KEY (day, member_id) +); +-- Simple daily counters, e.g. sign_ins. +CREATE TABLE IF NOT EXISTS daily_counts ( + metric text NOT NULL, + day date NOT NULL, + n integer NOT NULL DEFAULT 0, + PRIMARY KEY (metric, day) +); +-- Public page views, counted without cookies. A visitor is a hash of IP + browser with a random salt +-- that changes every day; the salt and the hashes are deleted after 2 days, so nobody (us included) +-- can link a visitor across days or back to an IP address. Only the daily totals are kept. +CREATE TABLE IF NOT EXISTS traffic_salts ( + day date PRIMARY KEY, + salt text NOT NULL +); +CREATE TABLE IF NOT EXISTS traffic_visitors ( + day date NOT NULL, + visitor text NOT NULL, + last_at timestamptz NOT NULL, + PRIMARY KEY (day, visitor) +); +CREATE TABLE IF NOT EXISTS traffic_daily ( + day date PRIMARY KEY, + views integer NOT NULL DEFAULT 0, + visitors integer NOT NULL DEFAULT 0, + visits integer NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS traffic_pages ( + day date NOT NULL, + path text NOT NULL, + views integer NOT NULL DEFAULT 0, + PRIMARY KEY (day, path) +); +CREATE TABLE IF NOT EXISTS traffic_referrers ( + day date NOT NULL, + host text NOT NULL, -- '' = direct or unknown + views integer NOT NULL DEFAULT 0, + PRIMARY KEY (day, host) +); +-- Start the active-member history from what we already know: each member's last active day. +-- Imported members count only once they have used the new site. +INSERT INTO member_days (day, member_id) + SELECT (last_active_at AT TIME ZONE 'UTC')::date, id FROM members + WHERE NOT (doc ? 'imported') OR last_active_at > (doc->'imported'->>'at')::timestamptz + ON CONFLICT DO NOTHING; diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index c9e6f94..738bd6c 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -209,6 +209,11 @@ export class AdminController { return this.p.adminDeleteField(await this.admin(a), s, k); } @Get('sites/:site/stats') async stats(@Headers('authorization') a: string, @Param('site') s: string) { return this.p.adminStats(await this.admin(a), s); } + @Get('sites/:site/dashboard') async dashboard(@Headers('authorization') a: string, @Param('site') s: string, @Query('days') d?: string) { + 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('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') { return this.p.adminModeration(await this.admin(a), s, st as any); } diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 8cecc5e..a2a8869 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -1,6 +1,6 @@ import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; -import { json } from 'express'; +import { json, text } from 'express'; import { buildModule, ErrorFilter } from './app'; import { config } from './config'; import { createPlatform } from './db'; @@ -54,6 +54,27 @@ async function main() { http.get('/healthz', async (_req, res) => { try { await control.listSites(); res.json({ ok: true }); } catch { res.status(503).json({ ok: false }); } }); + // Public page views from the site's own pages (navigator.sendBeacon, text/plain, so no CORS preflight + // and no cookies). The site comes from the page's Origin; on addresses that aren't a site domain + // (local dev, the default Azure address) the page names its site. Always answers 204. + http.post('/v1/hit', text({ type: () => true, limit: '2kb' }), async (req, res) => { + res.status(204).end(); + try { + const b = JSON.parse(typeof req.body === 'string' ? req.body : '{}') as { s?: unknown; p?: unknown; r?: unknown }; + let site = null; + const origin = req.headers.origin; + if (origin) { + try { + const host = new URL(origin).hostname.replace(/^www\./, ''); + const found = await control.findSite(host); + if (found?.domains.includes(host)) site = found; + } catch { /* not a URL */ } + } + if (!site && typeof b.s === 'string' && /^[a-z][a-z0-9]{1,29}$/.test(b.s)) site = await control.findSite(b.s); + if (!site || site.status === 'suspended') return; + await platform.recordPageView(site, { path: b.p, referrer: b.r, ip: req.ip, userAgent: req.headers['user-agent'] }); + } catch { /* counting must never break a page */ } + }); // Live events (server-sent events). Clients connect with their normal session header. http.get('/v1/events', async (req, res) => { let site, ctx; diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 2759150..26ecd40 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -2,7 +2,7 @@ // PgControlRepo talks to the shared control database; each PgSiteRepo talks to one site's own database. import type { AdminChallenge, AdminSession, AdminUser, Block, EventRsvp, SiteEvent, ContactOptIn, ContentPage, ControlRepo, Favorite, Like, Pass, Member, MemberQuery, MemberSession, - Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteRepo, Subscription, UsageKind, AuditEntry, VerificationChallenge, View, + Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View, } from '@whatbox/core'; import type { Pool } from 'pg'; @@ -234,6 +234,9 @@ export class PgSiteRepo implements SiteRepo { // True the first time an event id is seen. async cleanup(now: string) { await this.db.query('DELETE FROM sessions WHERE expires_at < $1', [now]); + // Visitor hashes and their salts are only needed for today's counts; daily totals stay. + await this.db.query("DELETE FROM traffic_salts WHERE day < ($1::timestamptz AT TIME ZONE 'UTC')::date - 2", [now]); + await this.db.query("DELETE FROM traffic_visitors WHERE day < ($1::timestamptz AT TIME ZONE 'UTC')::date - 2", [now]); await this.db.query('DELETE FROM challenges WHERE expires_at < $1', [now]); await this.db.query("DELETE FROM subscriptions WHERE status='pending' AND created_at < $1::timestamptz - interval '2 days'", [now]); await this.db.query("DELETE FROM webhook_events WHERE at < $1::timestamptz - interval '90 days'", [now]); @@ -369,6 +372,72 @@ export class PgSiteRepo implements SiteRepo { } async deleteSession(t: string) { await this.db.query('DELETE FROM sessions WHERE token=$1', [t]); } + // ---- dashboard counters + async markActive(memberId: string, day: string) { + await this.db.query('INSERT INTO member_days (day, member_id) VALUES ($1,$2) ON CONFLICT DO NOTHING', [day, memberId]); + } + async bumpDaily(metric: 'sign_ins', day: string, n = 1) { + await this.db.query('INSERT INTO daily_counts (metric, day, n) VALUES ($1,$2,$3) ON CONFLICT (metric, day) DO UPDATE SET n = daily_counts.n + $3', [metric, day, n]); + } + async trafficSalt(day: string, fresh: string) { + await this.db.query('INSERT INTO traffic_salts (day, salt) VALUES ($1,$2) ON CONFLICT DO NOTHING', [day, fresh]); + return (await this.db.query('SELECT salt FROM traffic_salts WHERE day=$1', [day])).rows[0].salt as string; + } + async recordHit(h: TrafficHit) { + // One round trip: upsert the visitor, then count a visitor / visit from what that upsert saw. + await this.db.query( + `WITH prev AS (SELECT last_at FROM traffic_visitors WHERE day=$1 AND visitor=$2), + up AS (INSERT INTO traffic_visitors (day, visitor, last_at) VALUES ($1,$2,$3) + ON CONFLICT (day, visitor) DO UPDATE SET last_at = GREATEST(traffic_visitors.last_at, $3) RETURNING 1), + flags AS (SELECT (NOT EXISTS (SELECT 1 FROM prev))::int AS new_visitor, + (NOT EXISTS (SELECT 1 FROM prev) OR (SELECT last_at FROM prev) < $3::timestamptz - interval '30 minutes')::int AS new_visit + FROM up) + INSERT INTO traffic_daily (day, views, visitors, visits) SELECT $1, 1, new_visitor, new_visit FROM flags + ON CONFLICT (day) DO UPDATE SET views = traffic_daily.views + 1, visitors = traffic_daily.visitors + EXCLUDED.visitors, visits = traffic_daily.visits + EXCLUDED.visits`, + [h.day, h.visitor, h.at], + ); + 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 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) })); + const D = (col: string) => `to_char((${col} AT TIME ZONE 'UTC')::date, 'YYYY-MM-DD')`; + const NATIVE = "NOT (doc ? 'imported')"; + const SEEN = "(NOT (doc ? 'imported') OR last_active_at > (doc->'imported'->>'at')::timestamptz)"; + const [head] = await q( + `SELECT (SELECT count(*) FROM members) AS members, + (SELECT count(*) FROM members WHERE doc ? 'imported') AS imp, + (SELECT count(*) FROM members WHERE doc ? 'imported' AND last_active_at > (doc->'imported'->>'at')::timestamptz) AS imp_back, + (SELECT count(*) FROM members WHERE ${SEEN} AND last_active_at >= $1::timestamptz - interval '1 day') AS d1, + (SELECT count(*) FROM members WHERE ${SEEN} AND last_active_at >= $1::timestamptz - interval '7 days') AS d7, + (SELECT count(*) FROM members WHERE ${SEEN} AND last_active_at >= $1::timestamptz - interval '30 days') AS d30, + (SELECT count(*) FROM moderation WHERE status='pending') AS waiting`, [nowIso]); + const since0 = since + 'T00:00:00Z'; + return { + members: Number(head.members), + signups: days(await q(`SELECT ${D('created_at')} AS day, count(*) AS n FROM members WHERE ${NATIVE} AND created_at >= $1 GROUP BY 1 ORDER BY 1`, [since0])), + signupsCompleted: days(await q(`SELECT ${D('created_at')} AS day, count(*) AS n FROM members WHERE ${NATIVE} AND profile_complete AND created_at >= $1 GROUP BY 1 ORDER BY 1`, [since0])), + imported: { + total: Number(head.imp), returned: Number(head.imp_back), + days: days(await q(`SELECT ${D("(doc->'imported'->>'at')::timestamptz")} AS day, count(*) AS n FROM members WHERE doc ? 'imported' GROUP BY 1 ORDER BY 1`, [])), + }, + active: { day: Number(head.d1), week: Number(head.d7), month: Number(head.d30) }, + activeDaily: days(await q(`SELECT to_char(day, 'YYYY-MM-DD') AS day, count(*) AS n FROM member_days WHERE day >= $1 GROUP BY 1 ORDER BY 1`)), + signIns: days(await q(`SELECT to_char(day, 'YYYY-MM-DD') AS day, n FROM daily_counts WHERE metric='sign_ins' AND day >= $1 ORDER BY 1`)), + messages: days(await q(`SELECT ${D('at')} AS day, count(*) AS n FROM messages WHERE id NOT LIKE 'msg\\_imp\\_%' AND at >= $1 GROUP BY 1 ORDER BY 1`, [since0])), + photos: days(await q(`SELECT ${D("(doc->>'createdAt')::timestamptz")} AS day, count(*) AS n FROM photos WHERE id NOT LIKE 'ph\\_imp\\_%' AND (doc->>'createdAt')::timestamptz >= $1 GROUP BY 1 ORDER BY 1`, [since0])), + moderationAdded: days(await q(`SELECT ${D('created_at')} AS day, count(*) AS n FROM moderation WHERE id NOT LIKE 'mod\\_imp\\_%' AND created_at >= $1 GROUP BY 1 ORDER BY 1`, [since0])), + moderationWaiting: Number(head.waiting), + traffic: (await q(`SELECT to_char(day, 'YYYY-MM-DD') AS day, views, visitors, visits FROM traffic_daily WHERE day >= $1 ORDER BY 1`)) + .map((r: any) => ({ day: r.day, views: Number(r.views), visitors: Number(r.visitors), visits: Number(r.visits) })), + topPages: (await q('SELECT path, sum(views)::int AS views FROM traffic_pages WHERE day >= $1 GROUP BY path ORDER BY 2 DESC, 1 LIMIT 10', [topSince])) + .map((r: any) => ({ path: r.path, views: Number(r.views) })), + referrers: (await q('SELECT host, sum(views)::int AS views FROM traffic_referrers WHERE day >= $1 GROUP BY host ORDER BY 2 DESC, 1 LIMIT 10', [topSince])) + .map((r: any) => ({ host: r.host, views: Number(r.views) })), + }; + } + async stats(nowIso: string) { const r = (await this.db.query( `SELECT diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 703893d..342f744 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -13,6 +13,7 @@ import { adminApi, IS_PREVIEW } from '../../lib/backend'; import { storage } from '../../lib/storage'; import { PlatformPanel } from '../../ui/PlatformPanel'; import { AuditList } from '../../ui/AuditList'; +import { NetworkDashboardView, SiteDashboardView } from '../../ui/Dashboard'; import { Avatar, Badge, Btn, Card, Check, Chip, ChipPicker, ErrorText, Field, fonts, H, Icon, Loading, Notice, PhotoTile, relTime, Segmented, ThemeOverrideProvider, Toggle, Txt, useTheme, useWide, type IconName, @@ -25,7 +26,7 @@ const ADMIN_THEME: SiteTheme = { const TOKEN_KEY = 'whatbox.admin.token'; type Tab = 'overview' | 'moderation' | 'members' | 'fields' | 'events' | 'pages' | 'settings'; const TABS: { key: Tab; label: string; icon: IconName }[] = [ - { key: 'overview', label: 'Overview', icon: 'grid' }, + { key: 'overview', label: 'Dashboard', icon: 'grid' }, { key: 'moderation', label: 'Moderation', icon: 'shield' }, { key: 'members', label: 'Members', icon: 'users' }, { key: 'fields', label: 'Profile fields', icon: 'sliders' }, @@ -184,6 +185,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited WhatBox platform + ) : (<> @@ -194,7 +196,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited {!site || !siteId ? : ( <> - {tab === 'overview' ? <> : null} + {tab === 'overview' ? <> setTab('moderation')} /> : null} {tab === 'moderation' ? : null} {tab === 'members' ? : null} {tab === 'fields' ? : null} @@ -230,28 +232,18 @@ function Stat({ label, value }: { label: string; value: number | string }) { ); } -function Overview({ stats, site, go }: { stats: SiteStats | null; site: Site; go: (t: Tab) => void }) { +function Overview({ stats, site }: { stats: SiteStats | null; site: Site; go: (t: Tab) => void }) { if (!stats) return ; const ms = site.settings.membership; return ( - - - - - - - - {stats.openModeration ? ( - - go('moderation')} /> - - ) : The moderation queue is clear.} How {site.name} is set up + {stats.members.toLocaleString('en-US')} members, {stats.paid.toLocaleString('en-US')} on Paid or VIP. Mode: {site.settings.mode}. Photos are {site.settings.photoModeration === 'pre' ? 'hidden until approved' : 'visible right away and reviewed after'}. Payments: {site.settings.paymentProvider}. Paywall: {ms.paywallEnabled ? `on, with ${TIERS.map((x) => ms.tiers[x].label).join(', ')} levels` : 'off, so every member has full access'}. Public teasers: {site.settings.mode === 'sensitive' ? 'never (sensitive site)' : site.settings.publicTeasers ? 'members can opt in' : 'off'}. + Google tags: {site.settings.googleTags?.enabled ? 'on for the public pages, after cookie consent' : 'off'}. ); @@ -816,7 +808,7 @@ function Settings({ api, site, onSite, role }: { api: AdminApi; site: Site; onSi const [limits, setLimits] = useState({ a: String(lim.newConversationsPerHour), b: String(lim.messagesPerMinute), c: String(lim.duplicateRecipientThreshold) }); const save = async (patch: Parameters[1]) => { setError(null); - try { onSite(await api.updateSite(site.id, patch)); } catch (e) { setError(e instanceof ApiError ? e.message : 'Could not save.'); } + try { onSite(await api.updateSite(site.id, patch)); return true; } catch (e) { setError(e instanceof ApiError ? e.message : 'Could not save.'); return false; } }; const section = (title: string, children: ReactNode, hint?: string) => ( @@ -887,6 +879,7 @@ function Settings({ api, site, onSite, role }: { api: AdminApi; site: Site; onSi site.settings.mode === 'sensitive' ? setError('Sensitive sites never show public teasers.') : save({ settings: { publicTeasers: v } })} /> ))} + {section('Site mode', ( save({ settings: { mode: v } })} /> ), role === 'platform' ? 'Only WhatBox can change this. Adult sites need an adult-friendly processor such as CCBill.' : 'Set by WhatBox. Ask your WhatBox contact to change it.')} @@ -894,6 +887,39 @@ function Settings({ api, site, onSite, role }: { api: AdminApi; site: Site; onSi ); } +function GoogleTagsSection({ site, save }: { site: Site; save: (p: Parameters[1]) => Promise }) { + const g = site.settings.googleTags; + const [form, setForm] = useState({ ga4Id: g?.ga4Id ?? '', adsId: g?.adsId ?? '', adsJoinLabel: g?.adsJoinLabel ?? '' }); + const [saved, setSaved] = useState(false); + const sensitive = site.settings.mode === 'sensitive', adult = site.settings.mode === 'adult'; + const patch = (enabled: boolean) => save({ settings: { googleTags: { enabled, ga4Id: form.ga4Id, adsId: form.adsId, adsJoinLabel: form.adsJoinLabel } } }).then(setSaved); + return ( + + Google Analytics and Google Ads + Optional. The dashboard already counts visitors without cookies. Turn this on to also send public page visits to your own Google accounts. Tags load only on the public pages, only after a visitor accepts cookies, and never once someone signs in or in the apps. + {sensitive || adult ? ( + + + {sensitive + ? 'With these tags on, Google learns that a visitor opened this site. Google Ads does not allow remarketing or personalized ads based on health conditions, including sexual health, so leave remarketing off in Google Ads. WhatBox turns off ad personalization and Google signals for this site either way. Many members of a site like this expect no trackers at all.' + : 'Google Ads restricts adult content, and ads for this site may be limited or refused. WhatBox turns off ad personalization and Google signals for this site.'} + + + ) : null} + + { setForm({ ...form, ga4Id: v }); setSaved(false); }} placeholder="G-XXXXXXXXXX" autoCapitalize="characters" /> + { setForm({ ...form, adsId: v }); setSaved(false); }} placeholder="AW-123456789" autoCapitalize="characters" /> + { setForm({ ...form, adsJoinLabel: v }); setSaved(false); }} placeholder="AbC-D_efG123" hint="Fires when a visitor clicks Join" /> + + patch(v)} /> + + patch(!!g?.enabled)} /> + {saved ? Saved. : null} + + + ); +} + const PERMS: { key: keyof TierPerms; label: string; kind: 'bool' | 'tiers' }[] = [ { key: 'seePublicPhotos', label: 'See public photos (beyond photo one)', kind: 'bool' }, { key: 'requestPrivatePhotos', label: 'Request private photos', kind: 'bool' }, @@ -904,7 +930,7 @@ const PERMS: { key: keyof TierPerms; label: string; kind: 'bool' | 'tiers' }[] = { key: 'readMessagesFrom', label: 'Read and answer messages from', kind: 'tiers' }, ]; -function TierMatrix({ site, save }: { site: Site; save: (p: Parameters[1]) => Promise }) { +function TierMatrix({ site, save }: { site: Site; save: (p: Parameters[1]) => Promise }) { const t = useTheme(); const ms = site.settings.membership; const [labels, setLabels] = useState(() => Object.fromEntries(TIERS.map((x) => [x, { label: ms.tiers[x].label, price: ms.tiers[x].priceLabel }])) as Record); diff --git a/apps/member/src/lib/backend.ts b/apps/member/src/lib/backend.ts index 17c25e7..ee92dc7 100644 --- a/apps/member/src/lib/backend.ts +++ b/apps/member/src/lib/backend.ts @@ -27,6 +27,7 @@ function local(): Promise { rateLimitScale: 100, // the demo signs in as the same people over and over snapshot, exposeDevCodes: true, + demoAnalytics: true, // placeholder traffic and activity for the admin dashboard onChange: () => { if (saveTimer) clearTimeout(saveTimer); saveTimer = setTimeout(() => { storage.set(SNAP_KEY, JSON.stringify(mp.snapshot())); }, 250); diff --git a/apps/member/src/ui/Dashboard.tsx b/apps/member/src/ui/Dashboard.tsx new file mode 100644 index 0000000..ed3de78 --- /dev/null +++ b/apps/member/src/ui/Dashboard.tsx @@ -0,0 +1,283 @@ +// 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 { useEffect, useState, type ReactNode } from 'react'; +import { Pressable, View } from 'react-native'; +import Svg, { Line, Path } from 'react-native-svg'; +import { Card, ErrorText, H, Loading, Notice, Segmented, Txt, useTheme } 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' }]; +const num = (n: number) => n.toLocaleString('en-US'); +const dayLabel = (d: string, withYear = false) => new Date(d + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', ...(withYear ? { year: 'numeric' } : {}), timeZone: 'UTC' }); + +const CHARTS: { key: KpiMetric; title: string; unit: [string, string]; hint?: string }[] = [ + { key: 'visitors', title: 'Unique visitors', unit: ['visitor', 'visitors'], hint: 'Public pages. Counted without cookies; a visitor is counted once per day.' }, + { key: 'views', title: 'Page views', unit: ['view', 'views'], hint: 'Public pages only, never member pages.' }, + { key: 'signups', title: 'New sign-ups', unit: ['sign-up', 'sign-ups'], hint: 'New accounts on this platform. Imported members are not included.' }, + { key: 'active', title: 'Active members', unit: ['member', 'members'], hint: 'Members who used the site that day.' }, + { key: 'signIns', title: 'Sign-ins', unit: ['sign-in', 'sign-ins'] }, + { key: 'messages', title: 'Messages sent', unit: ['message', 'messages'] }, + { key: 'photos', title: 'Photos uploaded', unit: ['photo', 'photos'] }, + { key: 'moderation', title: 'New moderation items', unit: ['item', 'items'], hint: 'Flags raised each day. Import flags are left out.' }, +]; + +function usePeriod(load: (days: number) => Promise, deps: unknown[]) { + const [days, setDays] = useState('30'); + const [data, setData] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { + let live = true; + setData(null); setError(null); + load(Number(days)).then((d) => { if (live) setData(d); }, (e) => { if (live) setError(e instanceof ApiError ? e.message : 'Could not load the dashboard.'); }); + return () => { live = false; }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [days, ...deps]); + return { days, setDays, data, error }; +} + +export function SiteDashboardView({ api, siteId, onModeration }: { api: AdminApi; siteId: string; onModeration?: () => void }) { + const { days, setDays, data, error } = usePeriod((d) => api.dashboard(siteId, d), [api, siteId]); + return ( + +
+ {error ? : !data ? : ( + <> + {data.error ? {data.error} : null} + + {data.imported.total ? : null} + + + ({ label: p.path, value: p.views }))} /> + ({ label: r.host || 'Direct or unknown', value: r.views }))} /> + + + + )} + + ); +} + +export function NetworkDashboardView({ api, title = 'All sites' }: { api: AdminApi; title?: string }) { + const { days, setDays, data, error } = usePeriod((d) => api.dashboardAll(d), [api]); + return ( + +
+ {error ? : !data ? : ( + <> + + + + + + )} + + ); +} + +function Header({ title, days, setDays, range }: { title?: string; days: Days; setDays: (d: Days) => void; range: string }) { + return ( + + + {title ? {title} : null} + {range ? `${range} (UTC)` : ' '} + + value={days} onChange={setDays} options={PERIODS} /> + + ); +} + +function Delta({ now, before }: { now: number; before: number }) { + if (!before && !now) return No change; + if (!before) return New this period; + const pct = Math.round(((now - before) / before) * 100); + const up = pct > 0; + return ( + + {pct === 0 ? 'Same as before' : `${up ? '▲' : '▼'} ${Math.abs(pct)}% vs previous`} + + ); +} + +function Tile({ label, value, sub }: { label: string; value: string; sub?: ReactNode }) { + return ( + + {label} + {value} + {sub} + + ); +} + +function Tiles({ d, onModeration }: { d: SiteDashboard | NetworkDashboard; onModeration?: () => void }) { + const t = useTheme(); + return ( + + } /> + } /> + {`${num(d.active.day)} today · ${num(d.active.week)} this week`}} /> + } /> + + + Waiting for review + {num(d.moderationWaiting)} + {d.moderationWaiting ? (onModeration ? 'Open the queue ›' : 'In moderation queues') : 'Queue is clear'} + + + + ); +} + +function ImportNote({ d }: { d: SiteDashboard }) { + const when = d.imported.days.map((x) => dayLabel(x.day, true)).join(', '); + return ( + + + {`Imported ${when}. They are not counted as new sign-ups. ${num(d.imported.returned)} of them ${d.imported.returned === 1 ? 'has' : 'have'} signed in on the new site so far`} + {d.signupsCompleted || d.totals.signups.now ? `. Of this period's ${num(d.totals.signups.now)} new sign-ups, ${num(d.signupsCompleted)} finished their profile.` : '.'} + + + ); +} + +function ChartGrid({ series, totals }: { series: KpiDay[]; totals: SiteDashboard['totals'] }) { + return ( + + {CHARTS.map((c) => ( + + ({ day: d.day, n: d[c.key] }))} + total={c.key === 'active' ? `${num(totals.active.now)} a day on average` : `${num(totals[c.key].now)} in total`} /> + + ))} + + ); +} + +// One series, one axis: thin bars from a zero baseline, a light grid, hover or tap a day for its value. +function BarChart({ title, hint, unit, data, total }: { title: string; hint?: string; unit: [string, string]; data: { day: string; n: number }[]; total: string }) { + const t = useTheme(); + const [w, setW] = useState(0); + const [hover, setHover] = useState(null); + const H_ = 132; + const max = Math.max(1, ...data.map((d) => d.n)); + const top = niceMax(max); + const slot = w / Math.max(1, data.length); + const bw = Math.max(1.5, Math.min(14, slot - (slot > 6 ? 2 : 1))); + const y = (v: number) => H_ - (v / top) * (H_ - 8); + const h = hover !== null ? data[hover] : null; + const label = h ? `${dayLabel(h.day)}: ${num(h.n)} ${h.n === 1 ? unit[0] : unit[1]}` : total; + return ( + + + {title} + {label} + + + + {num(top)} + {num(top / 2)} + 0 + + setW(e.nativeEvent.layout.width)} + accessible accessibilityLabel={`${title}. ${total}. Highest day ${num(max)}.`}> + {w ? ( + + + + {data.map((d, i) => { + if (!d.n) return null; + const x = i * slot + (slot - bw) / 2, yy = y(d.n), r = Math.min(3, bw / 2, (H_ - yy) / 2); + return ; + })} + + + ) : null} + + {data.map((d, i) => ( + setHover(i)} onHoverOut={() => setHover((x) => (x === i ? null : x))} + onPressIn={() => setHover(i)} accessibilityLabel={`${dayLabel(d.day)}: ${d.n}`} /> + ))} + + + + + {data[0] ? dayLabel(data[0].day) : ''} + {data.at(-1) ? dayLabel(data.at(-1)!.day) : ''} + + {hint ? {hint} : null} + + ); +} + +function niceMax(v: number) { + // even steps, so the half-way grid line is a whole number + const p = 10 ** Math.max(0, Math.floor(Math.log10(v))); + for (const m of [2, 4, 6, 8, 10]) if (m * p >= v) return m * p; + return 20 * p; +} + +function roundTop(x: number, y: number, w: number, h: number, r: number) { + return `M${x},${y + h} L${x},${y + r} Q${x},${y} ${x + r},${y} L${x + w - r},${y} Q${x + w},${y} ${x + w},${y + r} L${x + w},${y + h} Z`; +} + +function TopList({ title, rows, empty }: { title: string; rows: { label: string; value: number }[]; empty: string }) { + const t = useTheme(); + const max = Math.max(1, ...rows.map((r) => r.value)); + return ( + + + {title} + Views + + {rows.length ? rows.map((r) => ( + + + {r.label} + {num(r.value)} + + + + + + )) : {empty}} + + ); +} + +function SiteTable({ sites }: { sites: SiteDashboard[] }) { + const t = useTheme(); + const cols: { label: string; get: (s: SiteDashboard) => string }[] = [ + { label: 'Visitors', get: (s) => num(s.totals.visitors.now) }, + { label: 'Sign-ups', get: (s) => num(s.totals.signups.now) }, + { label: 'Active 30d', get: (s) => num(s.active.month) }, + { label: 'Messages', get: (s) => num(s.totals.messages.now) }, + { label: 'Review', get: (s) => num(s.moderationWaiting) }, + ]; + return ( + + By site + {sites.map((s) => ( + + + {s.name} + {`${num(s.members)} members${s.imported.total ? `, ${num(s.imported.total)} imported` : ''}${s.error ? ' · could not load' : ''}`} + + {cols.map((c) => ( + + {c.label} + {c.get(s)} + + ))} + + ))} + + ); +} + +function TrafficNote({ since }: { since?: string }) { + return ( + + {`Traffic is WhatBox's own count of the public pages: no cookies, no third parties, and no IP addresses kept. Visitors are counted once a day per device.${since ? ` Counting since ${dayLabel(since, true)}.` : ' Counting starts once this update is live.'} Days are in UTC.`} + + ); +} diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index 579e97b..e880428 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -102,3 +102,8 @@ summary{font-weight:700;cursor:pointer} .style-warm details{border:0;box-shadow:0 4px 12px color-mix(in srgb,var(--ink) 6%,transparent)} @media(max-width:820px){.hero{grid-template-columns:1fr;padding-block:36px;gap:28px}.nav .hide-sm{display:none}} +/* Cookie choice: shown only when the owner turned on Google tags for this site. */ +.consent{position:fixed;left:16px;right:16px;bottom:16px;z-index:50;max-width:560px;margin-inline:auto;background:var(--surface);color:var(--ink);border:1px solid var(--line);border-radius:14px;box-shadow:0 8px 30px rgba(0,0,0,.18);padding:16px 18px;display:grid;gap:12px;font-size:15px;line-height:1.45} +.consent p{margin:0} +.consent-actions{display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap} +.consent .btn{min-height:44px;cursor:pointer;font:inherit;font-weight:700} diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 6f0de94..30325fe 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -2,6 +2,7 @@ import type { Metadata } from 'next'; import type { ReactNode } from 'react'; import { landingStyle } from '@whatbox/core'; import { appUrl, getPages, getSite } from '../lib/site'; +import { Measure } from './measure'; import './globals.css'; export async function generateMetadata(): Promise { @@ -62,6 +63,7 @@ export default async function RootLayout({ children }: { children: ReactNode }) © {new Date().getFullYear()} WhatBox, LLC + ); diff --git a/apps/web/app/measure.tsx b/apps/web/app/measure.tsx new file mode 100644 index 0000000..47cb52a --- /dev/null +++ b/apps/web/app/measure.tsx @@ -0,0 +1,90 @@ +'use client'; +// Page view counting and (optional) Google tags for the public pages. +// +// 1. Every page view is sent to WhatBox's own API with sendBeacon: the path and the referring site, +// nothing else. No cookies, no local storage, no third party. This is what the admin dashboard shows. +// 2. Google Analytics / Google Ads load only if the site owner turned them on in Owner Admin AND the +// visitor pressed "Accept" on the cookie notice. The choice is remembered on this device only. +// These pages are public; the member app and native apps never load Google tags. +import { usePathname } from 'next/navigation'; +import { useEffect, useState } from 'react'; + +type Tags = { ga4Id?: string; adsId?: string; adsJoinLabel?: string; restricted: boolean }; +const CONSENT_KEY = 'wb_cookie_choice'; + +declare global { + interface Window { dataLayer?: unknown[]; gtag?: (...args: unknown[]) => void } +} + +function readChoice(): 'yes' | 'no' | null { + try { const v = window.localStorage.getItem(CONSENT_KEY); return v === 'yes' || v === 'no' ? v : null; } catch { return null; } +} +function saveChoice(v: 'yes' | 'no') { + try { window.localStorage.setItem(CONSENT_KEY, v); } catch { /* private mode: ask again next time */ } +} + +let googleLoaded = false; +function loadGoogle(tags: Tags) { + if (googleLoaded) return; + const first = tags.ga4Id ?? tags.adsId; + if (!first) return; + googleLoaded = true; + window.dataLayer = window.dataLayer ?? []; + window.gtag = function gtag() { window.dataLayer!.push(arguments); }; // eslint-disable-line prefer-rest-params + const g = window.gtag; + g('consent', 'default', { ad_storage: 'granted', analytics_storage: 'granted', ad_user_data: 'granted', ad_personalization: tags.restricted ? 'denied' : 'granted' }); + g('js', new Date()); + // Sensitive and adult sites: no remarketing lists, no ad personalization, no Google signals. + const opts = tags.restricted ? { allow_google_signals: false, allow_ad_personalization_signals: false } : {}; + if (tags.ga4Id) g('config', tags.ga4Id, opts); + if (tags.adsId) g('config', tags.adsId, opts); + const s = document.createElement('script'); + s.async = true; + s.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(first); + document.head.appendChild(s); + // Google Ads conversion: a visitor clicks a Join link (sign-up itself happens in the member app, + // where Google tags never run). + if (tags.adsId && tags.adsJoinLabel) { + document.addEventListener('click', (e) => { + const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + if (a && /\/join(\?|$)/.test(a.href) && !/mode=signin/.test(a.href)) { + window.gtag?.('event', 'conversion', { send_to: `${tags.adsId}/${tags.adsJoinLabel}`, transport_type: 'beacon' }); + } + }, { capture: true }); + } +} + +export function Measure({ api, site, tags }: { api: string; site: string; tags?: Tags }) { + const path = usePathname(); + const [ask, setAsk] = useState(false); + + useEffect(() => { + try { + const body = JSON.stringify({ s: site, p: window.location.pathname, r: document.referrer }); + if (navigator.sendBeacon) navigator.sendBeacon(api + '/v1/hit', body); + else fetch(api + '/v1/hit', { method: 'POST', body, keepalive: true, credentials: 'omit', mode: 'no-cors' }).catch(() => {}); + } catch { /* never break the page */ } + }, [api, site, path]); + + useEffect(() => { + if (!tags) return; + const c = readChoice(); + if (c === 'yes') loadGoogle(tags); + else if (c === null) setAsk(true); + }, [tags]); + + if (!tags || !ask) return null; + const choose = (v: 'yes' | 'no') => { saveChoice(v); setAsk(false); if (v === 'yes') loadGoogle(tags); }; + return ( +
+

+ We'd like to use Google cookies to see which pages and ads bring people here. They're only used on + these public pages, never once you sign in. +

+
+ + +
+
+ ); +} diff --git a/packages/core/src/analytics.ts b/packages/core/src/analytics.ts new file mode 100644 index 0000000..8759e3a --- /dev/null +++ b/packages/core/src/analytics.ts @@ -0,0 +1,147 @@ +// Admin dashboard helpers: cleaning up page views before they are counted, and turning one site's +// raw daily counts into chart series and period totals. Pure functions, shared by the API and the preview. +import { RuleError } from './rules'; +import type { DayCount, GoogleTags, KpiDay, KpiMetric, NetworkDashboard, Site, SiteDashboard, SiteKpiRaw } from './types'; + +export const DASHBOARD_DAYS = [7, 30, 90] as const; +export const KPI_METRICS: KpiMetric[] = ['views', 'visitors', 'visits', 'signups', 'signIns', 'active', 'messages', 'photos', 'moderation']; + +const DAY_MS = 86_400_000; +export const utcDay = (d: Date | string) => (typeof d === 'string' ? new Date(d) : d).toISOString().slice(0, 10); +export const addDays = (day: string, n: number) => utcDay(new Date(Date.parse(day + 'T00:00:00Z') + n * DAY_MS)); + +// Crawlers, link previews and headless browsers are not visitors. +const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|embedly|preview|headless|lighthouse|pingdom|monitor|curl|wget|python|axios|node-fetch|go-http/i; +export function isBotAgent(ua: string | undefined): boolean { + return !ua || ua.length < 20 || BOT_UA.test(ua); +} + +/** The page path only: no query string (it can carry emails or tokens), no fragment, bounded length. */ +export function cleanHitPath(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + let p = raw.split(/[?#]/)[0].trim(); + try { p = decodeURIComponent(p); } catch { return null; } + if (!p.startsWith('/') || p.length > 120 || !/^\/[A-Za-z0-9\-_/.~]*$/.test(p) || p.includes('//')) return null; + if (p.length > 1) p = p.replace(/\/+$/, ''); + return p.toLowerCase(); +} + +/** + * Just the referring site's host name ('' = direct, or a page on this same site). + * Search engines and big social sites are grouped under one name each. + */ +export function referrerHost(raw: unknown, ownDomains: string[]): string { + if (typeof raw !== 'string' || !raw) return ''; + let host: string; + try { + const u = new URL(raw); + if (u.protocol !== 'https:' && u.protocol !== 'http:') return ''; + host = u.hostname.toLowerCase().replace(/^(www|m|l|lm)\./, ''); + } catch { return ''; } + const own = ownDomains.map((d) => d.toLowerCase().replace(/^www\./, '')); + if (own.some((d) => host === d || host.endsWith('.' + d))) return ''; + if (/(^|\.)google\.[a-z.]+$/.test(host)) return 'google'; + if (/(^|\.)bing\.com$/.test(host)) return 'bing'; + if (/(^|\.)duckduckgo\.com$/.test(host)) return 'duckduckgo'; + if (/(^|\.)yahoo\.[a-z.]+$/.test(host)) return 'yahoo'; + if (/(^|\.)(facebook\.com|fb\.com)$/.test(host)) return 'facebook'; + if (/(^|\.)(t\.co|twitter\.com|x\.com)$/.test(host)) return 'x (twitter)'; + if (/(^|\.)reddit\.com$/.test(host)) return 'reddit'; + if (/(^|\.)instagram\.com$/.test(host)) return 'instagram'; + return host.length > 80 ? host.slice(0, 80) : host; +} + +// ---------- Google tags ---------- + +export function validateGoogleTags(input: Partial | undefined, current?: GoogleTags): GoogleTags { + const t: GoogleTags = { enabled: false, ...current, ...input }; + const clean = (v: string | undefined) => (v ?? '').trim() || undefined; + t.ga4Id = clean(t.ga4Id)?.toUpperCase(); + t.adsId = clean(t.adsId)?.toUpperCase(); + t.adsJoinLabel = clean(t.adsJoinLabel); + if (t.ga4Id && !/^G-[A-Z0-9]{4,16}$/.test(t.ga4Id)) throw new RuleError('bad_ga4', 'The Google Analytics ID looks like G-XXXXXXXXXX.'); + if (t.adsId && !/^AW-\d{6,14}$/.test(t.adsId)) throw new RuleError('bad_ads', 'The Google Ads ID looks like AW-123456789.'); + if (t.adsJoinLabel && !/^[A-Za-z0-9_-]{4,40}$/.test(t.adsJoinLabel)) throw new RuleError('bad_label', 'The conversion label is letters, digits, - and _ only.'); + if (t.adsJoinLabel && !t.adsId) throw new RuleError('bad_label', 'Add the Google Ads ID for that conversion label.'); + if (t.enabled && !t.ga4Id && !t.adsId) throw new RuleError('no_tags', 'Add a Google Analytics or Google Ads ID first.'); + t.enabled = !!t.enabled; + return t; +} + +/** What the public site needs to load Google tags, or undefined when they are off. */ +export function publicGoogleTags(site: Site) { + const g = site.settings.googleTags; + if (!g?.enabled || (!g.ga4Id && !g.adsId)) return undefined; + return { ga4Id: g.ga4Id, adsId: g.adsId, adsJoinLabel: g.adsJoinLabel, restricted: site.settings.mode !== 'standard' }; +} + +// ---------- Dashboard ---------- + +const emptyDay = (day: string): KpiDay => ({ day, views: 0, visitors: 0, visits: 0, signups: 0, signIns: 0, active: 0, messages: 0, photos: 0, moderation: 0 }); +const emptyTotals = () => Object.fromEntries(KPI_METRICS.map((k) => [k, { now: 0, before: 0 }])) as SiteDashboard['totals']; + +/** + * Builds one site's dashboard. `raw` must cover 2 × days, so each total can be compared with the + * period before it. Active members is a daily figure, so its total is the daily average. + */ +export function buildSiteDashboard(site: Site, raw: SiteKpiRaw, days: number, today: string): SiteDashboard { + const from = addDays(today, -(days - 1)); + const start = addDays(from, -days); + const byDay = new Map(); + for (let d = start; d <= today; d = addDays(d, 1)) byDay.set(d, emptyDay(d)); + const put = (rows: DayCount[], key: KpiMetric) => { for (const r of rows) { const x = byDay.get(r.day); if (x) x[key] += r.n; } }; + put(raw.signups, 'signups'); + put(raw.signIns, 'signIns'); + put(raw.activeDaily, 'active'); + put(raw.messages, 'messages'); + put(raw.photos, 'photos'); + put(raw.moderationAdded, 'moderation'); + for (const t of raw.traffic) { + const x = byDay.get(t.day); + if (x) { x.views += t.views; x.visitors += t.visitors; x.visits += t.visits; } + } + const all = [...byDay.values()]; + const series = all.filter((d) => d.day >= from); + const prior = all.filter((d) => d.day < from); + const totals = emptyTotals(); + for (const k of KPI_METRICS) { + totals[k].now = series.reduce((a, d) => a + d[k], 0); + totals[k].before = prior.reduce((a, d) => a + d[k], 0); + } + totals.active = { now: Math.round(totals.active.now / days), before: Math.round(totals.active.before / days) }; + return { + siteId: site.id, name: site.name, slug: site.slug, mode: site.settings.mode, days, from, to: today, series, totals, + members: raw.members, active: raw.active, + signupsCompleted: raw.signupsCompleted.filter((r) => r.day >= from).reduce((a, r) => a + r.n, 0), + imported: raw.imported, moderationWaiting: raw.moderationWaiting, topPages: raw.topPages, referrers: raw.referrers, + trafficSince: raw.traffic.find((t) => t.views > 0)?.day, + }; +} + +export function emptySiteDashboard(site: Site, days: number, today: string, error: string): SiteDashboard { + const raw: SiteKpiRaw = { + members: 0, signups: [], signupsCompleted: [], imported: { total: 0, returned: 0, days: [] }, active: { day: 0, week: 0, month: 0 }, + activeDaily: [], signIns: [], messages: [], photos: [], moderationAdded: [], moderationWaiting: 0, traffic: [], topPages: [], referrers: [], + }; + return { ...buildSiteDashboard(site, raw, days, today), error }; +} + +/** Adds sites together. Each site's numbers still come only from its own database. */ +export function combineDashboards(sites: SiteDashboard[], days: number, today: string): NetworkDashboard { + const from = addDays(today, -(days - 1)); + const series: KpiDay[] = []; + for (let d = from; d <= today; d = addDays(d, 1)) series.push(emptyDay(d)); + const totals = emptyTotals(); + for (const s of sites) { + s.series.forEach((d, i) => { for (const k of KPI_METRICS) series[i][k] += d[k]; }); + for (const k of KPI_METRICS) { totals[k].now += s.totals[k].now; totals[k].before += s.totals[k].before; } + } + const sum = (f: (s: SiteDashboard) => number) => sites.reduce((a, s) => a + f(s), 0); + return { + days, from, to: today, series, totals, + members: sum((s) => s.members), + active: { day: sum((s) => s.active.day), week: sum((s) => s.active.week), month: sum((s) => s.active.month) }, + moderationWaiting: sum((s) => s.moderationWaiting), + sites, + }; +} diff --git a/packages/core/src/api.ts b/packages/core/src/api.ts index 09992cf..38a34d5 100644 --- a/packages/core/src/api.ts +++ b/packages/core/src/api.ts @@ -6,7 +6,7 @@ import type { AccessRow, Platform, ProfilePatch } from './services'; import type { ActivityKind, ActivityList, AdminMemberProfile, AdminMemberRow, ClientPlatform, MemberEvent, DiscoverCard, ContentPage, ConversationSummary, ConversationView, MemberProfile, MemberStatus, ModerationDecision, ModerationView, MyProfile, PhotoKind, PhotoRating, ProfileFieldDef, PublicSite, SearchFilters, - SearchResult, Site, EventView, RsvpStatus, SiteEvent, GeoCountry, GeoPlace, SiteMode, SiteStats, Tier, AdminUser, AuditEntry, NewSiteInput, PlatformOverview, + SearchResult, Site, EventView, RsvpStatus, SiteEvent, GeoCountry, GeoPlace, SiteMode, SiteStats, Tier, AdminUser, AuditEntry, NewSiteInput, PlatformOverview, SiteDashboard, NetworkDashboard, } from './types'; export class ApiError extends Error { @@ -80,6 +80,10 @@ export interface AdminApi { saveField(siteId: string, def: ProfileFieldDef): Promise; deleteField(siteId: string, key: string): Promise; stats(siteId: string): Promise; + /** KPI charts for one site: traffic, sign-ups, active members, messages, photos, moderation. days: 7, 30 or 90. */ + dashboard(siteId: string, days: number): Promise; + /** The same, added up over every site this admin may see. */ + dashboardAll(days: number): Promise; moderation(siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all'): Promise; decide(siteId: string, itemId: string, decision: ModerationDecision, text?: string): Promise; /** Marks waiting "contact info in profile" items fine when today's check no longer finds contact details. */ @@ -192,6 +196,8 @@ export function createLocalAdminApi(platform: Platform): AdminApi { saveField: (s, d) => wrap(async () => platform.adminSaveField(await admin(), s, d)), deleteField: (s, k) => wrap(async () => platform.adminDeleteField(await admin(), s, k)), stats: (s) => wrap(async () => platform.adminStats(await admin(), s)), + dashboard: (s, d) => wrap(async () => platform.adminDashboard(await admin(), s, d)), + dashboardAll: (d) => wrap(async () => platform.adminDashboardAll(await admin(), d)), moderation: (s, st) => wrap(async () => platform.adminModeration(await admin(), s, st)), decide: (s, i, d, text) => wrap(async () => platform.adminDecide(await admin(), s, i, d, text)), recheckModeration: (s) => wrap(async () => platform.adminRecheckModeration(await admin(), s)), diff --git a/packages/core/src/demo-analytics.ts b/packages/core/src/demo-analytics.ts new file mode 100644 index 0000000..0c2db7a --- /dev/null +++ b/packages/core/src/demo-analytics.ts @@ -0,0 +1,42 @@ +// Placeholder dashboard history for the demo sites (preview, tests, dev seed). Never run on real sites. +import { addDays, utcDay } from './analytics'; +import type { SiteRepo } from './repo'; +import type { Site } from './types'; + +function rng(seed: number) { + let x = seed || 1; + return () => { x = (x * 1103515245 + 12345) % 2147483648; return x / 2147483648; }; +} + +const PAGES = ['/', '/', '/', '/', '/guides', '/about', '/safety', '/privacy', '/first-date-ideas', '/how-it-works']; +const REFS = ['https://www.google.com/', 'https://www.google.com/', 'https://www.google.com/', '', '', 'https://www.bing.com/', 'https://duckduckgo.com/', 'https://www.reddit.com/r/dating', 'https://www.facebook.com/']; + +export async function seedDemoAnalytics(repo: SiteRepo, site: Site, now: Date, memberIds: string[], days = 75) { + const r = rng(site.id.length * 131 + site.slug.charCodeAt(1)); + const today = utcDay(now); + const scale = site.settings.mode === 'sensitive' ? 0.6 : 1; + for (let i = days - 1; i >= 0; i--) { + const day = addDays(today, -i); + const weekday = new Date(day + 'T12:00:00Z').getUTCDay(); + const trend = 1 + (days - i) / days; // slowly growing + const visitors = Math.round((18 + r() * 14) * trend * scale * (weekday === 0 || weekday === 6 ? 1.3 : 1)); + for (let v = 0; v < visitors; v++) { + const visitor = `demo-${day}-${v}`; + const pages = 1 + Math.floor(r() * 3); + let at = Date.parse(day + 'T00:00:00Z') + Math.floor(r() * 20 * 3600_000); + for (let p = 0; p < pages; p++) { + await repo.recordHit({ day, at: new Date(at).toISOString(), path: PAGES[Math.floor(r() * PAGES.length)], refHost: p ? '' : refHost(REFS[Math.floor(r() * REFS.length)]), visitor }); + at += 60_000 + Math.floor(r() * 120_000); + } + } + const active = memberIds.filter(() => r() < 0.25 * scale * trend); + for (const id of active) await repo.markActive(id, day); + await repo.bumpDaily('sign_ins', day, Math.round(active.length * (0.4 + r() * 0.3))); + } +} + +function refHost(u: string) { + if (!u) return ''; + const h = new URL(u).hostname.replace(/^www\./, ''); + return h.startsWith('google.') ? 'google' : h === 'bing.com' ? 'bing' : h === 'duckduckgo.com' ? 'duckduckgo' : h; +} diff --git a/packages/core/src/http-client.ts b/packages/core/src/http-client.ts index d66b6b7..0e16b78 100644 --- a/packages/core/src/http-client.ts +++ b/packages/core/src/http-client.ts @@ -149,6 +149,8 @@ export function createHttpAdminApi(baseUrl: string): AdminApi { saveField: (id, def) => req('PUT', s(id) + '/fields/' + def.key, def), deleteField: (id, key) => req('DELETE', s(id) + '/fields/' + key), stats: (id) => req('GET', s(id) + '/stats'), + dashboard: (id, days) => req('GET', s(id) + '/dashboard?days=' + days), + dashboardAll: (days) => req('GET', '/v1/admin/dashboard?days=' + days), moderation: (id, status) => req('GET', s(id) + '/moderation?status=' + status), decide: (id, item, decision, text) => req('POST', s(id) + '/moderation/' + item, { decision, text }), recheckModeration: (id) => req('POST', s(id) + '/moderation-recheck', {}), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 459e02f..4088215 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,3 +13,5 @@ export * from './starter-content'; export * from './memory-platform'; export * from './stub-payments'; export * from './zoned-time'; +export * from './analytics'; +export * from './demo-analytics'; diff --git a/packages/core/src/memory-platform.ts b/packages/core/src/memory-platform.ts index ef4cf18..db4c1ad 100644 --- a/packages/core/src/memory-platform.ts +++ b/packages/core/src/memory-platform.ts @@ -5,6 +5,7 @@ import type { Clock, IdTokenVerifier, Notifier, PaymentGateway } from './repo'; import { DEMO_MEMBER_EMAIL, seedAdmins, seedSite, seedSites } from './seed'; import { Platform } from './services'; import { LocalEventHub } from './events'; +import { seedDemoAnalytics } from './demo-analytics'; export interface MemoryPlatformSnapshot { v: 1; control: ControlSnapshot; sites: Record } @@ -26,6 +27,7 @@ export async function createMemoryPlatform(opts: { allowSelfServeTier?: boolean; // default true: the in-memory platform is the preview payments?: Partial>; idTokens?: IdTokenVerifier; + demoAnalytics?: boolean; // placeholder dashboard history (the preview turns it on) } = {}): Promise { const keys = new DevKeyProvider(opts.masterKey ?? 'preview-master-key'); const now = opts.clock?.now() ?? new Date(); @@ -43,7 +45,9 @@ export async function createMemoryPlatform(opts: { const seed = seedSite(site, now, { demoMemberHash: { emailHash: await crypto.lookupHash(DEMO_MEMBER_EMAIL), emailEnc: await crypto.encrypt(DEMO_MEMBER_EMAIL) }, }); - sites.set(site.id, new MemorySiteRepo(seed)); + const repo = new MemorySiteRepo(seed); + if (opts.demoAnalytics) { await seedDemoAnalytics(repo, site, now, seed.members.map((m) => m.id)); await repo.cleanup(now.toISOString()); } + sites.set(site.id, repo); } } diff --git a/packages/core/src/memory-repo.ts b/packages/core/src/memory-repo.ts index cd80bc9..1ff0e15 100644 --- a/packages/core/src/memory-repo.ts +++ b/packages/core/src/memory-repo.ts @@ -4,7 +4,7 @@ import type { AdminChallenge, AdminSession, ControlRepo, MemberQuery, MemberSession, SiteRepo } from './repo'; import type { UsageKind, AuditEntry, EventRsvp, SiteEvent, AdminUser, Block, Favorite, Pass, ContactOptIn, ContentPage, Like, Member, Message, ModerationItem, Photo, - PrivateAccess, PushToken, Report, Subscription, ReviewStatus, Site, VerificationChallenge, View, + PrivateAccess, SiteKpiRaw, TrafficDay, TrafficHit, PushToken, Report, Subscription, ReviewStatus, Site, VerificationChallenge, View, } from './types'; const clone = (x: T): T => JSON.parse(JSON.stringify(x)); @@ -89,6 +89,23 @@ export interface SiteSnapshot { moderation: ModerationItem[]; pages: ContentPage[]; challenges: VerificationChallenge[]; sessions: MemberSession[]; push?: PushToken[]; subscriptions?: Subscription[]; events?: SiteEvent[]; rsvps?: EventRsvp[]; + analytics?: MemoryAnalytics; +} +export interface MemoryAnalytics { + activeDays: string[]; // "day|memberId" + daily: Record; // "metric|day" -> count + salts: { day: string; salt: string }[]; + visitors: { day: string; visitor: string; lastAt: string }[]; + traffic: TrafficDay[]; + pages: { day: string; path: string; views: number }[]; + refs: { day: string; host: string; views: number }[]; +} +const emptyAnalytics = (): MemoryAnalytics => ({ activeDays: [], daily: {}, salts: [], visitors: [], traffic: [], pages: [], refs: [] }); +const dayOf = (iso: string) => iso.slice(0, 10); +function countByDay(rows: T[], day: (r: T) => string | undefined, since: string): { day: string; n: number }[] { + const m = new Map(); + for (const r of rows) { const d = day(r); if (d && d >= since) m.set(d, (m.get(d) ?? 0) + 1); } + return [...m.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([d, n]) => ({ day: d, n })); } export class MemorySiteRepo implements SiteRepo { @@ -102,6 +119,7 @@ export class MemorySiteRepo implements SiteRepo { this.d.events ??= []; this.d.rsvps ??= []; this.d.favorites ??= []; + this.d.analytics ??= emptyAnalytics(); } snapshot(): SiteSnapshot { return clone(this.d); } @@ -297,6 +315,11 @@ export class MemorySiteRepo implements SiteRepo { const d = this.d; d.sessions = d.sessions.filter((s) => s.expiresAt > now); d.challenges = d.challenges.filter((c) => c.expiresAt > now); + // Visitor hashes and their salts are only needed for today's counts; daily totals stay. + const a = (d.analytics ??= emptyAnalytics()); + const keep = new Date(Date.parse(now) - 2 * 86400e3).toISOString().slice(0, 10); + a.salts = a.salts.filter((x) => x.day >= keep); + a.visitors = a.visitors.filter((x) => x.day >= keep); const stale = new Date(Date.parse(now) - 2 * 86400e3).toISOString(); d.subscriptions = (d.subscriptions ?? []).filter((s) => !(s.status === 'pending' && s.createdAt < stale)); const lapsed: string[] = []; @@ -312,6 +335,74 @@ export class MemorySiteRepo implements SiteRepo { async listPushTokens(id: string) { return clone((this.d.push ?? []).filter((x) => x.memberId === id)); } async deletePushToken(token: string) { this.d.push = (this.d.push ?? []).filter((x) => x.token !== token); } + async markActive(memberId: string, day: string) { + const a = this.d.analytics!, k = day + '|' + memberId; + if (!a.activeDays.includes(k)) a.activeDays.push(k); + } + async bumpDaily(metric: 'sign_ins', day: string, n = 1) { + const a = this.d.analytics!, k = metric + '|' + day; + a.daily[k] = (a.daily[k] ?? 0) + n; + } + async trafficSalt(day: string, fresh: string) { + const a = this.d.analytics!; + const hit = a.salts.find((x) => x.day === day); + if (hit) return hit.salt; + a.salts.push({ day, salt: fresh }); + return fresh; + } + async recordHit(h: TrafficHit) { + const a = this.d.analytics!; + let t = a.traffic.find((x) => x.day === h.day); + if (!t) { t = { day: h.day, views: 0, visitors: 0, visits: 0 }; a.traffic.push(t); } + t.views++; + const v = a.visitors.find((x) => x.day === h.day && x.visitor === h.visitor); + if (!v) { a.visitors.push({ day: h.day, visitor: h.visitor, lastAt: h.at }); t.visitors++; t.visits++; } + else { if (Date.parse(h.at) - Date.parse(v.lastAt) > 30 * 60_000) t.visits++; v.lastAt = h.at; } + const p = a.pages.find((x) => x.day === h.day && x.path === h.path); + if (p) p.views++; else a.pages.push({ day: h.day, path: h.path, views: 1 }); + const r = a.refs.find((x) => x.day === h.day && x.host === h.refHost); + if (r) r.views++; else a.refs.push({ day: h.day, host: h.refHost, views: 1 }); + } + async kpis(since: string, topSince: string, nowIso: string): Promise { + const d = this.d, a = d.analytics!; + const now = Date.parse(nowIso); + const ago = (days: number) => new Date(now - days * 86_400_000).toISOString(); + const native = d.members.filter((m) => !m.imported); + // An imported member counts as active only once they use the new site. + const seen = d.members.filter((m) => !m.imported || m.lastActiveAt > m.imported.at); + const sum = (rows: T[], key: (r: T) => string, val: (r: T) => number, limit: number) => { + const m = new Map(); + for (const r of rows) m.set(key(r), (m.get(key(r)) ?? 0) + val(r)); + return [...m.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0])).slice(0, limit); + }; + const imported = d.members.filter((m) => m.imported); + return { + members: d.members.length, + signups: countByDay(native, (m) => dayOf(m.createdAt), since), + signupsCompleted: countByDay(native.filter((m) => m.profileComplete), (m) => dayOf(m.createdAt), since), + imported: { + total: imported.length, + returned: imported.filter((m) => m.lastActiveAt > m.imported!.at).length, + days: countByDay(imported, (m) => dayOf(m.imported!.at), '0000'), + }, + active: { + day: seen.filter((m) => m.lastActiveAt >= ago(1)).length, + week: seen.filter((m) => m.lastActiveAt >= ago(7)).length, + month: seen.filter((m) => m.lastActiveAt >= ago(30)).length, + }, + activeDaily: countByDay(a.activeDays, (k) => k.slice(0, 10), since), + signIns: Object.entries(a.daily).filter(([k]) => k.startsWith('sign_ins|') && k.slice(9) >= since) + .map(([k, n]) => ({ day: k.slice(9), n })).sort((x, y) => x.day.localeCompare(y.day)), + messages: countByDay(d.messages.filter((m) => !m.id.startsWith('msg_imp_')), (m) => dayOf(m.at), since), + photos: countByDay(d.photos.filter((p) => !p.id.startsWith('ph_imp_')), (p) => p.createdAt && dayOf(p.createdAt), since), + moderationAdded: countByDay(d.moderation.filter((i) => !i.id.startsWith('mod_imp_')), (i) => dayOf(i.createdAt), since), + moderationWaiting: d.moderation.filter((i) => i.status === 'pending').length, + traffic: a.traffic.filter((t) => t.day >= since).sort((x, y) => x.day.localeCompare(y.day)).map((t) => ({ ...t })), + topPages: sum(a.pages.filter((p) => p.day >= topSince), (p) => p.path, (p) => p.views, 10).map(([path, views]) => ({ path, views })), + referrers: sum(a.refs.filter((r) => r.day >= topSince), (r) => r.host, (r) => r.views, 10).map(([host, views]) => ({ host, views })), + }; + } + async stats(nowIso: string) { const now = Date.parse(nowIso); const day = new Date(now - 86_400_000).toISOString(); diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index f31d9f2..3682f49 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -2,7 +2,7 @@ // a control database); the clickable preview implements them in memory. import type { AdminUser, AuditEntry, EventRsvp, SiteEvent, Block, Favorite, MemberEvent, Pass, ContactOptIn, ContentPage, Gender, Like, Member, Message, ModerationItem, - Photo, PrivateAccess, PushToken, Report, Subscription, SubscriptionStatus, ReviewStatus, Site, UsageKind, VerificationChallenge, View, + Photo, PrivateAccess, PushToken, Report, Subscription, SubscriptionStatus, ReviewStatus, Site, SiteKpiRaw, TrafficHit, UsageKind, VerificationChallenge, View, } from './types'; export interface AdminSession { token: string; adminId: string; expiresAt: string } @@ -141,6 +141,16 @@ export interface SiteRepo { listPushTokens(memberId: string): Promise; deletePushToken(token: string): Promise; + // dashboard counters. Everything stays in this site's own database. + markActive(memberId: string, day: string): Promise; // once per member per day + bumpDaily(metric: 'sign_ins', day: string, n?: number): Promise; + // Today's random salt for visitor hashes: returns the stored one, or stores `fresh`. Deleted after 2 days. + trafficSalt(day: string, fresh: string): Promise; + // Counts a public page view. A new visit starts when the visitor is new today or was idle 30 minutes. + recordHit(h: TrafficHit): Promise; + // Raw daily counts from sinceDay on (inclusive); top pages and referrers from topSinceDay on. + kpis(sinceDay: string, topSinceDay: string, nowIso: string): Promise; + // admin stats stats(nowIso: string): Promise<{ members: number; activeToday: number; newThisWeek: number; paid: number; messagesToday: number; diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts index 36b17ba..08f7063 100644 --- a/packages/core/src/services.ts +++ b/packages/core/src/services.ts @@ -3,6 +3,9 @@ import { LocalEventHub } from './events'; import { DevKeyProvider, hmacHex, type KeyProvider, randomCode, randomId, SiteCrypto } from './crypto'; import { builtinGeo, unitsForCountry } from './geo'; +import { + buildSiteDashboard, cleanHitPath, combineDashboards, DASHBOARD_DAYS, emptySiteDashboard, isBotAgent, publicGoogleTags, referrerHost, utcDay, addDays, validateGoogleTags, +} from './analytics'; import type { ControlRepo, Clock, EventSink, IdTokenVerifier, Notifier, PaymentGateway, PhotoStore, SiteProvisioner, SiteRepo } from './repo'; import { systemClock } from './repo'; import { DEFAULT_LICENSING, DEFAULT_NOTIFY, DEFAULT_STRICT, isGender, type HiddenPrefs, type NotifyPrefs, type StrictPrefs } from './types'; @@ -15,7 +18,7 @@ import type { NewSiteInput, SiteMode, PlatformOverview, PlatformSiteRow, SiteLicensing, SiteStatus, UsageKind, AdminUser, ClientPlatform, ContentPage, ConversationSummary, ConversationView, Gender, GeoPlace, GeoProvider, LocationInput, Member, MemberCard, MemberProfile, MemberStatus, ModerationDecision, ModerationItem, ModerationView, MyProfile, Photo, PhotoKind, PhotoRating, PhotoView, ProfileFieldDef, PublicSite, SearchFilters, SearchResult, Site, - SiteSettings, SiteStats, SiteTheme, EventRsvp, EventView, ProfileEvent, RsvpStatus, SiteEvent, + SiteSettings, SiteStats, SiteTheme, EventRsvp, NetworkDashboard, SiteDashboard, EventView, ProfileEvent, RsvpStatus, SiteEvent, } from './types'; export interface PlatformDeps { @@ -127,9 +130,31 @@ export class Platform { explicitPhotosAllowed: site.settings.explicitPhotosAllowed, publicTeasers: site.settings.mode !== 'sensitive' && site.settings.publicTeasers, units: site.settings.units, + googleTags: publicGoogleTags(site), }; } + // ---------------- Public page views (cookieless) ---------------- + + /** + * Counts one view of a public page. Nothing about the visitor is stored except a hash of their + * IP and browser with today's random salt, which is deleted after 2 days. + */ + async recordPageView(site: Site, input: { path: unknown; referrer: unknown; ip?: string; userAgent?: string }) { + if (isBotAgent(input.userAgent) || !input.ip) return { counted: false }; + const path = cleanHitPath(input.path); + if (!path) return { counted: false }; + // A generous cap per network, so a script can't flood the counts. + const n = await this.deps.control.hit(`hit:${site.id}:${input.ip}`, 3600, this.iso()); + if (n > 600) return { counted: false }; + const repo = await this.repo(site); + const at = this.iso(), day = utcDay(at); + const salt = await repo.trafficSalt(day, randomId() + randomId()); + const visitor = (await hmacHex(new TextEncoder().encode(salt), `${site.id}|${input.ip}|${input.userAgent}`)).slice(0, 32); + await repo.recordHit({ day, at, path, refHost: referrerHost(input.referrer, site.domains), visitor }); + return { counted: true }; + } + async publicPages(site: Site): Promise { const repo = await this.repo(site); return (await repo.listPages()).filter((p) => p.published); @@ -215,6 +240,9 @@ export class Platform { const repo = await this.repo(site); const token = site.slug + '.' + randomId(); await repo.saveSession({ token: await this.sessionKey(site, token), memberId: member.id, expiresAt: new Date(this.now().getTime() + SESSION_TTL_MS).toISOString() }); + const day = utcDay(this.now()); + await repo.bumpDaily('sign_ins', day).catch(() => {}); + await repo.markActive(member.id, day).catch(() => {}); this.changed(); return { token, isNew: isNew || !member.profileComplete }; } @@ -276,10 +304,13 @@ export class Platform { const me = await repo.getMember(s.memberId); if (!me) throw new RuleError('signed_out', 'Please sign in.', 401); if (me.status === 'suspended') throw new RuleError('suspended', 'This account is suspended.', 403); - // touch activity at most once a minute - if (this.now().getTime() - Date.parse(me.lastActiveAt) > 60_000) { + // touch activity at most once a minute, and note each day they use the site + const today = utcDay(this.now()); + const newDay = me.lastActiveAt.slice(0, 10) !== today; + if (newDay || this.now().getTime() - Date.parse(me.lastActiveAt) > 60_000) { me.lastActiveAt = this.iso(); await repo.saveMember(me); + if (newDay) await repo.markActive(me.id, today).catch(() => {}); } return { site, repo, me, platform }; } @@ -1341,6 +1372,37 @@ export class Platform { return { ...base, openModeration: (await repo.listModeration('pending')).length }; } + /** KPI dashboard for one site, from that site's own database only. */ + async adminDashboard(admin: AdminUser, siteId: string, days?: number): Promise { + const site = await this.adminSite(admin, siteId); + return this.siteDashboard(site, this.dashboardDays(days)); + } + + /** Every site this admin may see, added up: all sites for WhatBox, only their own for an owner. */ + async adminDashboardAll(admin: AdminUser, days?: number): Promise { + const n = this.dashboardDays(days); + const all = await this.deps.control.listSites(); + const mine = admin.role === 'platform' ? all : all.filter((s) => admin.siteIds.includes(s.id)); + const sites = await Promise.all(mine.map((s) => this.siteDashboard(s, n))); + return combineDashboards(sites, n, utcDay(this.now())); + } + + private dashboardDays(days?: number) { + return (DASHBOARD_DAYS as readonly number[]).includes(Number(days)) ? Number(days) : 30; + } + + private async siteDashboard(site: Site, days: number): Promise { + const today = utcDay(this.now()); + try { + const repo = await this.repo(site); + const raw = await repo.kpis(addDays(today, -(2 * days - 1)), addDays(today, -(days - 1)), this.iso()); + return buildSiteDashboard(site, raw, days, today); + } catch (e) { + console.error(`dashboard ${site.slug}`, e); + return emptySiteDashboard(site, days, today, 'This site\'s numbers could not be loaded right now.'); + } + } + async adminModeration(admin: AdminUser, siteId: string, status: 'pending' | 'approved' | 'rejected' | 'all'): Promise { const site = await this.adminSite(admin, siteId); const repo = await this.repo(site); @@ -1715,7 +1777,8 @@ export class Platform { site.theme = { ...site.theme, ...patch.theme }; } if (patch.settings) { - const { membership, mode, ...rest } = patch.settings; + const { membership, mode, googleTags, ...rest } = patch.settings; + if (googleTags) site.settings.googleTags = validateGoogleTags(googleTags, site.settings.googleTags); if (mode && mode !== site.settings.mode && admin.role !== 'platform') { throw new RuleError('forbidden', 'Only WhatBox can change a site mode.', 403); } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 36af1ea..0f31775 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -67,6 +67,19 @@ export interface SiteSettings { newMemberDays: number; // how long a new member gets a visibility boost passCooldownDays: number; // a passed profile can reappear after this }; + /** Optional Google Analytics / Google Ads tags. Off unless the owner turns them on. */ + googleTags?: GoogleTags; +} + +/** + * Google tags for one site. They load only on the public pages (never in the member app or the + * native apps), and only after the visitor accepts cookies on that site. + */ +export interface GoogleTags { + enabled: boolean; + ga4Id?: string; // Google Analytics 4 measurement ID, e.g. G-ABC123XYZ + adsId?: string; // Google Ads tag ID, e.g. AW-123456789 + adsJoinLabel?: string; // conversion label fired when a visitor clicks Join on the public site } export type Units = 'imperial' | 'metric'; @@ -515,6 +528,8 @@ export interface PublicSite { explicitPhotosAllowed: boolean; publicTeasers: boolean; units: Units; + /** Present only when the owner turned Google tags on. restricted: sensitive site, no ad personalization or Google signals. */ + googleTags?: { ga4Id?: string; adsId?: string; adsJoinLabel?: string; restricted: boolean }; } export interface SearchFilters { @@ -546,6 +561,68 @@ export interface SiteStats { openModeration: number; } +// ---------- Admin dashboard (KPIs) ---------- + +export interface DayCount { day: string; n: number } // day is YYYY-MM-DD in UTC +export interface TrafficDay { day: string; views: number; visitors: number; visits: number } + +/** One public page view, already cleaned up. visitor is a salted hash that changes every day. */ +export interface TrafficHit { day: string; at: string; path: string; refHost: string; visitor: string } + +/** Raw daily counts from one site's own database. The service fills gaps and adds totals. */ +export interface SiteKpiRaw { + members: number; + signups: DayCount[]; // new accounts made on this platform (imported members are left out) + signupsCompleted: DayCount[]; // of those, the ones who finished their profile, by the day they joined + imported: { total: number; returned: number; days: DayCount[] }; // by import day; returned = signed in since + active: { day: number; week: number; month: number }; // members seen in the last 1 / 7 / 30 days + activeDaily: DayCount[]; + signIns: DayCount[]; + messages: DayCount[]; + photos: DayCount[]; + moderationAdded: DayCount[]; + moderationWaiting: number; + traffic: TrafficDay[]; + topPages: { path: string; views: number }[]; + referrers: { host: string; views: number }[]; +} + +export type KpiMetric = 'views' | 'visitors' | 'visits' | 'signups' | 'signIns' | 'active' | 'messages' | 'photos' | 'moderation'; +export interface KpiDay { day: string; views: number; visitors: number; visits: number; signups: number; signIns: number; active: number; messages: number; photos: number; moderation: number } + +export interface SiteDashboard { + siteId: string; + name: string; + slug: string; + mode: SiteMode; + days: number; + from: string; // first day shown + to: string; // today (UTC) + series: KpiDay[]; + totals: Record; // this period vs the one before it + members: number; + active: { day: number; week: number; month: number }; + signupsCompleted: number; + imported: { total: number; returned: number; days: DayCount[] }; + moderationWaiting: number; + topPages: { path: string; views: number }[]; + referrers: { host: string; views: number }[]; + trafficSince?: string; // first day with any page views counted + error?: string; // the site's database could not be read +} + +export interface NetworkDashboard { + days: number; + from: string; + to: string; + series: KpiDay[]; + totals: Record; + members: number; + active: { day: number; week: number; month: number }; + moderationWaiting: number; + sites: SiteDashboard[]; +} + export interface AdminMemberRow { id: string; displayName: string; diff --git a/packages/core/test/dashboard.test.ts b/packages/core/test/dashboard.test.ts new file mode 100644 index 0000000..513159b --- /dev/null +++ b/packages/core/test/dashboard.test.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + ApiError, cleanHitPath, createLocalAdminApi, createLocalMemberApi, createMemoryPlatform, DEMO_MEMBER_EMAIL, DEMO_OWNER_EMAIL, isBotAgent, + referrerHost, utcDay, validateGoogleTags, +} from '../src/index'; + +const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'; + +async function adminFor(mp: Awaited>, email: string) { + const admin = createLocalAdminApi(mp.platform); + const st = await admin.start(email); + admin.setToken((await admin.verify(st.challengeId, st.devCode!)).token); + return admin; +} + +test('page paths and referrers are cleaned before counting', () => { + assert.equal(cleanHitPath('/Guides/?email=a@b.com#x'), '/guides'); + assert.equal(cleanHitPath('/'), '/'); + assert.equal(cleanHitPath('https://evil.example/x'), null); + assert.equal(cleanHitPath('/