Files
OpenFrame/lib/analytics/billing-events.ts
T
yusufipk 7ca5abd041 feat(analytics): record where paying customers actually came from
Adds first-party acquisition attribution and a sixteen-event funnel, written to
this deployment's own database and read back on /admin/growth. Nothing is sent
anywhere else, and the whole subsystem is off unless OPENFRAME_ENABLE_ANALYTICS
is set, so a self-hosted instance carries the tables empty and pays nothing.

The proxy gives a visitor an anonymous id and stores what brought them in two
first-party cookies; signup copies that onto the account and claims the events
the visitor produced before they had one, which is what joins the two halves of
the funnel. Recording happens where each step actually happens rather than in
the browser: an ad blocker cannot undercount landing views, and blocking rates
differ by channel, so an undercounted denominator would have made GitHub traffic
look like it converts better than it does.

Every event carries a dedupe key on a UNIQUE column, so "recorded exactly once"
is a property of the schema rather than of fifteen call sites. Subscription
events are derived by comparing the row being overwritten with the row being
written inside the existing Stripe sync, which makes them order-independent and
replay-safe.

The scoreboard reports step-to-step conversion with the denominator beside it,
and splits by source over a rolling 28-day window rather than a week: at this
volume a weekly per-source cell holds single digits, and a percentage computed
from three visits reads exactly as confidently as one computed from three
hundred.

"How did you hear about us?" is asked on the first onboarding screen, not on the
registration form. The number being measured is the signup conversion rate, and
a question added to that form would move it.
2026-08-01 20:00:27 +03:00

89 lines
3.2 KiB
TypeScript

// Turning Stripe state into funnel events.
//
// These four events are derived from a before/after comparison inside the sync
// that already re-reads every subscription a customer has, rather than from the
// webhook event types. That is deliberate: webhooks arrive out of order and get
// replayed, and `customer.subscription.updated` fires for changes that mean
// nothing here. Comparing the row we are about to overwrite with the row we are
// writing is order-independent, and the dedupe keys make a replay a no-op.
import type { BillingSubscriptionStatus } from '@prisma/client';
import { eventKey, recordEvent } from '@/lib/analytics/record';
import { isProductAnalyticsEnabled } from '@/lib/feature-flags';
export interface SubscriptionStateBefore {
status: BillingSubscriptionStatus;
cancelAtPeriodEnd: boolean;
/** Whether this account had already consumed a trial before this sync. */
hadTrial: boolean;
}
export interface SubscriptionStateAfter {
status: BillingSubscriptionStatus;
cancelAtPeriodEnd: boolean;
trialEndsAt: Date | null;
currentPeriodEnd: Date | null;
}
/**
* A cancellation and the reactivation that may follow it both belong to a
* billing cycle. Keying them on the period end lets a customer cancel, come
* back, and cancel again in a later cycle without the second one being
* swallowed as a duplicate, while the two Stripe writes that describe a single
* cancellation (the `cancel_at_period_end` flag now, the `canceled` status
* later) collapse into one event.
*/
function cycleMarker(currentPeriodEnd: Date | null): string {
return String(currentPeriodEnd ? currentPeriodEnd.getTime() : 0);
}
export async function recordSubscriptionTransition(params: {
userId: string;
subscriptionId: string;
before: SubscriptionStateBefore;
after: SubscriptionStateAfter;
}): Promise<void> {
if (!isProductAnalyticsEnabled()) return;
const { userId, subscriptionId, before, after } = params;
const cycle = cycleMarker(after.currentPeriodEnd);
// Once per account for its lifetime. A second trial is not a second start of
// the funnel, and Stripe will not grant one anyway.
if (after.trialEndsAt && !before.hadTrial) {
await recordEvent({
name: 'TRIAL_STARTED',
dedupeKey: eventKey('TRIAL_STARTED', userId),
userId,
});
}
// The paying moment. With a trial the status goes trialing -> active, so this
// fires on conversion rather than on signup for the trial.
if (after.status === 'ACTIVE' && before.status !== 'ACTIVE') {
await recordEvent({
name: 'SUBSCRIPTION_STARTED',
dedupeKey: eventKey('SUBSCRIPTION_STARTED', subscriptionId),
userId,
});
}
const startedCanceling = after.cancelAtPeriodEnd && !before.cancelAtPeriodEnd;
const becameCanceled = after.status === 'CANCELED' && before.status !== 'CANCELED';
if (startedCanceling || becameCanceled) {
await recordEvent({
name: 'SUBSCRIPTION_CANCELED',
dedupeKey: `SUBSCRIPTION_CANCELED:${subscriptionId}:${cycle}`,
userId,
});
}
if (!after.cancelAtPeriodEnd && before.cancelAtPeriodEnd && after.status !== 'CANCELED') {
await recordEvent({
name: 'SUBSCRIPTION_REACTIVATED',
dedupeKey: `SUBSCRIPTION_REACTIVATED:${subscriptionId}:${cycle}`,
userId,
});
}
}