From 763d12b888592e358ab507e65e3024d03a3912a9 Mon Sep 17 00:00:00 2001 From: JeremyFunk Date: Mon, 23 Nov 2026 14:18:37 +0100 Subject: [PATCH 1/4] fix(customers): a lead whose plans ended unpaid gets no more signals --- .../worker/objects/customers/evaluate.test.ts | 33 +++++++++++++++++++ .../src/worker/objects/customers/evaluate.ts | 9 +++++ 2 files changed, 42 insertions(+) diff --git a/apps/backend/src/worker/objects/customers/evaluate.test.ts b/apps/backend/src/worker/objects/customers/evaluate.test.ts index eb86f316b..2187bc861 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.test.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.test.ts @@ -597,6 +597,31 @@ describe("signal evaluation", () => { ).toEqual(notCovered) }) + it("a lead whose plans all ended unpaid gets no more signals", () => { + const left: FactsInput = { + account: { lifecycleStage: "lead", mrrMinor: 0 }, + activity: { ann: [-30] }, + priorActive: [[30, 1]], + subscriptions: [ + { status: "canceled", mrrMinor: 0, canceledAt: new Date(NOW.getTime() - 36 * 86_400_000) }, + ], + } + const ended = { _tag: "NoMatch", reason: "Plan ended" } + expect(run("inactive", left)).toEqual(ended) + expect(run("usage_drop", left)).toEqual(ended) + // A plan still live, no plan at all, or a stage set by hand: still someone to watch. + expect( + run("inactive", { + ...left, + subscriptions: [...left.subscriptions!, { status: "active", mrrMinor: 0 }], + })._tag, + ).toBe("Match") + expect(run("inactive", { ...left, subscriptions: [] })._tag).toBe("Match") + expect(run("inactive", { ...left, account: { lifecycleStage: "active", mrrMinor: 0 } })._tag).toBe( + "Match", + ) + }) + it("churned: announced once, until the customer pays or starts a paid plan again", () => { const ago = (days: number) => new Date(NOW.getTime() - days * 86_400_000) const churned: FactsInput = { @@ -937,6 +962,14 @@ describe("signal evaluation", () => { const narrow = orgFacts({ attention: { stages: ["active"], requiredSources: ["stripe"] } }) expect(run("response_overdue", lead, narrow)._tag).toBe("Match") expect(run("resolution_overdue", lead, narrow)._tag).toBe("Match") + // A plan that ended unpaid does not take back a reply it is owed. + expect( + run( + "response_overdue", + { ...lead, subscriptions: [{ status: "canceled", mrrMinor: 0 }] }, + narrow, + )._tag, + ).toBe("Match") // Other templates stay behind the coverage. expect(run("health_drop", lead, narrow)).toEqual({ _tag: "NoMatch", diff --git a/apps/backend/src/worker/objects/customers/evaluate.ts b/apps/backend/src/worker/objects/customers/evaluate.ts index 727d9bf6b..4828d1723 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.ts @@ -51,6 +51,7 @@ export interface RuleInput { export type NonMatchReason = | "Churned" + | "Plan ended" | "Not covered by Needs attention" | "Out of scope" | "Missing data source" @@ -775,9 +776,17 @@ export const missingSources = (template: SignalTemplate, org: OrgFacts): Readonl return required.length === 0 || required.some((provider) => org.connected.has(provider)) ? [] : required } +/** Every plan it held ended and none was ever paid for: it left before becoming a customer. */ +const leftUnpaid = (facts: AccountFacts) => + facts.stage === "lead" && + facts.subscriptions.length > 0 && + facts.subscriptions.every((sub) => sub.status === "canceled") + export const evaluate = (rule: RuleInput, facts: AccountFacts, org: OrgFacts): Evaluation => { // Churn is a customer's last entry: no other rule evaluates it after. if (facts.stage === "churned" && rule.template !== "churned") return noMatch("Churned") + // Nor does one after an unpaid plan ended, but a support issue it opened is still owed a reply. + if (leftUnpaid(facts) && !SLA_TEMPLATES.includes(rule.template)) return noMatch("Plan ended") // The SLA templates cover every customer: only the rule's own scope narrows them. if (!SLA_TEMPLATES.includes(rule.template) && !covered(facts, org)) return noMatch("Not covered by Needs attention") From 9d32e1f36a3bfa4ba0b8aed2b8878f08eb1ef0a3 Mon Sep 17 00:00:00 2001 From: JeremyFunk Date: Mon, 23 Nov 2026 14:24:53 +0100 Subject: [PATCH 2/4] fix(customers): a plan that paid keeps its account evaluated --- .../src/worker/objects/customers/evaluate.test.ts | 9 ++++++++- apps/backend/src/worker/objects/customers/evaluate.ts | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/backend/src/worker/objects/customers/evaluate.test.ts b/apps/backend/src/worker/objects/customers/evaluate.test.ts index 2187bc861..9d625c0ad 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.test.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.test.ts @@ -609,13 +609,20 @@ describe("signal evaluation", () => { const ended = { _tag: "NoMatch", reason: "Plan ended" } expect(run("inactive", left)).toEqual(ended) expect(run("usage_drop", left)).toEqual(ended) - // A plan still live, no plan at all, or a stage set by hand: still someone to watch. + // A plan still live, one that paid (a group's churned environment beside a lead one), no plan + // at all, or a stage set by hand: still someone to watch. expect( run("inactive", { ...left, subscriptions: [...left.subscriptions!, { status: "active", mrrMinor: 0 }], })._tag, ).toBe("Match") + expect( + run("inactive", { + ...left, + subscriptions: [...left.subscriptions!, { status: "canceled", mrrMinor: 3_900 }], + })._tag, + ).toBe("Match") expect(run("inactive", { ...left, subscriptions: [] })._tag).toBe("Match") expect(run("inactive", { ...left, account: { lifecycleStage: "active", mrrMinor: 0 } })._tag).toBe( "Match", diff --git a/apps/backend/src/worker/objects/customers/evaluate.ts b/apps/backend/src/worker/objects/customers/evaluate.ts index 4828d1723..55056a65f 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.ts @@ -780,7 +780,7 @@ export const missingSources = (template: SignalTemplate, org: OrgFacts): Readonl const leftUnpaid = (facts: AccountFacts) => facts.stage === "lead" && facts.subscriptions.length > 0 && - facts.subscriptions.every((sub) => sub.status === "canceled") + facts.subscriptions.every((sub) => sub.status === "canceled" && !pays(sub)) export const evaluate = (rule: RuleInput, facts: AccountFacts, org: OrgFacts): Evaluation => { // Churn is a customer's last entry: no other rule evaluates it after. From 549982d281499960e6f73cdaea70de1f2912d168 Mon Sep 17 00:00:00 2001 From: JeremyFunk Date: Mon, 23 Nov 2026 14:35:11 +0100 Subject: [PATCH 3/4] fix(customers): a canceled card trial is a churn, an abandoned checkout never started --- .../objects/customers/autumn/map.test.ts | 35 +++++++++- .../worker/objects/customers/autumn/map.ts | 66 ++++++++++++++----- .../objects/customers/compute-loop.test.ts | 56 ++++++++++++++++ .../worker/objects/customers/evaluate.test.ts | 5 ++ .../src/worker/objects/customers/evaluate.ts | 10 +-- .../src/worker/objects/customers/facts.ts | 21 ++++-- .../worker/objects/customers/ingest-live.ts | 26 ++++++++ .../src/worker/objects/customers/snapshot.ts | 15 +++-- .../src/page/customers/detail/billing-tab.ts | 17 +++-- packages/domain/src/customers/enums.ts | 3 + 10 files changed, 215 insertions(+), 39 deletions(-) diff --git a/apps/backend/src/worker/objects/customers/autumn/map.test.ts b/apps/backend/src/worker/objects/customers/autumn/map.test.ts index 957058aee..d38230f09 100644 --- a/apps/backend/src/worker/objects/customers/autumn/map.test.ts +++ b/apps/backend/src/worker/objects/customers/autumn/map.test.ts @@ -144,6 +144,7 @@ describe("Autumn plan → subscription", () => { currentPeriodEnd: "2026-12-01T09:20:00.000Z", cancelAtPeriodEnd: false, canceledAt: null, + cancellationReason: null, observedAt: OBSERVED, }) }) @@ -341,7 +342,33 @@ describe("Autumn plan → subscription", () => { expect(subOp(lapsing)).toMatchObject({ status: "active", mrrMinor: 300_000 }) }) - it("bills a card trial canceled before it converted nothing, from the plan's trial terms", () => { + it("reads a checkout never finished as abandoned, not as a plan that was canceled", () => { + const opened = SUB_ACME.started_at + const abandoned = { + ...SUB_ACME, + status: "expired", + canceled_at: null, + expires_at: opened + 3_600_000, + current_period_start: null, + current_period_end: null, + } + expect(subOp(abandoned)).toMatchObject({ + status: "canceled", + mrrMinor: 0, + cancelAtPeriodEnd: false, + cancellationReason: "checkout_abandoned", + }) + // Someone canceled it, it outlived any checkout, or it was a free plan: not a checkout. + expect(subOp({ ...abandoned, canceled_at: opened + 60_000 })).toMatchObject({ + cancellationReason: null, + }) + expect(subOp({ ...abandoned, expires_at: opened + 2 * DAY })).toMatchObject({ + cancellationReason: null, + }) + expect(subOp({ ...abandoned, plan_id: "free" })).toMatchObject({ cancellationReason: null }) + }) + + it("keeps a canceled card trial's price, from the plan's trial terms", () => { // Autumn clears `trial_ends_at` once the trial is over; the billing period was the trial's. const trialPlan = { ...PLAN_ENTERPRISE, free_trial: { duration_length: 14, duration_type: "day" } } const started = SUB_GLOBEX_TRIAL.started_at @@ -355,8 +382,10 @@ describe("Autumn plan → subscription", () => { } expect(subOp(canceled)).toMatchObject({ status: "canceled", - mrrMinor: 0, + mrrMinor: 300_000, billsByUsage: false, + // It ran to the end of the trial it asked to leave. + cancelAtPeriodEnd: true, trialEndsAt: new Date(started + 14 * DAY + 70 * 60_000).toISOString(), }) // A month's trial ends on the calendar: Jan 31 + 1 month is Feb 28, not 31 days later. @@ -370,7 +399,7 @@ describe("Autumn plan → subscription", () => { expires_at: Date.UTC(2026, 1, 28, 12, 10), } expect(subOp(monthTrial)).toMatchObject({ - mrrMinor: 0, + mrrMinor: 300_000, trialEndsAt: new Date(Date.UTC(2026, 1, 28, 13, 10)).toISOString(), }) const pastTrial = { ...monthTrial, expires_at: Date.UTC(2026, 2, 2, 12) } diff --git a/apps/backend/src/worker/objects/customers/autumn/map.ts b/apps/backend/src/worker/objects/customers/autumn/map.ts index 026f61d0e..d4b4bdb0f 100644 --- a/apps/backend/src/worker/objects/customers/autumn/map.ts +++ b/apps/backend/src/worker/objects/customers/autumn/map.ts @@ -45,6 +45,7 @@ import type { UpsertAccount, UpsertSubscription, } from "@hazel/domain/customers" +import { CHECKOUT_ABANDONED } from "@hazel/domain/customers" import type { Types } from "effect" import { addDays, DAY_MS, dayOf, startOfDay } from "../time" import { @@ -311,6 +312,30 @@ const trialEndOf = (subscription: AutumnSubscription, plan: AutumnPlan | undefin } } +/** Whether a plan bills anything: a price, usage, or prepaid units. */ +const isPaidPlan = (subscription: AutumnSubscription, plan: AutumnPlan | undefined, currency: string) => + subscriptionMrr(subscription, plan, currency) > 0 || + billsOutsideMrr(subscription.plan_id, plan, []) || + sellsPrepaid(plan) + +/** + * A checkout never finished. Autumn inserts a paid plan as pending when checkout opens, and expires + * it with the session (a day at most): ended, no cancellation asked for, no processor subscription. + */ +const abandonedCheckout = ( + subscription: AutumnSubscription, + plan: AutumnPlan | undefined, + currency: string, +) => + subscription.status === "expired" && + subscription.canceled_at == null && + subscription.current_period_start == null && + subscription.current_period_end == null && + subscription.started_at != null && + subscription.expires_at != null && + subscription.expires_at - subscription.started_at <= DAY_MS && + isPaidPlan(subscription, plan, currency) + /** * A batch of plans, read at `observedAt` (ingest drops a read older than one it applied). Skipped: * an entity-scoped plan, a `scheduled` one, and a row whose customer Autumn did not name. @@ -323,12 +348,15 @@ const trialEndOf = (subscription: AutumnSubscription, plan: AutumnPlan | undefin * its period end, and Autumn marks the current one canceled. It is a plan change, not a * cancellation, so the current plan keeps `cancelAtPeriodEnd` false. The free plan Autumn * schedules on a cancel (its group's `auto_enable` one) is no downgrade: the plan is canceling. - * - **Never billed**: a plan no processor ever billed (no billing period: a trial that lapsed - * unconverted, ended or still live until Autumn converts it), or one that ended within its trial - * ({@link trialEndOf}, sent as `trialEndsAt`: a card trial canceled before it converted has a - * billing period, the trial's), is MRR 0, so its account reads as a lead rather than a paying or - * churned customer. A customer Autumn gave no trial (one already used) that ends within the - * trial's length reads so too. + * - **Never billed**: a plan no processor ever held (no billing period: a trial that lapsed + * unconverted, ended or still live until Autumn converts it) is MRR 0, so its account reads as a + * lead rather than a paying or churned customer. + * - **Abandoned checkouts** ({@link abandonedCheckout}) are such a plan, sent with the reason + * `CHECKOUT_ABANDONED`: the plan never started, and the timeline says so. + * - **Canceled card trials**: a plan that ended within its trial ({@link trialEndOf}, sent as + * `trialEndsAt`) with a billing period, the trial's, keeps its price, and core reads it as a + * customer who left (`canceledCardTrial`). A customer Autumn gave no trial (one already used) that + * ends within the trial's length reads so too. * - **Converted trials**: Autumn clears a converted trial's `trial_ends_at`; a live plan whose * billing period starts at or after the trial's end ({@link trialEndOf}) sends that end as * `trialEndsAt`, so the account's `customerSince` and MRR history leave the trial days out. A @@ -365,14 +393,10 @@ export const subscriptionOps = ( subscriptions.flatMap((subscription) => { const plan = planOf(subscription) // Prepaid units are priced from balances a scheduled plan has none of yet. - const paid = - subscriptionMrr(subscription, plan, currency) > 0 || - billsOutsideMrr(subscription.plan_id, plan, []) || - sellsPrepaid(plan) return subscription.status === "scheduled" && base(subscription) && (subscription.auto_enable ?? plan?.auto_enable) !== true && - paid + isPaidPlan(subscription, plan, currency) ? [slotOf(customerOf(subscription), plan)] : [] }), @@ -409,7 +433,9 @@ export const subscriptionOps = ( const expired = status === "canceled" const trialEnd = subscription.trial_ends_at == null ? trialEndOf(subscription, plan) : null const endedAt = subscription.expires_at ?? subscription.canceled_at - const endedInTrial = expired && trialEnd !== null && endedAt != null && endedAt <= trialEnd + const abandoned = abandonedCheckout(subscription, plan, currency) + const endedInTrial = + !abandoned && expired && trialEnd !== null && endedAt != null && endedAt <= trialEnd // Live and billed for a period from its trial's end on: the trial converted (Autumn cleared // `trial_ends_at`). The first paid period's start is the exact end, a later one's the terms'. const periodStart = subscription.current_period_start @@ -426,9 +452,8 @@ export const subscriptionOps = ( // processor's subscription (its `subscriptions` row, `getApiSubscription`): a billed plan whose // mirror row is missing reads as never billed too. const neverBilled = - endedInTrial || - (subscription.current_period_end == null && - (expired || (status === "active" && plan?.free_trial != null))) + subscription.current_period_end == null && + (expired || (status === "active" && plan?.free_trial != null)) const balances = expired ? [] : (options.balances ?? []) const mrrMinor = neverBilled ? 0 @@ -456,12 +481,21 @@ export const subscriptionOps = ( trialEndsAt: isoOf(endedInTrial ? trialEnd : (convertedAt ?? subscription.trial_ends_at)), currentPeriodEnd: isoOf(subscription.current_period_end ?? subscription.expires_at), // A cancellation Autumn has recorded but not yet carried out: the plan runs to `expires_at`. - cancelAtPeriodEnd: canceling, + // A card trial that ran out its period keeps it, so its churn dates from the end. + cancelAtPeriodEnd: + canceling || + (endedInTrial && + !neverBilled && + subscription.canceled_at != null && + endedAt != null && + endedAt > subscription.canceled_at), canceledAt: expired ? isoOf(subscription.canceled_at ?? subscription.expires_at) : canceling ? isoOf(subscription.canceled_at) : null, + // Sent on every plan: a live one reusing an abandoned checkout's id clears it. + cancellationReason: abandoned ? CHECKOUT_ABANDONED : null, observedAt: options.observedAt, } // Unpriced, the op leaves the stored MRR as it is. diff --git a/apps/backend/src/worker/objects/customers/compute-loop.test.ts b/apps/backend/src/worker/objects/customers/compute-loop.test.ts index 748d6d8d9..3708df55f 100644 --- a/apps/backend/src/worker/objects/customers/compute-loop.test.ts +++ b/apps/backend/src/worker/objects/customers/compute-loop.test.ts @@ -1519,6 +1519,62 @@ describe("Customers compute and sync loop", () => { onNoMatch: "create", }) + it("announces a card trial canceled before converting as a churn, with no MRR lost", () => + run( + Effect.gen(function* () { + const world = yield* makeCustomersWorld + yield* world.ingest("clerk", [org("org_1")]) + yield* world.ingest("stripe", [ + { + ...subscription(5), + status: "canceled", + trialEndsAt: new Date(NOW.getTime() + 9 * DAY).toISOString(), + canceledAt: new Date(NOW.getTime() - DAY).toISOString(), + paymentMethod: { brand: "visa", last4: "4242", expMonth: 1, expYear: 2030 }, + }, + ]) + yield* world.object.run(runCompute(NOW)).pipe(Effect.orDie) + expect( + world.rows<{ lifecycleStage: string; mrrMinor: number }>( + `SELECT lifecycleStage, mrrMinor FROM customer_accounts`, + ), + ).toEqual([{ lifecycleStage: "churned", mrrMinor: 0 }]) + expect( + world.rows<{ reason: string }>( + `SELECT reason FROM customer_signals WHERE template = 'churned'`, + ), + ).toEqual([{ reason: "Canceled during the trial 1 day ago" }]) + expect(world.rows(`SELECT id FROM customer_mrr_movements`)).toEqual([]) + }), + )) + + it("replaces a plan's start and cancel with an abandoned checkout once Autumn shows it", () => + run( + Effect.gen(function* () { + const world = yield* makeCustomersWorld + yield* world.ingest("clerk", [org("org_1")]) + const ended: UpsertSubscription = { + ...subscription(1), + status: "canceled", + mrrMinor: 0, + canceledAt: new Date(NOW.getTime() - DAY).toISOString(), + } + const titles = () => + world + .rows<{ title: string }>( + `SELECT title FROM customer_events WHERE type LIKE 'subscription.%' ORDER BY title`, + ) + .map((row) => row.title) + yield* world.ingest("autumn", [ended]) + expect(titles()).toEqual(["Canceled Team", "Started Team"]) + const abandoned = { ...ended, cancellationReason: "checkout_abandoned" } + yield* world.ingest("autumn", [abandoned]) + expect(titles()).toEqual(["Abandoned checkout for Team"]) + yield* world.ingest("autumn", [abandoned]) + expect(titles()).toEqual(["Abandoned checkout for Team"]) + }), + )) + it("announces a churn once, and again only after a payment", () => run( Effect.gen(function* () { diff --git a/apps/backend/src/worker/objects/customers/evaluate.test.ts b/apps/backend/src/worker/objects/customers/evaluate.test.ts index 9d625c0ad..8d1f7d5b4 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.test.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.test.ts @@ -656,6 +656,11 @@ describe("signal evaluation", () => { // A trial it canceled before converting paid nothing. const trial = { ...resubscribed, trialEndsAt: ago(1) } expect(run("churned", { ...churned, subscriptions: [trial] })).toEqual(noMatch) + // With a card on file it was a customer: a new trial canceled is a new churn. + const paymentMethod = { brand: "visa", last4: "4242", expMonth: 1, expYear: 2030 } + expect(run("churned", { ...churned, subscriptions: [{ ...trial, paymentMethod }] })._tag).toBe( + "Match", + ) }) it("churned: a churn dated back to its failed invoice is announced from the plan's end", () => { diff --git a/apps/backend/src/worker/objects/customers/evaluate.ts b/apps/backend/src/worker/objects/customers/evaluate.ts index 55056a65f..45406cddb 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.ts @@ -28,6 +28,7 @@ import { type AccountFacts, activeUsersIn, billed, + canceledCardTrial, DERIVED_METRICS, formatMoney, type MetricPoint, @@ -37,6 +38,7 @@ import { renewedBetween, rollingActiveSeries, seriesOf, + wasCustomer, } from "./facts" import { addDays, DAY_MS, dayOf, daysBetween, daysSince } from "./time" @@ -712,7 +714,7 @@ const churned = sub.currentPeriodEnd <= org.now ? sub.currentPeriodEnd : sub.canceledAt, - paid: pays(sub), + paid: wasCustomer(sub), }, ], ) @@ -748,7 +750,7 @@ const churned = const currency = churn?.currency ?? org.currency return { step: 0, - reason: `${lost > 0 ? `Lost ${formatMoney(lost, currency)}/mo ` : ""}${days === 0 ? "today" : `${plural(days, "day")} ago`}`, + reason: `${lost > 0 ? `Lost ${formatMoney(lost, currency)}/mo ` : last !== undefined && canceledCardTrial(last) ? "Canceled during the trial " : ""}${days === 0 ? "today" : `${plural(days, "day")} ago`}`, evidence: { _tag: "delta", step: 0, @@ -776,11 +778,11 @@ export const missingSources = (template: SignalTemplate, org: OrgFacts): Readonl return required.length === 0 || required.some((provider) => org.connected.has(provider)) ? [] : required } -/** Every plan it held ended and none was ever paid for: it left before becoming a customer. */ +/** Every plan it held ended with no payment or card: it left before becoming a customer. */ const leftUnpaid = (facts: AccountFacts) => facts.stage === "lead" && facts.subscriptions.length > 0 && - facts.subscriptions.every((sub) => sub.status === "canceled" && !pays(sub)) + facts.subscriptions.every((sub) => sub.status === "canceled" && !wasCustomer(sub)) export const evaluate = (rule: RuleInput, facts: AccountFacts, org: OrgFacts): Evaluation => { // Churn is a customer's last entry: no other rule evaluates it after. diff --git a/apps/backend/src/worker/objects/customers/facts.ts b/apps/backend/src/worker/objects/customers/facts.ts index 1609e71c1..6926f4b10 100644 --- a/apps/backend/src/worker/objects/customers/facts.ts +++ b/apps/backend/src/worker/objects/customers/facts.ts @@ -229,22 +229,35 @@ const unconverted = (sub: schema.CustomerSubscription) => export const pays = (sub: schema.CustomerSubscription) => (sub.mrrMinor > 0 || sub.billsByUsage) && !unconverted(sub) +/** + * A trial taken with a card and canceled before it converted: a customer who left, though it never + * paid. Autumn prices only a trial a processor held; a Stripe one needs a card on file. + */ +export const canceledCardTrial = (sub: schema.CustomerSubscription) => + unconverted(sub) && + (sub.mrrMinor > 0 || sub.billsByUsage) && + (sub.provider !== "stripe" || sub.paymentMethod !== null) + +/** It was a customer on this plan: it paid for it, or gave a card for its trial. */ +export const wasCustomer = (sub: schema.CustomerSubscription) => pays(sub) || canceledCardTrial(sub) + /** Every plan that paid has ended, and no trial is running: a churned customer, unless it still owes. */ export const endedPaying = (subscriptions: ReadonlyArray) => subscriptions.some((sub) => sub.status === "canceled" && pays(sub)) && !subscriptions.some((sub) => sub.status === "trialing" || (billed(sub) && pays(sub))) /** - * It paid an invoice, or started a paid plan, after the churn announced at `since` and before its - * plans ended at `endedAt`: this is a new churn. Settling an old invoice after the end is not one. + * It paid an invoice, or started a paid plan or card trial, after the churn announced at `since` + * and before its plans ended at `endedAt`: this is a new churn. Settling an old invoice after the + * end is not one. */ export const renewedBetween = (facts: AccountFacts, since: Date, endedAt: Date) => facts.paymentsSinceChurn.some((paidAt) => paidAt > since && paidAt <= endedAt) || facts.subscriptions.some((sub) => { - const paidFrom = sub.trialEndsAt ?? sub.startedAt + const paidFrom = canceledCardTrial(sub) ? sub.startedAt : (sub.trialEndsAt ?? sub.startedAt) return ( sub.status !== "trialing" && - pays(sub) && + wasCustomer(sub) && paidFrom !== null && paidFrom > since && paidFrom <= endedAt diff --git a/apps/backend/src/worker/objects/customers/ingest-live.ts b/apps/backend/src/worker/objects/customers/ingest-live.ts index 23318943c..9f077c8e3 100644 --- a/apps/backend/src/worker/objects/customers/ingest-live.ts +++ b/apps/backend/src/worker/objects/customers/ingest-live.ts @@ -32,6 +32,7 @@ */ import { Database, SQLite, schema } from "@hazel/db" import { + CHECKOUT_ABANDONED, type ConnectionConfig, type CustomerProvider, type CustomerSource, @@ -1394,12 +1395,22 @@ const make = Effect.gen(function* () { externalId: `ingest:${type}:${provider}:${op.externalId}${type === "subscription.plan_changed" ? `:${op.planName}:${mrrMinor}` : ""}`, }) const observedAt = toDate(op.observedAt) + const abandoned = op.cancellationReason === CHECKOUT_ABANDONED + const abandonedEvent = event( + "subscription.checkout_abandoned", + `Abandoned checkout for ${planLabel(op.planName)}`, + values.canceledAt, + ) if (Option.isNone(existing)) { const [row] = yield* db.run( SQLite.insertInto(schema.customerSubscriptionsTable) .values({ provider, externalId: op.externalId, ...values, observedAt }) .returning("id"), ) + if (abandoned) { + yield* abandonedEvent + return outcome.created(row.id) + } yield* event("subscription.started", `Started ${planLabel(op.planName)}`, values.startedAt, { mrrMinor, status: op.status, @@ -1443,6 +1454,21 @@ const make = Effect.gen(function* () { } as never) .where(($) => [$.id.eq(sub.id)]), ) + if (abandoned) { + // Recorded as started and canceled before Hazel could tell: it never started. + if (sub.cancellationReason !== CHECKOUT_ABANDONED) { + for (const type of ["subscription.started", "subscription.canceled"]) { + yield* db.run( + SQLite.deleteFrom(schema.customerEventsTable).where(($) => [ + $.provider.eq(provider), + $.externalId.eq(`ingest:${type}:${provider}:${op.externalId}`), + ]), + ) + } + yield* abandonedEvent + } + return outcome.updated(sub.id) + } if (sub.planName !== op.planName || sub.mrrMinor !== mrrMinor) { if (op.status !== "canceled" && sub.status !== "trialing") { yield* event( diff --git a/apps/backend/src/worker/objects/customers/snapshot.ts b/apps/backend/src/worker/objects/customers/snapshot.ts index 274b493e6..e20cbdfb0 100644 --- a/apps/backend/src/worker/objects/customers/snapshot.ts +++ b/apps/backend/src/worker/objects/customers/snapshot.ts @@ -35,6 +35,7 @@ import { pays, type UnpaidEnd, unpaidEndOf, + wasCustomer, } from "./facts" import { inList, isActive } from "./sql" import { addDays, DAY_MS, dayOf, dayRange, daysBetween } from "./time" @@ -236,7 +237,7 @@ export const rollupAccount = (input: { : trialing.length > 0 ? "trialing" : account.customerSince !== null || - subscriptions.some((sub) => pays(sub) && sub.status === "canceled") + subscriptions.some((sub) => wasCustomer(sub) && sub.status === "canceled") ? owing ? "past_due" : "churned" @@ -357,10 +358,10 @@ export const billsNow = (sub: schema.CustomerSubscription) => billed(sub) && pay * Whose subscriptions count for one account's MRR, from its subscriptions (any status): Autumn once * its connection finished its first import (until then its data is partial) and it bills the * account now (`billsNow`), else Stripe when it does (a customer Autumn does not know, or billed in - * Stripe outside it). With neither billing now, the source stored last run (`stored`), so a payer - * ending in one provider churns there rather than switching; without one, the one that paid - * (Stripe's first), else Stripe's. An account with only one provider's subscriptions keeps that - * one either way, so an Autumn disconnect does not zero its MRR. + * Stripe outside it). With neither billing now, Autumn when only it knows the customer held a plan + * (`wasCustomer`), else the source stored last run (`stored`), so a payer ending in one provider + * churns there rather than switching, else Stripe's. An account with only one provider's + * subscriptions keeps that one either way, so an Autumn disconnect does not zero its MRR. */ export const billingProviderOf = ( autumnReady: boolean, @@ -373,8 +374,8 @@ export const billingProviderOf = ( if (stripe.length === 0) return "autumn" if (autumnReady && autumn.some(billsNow)) return "autumn" if (stripe.some(billsNow)) return "stripe" - if (stored !== null) return stored - return autumnReady && autumn.some(pays) && !stripe.some(pays) ? "autumn" : "stripe" + if (autumnReady && autumn.some(wasCustomer) && !stripe.some(wasCustomer)) return "autumn" + return stored ?? "stripe" } /** diff --git a/apps/web-foldkit/src/page/customers/detail/billing-tab.ts b/apps/web-foldkit/src/page/customers/detail/billing-tab.ts index fa8f31c5e..a14cc8d81 100644 --- a/apps/web-foldkit/src/page/customers/detail/billing-tab.ts +++ b/apps/web-foldkit/src/page/customers/detail/billing-tab.ts @@ -1,4 +1,5 @@ import type * as Customers from "@hazel/domain/customers" +import { CHECKOUT_ABANDONED } from "@hazel/domain/customers" import { Option } from "effect" import * as AsyncData from "foldkit/asyncData" import type { Html, HtmlBuilder } from "foldkit/html" @@ -142,7 +143,11 @@ const subscriptionCard = ( overdue: Customers.Invoice | null, ): Html => { const now = new Date(context.nowMs) - const [statusLabel, statusIntent] = SUBSCRIPTION_STATUS[subscription.status] + const abandoned = + subscription.status === "canceled" && subscription.cancellationReason === CHECKOUT_ABANDONED + const [statusLabel, statusIntent] = abandoned + ? (["Checkout abandoned", "outline"] as const) + : SUBSCRIPTION_STATUS[subscription.status] const date = (value: Customers.Subscription["startedAt"]) => value === null ? "—" : formatDate(value, { now, withYear: true }) return h.section( @@ -194,12 +199,14 @@ const subscriptionCard = ( [ fact(h, "Interval", INTERVAL_LABEL[subscription.interval]), fact(h, "Seats", String(subscription.quantity)), - fact(h, "Current period ends", date(subscription.currentPeriodEnd)), + fact(h, "Current period ends", abandoned ? "—" : date(subscription.currentPeriodEnd)), fact( h, overdue === null ? "Started" : "Amount overdue", overdue === null - ? date(subscription.startedAt) + ? abandoned + ? "—" + : date(subscription.startedAt) : h.span( [h.Class("text-danger-subtle-fg")], [ @@ -222,10 +229,10 @@ const subscriptionCard = ( fact(h, "Trial ends", date(subscription.trialEndsAt)), fact( h, - "Canceled", + abandoned ? "Abandoned" : "Canceled", subscription.canceledAt === null ? "—" - : `${date(subscription.canceledAt)}${subscription.cancellationReason ? ` · ${subscription.cancellationReason}` : ""}`, + : `${date(subscription.canceledAt)}${!abandoned && subscription.cancellationReason ? ` · ${subscription.cancellationReason}` : ""}`, ), ], ), diff --git a/packages/domain/src/customers/enums.ts b/packages/domain/src/customers/enums.ts index eb0d730b4..c3fff4812 100644 --- a/packages/domain/src/customers/enums.ts +++ b/packages/domain/src/customers/enums.ts @@ -27,6 +27,9 @@ export const SubscriptionStatus = Schema.Literals([ ]) export type SubscriptionStatus = typeof SubscriptionStatus.Type +/** A canceled subscription's `cancellationReason` when its checkout was never finished: it never started. */ +export const CHECKOUT_ABANDONED = "checkout_abandoned" + export const BillingInterval = Schema.Literals(["month", "year", "other"]) export type BillingInterval = typeof BillingInterval.Type From b7e00d367ff8ee14664ad9ae8689792a060fed4d Mon Sep 17 00:00:00 2001 From: JeremyFunk Date: Mon, 23 Nov 2026 14:44:53 +0100 Subject: [PATCH 4/4] fix(customers): a plan reusing an abandoned checkout's id shows as started --- .../objects/customers/compute-loop.test.ts | 3 ++ .../worker/objects/customers/ingest-live.ts | 46 +++++++++++-------- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/apps/backend/src/worker/objects/customers/compute-loop.test.ts b/apps/backend/src/worker/objects/customers/compute-loop.test.ts index 3708df55f..b7162151f 100644 --- a/apps/backend/src/worker/objects/customers/compute-loop.test.ts +++ b/apps/backend/src/worker/objects/customers/compute-loop.test.ts @@ -1572,6 +1572,9 @@ describe("Customers compute and sync loop", () => { expect(titles()).toEqual(["Abandoned checkout for Team"]) yield* world.ingest("autumn", [abandoned]) expect(titles()).toEqual(["Abandoned checkout for Team"]) + // A live plan reusing its id did start. + yield* world.ingest("autumn", [{ ...subscription(1), cancellationReason: null }]) + expect(titles()).toEqual(["Started Team"]) }), )) diff --git a/apps/backend/src/worker/objects/customers/ingest-live.ts b/apps/backend/src/worker/objects/customers/ingest-live.ts index 9f077c8e3..704584521 100644 --- a/apps/backend/src/worker/objects/customers/ingest-live.ts +++ b/apps/backend/src/worker/objects/customers/ingest-live.ts @@ -1401,16 +1401,7 @@ const make = Effect.gen(function* () { `Abandoned checkout for ${planLabel(op.planName)}`, values.canceledAt, ) - if (Option.isNone(existing)) { - const [row] = yield* db.run( - SQLite.insertInto(schema.customerSubscriptionsTable) - .values({ provider, externalId: op.externalId, ...values, observedAt }) - .returning("id"), - ) - if (abandoned) { - yield* abandonedEvent - return outcome.created(row.id) - } + const startEvents = Effect.gen(function* () { yield* event("subscription.started", `Started ${planLabel(op.planName)}`, values.startedAt, { mrrMinor, status: op.status, @@ -1428,6 +1419,26 @@ const make = Effect.gen(function* () { null, ) } + }) + const dropEvents = (types: ReadonlyArray) => + Effect.forEach( + types, + (type) => + db.run( + SQLite.deleteFrom(schema.customerEventsTable).where(($) => [ + $.provider.eq(provider), + $.externalId.eq(`ingest:${type}:${provider}:${op.externalId}`), + ]), + ), + { discard: true }, + ) + if (Option.isNone(existing)) { + const [row] = yield* db.run( + SQLite.insertInto(schema.customerSubscriptionsTable) + .values({ provider, externalId: op.externalId, ...values, observedAt }) + .returning("id"), + ) + yield* abandoned ? abandonedEvent : startEvents return outcome.created(row.id) } const sub = existing.value @@ -1457,18 +1468,17 @@ const make = Effect.gen(function* () { if (abandoned) { // Recorded as started and canceled before Hazel could tell: it never started. if (sub.cancellationReason !== CHECKOUT_ABANDONED) { - for (const type of ["subscription.started", "subscription.canceled"]) { - yield* db.run( - SQLite.deleteFrom(schema.customerEventsTable).where(($) => [ - $.provider.eq(provider), - $.externalId.eq(`ingest:${type}:${provider}:${op.externalId}`), - ]), - ) - } + yield* dropEvents(["subscription.started", "subscription.canceled"]) yield* abandonedEvent } return outcome.updated(sub.id) } + if (sub.cancellationReason === CHECKOUT_ABANDONED) { + // Its id now names a plan that did start. + yield* dropEvents(["subscription.checkout_abandoned"]) + yield* startEvents + return outcome.updated(sub.id) + } if (sub.planName !== op.planName || sub.mrrMinor !== mrrMinor) { if (op.status !== "canceled" && sub.status !== "trialing") { yield* event(