retention
This commit is contained in:
41
src/lib/analyticsActivity.ts
Normal file
41
src/lib/analyticsActivity.ts
Normal 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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user