diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index 47f14f3d..6621b36e 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -556,8 +556,10 @@ cancelling switched off (`scripts/stripe-setup.mjs`). "Cancel plan" on the billi app with a subscription of its own) opens up to three popups: a warning that the subscription will end, one offer to stay (15% off for 6 months, the coupon `genclass_stay_15`; never more than that, once per customer, never on top of another discount such as a promotion code's free months: `src/stripe.ts` retentionOffer), and a last confirmation. -A cancel during the trial ends the trial and Pro at once and charges nothing (the owner, 2026-11-15); a paid plan -runs to the end of its paid month and can be resumed until then ("Resume plan"). The owner gets `plan_cancelled` +A cancel ends the plan that day (the owner, 2026-11-18), a trial and a paid plan alike: a trial is charged nothing +(the owner, 2026-11-15), a paid plan gets no refund for the days left, and a discount or a promotion code's free +months end with it; the popups say so. A plan set to end later some other way (by hand in the Stripe dashboard) can +be resumed until then ("Resume plan"). The owner gets `plan_cancelled` and `retention_offer_taken` notices. A trial set to cancel any other way (by hand in the Stripe dashboard) is still ended at once by the webhook (`src/stripe.ts` trialCancelled). **The genclass command is Pro's** (the owner's "let's make the entire CLI paid"): a CLI session of an account with @@ -831,8 +833,8 @@ 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 and tax id; cancelling is on GenClass's own billing page (a paid plan at period end, a trial at - once: `src/billing.ts` cancelPlan). Cancelling with `prorate` and `invoice_now` would put the credit + invoices, email and tax id; cancelling is on GenClass's own billing page (the plan ends that day, trial or paid, + with no refund: `src/billing.ts` cancelPlan). 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: @@ -871,9 +873,9 @@ does about it. | `POST /api/billing/checkout` | `{ plan: "", quantity? }` (a plan priced above 0: `team`; `quantity` (or `seats`, read the same) 1 to 200 for a plan sold by quantity becomes the subscription's quantity, which the buyer can change on Stripe's page: the apps for Team, default the apps the account owns, or the seats of a per-seat plan, default 1; Checkout takes promotion codes; Enterprise has no Checkout), browser session and our `Origin` (403 otherwise, also for a CLI token). Creates the account's own Stripe customer once (email, description `GenClass account`, metadata `genclass=1` and `genclass_account`); never looks one up by email. A stored customer is checked first (`GET /v1/customers/`): its metadata must name the account, and every subscription on it must be GenClass's, else 409 with the contact address, nothing opened, and a `shared_customer` notice ("Stripe object ownership" below). Then it asks Stripe, not the database, whether that customer already has a GenClass subscription: one on this plan is a 409, one whose last payment failed (`past_due`, `unpaid`) is a 409 pointing to Manage billing, two at once (a switch still going through) or a paused one is a 409, and an active one on another paid plan is a switch: after the same invoice check as Manage billing, `{ url, switch: true }` of a Checkout for the new plan whose session and subscription carry `genclass_switch_from=` (success URL `...?done=1&to=`). Otherwise `{ url }` of a Checkout Session in subscription mode for that customer and the plan's lookup key (metadata `genclass=1`, `genclass_account`, `genclass_plan`; the subscription gets `genclass` and `genclass_account` and flexible billing mode; `client_reference_id` = account id; success `https://genclass.dev/account/billing?done=1`), with `managed_payments[enabled]=true` for a plan marked `managed_payments` (none today) when `MANAGED_PAYMENTS` is `on`. GenClass's open Checkout page of the account for the same plan (and the same switch) is reused, its other open pages are closed first, and any other open page is left alone. 503 unless the account can buy (above). | | `POST /api/billing/portal` | browser session and `Origin`; `{ url }` of a Billing Portal session (card, email and tax id, invoices; no plan switch, which is a new Checkout) on GenClass's own portal configuration: the one whose id `STRIPE_PORTAL_CONFIGURATION` (live) or `STRIPE_PORTAL_CONFIGURATION_TEST` (test) names, fetched by that id and checked (metadata `genclass=1`, active, not the default; cached 10 minutes), never the account's default one: without it, 503 ("run scripts/stripe-setup.mjs"). The portal acts on everything on the customer, so first the customer must be the account's (metadata), every subscription on it GenClass's, and each of its latest 100 invoices for a GenClass subscription; otherwise 409 with the contact address, no session, and a `shared_customer` notice. 409 before a first purchase, and when Stripe no longer has the customer (the stored ids are then cleared). | | `GET /api/billing/pro` | browser session or the genclass command's token; `{ ok, pro, via, trial_days }`: `pro` with the account's own plan, its trial or GenClass's grant (`via: "plan"`), a seat on a paying team (`"team"`), or where nothing is sold (`"open"`), the same answer as the command's own gate; `trial_days` the days free its first Pro would start with (null with Pro or none left). The page check (genclass-scan) asks it over its `ACCOUNTS` service binding for each report it shows: the score and the whole report are Pro's since 2026-11-15. 401 when not signed in. A Checkout with `next` (`/scan?url=...`, the page check's "Start 3 days free") returns there: success `/account/billing?done=1&next=...` (the plan page waits for the payment, then goes to the report), cancel to the report; `GET /account/billing?next=...` keeps it through the sign-in and sends an account that has Pro straight back. | -| `GET /api/billing/cancel[?project=]` | browser session: what the cancel popups say, `{ ok, plan, trial, ends, offer }` (`trial`: it would end at once; `offer`: `{ percent_off, months }` or null); nothing changes | +| `GET /api/billing/cancel[?project=]` | browser session: what the cancel popups say, `{ ok, plan, trial, ends, discount, offer }` (the plan would end that day; `trial`: nothing was charged; `ends`: the day the paid month would have run to; `discount`: a discount or free months end with it; `offer`: `{ percent_off, months }` or null); nothing changes | | `POST /api/billing/cancel/offer` | browser session and `Origin`, `{ project_id? }`: the person stays and the offer's coupon goes on the subscription; 409 when it cannot have it | -| `POST /api/billing/cancel` | browser session and `Origin`, `{ project_id? }`: a trial ends at once, a paid plan with its paid month; `{ ok, ended, ends }` | +| `POST /api/billing/cancel` | browser session and `Origin`, `{ project_id? }`: the plan ends that day, trial or paid, with no refund; `{ ok, ended: true, ends: null }` | | `POST /api/billing/resume` | browser session and `Origin`, `{ project_id? }`: a plan set to end goes on | | `POST /api/billing/webhook` | Stripe only. The raw body must carry a valid `Stripe-Signature` (HMAC-SHA256 of `t.body`, any `v1`, within 5 minutes) under `STRIPE_WEBHOOK_SECRET` with a live key or `STRIPE_WEBHOOK_SECRET_TEST` with a test key; else 400. An event signed with the other mode's secret, or whose `livemode` is not the key's mode, is answered 200 and ignored (a test endpoint left over after going live). Handles `customer.subscription.created`, `.updated` and `.deleted`, `invoice.paid`, `charge.refunded` and `charge.dispute.created`, and subscribes to nothing else: they arrive for the whole Stripe account, so first, with no Stripe call, the customer must be in `accounts.stripe_customer_id`, and the subscription must look like GenClass's (the one recorded for the account, metadata `genclass=1` on it or copied onto the invoice, or a `genclass_` lookup key on a price). From an invoice only its subscription id is read; a refund or dispute of a GenClass customer's charge sends the owner `charge_refunded` or `charge_disputed` (ids and amounts; a dispute names no customer, so its charge is read first). Then it fetches the subscription (its prices' products, its customer and its latest invoice expanded), which must be provably GenClass's (every price a `genclass_` lookup key on a `genclass_plan` product, or the subscription already recorded for the account) and the account's (its customer's `genclass_account` names the account), and writes the plan, status, `past_due_since`, period end (when it ended, for one cancelled at once), cancel flag and mode. A subscription the account has not been granted yet is written only once its latest invoice is paid (or asks for nothing), never on `active` alone; another subscription than the account's current one never overwrites a live plan unless it was chosen as below. When a subscription starts billing (`created`, `updated` with a status change, or `invoice.paid`), if the customer has two GenClass subscriptions that bill and are paid for (a switch, or two tabs paid), the account keeps one (a switch's new plan; otherwise a live one, then the plan listed later in `billing/plans.json`, then the newest): it is written to the account first, then each other one is refunded to its payment method (a switch's old plan: its unused time; a duplicate: its latest payment in full; once, by the metadata `genclass_refund`) and cancelled at once with no proration, and `NOTIFY_WEBHOOK` gets `plan_switch` or `duplicate_subscription` with the refunds. A new subscription that is never paid (`incomplete`, `incomplete_expired`, or `active` with its invoice unpaid) changes nothing. The end of the subscription recorded for the account is applied even when its customer's metadata is gone (Stripe erasing a buyer's data on request). A purchase of a plan with `custom_model` (Individual) is recorded (`custom_requests`, `NOTIFY_WEBHOOK`, naming the plan) only when Stripe reports that plan's price paid: the subscription's latest invoice is paid and has a positive line on it (a first invoice, a switch included, seen on `invoice.paid` or the subscription's own events). Every other event (another business's subscriptions, in a shared account) is answered 200, logged as `stripe webhook: ignored: `, not stored, and nothing about it is fetched. The ids of events about GenClass customers are kept 30 days (`billing_events`), so a redelivery changes nothing; a failure answers 500 and Stripe retries. | | `GET /api/billing` | browser session: `{ plan, subscription_status, current_period_end, cancel_at_period_end, on_sale, access, seats }` (`on_sale`: a plan is sold and this account can buy it); `access` is `paid`, `comp` (GenClass's grant), `open` (this server's `PLAN_GATES`) or null (Free); `seats`: the people the account holds, null for no limit | diff --git a/telemetry-worker/src/billing-pages.ts b/telemetry-worker/src/billing-pages.ts index 523192a7..acec973f 100644 --- a/telemetry-worker/src/billing-pages.ts +++ b/telemetry-worker/src/billing-pages.ts @@ -154,14 +154,15 @@ const WARN_ICON = /** * The popups a cancellation goes through (the owner, 2026-11-18): a warning that the subscription will end, one offer - * to stay for less (only when /api/billing/cancel says this subscription can have it), then a last confirmation. + * to stay for less (only when /api/billing/cancel says this subscription can have it), then a last confirmation. The + * plan ends the day it is cancelled, trial or paid, and the popups say so before the last button. * Their words are filled in by gcCancel from what the server says about the plan; nothing changes before the last * button, or the offer's. */ function cancelDialogs(): string { return ` ${WARN_ICON} -

If you continue, your subscription will end

+

If you continue, your subscription will end today

Your account goes back to ${esc(PLANS[0]?.name ?? "Free")}: ${esc((PLANS[0]?.summary ?? "").replace(/\.$/, "").replace(/^./, (ch) => ch.toLowerCase()))}.

@@ -203,14 +204,15 @@ function gcCancel(project){ gcPost("/api/billing/cancel" + (project ? "?project=" + encodeURIComponent(project) : ""), undefined, "GET").then(function(j){ gcBusy(open, false); info = j; var plan = j.plan || "paid", when = day(j.ends); - text("cx1p", j.trial ? "Your " + plan + " trial ends at once. Nothing is charged." : plan + " stays until " + when + ", then ends. You are not charged again."); + var lost = j.discount ? " Your discount or free months end today too and do not come back." : ""; + text("cx1p", j.trial ? "Your " + plan + " trial ends today, as soon as you cancel. Nothing is charged." + lost : plan + " ends today, as soon as you cancel, not on " + when + ". Nothing is refunded for the days left." + lost); if (j.offer) { text("cx2h", "Stay and pay " + j.offer.percent_off + "% less"); text("cx2p", "Keep " + plan + " and get " + j.offer.percent_off + "% off your next " + j.offer.months + " months. Nothing else changes."); document.getElementById("cx2take").lastChild.textContent = "Take " + j.offer.percent_off + "% off"; } - text("cx3h", "Cancel " + plan + "?"); - text("cx3p", j.trial ? "This is the last step. Your trial ends now." : "This is the last step. " + plan + " ends on " + when + "."); + text("cx3h", "Cancel " + plan + " today?"); + text("cx3p", j.trial ? "This is the last step. Your trial ends now." + lost : "This is the last step. " + plan + " ends now, with no refund." + lost); show(d1); }, function(x){ err.textContent = gcWhy(x); gcBusy(open, false); }); }); @@ -277,7 +279,7 @@ function statusLine(v: BillingView, plan: Plan): string { const total = (priceFor(plan, v.country ?? null).price_usd_cents.monthly ?? 0) * n; return `You are on the ${name} plan with ${n} seat${n === 1 ? "" : "s"}, ${esc(priceText(plan, v.country ?? null))} (${dollars(total)} a month). It renews on ${day(b.current_period_end)}. Add or remove seats in Manage billing.`; } - return `You are on the ${name} plan, ${esc(priceText(plan, v.country ?? null))}. It renews on ${day(b.current_period_end)}.`; + return `You are on the ${name} plan, ${esc(priceText(plan, v.country ?? null))}. It renews on ${day(b.current_period_end)}. If you cancel, it ends that day.`; } function planColumn(v: BillingView, p: Plan, current: Plan): string { diff --git a/telemetry-worker/src/billing.ts b/telemetry-worker/src/billing.ts index cbc05ae1..9350d999 100644 --- a/telemetry-worker/src/billing.ts +++ b/telemetry-worker/src/billing.ts @@ -13,8 +13,8 @@ // account's, or one app's own): {plan, trial, ends, offer} // POST /api/billing/cancel/offer {project_id?} browser session + Origin; takes the offer to stay (15% off for // 6 months, once per customer; src/stripe.ts retentionOffer) -// POST /api/billing/cancel {project_id?} browser session + Origin; a trial ends at once, a paid plan with -// its paid month +// POST /api/billing/cancel {project_id?} browser session + Origin; the plan ends that day, trial or +// paid; nothing is refunded // POST /api/billing/resume {project_id?} browser session + Origin; a plan set to end goes on // GET /api/billing browser session; the plan and the subscription // GET /account/billing the plan page (src/billing-pages.ts); ?next=/scan?url=... goes @@ -85,7 +85,6 @@ import { refreshSubscription, resumeSubscription, retentionOffer, - scheduleCancel, sharedCustomer, StripeError, stripeWebhook, @@ -595,14 +594,19 @@ async function cancelTarget(c: C, f: Fetch, a: Auth, projectId: string | null): /** The `project_id` of a cancel, offer or resume request's body: an app's id, or null for the account's plan. */ const projectIn = (body: Record): string | null => (typeof body.project_id === "string" && body.project_id ? body.project_id : null); +/** A subscription with a discount on it (a promotion code's free months, the offer to stay): it ends with the plan. */ +const discounted = (sub: Sub): boolean => (Array.isArray(sub?.discounts) && sub.discounts.length > 0) || !!sub?.discount; + /** Who and what, for the owner's notice: the account's email or login, and the app when the plan is one app's. */ const cancelWho = (t: CancelTarget): string => `${t.auth.account.email ?? t.auth.account.github_login ?? t.auth.account.id}${t.project ? `, app "${t.project.name}"` : ""}`; /** - * GET /api/billing/cancel: what the cancel popups say before anything changes. `trial`: the plan is in its free trial - * and ends at once; else it stays until `ends`. `offer`: the discount for staying, when this subscription can have it - * (a failure to read the coupon only hides the offer: cancelling never waits on it). + * GET /api/billing/cancel: what the cancel popups say before anything changes. The plan ends the day it is cancelled. + * `trial`: it is in its free trial, so nothing was charged; else `ends` is the day the paid month would have run to + * (the days up to it are lost, not refunded). `discount`: the subscription has a discount (a promotion code's free + * months, the offer to stay), which ends with it. `offer`: the discount for staying, when this subscription can have + * it (a failure to read the coupon only hides the offer: cancelling never waits on it). */ async function cancelInfo(c: C, f: Fetch, projectId: string | null): Promise { const a = await browserRead(c); @@ -614,7 +618,7 @@ async function cancelInfo(c: C, f: Fetch, projectId: string | null): Promise null); - return json(200, { ok: true, plan: t.name, trial: st.status === "trialing", ends: st.periodEnd, offer: offer ? { percent_off: offer.percent, months: offer.months } : null }); + return json(200, { ok: true, plan: t.name, trial: st.status === "trialing", ends: st.periodEnd, discount: discounted(t.sub), offer: offer ? { percent_off: offer.percent, months: offer.months } : null }); } catch (e) { return stripeFail(e); } @@ -646,8 +650,9 @@ async function cancelOffer(c: C, f: Fetch): Promise { } /** - * POST /api/billing/cancel: the last popup's button. A trial ends at once and nothing is charged; a paid plan is set - * to end with its paid month. The database is written from the subscription as Stripe has it after (the webhook's own + * POST /api/billing/cancel: the last popup's button. The plan ends now, the day it is cancelled (the owner, + * 2026-11-18), a trial and a paid plan alike: nothing more is charged, nothing is refunded for the days left of a paid + * month, and a discount or free months on it end too. The database is written from the subscription as Stripe has it after (the webhook's own * write; if that read fails, Stripe's event does it a moment later). The owner is told. */ async function cancelPlan(c: C, f: Fetch): Promise { @@ -661,21 +666,18 @@ async function cancelPlan(c: C, f: Fetch): Promise { const st = subscriptionState(t.sub); if (!HOLDING_STATUSES.has(st.status)) return fail(409, `your ${t.name} plan has already ended`); const trial = st.status === "trialing"; - if (trial) await cancelNow(c.env, f, t.sub.id as string); - else if (!st.cancelAtPeriodEnd) await scheduleCancel(c.env, f, t.sub.id as string); + await cancelNow(c.env, f, t.sub.id as string); await refreshSubscription({ env: c.env, db: c.db, fetch: f, now: c.now }, t.sub.id as string).catch(() => null); - if (trial || !st.cancelAtPeriodEnd) { - await notifyOwner( - { env: c.env, fetch: f, now: c.now }, - { - event: "plan_cancelled", - text: `${modeNote(c.env)}${t.name} cancelled ${trial ? "in its trial (ended at once, nothing charged)" : `(it ends ${st.periodEnd ? `on ${st.periodEnd.slice(0, 10)}` : "with its paid month"})`}: ${cancelWho(t)}.`, - account_id: a.account.id, - subscription_id: t.sub.id, - }, - ).catch(() => false); - } - return json(200, { ok: true, ended: trial, ends: trial ? null : st.periodEnd }); + await notifyOwner( + { env: c.env, fetch: f, now: c.now }, + { + event: "plan_cancelled", + text: `${modeNote(c.env)}${t.name} cancelled ${trial ? "in its trial (ended at once, nothing charged)" : `(ended at once${st.periodEnd ? `; it was paid up to ${st.periodEnd.slice(0, 10)}` : ""}, nothing refunded${discounted(t.sub) ? ", its discount ended too" : ""})`}: ${cancelWho(t)}.`, + account_id: a.account.id, + subscription_id: t.sub.id, + }, + ).catch(() => false); + return json(200, { ok: true, ended: true, ends: null }); } catch (e) { return stripeFail(e); } diff --git a/telemetry-worker/src/stripe.ts b/telemetry-worker/src/stripe.ts index 49688d53..a2e32bff 100644 --- a/telemetry-worker/src/stripe.ts +++ b/telemetry-worker/src/stripe.ts @@ -42,13 +42,15 @@ // 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. 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. +// (trialCancelled). A paid subscription set to end later in Stripe itself (the dashboard) still runs to that day. // - Cancelling is on GenClass's own pages (the owner, 2026-11-18; src/billing.ts cancel routes), not in Stripe's portal, // whose configuration has cancelling switched off (scripts/stripe-setup.mjs): a warning, then one offer to stay // (RETENTION_COUPON: at most RETENTION_MAX, 15% off for 6 months, once per customer, never on top of another -// discount), then a last confirmation. A trial ends at once (cancelNow), a paid plan at the end of its paid month -// (cancel_at_period_end), and a plan set to end can be resumed until then. Each write is followed by the same -// database write the webhook makes (refreshSubscription). +// discount), then a last confirmation. A cancel ends the plan that day (the owner, 2026-11-18: "it should end on +// the same day as they cancel it"), a trial and a paid plan alike (cancelNow): nothing is refunded for the days +// left, and a discount or a promotion code's free months end with it. A plan set to end later some other way (by +// hand in the Stripe dashboard, the portal before it lost cancelling) can be resumed until then. Each write is +// followed by the same database write the webhook makes (refreshSubscription). // - 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 @@ -494,7 +496,7 @@ export async function checkoutSession( /** * A Billing Portal session on GenClass's own portal configuration (never the account's default): card, invoices, - * email and tax id, seats. It offers no cancelling (GenClass's own pages do that: scheduleCancel) and no plan switch (scripts/stripe-setup.mjs): a Managed Payments + * email and tax id, seats. It offers no cancelling (GenClass's own pages do that: cancelNow) and no plan switch (scripts/stripe-setup.mjs): a Managed Payments * subscription cannot take another plan's price, so a switch is a new Checkout (src/billing.ts checkout). The portal shows * and acts on everything on the customer, so the caller first checks that it all is GenClass's (src/billing.ts portal). */ @@ -577,14 +579,9 @@ export async function applyRetention(env: Env, f: Fetch, subscriptionId: string, ); } -/** Set a paid subscription to end with its paid month: no further charge, the plan stays until then. */ -export async function scheduleCancel(env: Env, f: Fetch, subscriptionId: string): Promise { - await stripe(env, f, "POST", `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, { cancel_at_period_end: true }); -} - /** - * Undo a cancellation that has not happened yet, however it was set: cancel_at_period_end (scheduleCancel, an older - * integration) or a cancel_at date (Stripe's portal in flexible billing mode, while it still offered cancelling). + * Undo a cancellation that has not happened yet, however it was set: cancel_at_period_end (the Stripe dashboard, an + * older integration) or a cancel_at date (Stripe's portal in flexible billing mode, while it still offered cancelling). */ export async function resumeSubscription(env: Env, f: Fetch, sub: Obj): Promise { const id = idOf(sub?.id); @@ -898,8 +895,9 @@ export function cardOnFile(sub: Obj): boolean { * 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. + * subscription past its trial: a paid plan set to end later in Stripe itself (the dashboard; the portal no longer + * offers cancelling) still runs to that day. A cancel on GenClass's own page never comes through here: it ends the + * plan that day (billing.ts cancelPlan). Exported for tests. */ export function trialCancelled(sub: Obj): boolean { if (sub?.status !== "trialing") return false; diff --git a/telemetry-worker/test/cancel.test.ts b/telemetry-worker/test/cancel.test.ts index 85bbd8de..165965bc 100644 --- a/telemetry-worker/test/cancel.test.ts +++ b/telemetry-worker/test/cancel.test.ts @@ -6,7 +6,7 @@ import { call, cliToken, createApp, fakeStripe, GENCLASS_PORTAL, resetClock, set // Cancelling on GenClass's own pages (src/billing.ts cancel routes, src/stripe.ts retentionOffer; the owner, 2026-11-18): // what the popups are told, the one offer to stay (15% off for 6 months at most, once per customer, never on top of -// another discount), the cancel itself (a trial ends at once, a paid plan with its paid month), the resume, and who may +// another discount), the cancel itself (the plan ends that day, trial or paid, with no refund), the resume, and who may // do any of it. Stripe is the fake of test/account-helpers.ts. On the two-paid fixture, like test/billing.test.ts. vi.mock("../../billing/plans.json", async () => ({ default: (await import("./fixtures/plans-two-paid.json")).default })); @@ -40,11 +40,11 @@ async function paying(status = "active", over: Record = {}) { } describe("GET /api/billing/cancel: what the popups say, before anything changes", () => { - it("a paid plan: its name, when it would end, and the offer to stay; nothing is written", async () => { + it("a paid plan: its name, the day its paid month would have run to, and the offer to stay; nothing is written", async () => { const t = await paying(); const r = await t.get(); expect(r.status).toBe(200); - expect(await r.json()).toEqual({ ok: true, plan: "Pro", trial: false, ends: new Date(END * 1000).toISOString(), offer: { percent_off: 15, months: 6 } }); + expect(await r.json()).toEqual({ ok: true, plan: "Pro", trial: false, ends: new Date(END * 1000).toISOString(), discount: false, offer: { percent_off: 15, months: 6 } }); expect(t.writes()).toEqual([]); expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 0 }); }); @@ -56,7 +56,8 @@ describe("GET /api/billing/cancel: what the popups say, before anything changes" it("no offer on top of another discount, a second time for the same customer, or for a plan whose payment is overdue", async () => { const promo = await paying("active", { discounts: ["di_6monthsfree01"] }); - expect(await (await promo.get()).json()).toMatchObject({ ok: true, offer: null }); + // the popups are told about the discount (a promotion code's free months): it ends with the plan + expect(await (await promo.get()).json()).toMatchObject({ ok: true, discount: true, offer: null }); const again = await paying(); again.s.subs.set("sub_ada0000000", subscription("sub_ada0000000", again.account.id, CUS, "genclass_pro_monthly", "canceled", { metadata: { genclass: "1", genclass_account: again.account.id, genclass_retention: "2026-10-01T00:00:00.000Z" } })); expect(await (await again.get()).json()).toMatchObject({ ok: true, offer: null }); @@ -114,25 +115,33 @@ describe("POST /api/billing/cancel/offer: staying, for 15% less over 6 months", }); describe("POST /api/billing/cancel and /api/billing/resume", () => { - it("a paid plan is set to end with its paid month: it stays until then, the account's row says so at once, the owner is told", async () => { + it("a paid plan ends the day it is cancelled: the subscription is cancelled now, nothing is refunded, the account is on Free, the owner is told", async () => { const t = await paying(); const r = await t.post("/api/billing/cancel"); - expect(await r.json()).toEqual({ ok: true, ended: false, ends: new Date(END * 1000).toISOString() }); - expect(t.writes()).toEqual([`POST /v1/subscriptions/${SUB}`]); - expect(Object.fromEntries(t.s.calls.find((c) => c.method === "POST")!.form!)).toEqual({ cancel_at_period_end: "true" }); - expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 1 }); - expect(t.notices()).toEqual([expect.objectContaining({ event: "plan_cancelled", text: expect.stringContaining("Pro cancelled (it ends on 2026-") })]); - // the page now offers to resume it, and no second cancel + expect(await r.json()).toEqual({ ok: true, ended: true, ends: null }); + // one write: the cancel itself. No refund, no credit note, no end set for later + expect(t.writes()).toEqual([`DELETE /v1/subscriptions/${SUB}`]); + expect(t.sub.status).toBe("canceled"); + expect(t.row()).toEqual({ plan: "free", subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(t.notices()).toEqual([expect.objectContaining({ event: "plan_cancelled", text: expect.stringMatching(/Pro cancelled \(ended at once; it was paid up to 2026-\d\d-\d\d, nothing refunded\): ada@example\.com/) })]); + // the page has nothing left to cancel or resume const page = await (await call(t.env, "GET", "/account/billing", { cookie: t.cookie })).text(); - expect(page).toContain('id="resumeplan"'); + expect(page).not.toContain('id="resumeplan"'); expect(page).not.toContain('id="cancelplan"'); - expect(page).toContain("It is cancelled and will not renew; you can resume it below before then."); - // a second click changes nothing and sends no second notice - expect((await t.post("/api/billing/cancel")).status).toBe(200); + // a second click finds the plan ended: no write, no second notice + expect((await t.post("/api/billing/cancel")).status).toBe(409); expect(t.writes()).toHaveLength(1); expect(t.notices()).toHaveLength(1); }); + it("free months from a promotion code end with the plan, the same day", async () => { + const t = await paying("active", { discounts: ["di_6monthsfree01"] }); + expect(await (await t.post("/api/billing/cancel")).json()).toEqual({ ok: true, ended: true, ends: null }); + expect(t.writes()).toEqual([`DELETE /v1/subscriptions/${SUB}`]); + expect(t.row()).toEqual({ plan: "free", subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(t.notices()[0]!.text).toContain("nothing refunded, its discount ended too"); + }); + it("a trial ends at once: the subscription is cancelled now and the account is on Free", async () => { const t = await paying("trialing", { trial_end: END }); expect(await (await t.post("/api/billing/cancel")).json()).toEqual({ ok: true, ended: true, ends: null }); @@ -141,11 +150,10 @@ describe("POST /api/billing/cancel and /api/billing/resume", () => { expect(t.notices()[0]!.text).toContain("in its trial (ended at once, nothing charged)"); }); - it("resume undoes a cancel however it was set (cancel_at_period_end, or the portal's cancel_at)", async () => { - const t = await paying(); - await t.post("/api/billing/cancel"); + it("resume undoes an end set for later, however it was set (cancel_at_period_end, or the portal's cancel_at)", async () => { + const t = await paying("active", { cancel_at_period_end: true }); expect((await t.post("/api/billing/resume")).status).toBe(200); - expect(Object.fromEntries(t.s.calls.filter((c) => c.method === "POST")[1]!.form!)).toEqual({ cancel_at_period_end: "false" }); + expect(Object.fromEntries(t.s.calls.find((c) => c.method === "POST")!.form!)).toEqual({ cancel_at_period_end: "false" }); expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 0 }); const old = await paying("active", { cancel_at: END }); expect((await old.post("/api/billing/resume")).status).toBe(200); @@ -165,8 +173,8 @@ describe("POST /api/billing/cancel and /api/billing/resume", () => { t.sql.db.prepare("UPDATE projects SET plan = 'pro', subscription_id = ?, subscription_status = 'active' WHERE id = ?").run(own.id, app.id); expect(await (await t.get(`/api/billing/cancel?project=${app.id}`)).json()).toMatchObject({ ok: true, plan: "Pro", trial: false }); expect((await t.post("/api/billing/cancel", { project_id: app.id })).status).toBe(200); - expect(t.writes()).toEqual(["POST /v1/subscriptions/sub_app0000001"]); - expect(t.sql.rows("SELECT cancel_at_period_end FROM projects WHERE id = ?", app.id)[0]).toEqual({ cancel_at_period_end: 1 }); + expect(t.writes()).toEqual(["DELETE /v1/subscriptions/sub_app0000001"]); + expect(t.sql.rows("SELECT plan, subscription_status, cancel_at_period_end FROM projects WHERE id = ?", app.id)[0]).toEqual({ plan: null, subscription_status: "canceled", cancel_at_period_end: 0 }); expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 0 }); // the account's subscription is not an app's, and an app's is not the account's t.sql.db.prepare("UPDATE projects SET subscription_id = ? WHERE id = ?").run(SUB, app.id); @@ -216,7 +224,9 @@ describe("the billing page: Cancel plan opens the popups", () => { const t = await paying(); const page = await (await call(t.env, "GET", "/account/billing", { cookie: t.cookie })).text(); expect(page).toContain(''); - expect(page).toContain("If you continue, your subscription will end"); + expect(page).toContain("If you continue, your subscription will end today"); + expect(page).toContain("If you cancel, it ends that day."); + expect(page).toContain("Nothing is refunded for the days left."); for (const id of ["cx1", "cx2", "cx3"]) expect(page).toContain(`cancel your plan.'); expect(page).not.toContain("cancel in Manage billing");