retention

This commit is contained in:
2026-08-11 23:35:57 +02:00
parent ca1e432f80
commit e3276f5943
4 changed files with 77 additions and 23 deletions

View File

@@ -0,0 +1,41 @@
import { db } from '@/lib/db';
/**
* Records that a signed-in user looked at their own scan numbers.
*
* This exists because "inactive" cannot be answered from anything else we
* store. A session can stay alive for weeks without the user ever opening their
* analytics, so a login timestamp would call someone active who has not seen a
* number in a month. PostHog cannot answer it either - capture there is gated on
* cookie consent and runs client-side, so it covers an unknown subset.
*
* Written server-side, on the endpoint that serves the numbers. That endpoint is
* the single choke point for both the analytics page and the dashboard.
*/
/** Repeat views inside this window do not cause another write. */
const THROTTLE_MS = 60 * 60 * 1000;
export function touchAnalyticsView(userId: string): void {
const now = new Date();
const staleBefore = new Date(now.getTime() - THROTTLE_MS);
// updateMany, not update: the throttle lives in the WHERE clause, so a repeat
// view inside the window matches no rows instead of racing a read.
db.user
.updateMany({
where: {
id: userId,
OR: [
{ lastAnalyticsViewAt: null },
{ lastAnalyticsViewAt: { lt: staleBefore } },
],
},
data: { lastAnalyticsViewAt: now },
})
.catch((error) => {
// Fire and forget. Analytics must still render if this write fails - it
// also fails harmlessly if the column has not been added yet.
console.error('Failed to record analytics view:', error);
});
}