From 298104dca7e608b6d3132a0734fc55a56fc3f453 Mon Sep 17 00:00:00 2001 From: Mehar Khanna Date: Sun, 15 Nov 2026 21:59:38 -0500 Subject: [PATCH] Billing: a cancel during Pro's free trial ends the trial and Pro at once Stripe's portal cancels at the period end, which in a trial is the trial's end, so a cancelled trial kept Pro until then. The webhook now sees a trialing GenClass subscription set to cancel by its trial's end (cancel_at with flexible billing, or cancel_at_period_end), cancels it in Stripe right away and writes Free. Paid plans are unchanged: cancelled in the portal, they run to the end of the paid month. The portal's own cancel mode stays at_period_end, because it is one setting for every subscription and "immediately" would end paid plans at once too. Co-Authored-By: Claude Opus 5.5 --- scripts/stripe-setup.mjs | 7 +- telemetry-worker/README.md | 7 +- telemetry-worker/src/billing-pages.ts | 2 +- telemetry-worker/src/stripe.ts | 26 ++- telemetry-worker/test/project-plans.test.ts | 178 +++++++++++++++++++- 5 files changed, 214 insertions(+), 6 deletions(-) diff --git a/scripts/stripe-setup.mjs b/scripts/stripe-setup.mjs index 2fe730a9..9910df1f 100644 --- a/scripts/stripe-setup.mjs +++ b/scripts/stripe-setup.mjs @@ -30,8 +30,9 @@ // the live secret. An existing endpoint keeps its secret, since Stripe shows a secret only once (--new-webhook // deletes GenClass's endpoint, the one with that exact URL and description, and makes a new one); // 4. its own Billing Portal configuration (metadata genclass=1, a headline naming GenClass): cancel at the end of the -// period, update the card, invoices, and change the email or tax id on the GenClass customer (no address: GenClass -// has no use for one). It offers no plan switch: a subscription sold through Managed Payments cannot take another +// period (the worker's webhook ends a trial cancelled there at once: telemetry-worker/src/stripe.ts +// trialCancelled), update the card, invoices, and change the email or tax id on the GenClass customer (no address: +// GenClass has no use for one). It offers no plan switch: a subscription sold through Managed Payments cannot take another // plan's price, so the billing page switches plans with a new Checkout (telemetry-worker/src/billing.ts). To find // it the script lists the non-default configurations (is_default=false), reading their settings and changing none // but its own: the account's default configuration is never read or changed, and GenClass's is never made the @@ -336,6 +337,8 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe customer_update: { enabled: true, allowed_updates: ["email", "tax_id"] }, invoice_history: { enabled: true }, payment_method_update: { enabled: true }, + // one mode for every subscription: "immediately" would end paid plans at once too, so a paid plan runs to the end + // of its paid month, and the worker's webhook ends a trial cancelled here at once (src/stripe.ts trialCancelled) subscription_cancel: { enabled: true, mode: "at_period_end", diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index a487a2b9..54577cce 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -543,6 +543,9 @@ subscription bought per project under version 4 still covers its own app (never Pro. Free covers one app (`free_projects` past it). Every new app of an account opens its plan page once, a paying account's too: "Continue with Pro" (`POST /api/billing/projects//continue` writes `plan_chosen`). Pro's 3-day trial (card up front, once per account) starts on the account's first Checkout (`src/billing.ts` trialFor). +A cancel during the trial ends the trial and Pro at once (the owner, 2026-11-15): the portal schedules it for the +trial's end, and the webhook then cancels the subscription in Stripe and writes Free (`src/stripe.ts` trialCancelled). +A paid plan cancelled in the portal still runs to the end of its paid month. **The genclass command is Pro's** (the owner's "let's make the entire CLI paid"): a CLI session of an account with no plan (paid, trialing, a grant) and no active place in a paying team gets 402 `needs_pro` from every `/api/cli` route but the overview and the account, which carry `cli` (`src/cli.ts` cliPaid). Nothing is locked for a browser @@ -814,7 +817,9 @@ does about it. payment methods, billing address); the Customer Portal can be offered too; `subscription.default_payment_method` cannot be changed through the API for these subscriptions, only by the buyer in the portal ([how it works](https://docs.stripe.com/payments/managed-payments/how-it-works)). GenClass's portal keeps card, - invoices, email, tax id and cancel at period end. Cancelling with `prorate` and `invoice_now` would put the credit + invoices, email, tax id and cancel at period end. The portal's cancel mode is one setting for every + subscription, so it stays at period end for paid plans; a trial cancelled there is ended at once by the webhook + (`src/stripe.ts` trialCancelled). Cancelling with `prorate` and `invoice_now` would put the credit for unused time on the customer's balance for future invoices; both default to false ([cancel](https://docs.stripe.com/billing/subscriptions/cancel)), and GenClass sends neither: it refunds the unused time to the card instead (a refund can be partial and goes to the payment method charged: diff --git a/telemetry-worker/src/billing-pages.ts b/telemetry-worker/src/billing-pages.ts index 74592c1c..9cdf454e 100644 --- a/telemetry-worker/src/billing-pages.ts +++ b/telemetry-worker/src/billing-pages.ts @@ -148,7 +148,7 @@ function statusLine(v: BillingView, plan: Plan): string { return `You are on the ${name} plan until ${day(b.current_period_end)}. It is cancelled and will not renew; you can resume it in Manage billing before then.`; } if (b.subscription_status === "trialing") { - return `You are on the ${name} plan, in a trial until ${day(b.current_period_end)}. When it ends your card is charged for the first month (${esc(priceText(plan))}), unless you cancel before in Manage billing.`; + return `You are on the ${name} plan, in a trial until ${day(b.current_period_end)}. When it ends your card is charged for the first month (${esc(priceText(plan))}). Cancel in Manage billing before then and nothing is charged; ${esc(plan.name)} then ends at once.`; } if (plan.per_seat === true && v.access.seats !== null) { const n = v.access.seats; diff --git a/telemetry-worker/src/stripe.ts b/telemetry-worker/src/stripe.ts index 55813658..cd275f50 100644 --- a/telemetry-worker/src/stripe.ts +++ b/telemetry-worker/src/stripe.ts @@ -40,7 +40,9 @@ // has never had a subscription (billing.ts checkoutProject), never on a switch or a later one. Every Checkout still // collects a payment method up front (payment_method_collection "always"), and a subscription in Stripe's trialing // status that the account has not been granted yet counts only with a saved payment method (cardOnFile); Stripe -// charges the first month when the trial ends unless it is cancelled before. +// charges the first month when the trial ends unless it is cancelled before. A cancel during the trial ends it at +// once: Stripe's portal schedules it for the trial's end, and the webhook then cancels the subscription now +// (trialCancelled). A paid subscription cancelled in the portal still runs to the end of its paid month. // - One subscription per account. Checkout asks Stripe (not the database, which a late webhook leaves behind) whether // the customer already has one: the same plan is refused, the other plan is a switch (a Checkout whose subscription // carries metadata genclass_switch_from naming the one it replaces); an account's older unpaid Checkout pages are @@ -800,6 +802,20 @@ export function cardOnFile(sub: Obj): boolean { return !!(idOf(sub?.default_payment_method) ?? idOf(sub?.default_source) ?? idOf(c?.invoice_settings?.default_payment_method) ?? idOf(c?.default_source)); } +/** + * A subscription in its free trial that is set to cancel by the end of that trial: Stripe's portal (flexible billing + * mode) sets cancel_at to the period end, which in a trial is the trial's end, and an older integration sets + * cancel_at_period_end. GenClass ends such a trial at once instead of letting it run out (the owner, 2026-11-15). A + * cancel set for a later date (after a paid month, by hand in the Stripe dashboard) is left to Stripe, and so is any + * subscription past its trial: a paid plan cancelled in the portal still runs to the end of its paid month. Exported + * for tests. + */ +export function trialCancelled(sub: Obj): boolean { + if (sub?.status !== "trialing") return false; + if (sub?.cancel_at_period_end === true) return true; + return typeof sub?.cancel_at === "number" && typeof sub?.trial_end === "number" && sub.cancel_at <= sub.trial_end; +} + /** The project a per-project subscription is for (its metadata genclass_project, billing/plans.json version 4), or null. */ export const projectOf = (s: Obj): string | null => { const v = s?.metadata?.genclass_project; @@ -856,6 +872,14 @@ export async function handleEvent(x: EventContext, event: Obj): Promise { + /** The trial's end, which is also its first period's end: 29 h 46 min after T0. */ + const END = 1_792_000_000; + const DAY_S = 86_400; + /** Stripe as it cancels a subscription: status canceled, ended now. */ + const ending = (s: ReturnType): typeof s.fetch => async (u, init = {}) => { + const r = await s.fetch(u, init); + const id = /\/v1\/subscriptions\/([^/?]+)$/.exec(new URL(u).pathname)?.[1]; + if (init.method === "DELETE" && id && s.subs.has(id)) s.subs.get(id)!.ended_at = Math.floor(now().getTime() / 1000); + return r; + }; + /** An account whose Pro subscription is in its trial (with the card Checkout took), as the webhook wrote it. */ + async function inTrial() { + const b = await buyer(); + const fetch = ending(b.s); + const sub: Record = { ...accountSub("sub_ada0000001", b.account.id, "cus_ada0000001", "trialing"), default_payment_method: "pm_card00000001", trial_start: END - 3 * DAY_S, trial_end: END }; + b.s.subs.set(sub.id, sub); + expect((await json(deliver(b.env, stripeEvent("customer.subscription.created", sub), fetch))).result).toBe("applied"); + const row = () => b.sql.rows("SELECT plan, subscription_id, subscription_status, cancel_at_period_end FROM accounts")[0]; + const cancels = () => b.s.calls.filter((c) => c.method === "DELETE").map((c) => c.url.pathname); + const pro = async () => json(call(b.env, "GET", "/api/billing/pro", { cookie: b.cookie, origin: null })); + const send = async (type: string, f = fetch) => { + const r = await deliver(b.env, stripeEvent(type, b.s.subs.get("sub_ada0000001")!), f); + return { status: r.status, body: await r.json() as any }; + }; + expect(row()).toEqual({ plan: "team", subscription_id: "sub_ada0000001", subscription_status: "trialing", cancel_at_period_end: 0 }); + return { ...b, fetch, sub, row, cancels, pro, send }; + } + + it("trialCancelled: a trialing subscription set to cancel by its trial's end; never one set to cancel later, or past its trial", () => { + const trial = { status: "trialing", trial_end: END, cancel_at_period_end: false, cancel_at: null }; + expect(trialCancelled(trial)).toBe(false); + // the portal with flexible billing: cancel_at at the period end, the trial's end + expect(trialCancelled({ ...trial, cancel_at: END })).toBe(true); + expect(trialCancelled({ ...trial, cancel_at: END - DAY_S })).toBe(true); + // classic billing (or the API): cancel_at_period_end + expect(trialCancelled({ ...trial, cancel_at_period_end: true })).toBe(true); + // a cancel set after a paid month (by hand in the Stripe dashboard): left to Stripe + expect(trialCancelled({ ...trial, cancel_at: END + 30 * DAY_S })).toBe(false); + // no trial end to compare with + expect(trialCancelled({ ...trial, trial_end: null, cancel_at: END })).toBe(false); + // past the trial, a paid plan cancelled in the portal runs to the end of its paid month: never this + for (const status of ["active", "past_due", "canceled", "incomplete", "unpaid"]) { + expect(trialCancelled({ ...trial, status, cancel_at: END }), status).toBe(false); + expect(trialCancelled({ ...trial, status, cancel_at_period_end: true }), status).toBe(false); + } + }); + + it("the trial's plan page says that a cancel ends Pro at once and charges nothing", async () => { + const t = await inTrial(); + const page = await text(call(t.env, "GET", "/account/billing", { cookie: t.cookie })); + expect(page).toContain("in a trial until"); + expect(page).toContain("Cancel in Manage billing before then and nothing is charged; Pro then ends at once."); + }); + + it("cancelled in Stripe's portal (flexible billing: cancel_at at the trial's end): Stripe cancels it now, the account is on Free, and no second trial", async () => { + const t = await inTrial(); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + expect(await t.pro()).toMatchObject({ pro: true, via: "plan" }); + t.sub.cancel_at = END; + expect(await t.send("customer.subscription.updated")).toEqual({ status: 200, body: { received: true, result: "applied" } }); + // cancelled at once (no proration, no final invoice: nothing was paid, so nothing is refunded), then read back + expect(t.cancels()).toEqual(["/v1/subscriptions/sub_ada0000001"]); + expect(new URLSearchParams(t.s.calls.find((c) => c.method === "DELETE")!.url.search).toString()).toBe(""); + expect(t.s.calls.slice(-2).map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["DELETE /v1/subscriptions/sub_ada0000001", "GET /v1/subscriptions/sub_ada0000001"]); + expect(t.s.calls.some((c) => c.url.pathname.startsWith("/v1/refunds"))).toBe(false); + // Pro is gone now, not at the trial's end + expect(t.row()).toEqual({ plan: "free", subscription_id: "sub_ada0000001", subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(t.sql.rows("SELECT current_period_end FROM accounts")[0]).toEqual({ current_period_end: new Date(Math.floor(now().getTime() / 1000) * 1000).toISOString() }); + expect(await t.pro()).toEqual({ ok: true, pro: false, via: null, trial_days: null }); + expect(log.mock.calls.flat().join("\n")).toContain("subscription sub_ada0000001 was cancelled in its trial; ended it now"); + // the customer.subscription.deleted that follows writes the same, and cancels nothing again + expect(await t.send("customer.subscription.deleted")).toEqual({ status: 200, body: { received: true, result: "applied" } }); + expect(t.cancels()).toHaveLength(1); + expect(t.row()).toMatchObject({ plan: "free", subscription_status: "canceled" }); + // the plan page offers Pro without a trial: one trial per account + const page = await text(call(t.env, "GET", "/account/billing", { cookie: t.cookie })); + expect(page).toContain("You are on the Free plan."); + expect(page).not.toContain("free trial"); + const again = await call(t.env, "POST", "/api/billing/checkout", { body: { plan: "team" }, cookie: t.cookie, fetch: t.s.fetch }); + expect(again.status).toBe(200); + expect(((await again.json()) as any).trial_days).toBeNull(); + log.mockRestore(); + }); + + it("cancelled with cancel_at_period_end (classic billing, or the API): the same, ended now", async () => { + const t = await inTrial(); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + t.sub.cancel_at_period_end = true; + expect((await t.send("customer.subscription.updated")).body.result).toBe("applied"); + expect(t.cancels()).toEqual(["/v1/subscriptions/sub_ada0000001"]); + expect(t.row()).toMatchObject({ plan: "free", subscription_status: "canceled", cancel_at_period_end: 0 }); + log.mockRestore(); + }); + + it("whichever event brings it: an invoice.paid or a redelivery after the cancel finds it cancelled, and cancels nothing again", async () => { + const t = await inTrial(); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + t.sub.cancel_at = END; + // the trial's $0 invoice paid, delivered after the cancel: the subscription as Stripe has it now is what counts + const inv = { id: "in_trial000001", object: "invoice", customer: "cus_ada0000001", status: "paid", amount_due: 0, amount_paid: 0, parent: { subscription_details: { subscription: "sub_ada0000001", metadata: { genclass: "1" } } }, lines: { data: [] } }; + expect((await json(deliver(t.env, stripeEvent("invoice.paid", inv), t.fetch))).result).toBe("applied"); + expect(t.cancels()).toEqual(["/v1/subscriptions/sub_ada0000001"]); + expect(t.row()).toMatchObject({ plan: "free", subscription_status: "canceled" }); + expect((await t.send("customer.subscription.updated")).body.result).toBe("applied"); + expect(t.cancels()).toHaveLength(1); + log.mockRestore(); + }); + + it("a cancel Stripe fails answers 500 and changes nothing; Stripe's retry ends the trial", async () => { + const t = await inTrial(); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const err = vi.spyOn(console, "error").mockImplementation(() => {}); + let fail = 1; + const flaky: typeof t.fetch = async (u, init = {}) => + init.method === "DELETE" && fail-- > 0 ? new Response(JSON.stringify({ error: { message: "Stripe is having trouble" } }), { status: 500 }) : t.fetch(u, init); + t.sub.cancel_at = END; + const ev = stripeEvent("customer.subscription.updated", t.sub); + expect((await deliver(t.env, ev, flaky)).status).toBe(500); + expect(t.row()).toMatchObject({ plan: "team", subscription_status: "trialing", cancel_at_period_end: 0 }); + expect(t.s.subs.get("sub_ada0000001")!.status).toBe("trialing"); + // the same event again, as Stripe delivers it + expect(await json(deliver(t.env, ev, flaky))).toEqual({ received: true, result: "applied" }); + expect(t.row()).toMatchObject({ plan: "free", subscription_status: "canceled" }); + log.mockRestore(); + err.mockRestore(); + }); + + it("a trial set to cancel after a paid month (by hand in the Stripe dashboard) is left to Stripe", async () => { + const t = await inTrial(); + t.sub.cancel_at = END + 30 * DAY_S; + expect((await t.send("customer.subscription.updated")).body.result).toBe("applied"); + expect(t.cancels()).toEqual([]); + expect(t.row()).toEqual({ plan: "team", subscription_id: "sub_ada0000001", subscription_status: "trialing", cancel_at_period_end: 1 }); + }); + + it("unchanged for a paid plan: cancelled in the portal, Pro runs to the end of the paid month and nothing is cancelled now", async () => { + const b = await buyer(); + // past its trial: active, its first month paid + const sub: Record = { ...accountSub("sub_ada0000001", b.account.id, "cus_ada0000001", "active"), trial_start: END - 33 * DAY_S, trial_end: END - 30 * DAY_S }; + b.s.subs.set(sub.id, sub); + expect((await json(deliver(b.env, stripeEvent("customer.subscription.created", sub), b.s.fetch))).result).toBe("applied"); + const row = () => b.sql.rows("SELECT plan, subscription_status, current_period_end, cancel_at_period_end FROM accounts")[0]; + // the portal with flexible billing (cancel_at), then classic (cancel_at_period_end) + for (const cancel of [{ cancel_at: END, cancel_at_period_end: false }, { cancel_at: null, cancel_at_period_end: true }]) { + Object.assign(sub, cancel); + expect((await json(deliver(b.env, stripeEvent("customer.subscription.updated", sub), b.s.fetch))).result).toBe("applied"); + expect(row()).toEqual({ plan: "team", subscription_status: "active", current_period_end: new Date(END * 1000).toISOString(), cancel_at_period_end: 1 }); + } + expect(b.s.calls.filter((c) => c.method === "DELETE")).toEqual([]); + expect(await json(call(b.env, "GET", "/api/billing/pro", { cookie: b.cookie, origin: null }))).toMatchObject({ pro: true, via: "plan" }); + expect(await text(call(b.env, "GET", "/account/billing", { cookie: b.cookie }))).toContain("It is cancelled and will not renew; you can resume it in Manage billing before then."); + // Stripe ends it at the period end: Free then + sub.status = "canceled"; + expect((await json(deliver(b.env, stripeEvent("customer.subscription.deleted", sub), b.s.fetch))).result).toBe("applied"); + expect(row()).toMatchObject({ plan: "free", subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(b.s.calls.filter((c) => c.method === "DELETE")).toEqual([]); + }); + + it("a version-4 project's subscription cancelled in its trial ends now too; the account row is not touched", async () => { + const b = await buyer(); + const fetch = ending(b.s); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const sub: Record = { ...projectSub("sub_shop000001", b.account.id, "cus_ada0000001", b.shop.id!, "trialing"), default_payment_method: "pm_card00000001", trial_end: END }; + b.s.subs.set(sub.id, sub); + expect((await json(deliver(b.env, stripeEvent("customer.subscription.created", sub), fetch))).result).toBe("applied"); + expect(b.sql.rows("SELECT plan, subscription_status FROM projects WHERE name = 'Shop'")[0]).toEqual({ plan: "team", subscription_status: "trialing" }); + sub.cancel_at = END; + expect((await json(deliver(b.env, stripeEvent("customer.subscription.updated", sub), fetch))).result).toBe("applied"); + expect(b.s.calls.filter((c) => c.method === "DELETE").map((c) => c.url.pathname)).toEqual(["/v1/subscriptions/sub_shop000001"]); + expect(b.sql.rows("SELECT plan, subscription_status, cancel_at_period_end FROM projects WHERE name = 'Shop'")[0]).toEqual({ plan: null, subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(b.sql.rows("SELECT plan, subscription_id FROM accounts")[0]).toEqual({ plan: "free", subscription_id: null }); + log.mockRestore(); + }); +}); + describe("the webhook still writes a version-4 project's subscription to that project and touches nothing else", () => { it("two projects, two subscriptions: each project gets its plan, the account row stays, nothing is cancelled or refunded", async () => { const b = await buyer();