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
30 lines
1.2 KiB
TypeScript
30 lines
1.2 KiB
TypeScript
import type { SanitizedConfig } from "payload";
|
|
import { getPayload } from "payload";
|
|
|
|
import { purgeOldEvents, purgeOldSessions, RETENTION_DAYS } from "@/lib/analytics/rollup";
|
|
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
|
|
|
|
/**
|
|
* `bun run payload analytics-purge` - daily raw-event retention sweep
|
|
* (external cron). Deletes raw analytics events older than 90 days; the
|
|
* permanent daily aggregate tables are never touched. Sessions whose last
|
|
* activity predates the window go too (their events are gone and every
|
|
* aggregate is already permanent).
|
|
*/
|
|
export const script = async (config: SanitizedConfig) => {
|
|
const payload = await getPayload({ config });
|
|
const log = createBinLogger("analytics-purge", payload.logger);
|
|
|
|
try {
|
|
log.info(`[Analytics Purge] Deleting raw events older than ${RETENTION_DAYS} days...`);
|
|
const deleted = await purgeOldEvents(payload);
|
|
const sessions = await purgeOldSessions(payload);
|
|
log.info(
|
|
`[Analytics Purge] Complete. Deleted ${deleted} event(s), ${sessions} session(s).`,
|
|
);
|
|
process.exit(0);
|
|
} catch (error) {
|
|
log.error(`[Analytics Purge] Fatal: ${errorMessage(error)}`);
|
|
process.exit(1);
|
|
}
|
|
};
|