Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: wind-down lifecycle for expired trials (emails, ingestion block, deletion)

Carl-Gerhard Lindesvärda62e387c0bee
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.ts
index e6c31f398..26db5fec2 100644
--- a/apps/api/src/controllers/webhook.controller.ts
+++ b/apps/api/src/controllers/webhook.controller.ts
@@ -355,6 +355,15 @@ async function syncSubscriptionToOrg(
organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit
? { usageWarningSentAt: null, usageExceededSentAt: null }
: {}),
+ // Reaching checkout takes the org out of the wind-down population for good
+ // — that sequence only targets trials that never had a subscription — so
+ // release the ingestion block and any scheduled deletion. Guarded on the
+ // org actually being in wind-down so we never clear a `deleteAt` the owner
+ // set themselves. The wind-down cron re-checks this too, for the webhook we
+ // never receive.
+ ...(organization.windDownStartedAt
+ ? { windDownStartedAt: null, windDownStep: null, deleteAt: null }
+ : {}),
};
const changes = diffOrganizationFields(
diff --git a/apps/api/src/hooks/subscription.hook.test.ts b/apps/api/src/hooks/subscription.hook.test.ts
new file mode 100644
index 000000000..fe5db6cf5
--- /dev/null
+++ b/apps/api/src/hooks/subscription.hook.test.ts
@@ -0,0 +1,126 @@
+/**
+ * Tests for subscriptionHook — the preHandler that rejects ingestion for
+ * organizations blocked by the wind-down sequence.
+ *
+ * Three behaviours matter enough to pin down: it gates on the wind-down step
+ * rather than the subscription state (so an expired trial keeps ingesting
+ * until it has actually been warned), it answers 202 rather than a 4xx (the
+ * SDKs retry everything except 401 and 2xx), and it fails open.
+ */
+
+import type { FastifyReply, FastifyRequest } from 'fastify';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getOrganizationByProjectIdCached = vi.fn();
+
+vi.mock('@openpanel/db', () => ({
+ getOrganizationByProjectIdCached: (projectId: string) =>
+ getOrganizationByProjectIdCached(projectId),
+}));
+
+const { subscriptionHook } = await import('./subscription.hook');
+
+function makeReply() {
+ const status = vi.fn();
+ const send = vi.fn();
+ const reply = { status, send };
+ status.mockReturnValue(reply);
+ send.mockReturnValue(reply);
+ return { reply: reply as unknown as FastifyReply, status, send };
+}
+
+function makeReq(overrides: Partial<FastifyRequest> = {}) {
+ return {
+ client: { projectId: 'proj-1' },
+ log: { info: vi.fn(), error: vi.fn(), warn: vi.fn() },
+ ...overrides,
+ } as unknown as FastifyRequest;
+}
+
+beforeEach(() => {
+ vi.unstubAllEnvs();
+ vi.stubEnv('SELF_HOSTED', 'false');
+ getOrganizationByProjectIdCached.mockReset();
+});
+
+describe('subscriptionHook', () => {
+ it.each(['blocked', 'final_warning'])(
+ 'drops ingestion with 202 at step %s',
+ async (windDownStep) => {
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ windDownStep,
+ });
+ const { reply, status, send } = makeReply();
+
+ await subscriptionHook(makeReq() as never, reply);
+
+ // 202 rather than 402/403 on purpose: the SDKs treat every other
+ // non-2xx as retryable and would hammer this endpoint four times per
+ // event.
+ expect(status).toHaveBeenCalledWith(202);
+ expect(send).toHaveBeenCalledWith({ blocked: true });
+ },
+ );
+
+ it.each(['expired_notice', 'stopping_soon'])(
+ 'still accepts ingestion at step %s',
+ async (windDownStep) => {
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ windDownStep,
+ });
+ const { reply, status } = makeReply();
+
+ await subscriptionHook(makeReq() as never, reply);
+
+ expect(status).not.toHaveBeenCalled();
+ },
+ );
+
+ it('accepts ingestion from an expired trial that has not been warned yet', async () => {
+ // The reason the gate reads windDownStep and not subscriptionState: every
+ // lapsed trial is already trial_expired, so gating on state would block
+ // thousands of orgs the moment this ships.
+ getOrganizationByProjectIdCached.mockResolvedValue({
+ id: 'org-1',
+ subscriptionState: 'trial_expired',
+ windDownStep: null,
+ });
+ const { reply, status } = makeReply();
+
+ await subscriptionHook(makeReq() as never, reply);
+
+ expect(status).not.toHaveBeenCalled();
+ });
+
+ it('fails open when the organization lookup throws', async () => {
+ getOrganizationByProjectIdCached.mockRejectedValue(new Error('redis down'));
+ const { reply, status } = makeReply();
+ const req = makeReq();
+
+ await subscriptionHook(req as never, reply);
+
+ expect(status).not.toHaveBeenCalled();
+ expect(req.log.error).toHaveBeenCalled();
+ });
+
+ it('does nothing when self hosted', async () => {
+ vi.stubEnv('SELF_HOSTED', 'true');
+ const { reply, status } = makeReply();
+
+ await subscriptionHook(makeReq() as never, reply);
+
+ expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
+ expect(status).not.toHaveBeenCalled();
+ });
+
+ it('does nothing without a resolved client', async () => {
+ const { reply, status } = makeReply();
+
+ await subscriptionHook(makeReq({ client: null }) as never, reply);
+
+ expect(getOrganizationByProjectIdCached).not.toHaveBeenCalled();
+ expect(status).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/api/src/hooks/subscription.hook.ts b/apps/api/src/hooks/subscription.hook.ts
new file mode 100644
index 000000000..e63e536fb
--- /dev/null
+++ b/apps/api/src/hooks/subscription.hook.ts
@@ -0,0 +1,74 @@
+import { getOrganizationByProjectIdCached } from '@openpanel/db';
+import type {
+ DeprecatedPostEventPayload,
+ ITrackHandlerPayload,
+} from '@openpanel/validation';
+import type { FastifyReply, FastifyRequest } from 'fastify';
+
+/**
+ * Rejects ingestion for organizations that have been blocked by the wind-down
+ * sequence (see apps/worker/src/jobs/cron.wind-down.ts).
+ *
+ * Two things worth knowing about the shape of this:
+ *
+ * It gates on `windDownStep`, not on `subscriptionState`. Every expired trial
+ * is already in `trial_expired`, so gating on the state would block thousands
+ * of orgs the moment this ships, skipping the four warning emails entirely.
+ * The step only reaches 'blocked' after the org has been told three times.
+ *
+ * It answers 202, not 402 or 403. The SDKs treat only 401 and 2xx as terminal
+ * (packages/sdks/sdk/src/api.ts); every other status is thrown and retried
+ * three times with backoff, so a "correct" status code would multiply traffic
+ * from exactly the clients we are trying to quiet down. This matches how
+ * isBotHook already drops traffic.
+ */
+
+const BLOCKED_STEPS = new Set(['blocked', 'final_warning']);
+
+export async function subscriptionHook(
+ req: FastifyRequest<{
+ Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
+ }>,
+ reply: FastifyReply,
+) {
+ if (process.env.SELF_HOSTED === 'true') {
+ return;
+ }
+
+ const projectId = req.client?.projectId;
+ if (!projectId) {
+ return;
+ }
+
+ try {
+ // Cached for 5 minutes and invalidated by the Polar webhook, so paying
+ // again lifts the block on the next checkout rather than on a TTL.
+ const organization = await getOrganizationByProjectIdCached(projectId);
+
+ if (!organization?.windDownStep) {
+ return;
+ }
+
+ if (!BLOCKED_STEPS.has(organization.windDownStep)) {
+ return;
+ }
+
+ req.log.info(
+ {
+ organizationId: organization.id,
+ projectId,
+ windDownStep: organization.windDownStep,
+ },
+ 'Ingestion blocked by wind-down',
+ );
+
+ return reply.status(202).send({ blocked: true });
+ } catch (error) {
+ // Fail open. Dropping a paying customer's events because Redis or Postgres
+ // hiccuped is far worse than letting a blocked org through for a tick.
+ req.log.error(
+ { err: error, projectId },
+ 'Wind-down check failed, allowing ingestion',
+ );
+ }
+}
diff --git a/apps/api/src/routes/event.router.ts b/apps/api/src/routes/event.router.ts
index f1b791393..1d9e8cbea 100644
--- a/apps/api/src/routes/event.router.ts
+++ b/apps/api/src/routes/event.router.ts
@@ -3,11 +3,13 @@ import * as controller from '@/controllers/event.controller';
import { clientHook } from '@/hooks/client.hook';
import { duplicateHook } from '@/hooks/duplicate.hook';
import { isBotHook } from '@/hooks/is-bot.hook';
+import { subscriptionHook } from '@/hooks/subscription.hook';
const eventRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
fastify.addHook('preValidation', duplicateHook);
fastify.addHook('preHandler', clientHook);
fastify.addHook('preHandler', isBotHook);
+ fastify.addHook('preHandler', subscriptionHook);
fastify.route({
method: 'POST',
diff --git a/apps/api/src/routes/profile.router.ts b/apps/api/src/routes/profile.router.ts
index dcdba4e32..d1d03d5ac 100644
--- a/apps/api/src/routes/profile.router.ts
+++ b/apps/api/src/routes/profile.router.ts
@@ -2,10 +2,12 @@ import type { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi';
import * as controller from '@/controllers/profile.controller';
import { clientHook } from '@/hooks/client.hook';
import { isBotHook } from '@/hooks/is-bot.hook';
+import { subscriptionHook } from '@/hooks/subscription.hook';
const profileRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
fastify.addHook('preHandler', clientHook);
fastify.addHook('preHandler', isBotHook);
+ fastify.addHook('preHandler', subscriptionHook);
fastify.route({
method: 'POST',
diff --git a/apps/api/src/routes/track.router.ts b/apps/api/src/routes/track.router.ts
index 07afbcdc2..44d085620 100644
--- a/apps/api/src/routes/track.router.ts
+++ b/apps/api/src/routes/track.router.ts
@@ -5,11 +5,13 @@ import { fetchDeviceId, handler } from '@/controllers/track.controller';
import { clientHook } from '@/hooks/client.hook';
import { duplicateHook } from '@/hooks/duplicate.hook';
import { isBotHook } from '@/hooks/is-bot.hook';
+import { subscriptionHook } from '@/hooks/subscription.hook';
const trackRouter: FastifyPluginAsyncZodOpenApi = async (fastify) => {
fastify.addHook('preValidation', duplicateHook);
fastify.addHook('preHandler', clientHook);
fastify.addHook('preHandler', isBotHook);
+ fastify.addHook('preHandler', subscriptionHook);
await fastify.route({
method: 'POST',
diff --git a/apps/worker/src/boot-cron.ts b/apps/worker/src/boot-cron.ts
index 7c110d3c0..98df24b0b 100644
--- a/apps/worker/src/boot-cron.ts
+++ b/apps/worker/src/boot-cron.ts
@@ -118,6 +118,11 @@ export async function bootCron() {
type: 'dataHealth',
pattern: '30 7 * * *', // Daily 07:30 UTC — no-data / data-stopped rescue emails
},
+ {
+ name: 'windDown',
+ type: 'windDown',
+ pattern: '0 * * * *', // Hourly — expired-trial wind-down emails, block, delete
+ },
];
if (process.env.SELF_HOSTED && process.env.NODE_ENV === 'production') {
diff --git a/apps/worker/src/boot-debug.ts b/apps/worker/src/boot-debug.ts
index 95c0f9a44..34157e5be 100644
--- a/apps/worker/src/boot-debug.ts
+++ b/apps/worker/src/boot-debug.ts
@@ -31,6 +31,7 @@ const CRON_TYPES = [
'insightCleanup',
'weeklyDigest',
'dataHealth',
+ 'windDown',
] as const satisfies readonly CronQueueType[];
function escapeHtml(value: string) {
diff --git a/apps/worker/src/jobs/cron.onboarding.test.ts b/apps/worker/src/jobs/cron.onboarding.test.ts
index dc12c3e54..8bf20f552 100644
--- a/apps/worker/src/jobs/cron.onboarding.test.ts
+++ b/apps/worker/src/jobs/cron.onboarding.test.ts
@@ -159,6 +159,27 @@ describe('onboardingJob', () => {
});
it('marks onboarding completed once every email has been sent', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ org({
+ onboarding: 'onboarding-trial-ending',
+ createdAt: subDays(new Date(), 31),
+ }),
+ ]);
+
+ const result = await onboardingJob(job);
+
+ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { onboarding: 'completed' },
+ });
+ });
+
+ it('completes orgs left on the retired trial-ended pointer', async () => {
+ // The day-30 'onboarding-trial-ended' step moved to the wind-down sequence.
+ // Orgs still holding that pointer must finish the drip, not restart it from
+ // the welcome email. Code migration 21 settles these, but the runner has to
+ // be safe on its own for any that slip through.
dbMock.organization.findMany.mockResolvedValue([
org({
onboarding: 'onboarding-trial-ended',
@@ -169,6 +190,7 @@ describe('onboardingJob', () => {
const result = await onboardingJob(job);
expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
expect(dbMock.organization.update).toHaveBeenCalledWith({
where: { id: 'org-1' },
data: { onboarding: 'completed' },
diff --git a/apps/worker/src/jobs/cron.onboarding.ts b/apps/worker/src/jobs/cron.onboarding.ts
index 13678a92a..d87298d03 100644
--- a/apps/worker/src/jobs/cron.onboarding.ts
+++ b/apps/worker/src/jobs/cron.onboarding.ts
@@ -1,18 +1,32 @@
import type { Job } from 'bullmq';
-import { differenceInDays, format } from 'date-fns';
+import { format } from 'date-fns';
import { db, getOrganizationEventsCount } from '@openpanel/db';
-import {
- type EmailData,
- type EmailTemplate,
- sendEmail,
-} from '@openpanel/email';
import type { CronQueuePayload } from '@openpanel/queue';
import { getRecommendedPlan } from '@openpanel/payments';
+import {
+ type SequenceStep,
+ type SequenceSubject,
+ runSequence,
+ step,
+} from './lib/email-sequence';
import { logger } from '../utils/logger';
-// Types for the onboarding email system
+/**
+ * The getting-started drip, from signup to a few days before the trial ends.
+ *
+ * It stops at day 26. What happens *after* the trial expires belongs to
+ * cron.wind-down.ts, which is anchored on the expiry rather than on signup —
+ * see that file. The old day-30 'onboarding-trial-ended' step moved there as
+ * 'wind-down-expired'.
+ *
+ * The `onboarding` column stores the last sent step, and step names are equal
+ * to template names for historical reasons: in-flight orgs already hold those
+ * values. Renaming one strands every org sitting on it (the runner completes
+ * them rather than replaying the sequence, but they still stop early).
+ */
+
const orgQuery = {
include: {
createdBy: {
@@ -35,30 +49,18 @@ type OrgWithCreator = Awaited<
ReturnType<typeof db.organization.findMany<typeof orgQuery>>
>[number];
-type OnboardingUsage = {
+interface OnboardingUsage {
eventsCount: number;
hasData: boolean;
};
-type OnboardingContext = {
+interface OnboardingContext {
org: OrgWithCreator;
user: NonNullable<OrgWithCreator['createdBy']>;
// Lazy + memoized: only emails past the day gate pay for the ClickHouse count.
getUsage: () => Promise<OnboardingUsage>;
};
-type OnboardingEmail<T extends EmailTemplate = EmailTemplate> = {
- day: number;
- template: T;
- shouldSend?: (ctx: OnboardingContext) => Promise<boolean | 'complete'>;
- data: (ctx: OnboardingContext) => EmailData<T> | Promise<EmailData<T>>;
-};
-
-// Helper to create type-safe email entries with correlated template/data types
-function email<T extends EmailTemplate>(config: OnboardingEmail<T>) {
- return config;
-}
-
function createUsageGetter(org: OrgWithCreator) {
let promise: Promise<OnboardingUsage> | null = null;
return () => {
@@ -95,10 +97,10 @@ const getters = {
},
} as const;
-// Declarative email schedule - easy to add, remove, or reorder
-const ONBOARDING_EMAILS = [
- email({
+export const ONBOARDING_EMAILS: SequenceStep<OnboardingContext>[] = [
+ step<OnboardingContext, 'onboarding-welcome'>({
day: 0,
+ step: 'onboarding-welcome',
template: 'onboarding-welcome',
data: async (ctx) => ({
firstName: getters.firstName(ctx),
@@ -106,8 +108,9 @@ const ONBOARDING_EMAILS = [
hasData: (await ctx.getUsage()).hasData,
}),
}),
- email({
+ step<OnboardingContext, 'onboarding-what-to-track'>({
day: 2,
+ step: 'onboarding-what-to-track',
template: 'onboarding-what-to-track',
data: async (ctx) => {
const usage = await ctx.getUsage();
@@ -118,8 +121,9 @@ const ONBOARDING_EMAILS = [
};
},
}),
- email({
+ step<OnboardingContext, 'onboarding-dashboards'>({
day: 6,
+ step: 'onboarding-dashboards',
template: 'onboarding-dashboards',
data: async (ctx) => {
const usage = await ctx.getUsage();
@@ -131,16 +135,18 @@ const ONBOARDING_EMAILS = [
};
},
}),
- email({
+ step<OnboardingContext, 'onboarding-feature-request'>({
day: 14,
+ step: 'onboarding-feature-request',
template: 'onboarding-feature-request',
data: async (ctx) => ({
firstName: getters.firstName(ctx),
hasData: (await ctx.getUsage()).hasData,
}),
}),
- email({
+ step<OnboardingContext, 'onboarding-trial-ending'>({
day: 26,
+ step: 'onboarding-trial-ending',
template: 'onboarding-trial-ending',
shouldSend: async ({ org }) => {
if (org.subscriptionStatus === 'active') {
@@ -160,29 +166,9 @@ const ONBOARDING_EMAILS = [
};
},
}),
- email({
- day: 30,
- template: 'onboarding-trial-ended',
- shouldSend: async ({ org }) => {
- if (org.subscriptionStatus === 'active') {
- return 'complete';
- }
- return true;
- },
- data: async (ctx) => {
- const usage = await ctx.getUsage();
- return {
- firstName: getters.firstName(ctx),
- billingUrl: getters.billingUrl(ctx),
- recommendedPlan: await getters.recommendedPlan(ctx),
- hasData: usage.hasData,
- eventsCount: usage.eventsCount,
- };
- },
- }),
];
-export async function onboardingJob(job: Job<CronQueuePayload>) {
+export async function onboardingJob(_job: Job<CronQueuePayload>) {
if (process.env.SELF_HOSTED === 'true') {
return null;
}
@@ -203,127 +189,51 @@ export async function onboardingJob(job: Job<CronQueuePayload>) {
logger.info(`Found ${orgs.length} organizations in onboarding`);
- let emailsSent = 0;
- let orgsCompleted = 0;
- let orgsSkipped = 0;
-
- for (const org of orgs) {
- // Skip if no creator or creator is deleted
- if (!org.createdBy || org.createdBy.deletedAt) {
- orgsSkipped++;
- continue;
- }
-
- const user = org.createdBy;
- const ctx: OnboardingContext = {
- org,
- user,
- getUsage: createUsageGetter(org),
- };
- const daysSinceOrgCreation = differenceInDays(new Date(), org.createdAt);
+ const contactable = orgs.filter(
+ (org) => org.createdBy && !org.createdBy.deletedAt,
+ );
+ const withoutCreator = orgs.length - contactable.length;
- // Find the next email to send
- // If org.onboarding is null or empty string, they haven't received any email yet
- const lastSentIndex = org.onboarding
- ? ONBOARDING_EMAILS.findIndex((e) => e.template === org.onboarding)
- : -1;
- const nextEmailIndex = lastSentIndex + 1;
+ const subjects: SequenceSubject<OnboardingContext>[] = contactable.map(
+ (org) => {
+ const user = org.createdBy as NonNullable<OrgWithCreator['createdBy']>;
+ return {
+ id: org.id,
+ email: user.email,
+ anchor: org.createdAt,
+ pointer: org.onboarding,
+ ctx: { org, user, getUsage: createUsageGetter(org) },
+ };
+ },
+ );
- // No more emails to send
- if (nextEmailIndex >= ONBOARDING_EMAILS.length) {
+ const result = await runSequence({
+ name: 'onboarding',
+ steps: ONBOARDING_EMAILS,
+ subjects,
+ logger,
+ onAdvance: async (subject, stepName) => {
await db.organization.update({
- where: { id: org.id },
- data: { onboarding: 'completed' },
+ where: { id: subject.id },
+ data: { onboarding: stepName },
});
- orgsCompleted++;
- logger.info(
- `Completed onboarding for organization ${org.id} (all emails sent)`,
- );
- continue;
- }
-
- const nextEmail = ONBOARDING_EMAILS[nextEmailIndex];
- if (!nextEmail) {
- continue;
- }
-
- logger.info(
- {
- daysSinceOrgCreation,
- nextEmailDay: nextEmail.day,
- orgCreatedAt: org.createdAt,
- today: new Date(),
- },
- `Checking if enough days have passed for organization ${org.id}`,
- );
- // Check if enough days have passed
- if (daysSinceOrgCreation < nextEmail.day) {
- orgsSkipped++;
- continue;
- }
-
- // Check shouldSend callback if defined
- if (nextEmail.shouldSend) {
- const result = await nextEmail.shouldSend(ctx);
-
- if (result === 'complete') {
- await db.organization.update({
- where: { id: org.id },
- data: { onboarding: 'completed' },
- });
- orgsCompleted++;
- logger.info(
- `Completed onboarding for organization ${org.id} (shouldSend returned complete)`,
- );
- continue;
- }
-
- if (result === false) {
- orgsSkipped++;
- continue;
- }
- }
-
- try {
- const emailData = await nextEmail.data(ctx);
-
- await sendEmail(nextEmail.template, {
- to: user.email,
- data: emailData as never,
- });
-
- // Update onboarding to the template name we just sent
+ },
+ onComplete: async (subject) => {
await db.organization.update({
- where: { id: org.id },
- data: { onboarding: nextEmail.template },
+ where: { id: subject.id },
+ data: { onboarding: 'completed' },
});
-
- emailsSent++;
- logger.info(
- `Sent onboarding email "${nextEmail.template}" to organization ${org.id} (user ${user.id})`,
- );
- } catch (error) {
- logger.error(
- { err: error, template: nextEmail.template },
- `Failed to send onboarding email to organization ${org.id}`,
- );
- }
- }
-
- logger.info(
- {
- totalOrgs: orgs.length,
- emailsSent,
- orgsCompleted,
- orgsSkipped,
},
- 'Completed onboarding email job',
- );
+ });
- return {
+ const summary = {
totalOrgs: orgs.length,
- emailsSent,
- orgsCompleted,
- orgsSkipped,
+ emailsSent: result.emailsSent,
+ orgsCompleted: result.completed,
+ orgsSkipped: result.deferred + result.stepsSkipped + withoutCreator,
};
+
+ logger.info(summary, 'Completed onboarding email job');
+
+ return summary;
}
diff --git a/apps/worker/src/jobs/cron.ts b/apps/worker/src/jobs/cron.ts
index b922ab670..ec8bcfaa7 100644
--- a/apps/worker/src/jobs/cron.ts
+++ b/apps/worker/src/jobs/cron.ts
@@ -13,6 +13,7 @@ import { dataHealthCronJob } from './cron.data-health';
import { jobDelete } from './cron.delete';
import { insightCleanupCronJob } from './cron.insight-cleanup';
import { weeklyDigestCronJob } from './cron.weekly-digest';
+import { windDownCronJob } from './cron.wind-down';
import { onboardingJob } from './cron.onboarding';
import { ping } from './cron.ping';
import { salt } from './cron.salt';
@@ -79,5 +80,8 @@ export async function cronJob(job: Job<CronQueuePayload>) {
case 'dataHealth': {
return await dataHealthCronJob();
}
+ case 'windDown': {
+ return await windDownCronJob();
+ }
}
}
diff --git a/apps/worker/src/jobs/cron.wind-down.test.ts b/apps/worker/src/jobs/cron.wind-down.test.ts
new file mode 100644
index 000000000..e51aeb33b
--- /dev/null
+++ b/apps/worker/src/jobs/cron.wind-down.test.ts
@@ -0,0 +1,332 @@
+/**
+ * The db, email and pricing modules are replaced wholesale — these assert the
+ * job's decisions (who enters, which step fires, what gets written), not any
+ * real persistence.
+ */
+import { subDays } from 'date-fns';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ dbMock,
+ getOrganizationEventsCountMock,
+ getOrganizationEventsCountSinceMock,
+ getLastEventPerProjectMock,
+ sendEmailMock,
+ getRecommendedPlanMock,
+} = vi.hoisted(() => ({
+ dbMock: {
+ organization: {
+ findMany: vi.fn(),
+ update: vi.fn().mockResolvedValue({}),
+ updateMany: vi.fn().mockResolvedValue({ count: 0 }),
+ },
+ },
+ getOrganizationEventsCountMock: vi.fn(),
+ getOrganizationEventsCountSinceMock: vi.fn(),
+ getLastEventPerProjectMock: vi.fn(),
+ sendEmailMock: vi.fn().mockResolvedValue({}),
+ getRecommendedPlanMock: vi.fn(),
+}));
+
+vi.mock('@openpanel/db', () => ({
+ db: dbMock,
+ getOrganizationEventsCount: getOrganizationEventsCountMock,
+ getOrganizationEventsCountSince: getOrganizationEventsCountSinceMock,
+ getLastEventPerProject: getLastEventPerProjectMock,
+}));
+vi.mock('@openpanel/email', () => ({ sendEmail: sendEmailMock }));
+vi.mock('@openpanel/payments', () => ({
+ getRecommendedPlan: getRecommendedPlanMock,
+}));
+const { buildWinBackHighlightMock } = vi.hoisted(() => ({
+ buildWinBackHighlightMock: vi.fn(),
+}));
+vi.mock('./lib/win-back-highlight', () => ({
+ buildWinBackHighlight: buildWinBackHighlightMock,
+ HIGHLIGHT_MIN_RECENT_EVENTS: 1000,
+}));
+
+import { windDownCronJob } from './cron.wind-down';
+
+type OrgOverrides = Record<string, unknown>;
+
+function makeOrg(overrides: OrgOverrides = {}) {
+ return {
+ id: 'org-1',
+ subscriptionState: 'trial_expired',
+ subscriptionStatus: 'trialing',
+ subscriptionEndsAt: subDays(new Date(), 800),
+ subscriptionId: null,
+ windDownStartedAt: null,
+ windDownStep: null,
+ deleteAt: null,
+ createdBy: {
+ id: 'user-1',
+ email: '[email protected]',
+ firstName: 'Alex',
+ deletedAt: null,
+ },
+ projects: [{ id: 'project-1', name: 'acme-web' }],
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllEnvs();
+ vi.stubEnv('SELF_HOSTED', 'false');
+ vi.stubEnv('DASHBOARD_URL', 'https://dashboard.openpanel.dev');
+ dbMock.organization.update.mockResolvedValue({});
+ dbMock.organization.updateMany.mockResolvedValue({ count: 0 });
+ sendEmailMock.mockResolvedValue({});
+ getOrganizationEventsCountMock.mockResolvedValue(1000);
+ getOrganizationEventsCountSinceMock.mockResolvedValue(250);
+ // Default: nothing has sent recently.
+ getLastEventPerProjectMock.mockResolvedValue(new Map());
+ buildWinBackHighlightMock.mockResolvedValue(undefined);
+ getRecommendedPlanMock.mockReturnValue('100K events per month for $20.00');
+});
+
+describe('windDownCronJob', () => {
+ it('does nothing when self hosted', async () => {
+ vi.stubEnv('SELF_HOSTED', 'true');
+
+ expect(await windDownCronJob()).toBeNull();
+ expect(dbMock.organization.findMany).not.toHaveBeenCalled();
+ });
+
+ it('starts a long-expired org at step 0 rather than at deletion', async () => {
+ // The anchor decision, asserted directly: this org's trial ended 800 days
+ // ago. Measuring the schedule from subscriptionEndsAt would put it past
+ // every step and delete it without warning.
+ dbMock.organization.findMany.mockResolvedValue([makeOrg()]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ entering: 1, emailsSent: 1 });
+ expect(sendEmailMock).toHaveBeenCalledWith('wind-down-expired', {
+ data: expect.objectContaining({ firstName: 'Alex' }),
+ });
+ expect(dbMock.organization.updateMany).toHaveBeenCalledWith({
+ where: { id: { in: ['org-1'] } },
+ data: { windDownStartedAt: expect.any(Date) },
+ });
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { windDownStep: 'expired_notice' },
+ });
+ // Nothing scheduled for deletion on the way in.
+ expect(dbMock.organization.update).not.toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ deleteAt: expect.anything() }),
+ }),
+ );
+ });
+
+ it('caps how many organizations enter per run', async () => {
+ vi.stubEnv('WIND_DOWN_MAX_PER_RUN', '2');
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({ id: 'org-1' }),
+ makeOrg({ id: 'org-2' }),
+ makeOrg({ id: 'org-3' }),
+ makeOrg({ id: 'org-4' }),
+ ]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ entering: 2 });
+ expect(dbMock.organization.updateMany).toHaveBeenCalledWith({
+ where: { id: { in: ['org-1', 'org-2'] } },
+ data: { windDownStartedAt: expect.any(Date) },
+ });
+ });
+
+ it('blocks ingestion by advancing the pointer on day 21', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({
+ windDownStartedAt: subDays(new Date(), 21),
+ windDownStep: 'stopping_soon',
+ }),
+ ]);
+
+ await windDownCronJob();
+
+ expect(sendEmailMock).toHaveBeenCalledWith(
+ 'wind-down-blocked',
+ expect.anything(),
+ );
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { windDownStep: 'blocked' },
+ });
+ });
+
+ it('arms deletion once the final warning is delivered', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({
+ windDownStartedAt: subDays(new Date(), 44),
+ windDownStep: 'blocked',
+ }),
+ ]);
+
+ await windDownCronJob();
+
+ expect(sendEmailMock).toHaveBeenCalledWith(
+ 'wind-down-final-warning',
+ expect.anything(),
+ );
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { deleteAt: expect.any(Date) },
+ });
+ expect(dbMock.organization.update).toHaveBeenCalledWith({
+ where: { id: 'org-1' },
+ data: { windDownStep: 'final_warning' },
+ });
+ });
+
+ it('does not arm deletion when the final warning was not delivered', async () => {
+ sendEmailMock.mockResolvedValue(null);
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({
+ windDownStartedAt: subDays(new Date(), 44),
+ windDownStep: 'blocked',
+ }),
+ ]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ emailsSent: 0, failed: 1 });
+ expect(dbMock.organization.update).not.toHaveBeenCalled();
+ });
+
+ it('releases an organization that subscribed mid-sequence', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({
+ subscriptionState: 'active',
+ subscriptionStatus: 'active',
+ subscriptionId: 'sub-123',
+ windDownStartedAt: subDays(new Date(), 30),
+ windDownStep: 'blocked',
+ deleteAt: new Date(),
+ }),
+ ]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ recovered: 1, emailsSent: 0 });
+ expect(dbMock.organization.updateMany).toHaveBeenCalledWith({
+ where: { id: { in: ['org-1'] } },
+ data: { windDownStartedAt: null, windDownStep: null, deleteAt: null },
+ });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ });
+
+ it('skips organizations with no one to warn', async () => {
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({ createdBy: null }),
+ makeOrg({
+ id: 'org-2',
+ createdBy: {
+ id: 'user-2',
+ email: '[email protected]',
+ firstName: null,
+ deletedAt: new Date(),
+ },
+ }),
+ ]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ entering: 0, emailsSent: 0 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ });
+
+ describe('still-tracking organizations', () => {
+ // The population this whole sequence is aimed at: trial lapsed months ago,
+ // SDKs never stopped, never paid a cent.
+ it('lets organizations that are still tracking into the sequence first', async () => {
+ vi.stubEnv('WIND_DOWN_MAX_PER_RUN', '1');
+ getLastEventPerProjectMock.mockResolvedValue(
+ new Map([['project-active', subDays(new Date(), 1)]]),
+ );
+ // The dormant org is returned first, so only ordering can save the
+ // active one from being crowded out by the long tail.
+ dbMock.organization.findMany.mockResolvedValue([
+ makeOrg({
+ id: 'org-dormant',
+ projects: [{ id: 'project-dormant', name: 'dormant-web' }],
+ }),
+ makeOrg({
+ id: 'org-active',
+ projects: [{ id: 'project-active', name: 'active-web' }],
+ }),
+ ]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ entering: 1, stillTracking: 1 });
+ expect(dbMock.organization.updateMany).toHaveBeenCalledWith({
+ where: { id: { in: ['org-active'] } },
+ data: { windDownStartedAt: expect.any(Date) },
+ });
+ });
+
+ it('sends current volume, project names and the data highlight', async () => {
+ getLastEventPerProjectMock.mockResolvedValue(
+ new Map([['project-1', subDays(new Date(), 1)]]),
+ );
+ getOrganizationEventsCountMock.mockResolvedValue(842_110);
+ getOrganizationEventsCountSinceMock.mockResolvedValue(128_400);
+ buildWinBackHighlightMock.mockResolvedValue(
+ 'acme-web had a strong month.',
+ );
+ dbMock.organization.findMany.mockResolvedValue([makeOrg()]);
+
+ await windDownCronJob();
+
+ expect(sendEmailMock).toHaveBeenCalledWith('wind-down-expired', {
+ data: expect.objectContaining({
+ stillTracking: true,
+ eventsCount: 842_110,
+ recentEventsCount: 128_400,
+ projectNames: ['acme-web'],
+ highlight: 'acme-web had a strong month.',
+ }),
+ });
+ expect(buildWinBackHighlightMock).toHaveBeenCalledWith({
+ project: { id: 'project-1', name: 'acme-web' },
+ recentEventsCount: 128_400,
+ });
+ });
+
+ it('asks for no highlight when the org is not still tracking', async () => {
+ dbMock.organization.findMany.mockResolvedValue([makeOrg()]);
+
+ await windDownCronJob();
+
+ expect(buildWinBackHighlightMock).not.toHaveBeenCalled();
+ expect(sendEmailMock).toHaveBeenCalledWith('wind-down-expired', {
+ data: expect.objectContaining({ highlight: undefined }),
+ });
+ });
+
+ it('does not call an org still tracking when its last event is old', async () => {
+ getLastEventPerProjectMock.mockResolvedValue(
+ new Map([['project-1', subDays(new Date(), 200)]]),
+ );
+ dbMock.organization.findMany.mockResolvedValue([makeOrg()]);
+
+ const result = await windDownCronJob();
+
+ expect(result).toMatchObject({ stillTracking: 0 });
+ expect(sendEmailMock).toHaveBeenCalledWith('wind-down-expired', {
+ data: expect.objectContaining({ stillTracking: false }),
+ });
+ });
+ });
+});
diff --git a/apps/worker/src/jobs/cron.wind-down.ts b/apps/worker/src/jobs/cron.wind-down.ts
new file mode 100644
index 000000000..3e403b704
--- /dev/null
+++ b/apps/worker/src/jobs/cron.wind-down.ts
@@ -0,0 +1,444 @@
+import {
+ db,
+ getLastEventPerProject,
+ getOrganizationEventsCount,
+ getOrganizationEventsCountSince,
+} from '@openpanel/db';
+import { getRecommendedPlan } from '@openpanel/payments';
+import { addDays, differenceInDays, format, subDays } from 'date-fns';
+import {
+ type SequenceStep,
+ type SequenceSubject,
+ runSequence,
+ step,
+} from './lib/email-sequence';
+import {
+ type HighlightProject,
+ buildWinBackHighlight,
+} from './lib/win-back-highlight';
+import { logger } from '../utils/logger';
+
+/**
+ * Wind-down: what happens to a trial that expired without a purchase.
+ *
+ * Four emails over 44 days, then deletion. Ingestion keeps flowing until day
+ * 21 so the first two emails have something to be about; from day 21 the
+ * ingestion hook rejects events (see apps/api/src/hooks/subscription.hook.ts,
+ * which reads `windDownStep`). Day 44 arms `deleteAt`, and the existing delete
+ * cron sweeps it seven days later.
+ *
+ * The schedule is measured from `windDownStartedAt`, stamped when an org
+ * enters. That is the whole reason the column exists: `subscriptionEndsAt` for
+ * the existing backlog is hundreds of days old, so anchoring there would put
+ * every one of them past day 44 on the first tick.
+ *
+ * The population this is really aimed at is the org whose trial lapsed months
+ * ago and whose SDKs never stopped — still sending events, still costing
+ * storage, never billed. Those orgs are the ones worth converting, so they
+ * enter the sequence first and their emails lead with what they are currently
+ * sending rather than with a lifetime total.
+ */
+
+const BLOCK_DAY = 21;
+const FINAL_WARNING_DAY = 44;
+const DELETE_GRACE_DAYS = 7;
+
+/** Sent something this recently, so the SDKs are demonstrably still live. */
+const STILL_TRACKING_WITHIN_DAYS = 7;
+/** Window behind the "you are still sending us this much" figure. */
+const RECENT_VOLUME_DAYS = 30;
+
+/** Orgs allowed to *enter* the sequence per tick. Entry staggers the cohort. */
+const DEFAULT_MAX_PER_RUN = 100;
+
+function getMaxPerRun(): number {
+ const parsed = Number.parseInt(process.env.WIND_DOWN_MAX_PER_RUN ?? '', 10);
+ return Number.isNaN(parsed) || parsed <= 0 ? DEFAULT_MAX_PER_RUN : parsed;
+}
+
+const orgQuery = {
+ include: {
+ createdBy: {
+ select: { id: true, email: true, firstName: true, deletedAt: true },
+ },
+ projects: { select: { id: true, name: true } },
+ },
+} as const;
+
+type OrgWithCreator = Awaited<
+ ReturnType<typeof db.organization.findMany<typeof orgQuery>>
+>[number];
+
+interface WindDownUsage {
+ /** Everything ever collected — what deletion would destroy. */
+ eventsCount: number;
+ /** Collected in the last RECENT_VOLUME_DAYS — what blocking would stop. */
+ recentEventsCount: number;
+ hasData: boolean;
+}
+
+interface WindDownContext {
+ org: OrgWithCreator;
+ user: NonNullable<OrgWithCreator['createdBy']>;
+ /** Day 0 of this org's schedule. */
+ startedAt: Date;
+ lastEventAt: Date | null;
+ /** SDKs are still sending right now, months after the trial lapsed. */
+ stillTracking: boolean;
+ /** The org's most recently active project — where the highlight facts come from. */
+ highlightProject: HighlightProject | null;
+ getUsage: () => Promise<WindDownUsage>;
+ getHighlight: () => Promise<string | undefined>;
+}
+
+// Lazy + memoized like getUsage: only still-tracking orgs that clear a day
+// gate pay for the stats queries and the AI call, and each org pays once per
+// tick even though two steps include the highlight.
+function createHighlightGetter(ctx: {
+ stillTracking: boolean;
+ highlightProject: HighlightProject | null;
+ getUsage: () => Promise<WindDownUsage>;
+}) {
+ let promise: Promise<string | undefined> | null = null;
+ return () => {
+ if (!ctx.stillTracking) {
+ return Promise.resolve(undefined);
+ }
+ promise ??= ctx.getUsage().then(({ recentEventsCount }) =>
+ buildWinBackHighlight({
+ project: ctx.highlightProject,
+ recentEventsCount,
+ }),
+ );
+ return promise;
+ };
+}
+
+function createUsageGetter(org: OrgWithCreator) {
+ let promise: Promise<WindDownUsage> | null = null;
+ return () => {
+ const projectIds = org.projects.map((project) => project.id);
+ // Only orgs that clear a day gate pay for these two ClickHouse counts, and
+ // each org pays at most once per tick.
+ promise ??= Promise.all([
+ getOrganizationEventsCount(projectIds),
+ getOrganizationEventsCountSince(
+ projectIds,
+ subDays(new Date(), RECENT_VOLUME_DAYS),
+ ),
+ ]).then(([eventsCount, recentEventsCount]) => ({
+ eventsCount,
+ recentEventsCount,
+ hasData: eventsCount > 0,
+ }));
+ return promise;
+ };
+}
+
+const getters = {
+ firstName: (ctx: WindDownContext) => ctx.user.firstName || undefined,
+ billingUrl: (ctx: WindDownContext) =>
+ `${process.env.DASHBOARD_URL}/${ctx.org.id}/billing`,
+ blockDate: (ctx: WindDownContext) =>
+ format(addDays(ctx.startedAt, BLOCK_DAY), 'MMMM d'),
+ deleteDate: (ctx: WindDownContext) =>
+ format(
+ addDays(ctx.startedAt, FINAL_WARNING_DAY + DELETE_GRACE_DAYS),
+ 'MMMM d',
+ ),
+ trialEndedDate: (ctx: WindDownContext) =>
+ ctx.org.subscriptionEndsAt
+ ? format(ctx.org.subscriptionEndsAt, 'MMMM d, yyyy')
+ : undefined,
+ recommendedPlan: async (ctx: WindDownContext) => {
+ // Price against what they actually send now, not a lifetime total that
+ // would quote a plan far bigger than they need.
+ const { recentEventsCount, eventsCount } = await ctx.getUsage();
+ return getRecommendedPlan(
+ recentEventsCount || eventsCount,
+ (plan) =>
+ `${plan.formattedEvents} events per month for ${plan.formattedPrice}`,
+ );
+ },
+} as const;
+
+async function baseData(ctx: WindDownContext) {
+ const usage = await ctx.getUsage();
+ return {
+ firstName: getters.firstName(ctx),
+ billingUrl: getters.billingUrl(ctx),
+ hasData: usage.hasData,
+ eventsCount: usage.eventsCount,
+ recentEventsCount: usage.recentEventsCount,
+ stillTracking: ctx.stillTracking,
+ projectNames: ctx.org.projects.map((project) => project.name),
+ };
+}
+
+export const WIND_DOWN_STEPS: SequenceStep<WindDownContext>[] = [
+ step<WindDownContext, 'wind-down-expired'>({
+ day: 0,
+ step: 'expired_notice',
+ template: 'wind-down-expired',
+ data: async (ctx) => ({
+ ...(await baseData(ctx)),
+ blockDate: getters.blockDate(ctx),
+ trialEndedDate: getters.trialEndedDate(ctx),
+ recommendedPlan: await getters.recommendedPlan(ctx),
+ highlight: await ctx.getHighlight(),
+ }),
+ }),
+ step<WindDownContext, 'wind-down-stopping-soon'>({
+ day: 14,
+ step: 'stopping_soon',
+ template: 'wind-down-stopping-soon',
+ data: async (ctx) => ({
+ ...(await baseData(ctx)),
+ blockDate: getters.blockDate(ctx),
+ recommendedPlan: await getters.recommendedPlan(ctx),
+ highlight: await ctx.getHighlight(),
+ }),
+ }),
+ step<WindDownContext, 'wind-down-blocked'>({
+ day: BLOCK_DAY,
+ step: 'blocked',
+ template: 'wind-down-blocked',
+ // No onSent: advancing the pointer to 'blocked' *is* the block, because
+ // the ingestion hook reads the pointer.
+ data: async (ctx) => ({
+ ...(await baseData(ctx)),
+ deleteDate: getters.deleteDate(ctx),
+ }),
+ }),
+ step<WindDownContext, 'wind-down-final-warning'>({
+ day: FINAL_WARNING_DAY,
+ step: 'final_warning',
+ template: 'wind-down-final-warning',
+ // Never arm deletion off an email that didn't go out.
+ requireDelivery: true,
+ onSent: async (ctx) => {
+ await db.organization.update({
+ where: { id: ctx.org.id },
+ data: { deleteAt: addDays(new Date(), DELETE_GRACE_DAYS) },
+ });
+ },
+ data: async (ctx) => ({
+ ...(await baseData(ctx)),
+ deleteDate: format(addDays(new Date(), DELETE_GRACE_DAYS), 'MMMM d'),
+ }),
+ }),
+];
+
+/** Newest event across all of an organization's projects. */
+function lastEventFor(
+ org: OrgWithCreator,
+ lastEventPerProject: Map<string, Date>,
+): Date | null {
+ let latest: Date | null = null;
+ for (const project of org.projects) {
+ const seen = lastEventPerProject.get(project.id);
+ if (seen && (latest === null || seen > latest)) {
+ latest = seen;
+ }
+ }
+ return latest;
+}
+
+export async function windDownCronJob() {
+ if (process.env.SELF_HOSTED === 'true') {
+ return null;
+ }
+
+ const now = new Date();
+
+ // `subscriptionState` is computed and can't appear in a `where`, so prefilter
+ // on the raw columns and refine below. The second arm of the OR catches orgs
+ // already in the sequence, including any that have since subscribed and need
+ // clearing. Note there is deliberately no filter on event volume: an org that
+ // never sent anything and one still sending millions are both in scope, they
+ // just get different copy and different priority.
+ const candidates = await db.organization.findMany({
+ where: {
+ OR: [
+ { windDownStartedAt: { not: null } },
+ {
+ AND: [
+ {
+ OR: [
+ { subscriptionStatus: null },
+ { subscriptionStatus: 'trialing' },
+ ],
+ },
+ { subscriptionEndsAt: { lt: now } },
+ { subscriptionId: null },
+ ],
+ },
+ ],
+ },
+ ...orgQuery,
+ });
+
+ const expired = candidates.filter(
+ (org) => org.subscriptionState === 'trial_expired',
+ );
+
+ // Recovered: subscribed (or otherwise left trial_expired) while in the
+ // sequence. The Polar webhook clears these on the spot; this is the
+ // belt-and-braces pass for a webhook we never received.
+ const recovered = candidates.filter(
+ (org) =>
+ org.windDownStartedAt !== null &&
+ org.subscriptionState !== 'trial_expired',
+ );
+
+ if (recovered.length > 0) {
+ await db.organization.updateMany({
+ where: { id: { in: recovered.map((org) => org.id) } },
+ data: { windDownStartedAt: null, windDownStep: null, deleteAt: null },
+ });
+ }
+
+ // Without a creator we have nobody to warn, so the sequence can't run. Such
+ // orgs are left alone; the delete cron already sweeps ones with no admin.
+ const contactable = expired.filter(
+ (org) => org.createdBy && !org.createdBy.deletedAt,
+ );
+
+ // One cheap aggregate for the whole instance, same source the data-health
+ // job uses. It answers "are the SDKs still live", which decides both the
+ // copy and who gets in first.
+ const lastEventPerProject = await getLastEventPerProject();
+ const stillTrackingCutoff = subDays(now, STILL_TRACKING_WITHIN_DAYS);
+
+ const activity = new Map<string, { lastEventAt: Date | null; still: boolean }>(
+ contactable.map((org) => {
+ const lastEventAt = lastEventFor(org, lastEventPerProject);
+ return [
+ org.id,
+ {
+ lastEventAt,
+ still: lastEventAt !== null && lastEventAt > stillTrackingCutoff,
+ },
+ ];
+ }),
+ );
+
+ // Orgs still sending go first: they are the ones there is anything to
+ // convert, and letting them lead means their response is visible before the
+ // long dormant tail enters.
+ const entering = contactable
+ .filter((org) => org.windDownStartedAt === null)
+ .sort((a, b) => {
+ const left = activity.get(a.id);
+ const right = activity.get(b.id);
+ if (left?.still !== right?.still) {
+ return left?.still ? -1 : 1;
+ }
+ return (
+ (right?.lastEventAt?.getTime() ?? 0) -
+ (left?.lastEventAt?.getTime() ?? 0)
+ );
+ })
+ .slice(0, getMaxPerRun());
+
+ if (entering.length > 0) {
+ await db.organization.updateMany({
+ where: { id: { in: entering.map((org) => org.id) } },
+ data: { windDownStartedAt: now },
+ });
+ }
+
+ const enteringIds = new Set(entering.map((org) => org.id));
+ const active = contactable.filter(
+ (org) => org.windDownStartedAt !== null || enteringIds.has(org.id),
+ );
+
+ const subjects: SequenceSubject<WindDownContext>[] = active.map((org) => {
+ const user = org.createdBy as NonNullable<OrgWithCreator['createdBy']>;
+ const startedAt = org.windDownStartedAt ?? now;
+ const seen = activity.get(org.id);
+
+ // Most recently active project carries the highlight facts.
+ let highlightProject: HighlightProject | null = null;
+ let highlightSeen: Date | null = null;
+ for (const project of org.projects) {
+ const projectSeen = lastEventPerProject.get(project.id);
+ if (projectSeen && (!highlightSeen || projectSeen > highlightSeen)) {
+ highlightSeen = projectSeen;
+ highlightProject = project;
+ }
+ }
+
+ const getUsage = createUsageGetter(org);
+ const stillTracking = seen?.still ?? false;
+ return {
+ id: org.id,
+ email: user.email,
+ anchor: startedAt,
+ pointer: org.windDownStep,
+ ctx: {
+ org,
+ user,
+ startedAt,
+ lastEventAt: seen?.lastEventAt ?? null,
+ stillTracking,
+ highlightProject,
+ getUsage,
+ getHighlight: createHighlightGetter({
+ stillTracking,
+ highlightProject,
+ getUsage,
+ }),
+ },
+ };
+ });
+
+ const result = await runSequence({
+ name: 'wind-down',
+ steps: WIND_DOWN_STEPS,
+ subjects,
+ logger,
+ onAdvance: async (subject, stepName) => {
+ await db.organization.update({
+ where: { id: subject.id },
+ data: { windDownStep: stepName },
+ });
+ },
+ // No onComplete on purpose: the final pointer has to stay put, because
+ // the ingestion hook reads it. Marking the sequence 'completed' would
+ // unblock an org that is on its way to deletion.
+ });
+
+ const stillTrackingCount = [...activity.values()].filter(
+ (entry) => entry.still,
+ ).length;
+
+ logger.info(
+ {
+ candidates: candidates.length,
+ expired: expired.length,
+ recovered: recovered.length,
+ entering: entering.length,
+ stillTracking: stillTrackingCount,
+ ...result,
+ },
+ 'Wind-down cron complete',
+ );
+
+ return {
+ expired: expired.length,
+ recovered: recovered.length,
+ entering: entering.length,
+ stillTracking: stillTrackingCount,
+ ...result,
+ };
+}
+
+/** Days into the sequence, for logging and the debug route. */
+export function windDownDay(org: {
+ windDownStartedAt: Date | null;
+}): number | null {
+ return org.windDownStartedAt
+ ? differenceInDays(new Date(), org.windDownStartedAt)
+ : null;
+}
diff --git a/apps/worker/src/jobs/lib/email-sequence.test.ts b/apps/worker/src/jobs/lib/email-sequence.test.ts
new file mode 100644
index 000000000..5ce565bae
--- /dev/null
+++ b/apps/worker/src/jobs/lib/email-sequence.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Unit tests for the sequence runner. `sendEmail` is mocked, so these assert
+ * decisions — which step fires, whether the pointer moves, whether side
+ * effects run — rather than delivery.
+ */
+import { subDays } from 'date-fns';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { sendEmailMock } = vi.hoisted(() => ({
+ sendEmailMock: vi.fn().mockResolvedValue({}),
+}));
+
+vi.mock('@openpanel/email', () => ({ sendEmail: sendEmailMock }));
+
+import {
+ type SequenceStep,
+ type SequenceSubject,
+ runSequence,
+ step,
+} from './email-sequence';
+
+type Ctx = { id: string };
+
+const logger = {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+};
+
+function makeSteps(
+ overrides: Partial<SequenceStep<Ctx>>[] = [],
+): SequenceStep<Ctx>[] {
+ const base: SequenceStep<Ctx>[] = [
+ step<Ctx, 'onboarding-welcome'>({
+ day: 0,
+ step: 'first',
+ template: 'onboarding-welcome',
+ data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),
+ }),
+ step<Ctx, 'onboarding-dashboards'>({
+ day: 10,
+ step: 'second',
+ template: 'onboarding-dashboards',
+ data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),
+ }),
+ ];
+ return base.map((entry, index) => ({ ...entry, ...overrides[index] }));
+}
+
+function makeSubject(
+ pointer: string | null,
+ daysAgo: number,
+): SequenceSubject<Ctx> {
+ return {
+ id: 'subject-1',
+ email: '[email protected]',
+ anchor: subDays(new Date(), daysAgo),
+ pointer,
+ ctx: { id: 'subject-1' },
+ };
+}
+
+function run(
+ steps: SequenceStep<Ctx>[],
+ subjects: SequenceSubject<Ctx>[],
+ extra: Partial<Parameters<typeof runSequence<Ctx>>[0]> = {},
+) {
+ const onAdvance = vi.fn().mockResolvedValue(undefined);
+ const onComplete = vi.fn().mockResolvedValue(undefined);
+ return {
+ onAdvance,
+ onComplete,
+ result: runSequence<Ctx>({
+ name: 'test',
+ steps,
+ subjects,
+ onAdvance,
+ onComplete,
+ logger,
+ ...extra,
+ }),
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ sendEmailMock.mockResolvedValue({});
+});
+
+describe('runSequence', () => {
+ it('sends the first step and advances the pointer', async () => {
+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);
+
+ expect(await result).toMatchObject({ emailsSent: 1 });
+ expect(sendEmailMock).toHaveBeenCalledWith('onboarding-welcome', {
+ data: expect.objectContaining({ firstName: 'A' }),
+ });
+ expect(onAdvance).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'subject-1' }),
+ 'first',
+ );
+ });
+
+ it('defers a step whose day gate has not been reached', async () => {
+ const { onAdvance, result } = run(makeSteps(), [makeSubject('first', 3)]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ expect(onAdvance).not.toHaveBeenCalled();
+ });
+
+ it("completes rather than replays when the pointer is unknown", async () => {
+ // The whole reason this branch exists: the old findIndex returned -1 for a
+ // removed step, which restarted the sequence from the top.
+ const { onAdvance, onComplete, result } = run(makeSteps(), [
+ makeSubject('a-step-that-was-renamed', 40),
+ ]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ expect(onAdvance).not.toHaveBeenCalled();
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it("advances past a step whose guard returns 'skip' and sends the next", async () => {
+ const steps = makeSteps([{ shouldSend: async () => 'skip' as const }]);
+ const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);
+
+ expect(await result).toMatchObject({ emailsSent: 1, stepsSkipped: 1 });
+ expect(onAdvance).toHaveBeenNthCalledWith(1, expect.anything(), 'first');
+ expect(onAdvance).toHaveBeenNthCalledWith(2, expect.anything(), 'second');
+ expect(sendEmailMock).toHaveBeenCalledTimes(1);
+ expect(sendEmailMock).toHaveBeenCalledWith(
+ 'onboarding-dashboards',
+ expect.anything(),
+ );
+ });
+
+ it('holds the pointer when a guard returns false', async () => {
+ const steps = makeSteps([{ shouldSend: async () => false }]);
+ const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });
+ expect(onAdvance).not.toHaveBeenCalled();
+ });
+
+ it("finishes the sequence when a guard returns 'complete'", async () => {
+ const steps = makeSteps([{ shouldSend: async () => 'complete' as const }]);
+ const { onComplete, result } = run(steps, [makeSubject(null, 40)]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ });
+
+ it('completes once the last step has been sent', async () => {
+ const { onComplete, result } = run(makeSteps(), [makeSubject('second', 40)]);
+
+ expect(await result).toMatchObject({ completed: 1 });
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('completes when the final step is skipped', async () => {
+ const steps = makeSteps([
+ undefined as never,
+ { shouldSend: async () => 'skip' as const },
+ ]);
+ const { onComplete, result } = run(steps, [makeSubject('first', 40)]);
+
+ expect(await result).toMatchObject({ stepsSkipped: 1, completed: 1 });
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs onSent before advancing', async () => {
+ const calls: string[] = [];
+ const steps = makeSteps([
+ {
+ onSent: async () => {
+ calls.push('onSent');
+ },
+ },
+ ]);
+ const onAdvance = vi.fn(async () => {
+ calls.push('advance');
+ });
+
+ await runSequence<Ctx>({
+ name: 'test',
+ steps,
+ subjects: [makeSubject(null, 0)],
+ onAdvance,
+ onComplete: vi.fn().mockResolvedValue(undefined),
+ logger,
+ });
+
+ expect(calls).toEqual(['onSent', 'advance']);
+ });
+
+ describe('requireDelivery', () => {
+ it('does not advance or run onSent when the send is suppressed', async () => {
+ // sendEmail resolves null (rather than throwing) for a suppressed or
+ // misconfigured send, which is exactly the case a destructive step must
+ // not act on.
+ sendEmailMock.mockResolvedValue(null);
+ const onSent = vi.fn();
+ const steps = makeSteps([{ requireDelivery: true, onSent }]);
+ const { onAdvance, result } = run(steps, [makeSubject(null, 0)]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });
+ expect(onSent).not.toHaveBeenCalled();
+ expect(onAdvance).not.toHaveBeenCalled();
+ expect(logger.error).toHaveBeenCalled();
+ });
+
+ it('advances a step without the flag even when the send is suppressed', async () => {
+ sendEmailMock.mockResolvedValue(null);
+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);
+
+ expect(await result).toMatchObject({ emailsSent: 1 });
+ expect(onAdvance).toHaveBeenCalledWith(expect.anything(), 'first');
+ });
+ });
+
+ it('holds the pointer when the send throws', async () => {
+ sendEmailMock.mockRejectedValue(new Error('smtp down'));
+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);
+
+ expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });
+ expect(onAdvance).not.toHaveBeenCalled();
+ });
+
+});
diff --git a/apps/worker/src/jobs/lib/email-sequence.ts b/apps/worker/src/jobs/lib/email-sequence.ts
new file mode 100644
index 000000000..69fb25d8a
--- /dev/null
+++ b/apps/worker/src/jobs/lib/email-sequence.ts
@@ -0,0 +1,260 @@
+import { type EmailData, type EmailTemplate, sendEmail } from '@openpanel/email';
+import { differenceInDays } from 'date-fns';
+
+/**
+ * A day-gated email sequence runner, shared by the onboarding drip and the
+ * wind-down track.
+ *
+ * Each subject carries a pointer (the last step whose email was sent) and an
+ * anchor date. On every tick the runner resolves the next step, checks the day
+ * gate and the step's own guard, sends, then advances the pointer.
+ *
+ * Three deliberate differences from the original inline implementation in
+ * cron.onboarding.ts, all of which matter once a sequence ends in deletion:
+ *
+ * 1. The pointer resolves by step name and an *unknown* name completes the
+ * sequence rather than restarting it. The old `findIndex` returned -1 for a
+ * renamed or removed step, which silently sent the subject back to step 0.
+ * 2. `'skip'` advances past a step; `false` only defers it. The old code had
+ * one value for both, so a step that should be passed over stalled the
+ * sequence permanently.
+ * 3. `requireDelivery` refuses to advance unless the email actually went out.
+ * `sendEmail` returns null instead of throwing when a send is suppressed or
+ * misconfigured, so a step with side effects could otherwise fire on an
+ * email nobody received.
+ */
+
+/**
+ * - `true` send it now
+ * - `false` not yet — leave the pointer put and reconsider next tick
+ * - `'skip'` doesn't apply to this subject — advance without sending
+ * - `'complete'` the sequence is finished for this subject
+ */
+export type StepResult = boolean | 'skip' | 'complete';
+
+export interface SequenceStep<TCtx, T extends EmailTemplate = EmailTemplate> {
+ /** Whole days since the anchor before this step may fire. */
+ day: number;
+ /**
+ * Stable identifier persisted as the pointer. Renaming one is a data
+ * migration, not a refactor — see the unknown-pointer rule above.
+ */
+ step: string;
+ template: T;
+ /**
+ * Only advance the pointer if the send is confirmed. Use for any step whose
+ * `onSent` has consequences the subject was promised an email about.
+ */
+ requireDelivery?: boolean;
+ shouldSend?: (ctx: TCtx) => Promise<StepResult>;
+ data: (ctx: TCtx) => EmailData<T> | Promise<EmailData<T>>;
+ /** Applied after a confirmed send, before the pointer advances. */
+ onSent?: (ctx: TCtx) => Promise<void>;
+};
+
+/** Keeps `template` and `data` correlated; TS can't infer that from the array. */
+export function step<TCtx, T extends EmailTemplate>(
+ config: SequenceStep<TCtx, T>,
+): SequenceStep<TCtx, EmailTemplate> {
+ return config as SequenceStep<TCtx, EmailTemplate>;
+}
+
+export interface SequenceSubject<TCtx> {
+ /** For logging only. */
+ id: string;
+ /** Recipient address. */
+ email: string;
+ /** Day gates are measured from here. */
+ anchor: Date;
+ /** Last sent step, or null if the sequence hasn't started. */
+ pointer: string | null;
+ ctx: TCtx;
+};
+
+export interface SequenceResult {
+ emailsSent: number;
+ completed: number;
+ /** Subjects left where they were (day gate or a `false` guard). */
+ deferred: number;
+ /** Steps advanced past without sending. */
+ stepsSkipped: number;
+ /** Sends that threw, or that `requireDelivery` rejected. */
+ failed: number;
+};
+
+interface Logger {
+ info: (obj: unknown, msg?: string) => void;
+ warn: (obj: unknown, msg?: string) => void;
+ error: (obj: unknown, msg?: string) => void;
+};
+
+export interface RunSequenceOptions<TCtx> {
+ /** Sequence name, for log lines. */
+ name: string;
+ steps: SequenceStep<TCtx, EmailTemplate>[];
+ subjects: SequenceSubject<TCtx>[];
+ /** Persist the pointer after a send or a skip. */
+ onAdvance: (subject: SequenceSubject<TCtx>, step: string) => Promise<void>;
+ /**
+ * No steps remain, or a guard returned 'complete'. Omit it when the final
+ * pointer must be preserved because something else reads it — a wind-down
+ * org at 'final_warning' is still blocked from ingesting, so overwriting
+ * that pointer with a completion sentinel would quietly unblock it.
+ */
+ onComplete?: (subject: SequenceSubject<TCtx>) => Promise<void>;
+ logger: Logger;
+};
+
+export async function runSequence<TCtx>({
+ name,
+ steps,
+ subjects,
+ onAdvance,
+ onComplete,
+ logger,
+}: RunSequenceOptions<TCtx>): Promise<SequenceResult> {
+ const result: SequenceResult = {
+ emailsSent: 0,
+ completed: 0,
+ deferred: 0,
+ stepsSkipped: 0,
+ failed: 0,
+ };
+ const now = new Date();
+
+ for (const subject of subjects) {
+ const startIndex = resolveIndex(steps, subject.pointer);
+
+ if (startIndex === 'unknown') {
+ // A step that no longer exists. Completing is the safe reading — the
+ // alternative is replaying the sequence from the top.
+ logger.warn(
+ { sequence: name, subject: subject.id, pointer: subject.pointer },
+ 'Unknown sequence pointer, marking complete',
+ );
+ await onComplete?.(subject);
+ result.completed++;
+ continue;
+ }
+
+ // One tick can cross several steps when guards skip, but never more than
+ // the sequence length.
+ let index = startIndex + 1;
+
+ while (index < steps.length) {
+ const current = steps[index];
+ if (!current) {
+ break;
+ }
+
+ if (differenceInDays(now, subject.anchor) < current.day) {
+ result.deferred++;
+ break;
+ }
+
+ const guard = current.shouldSend
+ ? await current.shouldSend(subject.ctx)
+ : true;
+
+ if (guard === 'complete') {
+ await onComplete?.(subject);
+ result.completed++;
+ break;
+ }
+
+ if (guard === false) {
+ result.deferred++;
+ break;
+ }
+
+ if (guard === 'skip') {
+ await onAdvance(subject, current.step);
+ result.stepsSkipped++;
+ index++;
+ continue;
+ }
+
+ const sent = await sendStep({
+ sequence: name,
+ subject,
+ step: current,
+ logger,
+ });
+
+ if (!sent) {
+ result.failed++;
+ break;
+ }
+
+ await current.onSent?.(subject.ctx);
+ await onAdvance(subject, current.step);
+ result.emailsSent++;
+ break;
+ }
+
+ if (index >= steps.length) {
+ await onComplete?.(subject);
+ result.completed++;
+ }
+ }
+
+ logger.info({ sequence: name, ...result }, `Sequence ${name} tick`);
+
+ return result;
+}
+
+function resolveIndex<TCtx>(
+ steps: SequenceStep<TCtx, EmailTemplate>[],
+ pointer: string | null,
+): number | 'unknown' {
+ if (!pointer) {
+ return -1;
+ }
+ const index = steps.findIndex((entry) => entry.step === pointer);
+ return index === -1 ? 'unknown' : index;
+}
+
+async function sendStep<TCtx>({
+ sequence,
+ subject,
+ step: current,
+ logger,
+}: {
+ sequence: string;
+ subject: SequenceSubject<TCtx>;
+ step: SequenceStep<TCtx, EmailTemplate>;
+ logger: Logger;
+}): Promise<boolean> {
+ try {
+ const data = await current.data(subject.ctx);
+
+ const delivery = await sendEmail(current.template, {
+ to: subject.email,
+ data: data as never,
+ });
+
+ // A null return means suppressed, unparseable, or no provider configured —
+ // note that a local environment without RESEND_API_KEY/SMTP_HOST always
+ // lands here, so requireDelivery steps won't advance in dev.
+ if (current.requireDelivery && delivery === null) {
+ logger.error(
+ {
+ sequence,
+ subject: subject.id,
+ step: current.step,
+ template: current.template,
+ },
+ 'Sequence email required delivery but was not sent, holding pointer',
+ );
+ return false;
+ }
+
+ return true;
+ } catch (error) {
+ logger.error(
+ { err: error, sequence, subject: subject.id, step: current.step },
+ 'Failed to send sequence email',
+ );
+ return false;
+ }
+}
diff --git a/apps/worker/src/jobs/lib/win-back-highlight.test.ts b/apps/worker/src/jobs/lib/win-back-highlight.test.ts
new file mode 100644
index 000000000..cfb7edb9f
--- /dev/null
+++ b/apps/worker/src/jobs/lib/win-back-highlight.test.ts
@@ -0,0 +1,135 @@
+/**
+ * The stats services and the AI call are mocked — these assert the gating and
+ * fallback decisions, which are the point of the module: a highlight is a
+ * bonus, never a reason an email fails or embarrasses us with tiny numbers.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ getAnalyticsOverviewCoreMock,
+ getTopPagesCoreMock,
+ generateWinBackPitchMock,
+} = vi.hoisted(() => ({
+ getAnalyticsOverviewCoreMock: vi.fn(),
+ getTopPagesCoreMock: vi.fn(),
+ generateWinBackPitchMock: vi.fn(),
+}));
+
+vi.mock('@openpanel/db', () => ({
+ getAnalyticsOverviewCore: getAnalyticsOverviewCoreMock,
+ getTopPagesCore: getTopPagesCoreMock,
+}));
+vi.mock('@openpanel/ai', () => ({
+ generateWinBackPitch: generateWinBackPitchMock,
+}));
+
+import { buildWinBackHighlight } from './win-back-highlight';
+
+const project = { id: 'project-1', name: 'acme-web' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getAnalyticsOverviewCoreMock.mockResolvedValue({
+ summary: { unique_visitors: 12_400 },
+ series: [
+ { date: '2026-08-01', unique_visitors: 300 },
+ { date: '2026-08-12', unique_visitors: 840 },
+ { date: '2026-08-20', unique_visitors: 500 },
+ ],
+ });
+ getTopPagesCoreMock.mockResolvedValue([
+ { path: '/pricing', sessions: 2100, pageviews: 3400 },
+ ]);
+ generateWinBackPitchMock.mockResolvedValue(
+ 'acme-web had a strong month with 12,400 visitors.',
+ );
+});
+
+describe('buildWinBackHighlight', () => {
+ it('returns the AI pitch built from the collected facts', async () => {
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toBe('acme-web had a strong month with 12,400 visitors.');
+ expect(generateWinBackPitchMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectName: 'acme-web',
+ uniqueVisitors: 12_400,
+ busiestDay: { date: 'August 12', visitors: 840 },
+ topPage: { path: '/pricing', sessions: 2100 },
+ }),
+ );
+ });
+
+ it('skips low-volume orgs entirely — tiny facts undercut the email', async () => {
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 999,
+ });
+
+ expect(highlight).toBeUndefined();
+ expect(getAnalyticsOverviewCoreMock).not.toHaveBeenCalled();
+ expect(generateWinBackPitchMock).not.toHaveBeenCalled();
+ });
+
+ it('skips when there is no project to pull facts from', async () => {
+ const highlight = await buildWinBackHighlight({
+ project: null,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toBeUndefined();
+ });
+
+ it('falls back to a deterministic sentence when the AI call fails', async () => {
+ generateWinBackPitchMock.mockRejectedValue(new Error('rate limited'));
+
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toContain('acme-web had 12,400 visitors');
+ expect(highlight).toContain('August 12');
+ expect(highlight).toContain('/pricing');
+ });
+
+ it('falls back when the AI returns an empty pitch', async () => {
+ generateWinBackPitchMock.mockResolvedValue(' ');
+
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toContain('acme-web had 12,400 visitors');
+ });
+
+ it('returns nothing when the stats queries fail — the email still goes out', async () => {
+ getAnalyticsOverviewCoreMock.mockRejectedValue(new Error('ch down'));
+
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toBeUndefined();
+ expect(generateWinBackPitchMock).not.toHaveBeenCalled();
+ });
+
+ it('returns nothing for a window with zero visitors', async () => {
+ getAnalyticsOverviewCoreMock.mockResolvedValue({
+ summary: { unique_visitors: 0 },
+ series: [],
+ });
+
+ const highlight = await buildWinBackHighlight({
+ project,
+ recentEventsCount: 50_000,
+ });
+
+ expect(highlight).toBeUndefined();
+ });
+});
diff --git a/apps/worker/src/jobs/lib/win-back-highlight.ts b/apps/worker/src/jobs/lib/win-back-highlight.ts
new file mode 100644
index 000000000..8eb337d8b
--- /dev/null
+++ b/apps/worker/src/jobs/lib/win-back-highlight.ts
@@ -0,0 +1,154 @@
+import { generateWinBackPitch } from '@openpanel/ai';
+import { getAnalyticsOverviewCore, getTopPagesCore } from '@openpanel/db';
+import { format, subDays } from 'date-fns';
+import { logger } from '../../utils/logger';
+
+/**
+ * The personalized paragraph in the wind-down emails: a couple of concrete
+ * facts from the org's own recent data ("your busiest day was...", "your
+ * most-viewed page is...") turned into prose by a small AI call.
+ *
+ * The reasoning: the people this sequence targets stopped opening their
+ * dashboard long ago, so deadlines alone read as noise. A specific fact they
+ * didn't know — one only the product could tell them — is the reminder that
+ * the thing they're about to lose actually *does* something.
+ *
+ * Three deliberate properties:
+ * - Gated on volume. Below HIGHLIGHT_MIN_RECENT_EVENTS the "facts" are
+ * trivia ("your busiest day had 3 visitors") and would undercut the email,
+ * so low-volume orgs simply get no highlight paragraph.
+ * - Never fails the email. AI throwing, or the stats queries throwing, falls
+ * back to a deterministic sentence or to nothing at all.
+ * - Facts come from the org's most recently active project only. One project
+ * keeps the queries bounded and the copy concrete ("on acme-web") instead
+ * of a mush of totals across projects.
+ */
+
+export const HIGHLIGHT_MIN_RECENT_EVENTS = 1000;
+const HIGHLIGHT_WINDOW_DAYS = 30;
+
+export interface HighlightProject {
+ id: string;
+ name: string;
+}
+
+interface HighlightFacts {
+ projectName: string;
+ eventsCount: number;
+ uniqueVisitors: number;
+ busiestDay?: { date: string; visitors: number };
+ topPage?: { path: string; sessions: number };
+}
+
+const formatCount = (n: number) => new Intl.NumberFormat('en-US').format(n);
+
+async function collectFacts(
+ project: HighlightProject,
+ recentEventsCount: number,
+): Promise<HighlightFacts | null> {
+ const now = new Date();
+ const startDate = subDays(now, HIGHLIGHT_WINDOW_DAYS).toISOString();
+ const endDate = now.toISOString();
+
+ const [overview, topPages] = await Promise.all([
+ getAnalyticsOverviewCore({
+ projectId: project.id,
+ startDate,
+ endDate,
+ interval: 'day',
+ }),
+ getTopPagesCore({ projectId: project.id, startDate, endDate, limit: 1 }),
+ ]);
+
+ const uniqueVisitors = overview.summary.unique_visitors ?? 0;
+ if (uniqueVisitors === 0) {
+ return null;
+ }
+
+ let busiestDay: HighlightFacts['busiestDay'];
+ for (const row of overview.series) {
+ if (
+ row.unique_visitors > 0 &&
+ (!busiestDay || row.unique_visitors > busiestDay.visitors)
+ ) {
+ busiestDay = {
+ date: format(new Date(row.date), 'MMMM d'),
+ visitors: row.unique_visitors,
+ };
+ }
+ }
+
+ const top = topPages[0];
+
+ return {
+ projectName: project.name,
+ eventsCount: recentEventsCount,
+ uniqueVisitors,
+ busiestDay,
+ topPage: top ? { path: top.path, sessions: top.sessions } : undefined,
+ };
+}
+
+/** What the reader gets when the AI is unavailable — plain but still theirs. */
+function deterministicPitch(facts: HighlightFacts): string {
+ const parts: string[] = [
+ `In the last 30 days, ${facts.projectName} had ${formatCount(facts.uniqueVisitors)} visitors`,
+ ];
+ if (facts.busiestDay) {
+ parts.push(
+ `with its busiest day on ${facts.busiestDay.date} (${formatCount(facts.busiestDay.visitors)} visitors)`,
+ );
+ }
+ if (facts.topPage) {
+ parts.push(`— ${facts.topPage.path} was the most-visited page`);
+ }
+ return `${parts.join(' ')}.`;
+}
+
+export async function buildWinBackHighlight({
+ project,
+ recentEventsCount,
+}: {
+ project: HighlightProject | null;
+ recentEventsCount: number;
+}): Promise<string | undefined> {
+ if (!project || recentEventsCount < HIGHLIGHT_MIN_RECENT_EVENTS) {
+ return undefined;
+ }
+
+ let facts: HighlightFacts | null;
+ try {
+ facts = await collectFacts(project, recentEventsCount);
+ } catch (error) {
+ logger.warn(
+ { err: error, projectId: project.id },
+ 'Win-back highlight stats failed, sending without highlight',
+ );
+ return undefined;
+ }
+
+ if (!facts) {
+ return undefined;
+ }
+
+ try {
+ const pitch = await generateWinBackPitch({
+ projectName: facts.projectName,
+ window: 'the last 30 days',
+ eventsCount: facts.eventsCount,
+ uniqueVisitors: facts.uniqueVisitors,
+ busiestDay: facts.busiestDay,
+ topPage: facts.topPage,
+ });
+ if (pitch.trim()) {
+ return pitch.trim();
+ }
+ } catch (error) {
+ logger.warn(
+ { err: error, projectId: project.id },
+ 'Win-back pitch AI call failed, using deterministic fallback',
+ );
+ }
+
+ return deterministicPitch(facts);
+}
diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts
index 3100396c1..90accb2a7 100644
--- a/packages/ai/src/index.ts
+++ b/packages/ai/src/index.ts
@@ -2,3 +2,4 @@ export * from './providers';
export * from './enrich';
export * from './narrative';
export * from './explain';
+export * from './win-back';
diff --git a/packages/ai/src/win-back.ts b/packages/ai/src/win-back.ts
new file mode 100644
index 000000000..55d044b02
--- /dev/null
+++ b/packages/ai/src/win-back.ts
@@ -0,0 +1,92 @@
+// Wind-down win-back pitch: one short OpenAI call that turns a lapsed trial's
+// recent stats into a two-sentence selling argument for the wind-down emails.
+// Same one-shot structured-output pattern as narrative.ts — and like the
+// narrative, the caller must treat a throw as "no pitch", never as a failed
+// email: the wind-down job falls back to a deterministic sentence built from
+// the same facts.
+import { betterAgent, defineAgent } from '@better-agent/core';
+import { z } from 'zod';
+import { ALLOWED_MODELS, resolveModel } from './providers';
+
+const WIN_BACK_MODEL_ID = 'gpt-4-1-mini';
+
+function winBackModel() {
+ const entry =
+ ALLOWED_MODELS.find((m) => m.id === WIN_BACK_MODEL_ID) ??
+ ALLOWED_MODELS.find((m) => m.group === 'OpenAI');
+ if (!entry) {
+ throw new Error('No OpenAI model available for win-back pitch');
+ }
+ return resolveModel(entry);
+}
+
+export interface WinBackPitchInput {
+ projectName: string;
+ /** e.g. "the last 30 days" */
+ window: string;
+ eventsCount: number;
+ uniqueVisitors: number;
+ busiestDay?: { date: string; visitors: number };
+ topPage?: { path: string; sessions: number };
+}
+
+const winBackOutputSchema = z.object({ pitch: z.string() });
+const winBackOutputJsonSchema = z.toJSONSchema(winBackOutputSchema, {
+ target: 'draft-07',
+});
+
+const INSTRUCTION = `You write one short paragraph for an email to someone whose analytics trial expired months ago but whose website is still sending us tracking data. They have not looked at their dashboard in a long time. The email's goal is to get them to subscribe before we stop recording their events.
+
+You receive their real stats from the recent window. Write 1-2 plain sentences with the most interesting concrete facts. The reader should think "huh, I didn't know that", not "I am being marketed to". The paragraph sits inside an email written in the founder's own casual voice, so it must read like a person, not a report.
+
+Rules:
+- No greeting and no sign-off (those are added around your text).
+- No bullet lists, no markdown, no headings, no emoji. Just prose.
+- Never mention the trial, pricing, deadlines, or that anything will be blocked. The surrounding email handles that.
+- Never invent data; only use the numbers given. If the numbers are modest, keep it matter-of-fact.
+- State the facts and stop. No concluding sentence about what the numbers mean, show, or suggest.
+- No trailing participle clauses ("..., showing steady growth").
+- No "not just X, but Y" constructions.
+- Plain verbs: prefer "had", "was", "sent", "came from". Do not rotate through attracted, drew, saw, garnered, tracked as substitutes.
+- Banned words: strong, notably, impressive, steady, robust, vibrant, significant, momentum, engagement, journey, insights, leverage, delve, testament, underscore, pivotal, crucial, remarkable, "during this period".
+- No em dashes.
+- Contractions are fine.`;
+
+let _app: ReturnType<typeof betterAgent> | null = null;
+function getApp() {
+ if (_app) {
+ return _app;
+ }
+ const agent = defineAgent({
+ name: 'win-back-pitch',
+ description: 'Writes a wind-down win-back paragraph (one-shot).',
+ model: winBackModel(),
+ contextSchema: z.object({}),
+ outputSchema: {
+ schema: winBackOutputJsonSchema,
+ name: 'win_back_pitch',
+ strict: true,
+ },
+ instruction: () => INSTRUCTION,
+ tools: () => [],
+ maxSteps: 1,
+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts
+ } as any);
+ _app = betterAgent({ agents: [agent] });
+ return _app;
+}
+
+export async function generateWinBackPitch(
+ input: WinBackPitchInput,
+): Promise<string> {
+ const result = (await getApp().run('win-back-pitch', {
+ input: JSON.stringify(input),
+ context: {},
+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts
+ } as any)) as { structured?: { pitch: string } };
+
+ // The instruction bans em dashes, but the model slips one in often enough
+ // that a prompt rule alone won't hold across hundreds of sends. Commas read
+ // fine in every construction it produces them in.
+ return (result.structured?.pitch ?? '').replace(/\s*[—–]\s*/g, ', ').trim();
+}
diff --git a/packages/constants/index.ts b/packages/constants/index.ts
index 6f4324ebf..73e1996cb 100644
--- a/packages/constants/index.ts
+++ b/packages/constants/index.ts
@@ -611,6 +611,14 @@ export const emailCategories = {
description:
'Important notices about your projects: tracking stopped sending data, event limits, and alerts from your notification rules',
},
+ // Kept separate from `onboarding` on purpose: opting out of getting-started
+ // tips must not also opt you out of being told your account is winding down.
+ // The final deletion warning has no category at all, so it always sends.
+ account_lifecycle: {
+ label: 'Account status',
+ description:
+ 'Notices about your trial ending, event ingestion being paused, and data scheduled for removal',
+ },
} as const;
export type EmailCategory = keyof typeof emailCategories;
diff --git a/packages/db/code-migrations/21-wind-down-onboarding-pointer.ts b/packages/db/code-migrations/21-wind-down-onboarding-pointer.ts
new file mode 100644
index 000000000..c4856f9c2
--- /dev/null
+++ b/packages/db/code-migrations/21-wind-down-onboarding-pointer.ts
@@ -0,0 +1,55 @@
+/**
+ * Retire the 'onboarding-trial-ended' pointer.
+ *
+ * The onboarding drip used to end with a day-30 'onboarding-trial-ended'
+ * email. That moment now belongs to the wind-down sequence (step 0,
+ * 'wind-down-expired'), which is anchored on trial expiry rather than signup,
+ * so the step was removed from ONBOARDING_EMAILS.
+ *
+ * Organizations whose `onboarding` column still holds the removed name are
+ * left pointing at a step that no longer exists. The sequence runner treats an
+ * unknown pointer as "sequence complete" precisely so this cannot replay the
+ * drip from the welcome email — but it does so one organization at a time,
+ * emitting a warning for each. Settling them here keeps that path for genuine
+ * accidents rather than for a rename we already know about.
+ *
+ * pnpm with-env jiti ./code-migrations/21-wind-down-onboarding-pointer.ts --dry
+ */
+import { db } from '../src/prisma-client';
+import { getIsDry, printBoxMessage } from './helpers';
+
+const RETIRED_POINTER = 'onboarding-trial-ended';
+
+export async function up() {
+ const isDry = getIsDry();
+
+ const stranded = await db.organization.count({
+ where: { onboarding: RETIRED_POINTER },
+ });
+
+ printBoxMessage('📋 Plan', [
+ `Organizations pointing at "${RETIRED_POINTER}": ${stranded}`,
+ 'They will be marked as onboarding: "completed"',
+ ]);
+
+ if (stranded === 0) {
+ printBoxMessage('✅ Nothing to do', [
+ 'No organization holds the retired pointer',
+ ]);
+ return;
+ }
+
+ if (isDry) {
+ printBoxMessage('🕒 Dry run - nothing written', [
+ `Would update ${stranded} organization(s)`,
+ ]);
+ return;
+ }
+
+ const { count } = await db.organization.updateMany({
+ where: { onboarding: RETIRED_POINTER },
+ data: { onboarding: 'completed' },
+ });
+
+ printBoxMessage('✅ Done', [`Updated ${count} organization(s)`]);
+}
diff --git a/packages/db/prisma/migrations/20260828120000_organization_wind_down/migration.sql b/packages/db/prisma/migrations/20260828120000_organization_wind_down/migration.sql
new file mode 100644
index 000000000..e16285b51
--- /dev/null
+++ b/packages/db/prisma/migrations/20260828120000_organization_wind_down/migration.sql
@@ -0,0 +1,18 @@
+-- Wind-down: the lifecycle between an expired trial and deleting the data.
+--
+-- "windDownStartedAt" is the schedule anchor, stamped when an organization
+-- enters the sequence. It exists precisely because "subscriptionEndsAt" cannot
+-- serve that role: every organization already in trial_expired has an expiry
+-- weeks or months in the past, so a schedule measured from it would place them
+-- all past the final step immediately and delete them without a single warning
+-- email. Anchoring on entry puts the whole backlog at day 0 instead.
+--
+-- "windDownStep" is the last step whose email was sent. It doubles as the
+-- ingestion gate: 'blocked' and 'final_warning' cause the API to reject events
+-- (see apps/api/src/hooks/subscription.hook.ts). Both columns are NULL for
+-- every existing row, so this migration blocks nothing on its own; blocking
+-- only starts once the wind-down cron has walked an org to day 21.
+ALTER TABLE "organizations" ADD COLUMN "windDownStartedAt" TIMESTAMP(3);
+ALTER TABLE "organizations" ADD COLUMN "windDownStep" TEXT;
+
+CREATE INDEX "organizations_windDownStartedAt_idx" ON "organizations"("windDownStartedAt");
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index e3dbdda50..f7b0ff0e9 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -121,12 +121,22 @@ model Organization {
/// [IPrismaSubscriptionDiscount]
subscriptionDiscount Json?
+ // Wind-down: trial expired -> ingestion blocked -> data deleted.
+ // Anchored on windDownStartedAt (stamped when the org enters the sequence)
+ // rather than subscriptionEndsAt: existing trial_expired orgs have an expiry
+ // hundreds of days in the past, so anchoring there would skip every email and
+ // delete them on the first tick.
+ windDownStartedAt DateTime?
+ /// [IPrismaWindDownStep]
+ windDownStep String?
+
// When deleteAt > now(), the organization will be deleted
deleteAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
+ @@index([windDownStartedAt])
@@map("organizations")
}
diff --git a/packages/db/src/services/organization.service.ts b/packages/db/src/services/organization.service.ts
index 7aeca5a68..707761790 100644
--- a/packages/db/src/services/organization.service.ts
+++ b/packages/db/src/services/organization.service.ts
@@ -265,6 +265,29 @@ export async function getOrganizationEventsCount(projectIds: string[]) {
return res[0]?.count ?? 0;
}
+// Events in a recent window, for organizations whose trial lapsed but whose
+// SDKs never stopped. The lifetime count above says "you once used this"; this
+// one says "you are using this right now", which is the only number that
+// actually argues for a subscription.
+export async function getOrganizationEventsCountSince(
+ projectIds: string[],
+ since: Date
+) {
+ if (projectIds.length === 0) {
+ return 0;
+ }
+
+ const { sb, getSql } = createSqlBuilder();
+
+ sb.select.count = 'COUNT(*) AS count';
+ sb.where.projectIds = `project_id IN (${projectIds.map((id) => sqlstring.escape(id)).join(',')})`;
+ sb.where.names = `name NOT IN ('session_start', 'session_end')`;
+ sb.where.createdAt = `created_at >= ${sqlstring.escape(formatClickhouseDate(since, true))}`;
+
+ const res = await chQuery<{ count: number }>(getSql());
+ return res[0]?.count ?? 0;
+}
+
export async function getOrganizationBillingEventsCountSerie(
organization: IServiceOrganization & { projects: { id: string }[] },
{
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index 160f3a85b..69b4cde77 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -58,6 +58,14 @@ declare global {
duration: 'once' | 'forever' | 'repeating';
durationInMonths: number | null;
};
+ // Steps of the wind-down sequence, in order. The column stores the last
+ // step whose email was sent; `blocked` and `final_warning` also mean
+ // ingestion is rejected. See apps/worker/src/jobs/cron.wind-down.ts.
+ type IPrismaWindDownStep =
+ | 'expired_notice'
+ | 'stopping_soon'
+ | 'blocked'
+ | 'final_warning';
// Mirrors Polar's CustomerCancellationReason enum.
type IPrismaCancellationReason =
| 'too_expensive'
diff --git a/packages/email/src/emails/index.tsx b/packages/email/src/emails/index.tsx
index 60a5ea258..1f56ea5dd 100644
--- a/packages/email/src/emails/index.tsx
+++ b/packages/email/src/emails/index.tsx
@@ -9,9 +9,6 @@ import OnboardingDashboards, {
import OnboardingFeatureRequest, {
zOnboardingFeatureRequest,
} from './onboarding-feature-request';
-import OnboardingTrialEnded, {
- zOnboardingTrialEnded,
-} from './onboarding-trial-ended';
import OnboardingTrialEnding, {
zOnboardingTrialEnding,
} from './onboarding-trial-ending';
@@ -29,6 +26,14 @@ import UsageLimitExceeded, {
} from './usage-limit-exceeded';
import UsageNearLimit, { zUsageNearLimit } from './usage-near-limit';
import WeeklyDigest, { zWeeklyDigest } from './weekly-digest';
+import WindDownBlocked, { zWindDownBlocked } from './wind-down-blocked';
+import WindDownExpired, { zWindDownExpired } from './wind-down-expired';
+import WindDownFinalWarning, {
+ zWindDownFinalWarning,
+} from './wind-down-final-warning';
+import WindDownStoppingSoon, {
+ zWindDownStoppingSoon,
+} from './wind-down-stopping-soon';
export const templates = {
invite: {
@@ -80,11 +85,40 @@ export const templates = {
// check, no List-Unsubscribe header).
category: 'onboarding' as const,
},
- 'onboarding-trial-ended': {
- subject: () => 'Your trial ended, dashboard is locked',
- Component: OnboardingTrialEnded,
- schema: zOnboardingTrialEnded,
- category: 'onboarding' as const,
+ 'wind-down-expired': {
+ subject: (data: z.infer<typeof zWindDownExpired>) =>
+ data.stillTracking
+ ? "You're still sending events, but your trial ended"
+ : 'Your trial ended, dashboard is locked',
+ Component: WindDownExpired,
+ schema: zWindDownExpired,
+ category: 'account_lifecycle' as const,
+ },
+ 'wind-down-stopping-soon': {
+ subject: (data: z.infer<typeof zWindDownStoppingSoon>) =>
+ `We stop recording your events on ${data.blockDate}`,
+ Component: WindDownStoppingSoon,
+ schema: zWindDownStoppingSoon,
+ category: 'account_lifecycle' as const,
+ },
+ 'wind-down-blocked': {
+ subject: (data: z.infer<typeof zWindDownBlocked>) =>
+ data.stillTracking
+ ? 'Your events are no longer being recorded'
+ : 'Event tracking paused for your projects',
+ Component: WindDownBlocked,
+ schema: zWindDownBlocked,
+ category: 'account_lifecycle' as const,
+ },
+ 'wind-down-final-warning': {
+ subject: (data: z.infer<typeof zWindDownFinalWarning>) =>
+ `Final notice: your data is deleted on ${data.deleteDate}`,
+ Component: WindDownFinalWarning,
+ schema: zWindDownFinalWarning,
+ // Deliberately uncategorised, which makes it transactional: no suppression
+ // check and no unsubscribe link. Telling someone their data is about to be
+ // erased is a service notice, not marketing, and it must not be silenced
+ // by an earlier opt-out.
},
'weekly-digest': {
subject: (data: z.infer<typeof zWeeklyDigest>) =>
diff --git a/packages/email/src/emails/onboarding-trial-ended.tsx b/packages/email/src/emails/onboarding-trial-ended.tsx
deleted file mode 100644
index a2b40590b..000000000
--- a/packages/email/src/emails/onboarding-trial-ended.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { Text } from '@react-email/components';
-import React from 'react';
-import { z } from 'zod';
-import { Button } from '../components/button';
-import { Layout } from '../components/layout';
-import { withUtm } from '../utm';
-
-export const zOnboardingTrialEnded = z.object({
- firstName: z.string().optional(),
- billingUrl: z.string(),
- recommendedPlan: z.string().optional(),
- hasData: z.boolean().default(true),
- eventsCount: z.number().optional(),
-});
-
-const formatEvents = (count: number) =>
- new Intl.NumberFormat('en-US').format(count);
-
-export type Props = z.infer<typeof zOnboardingTrialEnded>;
-export default OnboardingTrialEnded;
-export function OnboardingTrialEnded({
- firstName,
- billingUrl = 'https://dashboard.openpanel.dev',
- recommendedPlan,
- hasData = true,
- eventsCount,
- unsubscribeUrl,
-}: Props & { unsubscribeUrl?: string }) {
- if (!hasData) {
- return (
- <Layout unsubscribeUrl={unsubscribeUrl}>
- <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>
- Your trial ended today. No events ever came in, so nothing is lost.
- The empty workspace will be cleaned up and that's the end of it.
- </Text>
- <Text>
- If you want to give OpenPanel another go some day, it'll be here. And
- if you remember what made you bounce, I'd like to hear it. One line
- is fine.
- </Text>
- <Text>Carl</Text>
- </Layout>
- );
- }
-
- return (
- <Layout unsubscribeUrl={unsubscribeUrl}>
- <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
- <Text>Your trial ended today, so your dashboard is locked.</Text>
- <Text>
- Your data isn't gone.
- {eventsCount
- ? ` The ${formatEvents(eventsCount)} events you tracked are still stored, and incoming events are still accepted for now.`
- : ' Everything you tracked is still stored, and incoming events are still accepted for now.'}{' '}
- Upgrade and everything picks up where it left off.
- </Text>
- <Text>
- {recommendedPlan
- ? `Based on your volume: ${recommendedPlan}.`
- : 'Plans start at $2.50 a month.'}
- </Text>
- <Text>
- <Button href={withUtm(billingUrl, 'onboarding-trial-ended')}>
- Upgrade
- </Button>
- </Text>
- <Text>
- If you don't upgrade, the workspace is eventually removed along with
- its data. I'm saying that plainly so it's not a surprise, not to
- pressure you.
- </Text>
- <Text>
- If OpenPanel wasn't right for you, a one-line reply saying why helps me
- more than you'd think.
- </Text>
- <Text>Carl</Text>
- </Layout>
- );
-}
-
-OnboardingTrialEnded.PreviewProps = {
- firstName: 'Alex',
- billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
- recommendedPlan: '100K events per month for $20.00',
- hasData: true,
- eventsCount: 84211,
-};
diff --git a/packages/email/src/emails/wind-down-blocked.tsx b/packages/email/src/emails/wind-down-blocked.tsx
new file mode 100644
index 000000000..dc4cbb723
--- /dev/null
+++ b/packages/email/src/emails/wind-down-blocked.tsx
@@ -0,0 +1,123 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zWindDownBlocked = z.object({
+ firstName: z.string().optional(),
+ billingUrl: z.string(),
+ deleteDate: z.string(),
+ hasData: z.boolean().default(true),
+ stillTracking: z.boolean().default(false),
+ eventsCount: z.number().optional(),
+ recentEventsCount: z.number().optional(),
+});
+
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zWindDownBlocked>;
+export default WindDownBlocked;
+export function WindDownBlocked({
+ firstName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ deleteDate,
+ hasData = true,
+ stillTracking = false,
+ eventsCount,
+ recentEventsCount,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const greeting = <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>;
+ const cta = (
+ <Text>
+ <Button href={withUtm(billingUrl, 'wind-down-blocked')}>
+ Resume tracking
+ </Button>
+ </Text>
+ );
+
+ if (stillTracking) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ As of today we've stopped recording events from your projects.
+ {recentEventsCount
+ ? ` Your SDKs are still sending — around ${formatEvents(recentEventsCount)} events over the last month — and from now on those requests are discarded.`
+ : ' Your SDKs will keep sending; those requests are now discarded.'}
+ </Text>
+ <Text>
+ Nothing has been deleted.
+ {eventsCount
+ ? ` The ${formatEvents(eventsCount)} events collected before today are intact`
+ : ' Everything collected before today is intact'}{' '}
+ and waiting. Subscribe and recording resumes within a few minutes,
+ with your full history where you left it — though the gap from today
+ onward can't be backfilled.
+ </Text>
+ {cta}
+ <Text>
+ Being straight about what comes next: if the workspace is still
+ inactive on {deleteDate}, it and its data get removed. I'll send one
+ more email well before that.
+ </Text>
+ <Text>
+ If pricing is the problem, reply — I'd rather find something that
+ works than lose the data.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ if (hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ As of today your projects no longer accept new events. Nothing has
+ been deleted —
+ {eventsCount
+ ? ` the ${formatEvents(eventsCount)} events already collected are intact`
+ : ' everything already collected is intact'}{' '}
+ and a plan brings it all straight back.
+ </Text>
+ {cta}
+ <Text>
+ If the workspace is still inactive on {deleteDate}, it and its data
+ get removed. I'll send one more email before that happens.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ Your workspace is now closed to new events. Nothing was ever tracked in
+ it, so this is mostly housekeeping on my end.
+ </Text>
+ <Text>
+ It stays recoverable until {deleteDate}. Pick a plan before then and it
+ comes straight back.
+ </Text>
+ {cta}
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+WindDownBlocked.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ deleteDate: 'April 10',
+ hasData: true,
+ stillTracking: true,
+ eventsCount: 842_110,
+ recentEventsCount: 128_400,
+};
diff --git a/packages/email/src/emails/wind-down-expired.tsx b/packages/email/src/emails/wind-down-expired.tsx
new file mode 100644
index 000000000..d1731937f
--- /dev/null
+++ b/packages/email/src/emails/wind-down-expired.tsx
@@ -0,0 +1,177 @@
+import { Link, Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zWindDownExpired = z.object({
+ firstName: z.string().optional(),
+ billingUrl: z.string(),
+ blockDate: z.string(),
+ trialEndedDate: z.string().optional(),
+ recommendedPlan: z.string().optional(),
+ hasData: z.boolean().default(true),
+ /** SDKs are demonstrably still sending, months after the trial lapsed. */
+ stillTracking: z.boolean().default(false),
+ eventsCount: z.number().optional(),
+ recentEventsCount: z.number().optional(),
+ projectNames: z.array(z.string()).default([]),
+ /**
+ * AI-written (or deterministic-fallback) paragraph of concrete facts from
+ * the org's own recent data. Only present for still-tracking orgs above the
+ * volume threshold — see win-back-highlight.ts in the worker.
+ */
+ highlight: z.string().optional(),
+});
+
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zWindDownExpired>;
+export default WindDownExpired;
+export function WindDownExpired({
+ firstName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ blockDate,
+ trialEndedDate,
+ recommendedPlan,
+ hasData = true,
+ stillTracking = false,
+ eventsCount,
+ recentEventsCount,
+ projectNames = [],
+ highlight,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const greeting = <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>;
+ const projectLabel =
+ projectNames.length === 1
+ ? projectNames[0]
+ : projectNames.length > 1
+ ? `${projectNames[0]} and ${projectNames.length - 1} more`
+ : undefined;
+ const mcpPitch = (
+ <Text>
+ A lot has shipped since your trial — including our{' '}
+ <Link href={withUtm('https://openpanel.dev/docs/mcp', 'wind-down-expired')}>
+ MCP server
+ </Link>
+ : connect Claude, Cursor, or any MCP client and ask questions about this
+ data in plain English.
+ </Text>
+ );
+ const cta = (
+ <Text>
+ <Button href={withUtm(billingUrl, 'wind-down-expired')}>
+ Choose a plan
+ </Button>
+ </Text>
+ );
+
+ // Still sending. The persuasive fact is the live volume, not the history.
+ if (stillTracking) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ Your OpenPanel tracking is still running
+ {trialEndedDate ? `, even though your trial ended ${trialEndedDate}` : ''}
+ .
+ {recentEventsCount
+ ? ` You've sent ${formatEvents(recentEventsCount)} events in the last 30 days and we've recorded every one of them.`
+ : ' Your SDKs are still sending and we are still recording.'}
+ </Text>
+ {highlight ? <Text>{highlight}</Text> : null}
+ <Text>
+ I'd rather tell you than let it lapse quietly: on {blockDate} we stop
+ accepting events from your projects. Your SDKs will keep firing, but
+ nothing will be recorded, and your history gets a permanent gap
+ starting that day.
+ </Text>
+ <Text>
+ {recommendedPlan
+ ? `For what you're actually sending, that's ${recommendedPlan}.`
+ : 'Plans start at $2.50 a month.'}{' '}
+ Subscribe before {blockDate} and nothing changes — same data, same
+ setup, dashboard unlocked.
+ </Text>
+ {cta}
+ {mcpPitch}
+ <Text>
+ If the price is the blocker, or you only need part of what you're
+ sending, reply and we'll work something out.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ // Tracked at some point, but nothing recent.
+ if (hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ Your trial ended{trialEndedDate ? ` ${trialEndedDate}` : ''}, so the
+ dashboard is locked. Your data
+ {projectLabel ? ` from ${projectLabel}` : ''} is still here —
+ {eventsCount
+ ? ` all ${formatEvents(eventsCount)} events of it.`
+ : ' everything you tracked is stored.'}
+ </Text>
+ <Text>
+ Nothing has been sent in a while, so I'm assuming you moved on. If
+ that's right you can ignore this; I'll close the workspace down over
+ the next few weeks and send a reminder before anything is removed.
+ </Text>
+ <Text>
+ If you'd rather pick it back up,{' '}
+ {recommendedPlan
+ ? `a plan for your volume is ${recommendedPlan}`
+ : 'plans start at $2.50 a month'}{' '}
+ and everything resumes where it left off.
+ </Text>
+ {cta}
+ {mcpPitch}
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ // Never sent an event.
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ Your OpenPanel trial has ended. No events ever reached us, so there's
+ nothing stored and nothing for you to lose.
+ </Text>
+ <Text>
+ I'll close the workspace down over the next few weeks unless you pick a
+ plan. You'll get a reminder before anything is removed.
+ </Text>
+ {cta}
+ <Text>
+ If something got in the way during setup, I'd genuinely like to know.
+ One line is plenty.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+WindDownExpired.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ blockDate: 'March 14',
+ trialEndedDate: 'November 3, 2025',
+ recommendedPlan: '100K events per month for $20.00',
+ hasData: true,
+ stillTracking: true,
+ eventsCount: 842_110,
+ recentEventsCount: 128_400,
+ projectNames: ['acme-web', 'acme-docs'],
+ highlight:
+ 'acme-web had 12,400 visitors in the last 30 days, peaking at 840 on November 12 — and /pricing was the page they visited most.',
+};
diff --git a/packages/email/src/emails/wind-down-final-warning.tsx b/packages/email/src/emails/wind-down-final-warning.tsx
new file mode 100644
index 000000000..bd7eb2119
--- /dev/null
+++ b/packages/email/src/emails/wind-down-final-warning.tsx
@@ -0,0 +1,89 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zWindDownFinalWarning = z.object({
+ firstName: z.string().optional(),
+ billingUrl: z.string(),
+ deleteDate: z.string(),
+ hasData: z.boolean().default(true),
+ stillTracking: z.boolean().default(false),
+ eventsCount: z.number().optional(),
+ recentEventsCount: z.number().optional(),
+});
+
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zWindDownFinalWarning>;
+export default WindDownFinalWarning;
+export function WindDownFinalWarning({
+ firstName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ deleteDate,
+ hasData = true,
+ stillTracking = false,
+ eventsCount,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>
+ <Text>
+ This is the last email I'll send about this, and it's the one with real
+ consequences, so I'll keep it short.
+ </Text>
+ <Text>
+ <strong>
+ On {deleteDate} your OpenPanel organization and everything in it will
+ be permanently deleted.
+ </strong>{' '}
+ That means your projects, your settings, and
+ {hasData && eventsCount
+ ? ` all ${formatEvents(eventsCount)} events you've collected.`
+ : ' any data associated with the account.'}{' '}
+ This cannot be undone, and I won't be able to recover it afterwards.
+ </Text>
+ {stillTracking ? (
+ <Text>
+ Worth flagging: your SDKs are still installed and still calling us.
+ After {deleteDate} those calls will fail against a workspace that no
+ longer exists, so it's worth either subscribing or removing the
+ tracking code.
+ </Text>
+ ) : null}
+ <Text>
+ It's been six weeks since your trial ended and I've written three times
+ before this, so I don't want it to land as a surprise.
+ </Text>
+ <Text>
+ Starting a plan before {deleteDate} cancels the deletion and restores
+ everything immediately.
+ </Text>
+ <Text>
+ <Button href={withUtm(billingUrl, 'wind-down-final-warning')}>
+ Keep my data
+ </Button>
+ </Text>
+ <Text>
+ If you want the data but not the subscription, reply before {deleteDate}{' '}
+ and I'll export it for you. If you'd rather it were gone, you don't need
+ to do anything at all.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+WindDownFinalWarning.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ deleteDate: 'April 10',
+ hasData: true,
+ stillTracking: true,
+ eventsCount: 842_110,
+ recentEventsCount: 128_400,
+};
diff --git a/packages/email/src/emails/wind-down-stopping-soon.tsx b/packages/email/src/emails/wind-down-stopping-soon.tsx
new file mode 100644
index 000000000..332691675
--- /dev/null
+++ b/packages/email/src/emails/wind-down-stopping-soon.tsx
@@ -0,0 +1,129 @@
+import { Text } from '@react-email/components';
+import React from 'react';
+import { z } from 'zod';
+import { Button } from '../components/button';
+import { Layout } from '../components/layout';
+import { withUtm } from '../utm';
+
+export const zWindDownStoppingSoon = z.object({
+ firstName: z.string().optional(),
+ billingUrl: z.string(),
+ blockDate: z.string(),
+ recommendedPlan: z.string().optional(),
+ hasData: z.boolean().default(true),
+ stillTracking: z.boolean().default(false),
+ eventsCount: z.number().optional(),
+ recentEventsCount: z.number().optional(),
+ projectNames: z.array(z.string()).default([]),
+ highlight: z.string().optional(),
+});
+
+const formatEvents = (count: number) =>
+ new Intl.NumberFormat('en-US').format(count);
+
+export type Props = z.infer<typeof zWindDownStoppingSoon>;
+export default WindDownStoppingSoon;
+export function WindDownStoppingSoon({
+ firstName,
+ billingUrl = 'https://dashboard.openpanel.dev',
+ blockDate,
+ recommendedPlan,
+ hasData = true,
+ stillTracking = false,
+ eventsCount,
+ recentEventsCount,
+ highlight,
+ unsubscribeUrl,
+}: Props & { unsubscribeUrl?: string }) {
+ const greeting = <Text>Hi{firstName ? ` ${firstName}` : ''},</Text>;
+ const cta = (
+ <Text>
+ <Button href={withUtm(billingUrl, 'wind-down-stopping-soon')}>
+ Keep tracking
+ </Button>
+ </Text>
+ );
+
+ if (stillTracking) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ One week left: on {blockDate} we stop recording events from your
+ projects.
+ </Text>
+ <Text>
+ {recentEventsCount
+ ? `You're sending roughly ${formatEvents(recentEventsCount)} events a month right now. `
+ : "You're still sending events. "}
+ All of that stops being recorded on {blockDate} — the requests will
+ still go out, they just won't land anywhere. Whatever you'd want to
+ look back on later starts missing from that date.
+ </Text>
+ {highlight ? <Text>{highlight}</Text> : null}
+ <Text>
+ {recommendedPlan
+ ? `Keeping it running costs ${recommendedPlan}.`
+ : 'Plans start at $2.50 a month.'}{' '}
+ Nothing about your setup changes — no redeploy, no new keys.
+ </Text>
+ {cta}
+ <Text>
+ Need longer, or want to talk through which plan fits? Reply and I'll
+ sort it out.
+ </Text>
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ if (hasData) {
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ A heads-up with a date on it: on {blockDate} we stop accepting events
+ from your projects, and the workspace starts winding down.
+ </Text>
+ <Text>
+ Everything already collected stays put for now
+ {eventsCount ? `, all ${formatEvents(eventsCount)} events of it` : ''}
+ . If you want to keep it, a plan before {blockDate} keeps everything
+ exactly as it is.
+ </Text>
+ {cta}
+ <Text>Carl</Text>
+ </Layout>
+ );
+ }
+
+ return (
+ <Layout unsubscribeUrl={unsubscribeUrl}>
+ {greeting}
+ <Text>
+ Quick follow-up: your trial ended a couple of weeks ago and the
+ workspace is still empty, so I'll be closing it on {blockDate}.
+ </Text>
+ <Text>
+ If you'd rather keep it, picking a plan stops the clock. Otherwise you
+ can ignore this — I'll send one more note before anything goes.
+ </Text>
+ {cta}
+ <Text>Carl</Text>
+ </Layout>
+ );
+}
+
+WindDownStoppingSoon.PreviewProps = {
+ firstName: 'Alex',
+ billingUrl: 'https://dashboard.openpanel.dev/org-id/billing',
+ blockDate: 'March 14',
+ recommendedPlan: '100K events per month for $20.00',
+ hasData: true,
+ stillTracking: true,
+ eventsCount: 842_110,
+ recentEventsCount: 128_400,
+ projectNames: ['acme-web'],
+ highlight:
+ 'acme-web had 12,400 visitors in the last 30 days, peaking at 840 on November 12 — and /pricing was the page they visited most.',
+};
diff --git a/packages/queue/src/queues.ts b/packages/queue/src/queues.ts
index 6e22782cb..806829cb1 100644
--- a/packages/queue/src/queues.ts
+++ b/packages/queue/src/queues.ts
@@ -181,6 +181,10 @@ export type CronQueuePayloadDataHealth = {
type: 'dataHealth';
payload: undefined;
};
+export type CronQueuePayloadWindDown = {
+ type: 'windDown';
+ payload: undefined;
+};
export type CronQueuePayload =
| CronQueuePayloadSalt
| CronQueuePayloadFlushEvents
@@ -199,7 +203,8 @@ export type CronQueuePayload =
| CronQueuePayloadSessionVacuum
| CronQueuePayloadInsightCleanup
| CronQueuePayloadWeeklyDigest
- | CronQueuePayloadDataHealth;
+ | CronQueuePayloadDataHealth
+ | CronQueuePayloadWindDown;
export type CronQueueType = CronQueuePayload['type'];