Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions apps/backend/src/worker/objects/customers/autumn/map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ describe("Autumn plan → subscription", () => {
currentPeriodEnd: "2026-12-01T09:20:00.000Z",
cancelAtPeriodEnd: false,
canceledAt: null,
cancellationReason: null,
observedAt: OBSERVED,
})
})
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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) }
Expand Down
66 changes: 50 additions & 16 deletions apps/backend/src/worker/objects/customers/autumn/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)]
: []
}),
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down
59 changes: 59 additions & 0 deletions apps/backend/src/worker/objects/customers/compute-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,65 @@ 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"])
// A live plan reusing its id did start.
yield* world.ingest("autumn", [{ ...subscription(1), cancellationReason: null }])
expect(titles()).toEqual(["Started Team"])
}),
))

it("announces a churn once, and again only after a payment", () =>
run(
Effect.gen(function* () {
Expand Down
45 changes: 45 additions & 0 deletions apps/backend/src/worker/objects/customers/evaluate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,38 @@ 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, 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",
)
})

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 = {
Expand Down Expand Up @@ -624,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", () => {
Expand Down Expand Up @@ -937,6 +974,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",
Expand Down
15 changes: 13 additions & 2 deletions apps/backend/src/worker/objects/customers/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
type AccountFacts,
activeUsersIn,
billed,
canceledCardTrial,
DERIVED_METRICS,
formatMoney,
type MetricPoint,
Expand All @@ -37,6 +38,7 @@ import {
renewedBetween,
rollingActiveSeries,
seriesOf,
wasCustomer,
} from "./facts"
import { addDays, DAY_MS, dayOf, daysBetween, daysSince } from "./time"

Expand All @@ -51,6 +53,7 @@ export interface RuleInput {

export type NonMatchReason =
| "Churned"
| "Plan ended"
| "Not covered by Needs attention"
| "Out of scope"
| "Missing data source"
Expand Down Expand Up @@ -711,7 +714,7 @@ const churned =
sub.currentPeriodEnd <= org.now
? sub.currentPeriodEnd
: sub.canceledAt,
paid: pays(sub),
paid: wasCustomer(sub),
},
],
)
Expand Down Expand Up @@ -747,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,
Expand Down Expand Up @@ -775,9 +778,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 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" && !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.
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")
Expand Down
Loading