Phase 1 of replacing Microsoft Clarity with first-party usage analytics: - Plain Postgres tables via shared DDL module (src/lib/analytics/schema.ts) executed by both the add_analytics_tables migration and the test bootstrap; test-db.ts drops them around drizzle push (composite-PK introspector bug) - /api/collect beacon collector with IP/UA enrichment, retroactive login attribution, bot blocklist, per-IP rate limiting, strict validation - Client SDK (src/lib/client-analytics): SPA pageviews, clicks, scroll depth, focus, data-track visibility, heartbeats; NEXT_PUBLIC_ANALYTICS_DEV=1 dev gate with console mirror; mounted beside Clarity in the two frontend layouts - Hourly rollup + daily retention bins (payload analytics-rollup/-purge) - Chronicle read progress/completion, wiki new-clicked/created, minigame route mapping custom events - admin:analytics:manage permission (+ roles enum migration) and the /admin/analytics Payload view with six recharts-backed report panels
45 lines
1.8 KiB
TypeScript
45 lines
1.8 KiB
TypeScript
import type { SanitizedConfig } from "payload";
|
|
import { getPayload } from "payload";
|
|
|
|
import { buildGameKeyMap } from "@/lib/analytics/games";
|
|
import { recentDays, rollupDay, type AnalyticsDay } from "@/lib/analytics/rollup";
|
|
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
|
|
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
|
|
|
|
/**
|
|
* `bun run payload analytics-rollup` - hourly aggregate rollup (external
|
|
* cron). Recomputes the permanent daily aggregate tables from raw analytics
|
|
* events for today and yesterday UTC (yesterday rides along so late beacons
|
|
* still land in a complete row; every day is recomputed delete-then-insert,
|
|
* so re-runs are idempotent).
|
|
*
|
|
* Backfill override: `ANALYTICS_ROLLUP_DAY=YYYY-MM-DD` rolls up exactly that
|
|
* one day.
|
|
*/
|
|
export const script = async (config: SanitizedConfig) => {
|
|
const payload = await getPayload({ config });
|
|
const log = createBinLogger("analytics-rollup", payload.logger);
|
|
|
|
try {
|
|
log.info("[Analytics Rollup] Starting daily aggregate rollup...");
|
|
|
|
const override = process.env.ANALYTICS_ROLLUP_DAY as AnalyticsDay | undefined;
|
|
const days = override ? [override] : recentDays(2);
|
|
|
|
const registry = await loadMinigameRegistry(payload);
|
|
const slugToKey = Object.fromEntries(buildGameKeyMap(registry).entries());
|
|
|
|
for (const day of days) {
|
|
const result = await rollupDay(payload, day, slugToKey);
|
|
log.info(
|
|
`[Analytics Rollup] ${day}: pages=${result.pages} users=${result.users} games=${result.games} chronicle=${result.chronicle}`,
|
|
);
|
|
}
|
|
|
|
log.info(`[Analytics Rollup] Complete (${days.join(", ")}).`);
|
|
process.exit(0);
|
|
} catch (error) {
|
|
log.error(`[Analytics Rollup] Fatal: ${errorMessage(error)}`);
|
|
process.exit(1);
|
|
}
|
|
};
|