From 467c0a421d5a16693137e14b190924eb4af098f8 Mon Sep 17 00:00:00 2001 From: Mehar Khanna Date: Wed, 18 Nov 2026 01:10:13 -0500 Subject: [PATCH] Billing: cancelling on GenClass's own page, behind a warning, one offer to stay (15% off for 6 months) and a last confirmation Cancel plan on the billing page (and on the plan page of an app with its own subscription) opens up to three popups. A trial ends at once, a paid plan with its paid month and can be resumed until then. The offer is the coupon genclass_stay_15: never more than 15% for 6 months, once per customer, never on top of another discount. Stripe's portal no longer offers cancelling (scripts/stripe-setup.mjs). The owner is told of every cancel and every offer taken. Co-Authored-By: Claude Fable 5.2 --- scripts/stripe-setup.mjs | 47 +++- telemetry-worker/README.md | 23 +- telemetry-worker/src/auth.ts | 2 +- telemetry-worker/src/billing-pages.ts | 146 +++++++++-- telemetry-worker/src/billing.ts | 181 +++++++++++++- telemetry-worker/src/stripe.ts | 90 ++++++- telemetry-worker/test/account-helpers.ts | 23 +- telemetry-worker/test/billing.test.ts | 4 +- telemetry-worker/test/cancel.test.ts | 229 ++++++++++++++++++ telemetry-worker/test/plans.test.ts | 6 +- telemetry-worker/test/project-plans.test.ts | 6 +- .../test/stripe-setup-private.test.ts | 2 + telemetry-worker/test/stripe-setup.test.ts | 14 +- 13 files changed, 727 insertions(+), 46 deletions(-) create mode 100644 telemetry-worker/test/cancel.test.ts diff --git a/scripts/stripe-setup.mjs b/scripts/stripe-setup.mjs index f392e826..6f026ad9 100644 --- a/scripts/stripe-setup.mjs +++ b/scripts/stripe-setup.mjs @@ -33,15 +33,19 @@ // STRIPE_WEBHOOK_SECRET in live mode, STRIPE_WEBHOOK_SECRET_TEST in test mode, so a test run can never replace // 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 (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 +// 4. its own Billing Portal configuration (metadata genclass=1, a headline naming GenClass): 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 cancelling: a plan is cancelled on GenClass's own billing page, behind a warning and one offer to +// stay (the owner, 2026-11-18; telemetry-worker/src/billing.ts cancel routes). 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 // default. Its id goes to the worker with `npx wrangler secret put` (STRIPE_PORTAL_CONFIGURATION in live mode, // STRIPE_PORTAL_CONFIGURATION_TEST in test mode): the worker fetches that one configuration by id, and lists none. +// 5. the coupon of that offer to stay (telemetry-worker/src/stripe.ts RETENTION_COUPON and RETENTION_MAX: 15% off for +// 6 months, metadata genclass=1), read by its id and created when missing. Stripe coupons cannot be edited: one +// with other terms is reported and left alone (the worker offers it only within RETENTION_MAX), and one with that +// id that is not GenClass's stops the script. // Everything is read and checked first; changes start only when every check passed. Then it prints the remaining // steps. Running it again changes only what differs (its portal configuration is written again with the same // settings, and its id stored again). Account-wide settings (Managed Payments, business details, branding, customer @@ -71,6 +75,10 @@ const LOOKUP_PREFIX = "genclass_"; const stripeTs = readFileSync(join(WORKER, "src/stripe.ts"), "utf8"); export const API_VERSION = /export const STRIPE_VERSION = "([^"]+)"/.exec(stripeTs)?.[1]; export const EVENTS = [...(/export const WEBHOOK_EVENTS = \[([^\]]+)\]/.exec(stripeTs)?.[1] ?? "").matchAll(/"([a-z_.]+)"/g)].map((m) => m[1]); +/** The offer to stay's coupon id and terms, as the worker has them (src/stripe.ts RETENTION_COUPON, RETENTION_MAX). */ +export const RETENTION_COUPON = /export const RETENTION_COUPON = "([a-z0-9_]+)"/.exec(stripeTs)?.[1]; +const retentionMax = /export const RETENTION_MAX = \{ percent: (\d+), months: (\d+) \}/.exec(stripeTs); +export const RETENTION = retentionMax ? { percent: Number(retentionMax[1]), months: Number(retentionMax[2]) } : null; const PLANS = JSON.parse(readFileSync(process.env.GENCLASS_PLANS_FILE ? resolve(process.env.GENCLASS_PLANS_FILE) : join(ROOT, "billing/plans.json"), "utf8")); // the private prices, as the Worker secret PLANS_PRIVATE holds them: { plans: { : { stripe_product?, country_prices? } } } { @@ -141,6 +149,7 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe const DRY = args.has("--dry-run"); const NEW_WEBHOOK = args.has("--new-webhook"); if (!API_VERSION || EVENTS.length === 0) fail("could not read STRIPE_VERSION and WEBHOOK_EVENTS from telemetry-worker/src/stripe.ts"); + if (!RETENTION_COUPON || !RETENTION) fail("could not read RETENTION_COUPON and RETENTION_MAX from telemetry-worker/src/stripe.ts"); const KEY = (env.STRIPE_SECRET_KEY ?? "").trim(); const mode = /^(sk|rk)_test_/.test(KEY) ? "test" : /^(sk|rk)_live_/.test(KEY) ? "live" : null; if (!mode) fail("set STRIPE_SECRET_KEY to a Stripe secret key (sk_test_... or sk_live_...) in your environment"); @@ -378,13 +387,9 @@ 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", - cancellation_reason: { enabled: true, options: ["too_expensive", "missing_features", "switched_service", "unused", "other"] }, - }, + // no cancelling here: GenClass's billing page cancels (a warning, one offer to stay, a last confirmation; + // telemetry-worker/src/billing.ts), so nobody ends a plan without having seen them + subscription_cancel: { enabled: false }, // no plan switch here: a Managed Payments subscription cannot take another plan's price, and must not move // onto a subscription outside Managed Payments; the billing page switches with a new Checkout. The one update // allowed is the quantity of a per-seat or per-app plan's own price @@ -421,15 +426,35 @@ export async function main({ argv = process.argv.slice(2), env = process.env, fe say(`${PORTAL_NAME} (${id}) stored on the worker.`); } + /** The offer to stay's coupon by its id: null when missing; one that is not GenClass's stops the script. */ + async function readRetention() { + const c = await stripe("GET", `/v1/coupons/${RETENTION_COUPON}`, undefined, { missingOk: true }); + if (c && c.metadata?.genclass !== MARK) fail(`coupon ${RETENTION_COUPON} exists but is not GenClass's (no metadata genclass=${MARK}); nothing was changed`); + return c; + } + + async function retention(existing) { + const terms = `${RETENTION.percent}% off for ${RETENTION.months} months`; + if (existing) { + const same = existing.percent_off === RETENTION.percent && existing.duration === "repeating" && existing.duration_in_months === RETENTION.months && existing.valid === true; + say(`coupon ${RETENTION_COUPON} (the offer to stay): ${same ? "unchanged" : `it is not ${terms} and valid; Stripe coupons cannot be edited, so delete it in the dashboard and run this again (the worker offers it only within ${terms})`}`); + return; + } + would(`create coupon ${RETENTION_COUPON} (the offer to stay: ${terms})`); + if (!DRY) await stripe("POST", "/v1/coupons", { id: RETENTION_COUPON, name: `Thanks for staying: ${RETENTION.percent}% off`, percent_off: RETENTION.percent, duration: "repeating", duration_in_months: RETENTION.months, metadata: { genclass: MARK } }); + } + // ------------------------------------------------------------------------------------------- run say(`Stripe ${mode} mode${DRY ? ", dry run (nothing is changed)" : ""}. API version ${API_VERSION}. Only GenClass's own objects are read or changed.`); const state = await readPlans(); const endpoints = (await readWebhooks()).filter((w) => w.description === WEBHOOK_DESCRIPTION); const existingPortal = await readPortal(); + const existingCoupon = await readRetention(); const made = await products(state); await webhook(endpoints); await portal(existingPortal, made); + await retention(existingCoupon); const dashboard = ` Dashboard steps for GenClass's Stripe account, in this mode, before the worker gets its key (the reasons are in telemetry-worker/README.md, "Paid plans"): diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index b2cc989a..47f14f3d 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -551,9 +551,15 @@ 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. +**Cancelling is on GenClass's own pages** (the owner, 2026-11-18), not in Stripe's portal, whose configuration has +cancelling switched off (`scripts/stripe-setup.mjs`). "Cancel plan" on the billing page (or on the plan page of an +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` +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 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 @@ -825,9 +831,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, 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 + 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 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: @@ -864,8 +869,12 @@ does about it. | route | behaviour | |---|---| | `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 (cancel at period end, 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). | +| `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 | +| `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/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 | | `POST /api/billing/trial` | 410: GenClass has no trial any more ([Grants and no trial](#grants-enterprise-and-no-trial)) | diff --git a/telemetry-worker/src/auth.ts b/telemetry-worker/src/auth.ts index 18f39964..14184014 100644 --- a/telemetry-worker/src/auth.ts +++ b/telemetry-worker/src/auth.ts @@ -1712,7 +1712,7 @@ async function deleteProject(c: C, id: string): Promise { // a project that is paid for is not deleted while its subscription still bills: nobody pays for an app that is gone const paid = await c.db.prepare("SELECT subscription_status FROM projects WHERE id = ?").bind(id).first<{ subscription_status: string | null }>(); if (paid?.subscription_status && ["active", "trialing", "past_due", "unpaid"].includes(paid.subscription_status)) { - return fail(409, `${p.name} has a paid plan: cancel it in Manage billing (${c.cfg.origin}/account/billing) first, then delete the project`); + return fail(409, `${p.name} has a paid plan: cancel it on its plan page (${c.cfg.origin}/account/billing?project=${p.id}) first, then delete the project`); } await c.db.batch([ c.db.prepare("DELETE FROM integrations WHERE project_id = ?").bind(id), diff --git a/telemetry-worker/src/billing-pages.ts b/telemetry-worker/src/billing-pages.ts index 54979f57..523192a7 100644 --- a/telemetry-worker/src/billing-pages.ts +++ b/telemetry-worker/src/billing-pages.ts @@ -132,6 +132,110 @@ const BILLING_CSS = ` @media (max-width:767px){.plan .tag{font-size:12px}} `; +/** The statuses of a subscription that exists and can still bill (src/stripe.ts HOLDING_STATUSES): one that can be cancelled. */ +const CANCELLABLE = new Set(["active", "trialing", "past_due", "unpaid", "paused"]); + +const CANCEL_CSS = ` +dialog.cx{margin:auto;max-height:calc(100vh - 32px);overflow:auto;max-width:440px;width:calc(100% - 32px);border:1px solid var(--rule);border-radius:14px;background:var(--paper);color:var(--ink);padding:24px 24px 20px} +dialog.cx::backdrop{background:rgba(0,0,0,.62)} +dialog.cx h2{font-size:21px;line-height:1.25;margin:0 0 8px} +dialog.cx p{font-size:14.5px;line-height:1.55;color:var(--ink2);margin:0 0 8px} +dialog.cx .err:empty{display:none} +.cx-warn{width:44px;height:44px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:var(--warn-t);color:var(--warn);margin-bottom:14px} +.cx-warn svg{width:24px;height:24px} +.cx-act{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px} +.cx-act .btn{flex:1 1 auto;justify-content:center} +.cx-act[hidden]{display:none} +#manage .acct-form{display:flex;gap:10px;flex-wrap:wrap} +`; + +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. + * 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

+

+

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

+
+
+ +

+

+ +
+ +
+ + ${WARN_ICON} +

+

+ +
+
`; +} + +/** gcCancel(projectId or null): wires #cancelplan to the popups and #resumeplan to its route; errors go to #cancelerr. */ +const CANCEL_JS = ` +function gcCancel(project){ + var open = document.getElementById("cancelplan"), resume = document.getElementById("resumeplan"), err = document.getElementById("cancelerr"); + var body = project ? { project_id: project } : {}; + function show(d){ if (d.showModal) d.showModal(); else d.setAttribute("open", ""); } + function hide(d){ if (!d.open) return; if (d.close) d.close(); else d.removeAttribute("open"); } + function day(iso){ var d = new Date(iso); return !iso || isNaN(d) ? "the end of your paid month" : d.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" }); } + function text(id, t){ document.getElementById(id).textContent = t; } + if (resume) resume.addEventListener("click", function(e){ + e.preventDefault(); err.textContent = ""; gcBusy(resume, true, "Resuming..."); + gcPost("/api/billing/resume", body).then(function(){ location.reload(); }, function(x){ err.textContent = gcWhy(x); gcBusy(resume, false); }); + }); + var d1 = document.getElementById("cx1"), d2 = document.getElementById("cx2"), d3 = document.getElementById("cx3"); + if (!open || !d1 || !d2 || !d3) return; + var info = null, kept = false; + open.addEventListener("click", function(e){ + e.preventDefault(); err.textContent = ""; gcBusy(open, true, "One moment..."); + 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."); + 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 + "."); + show(d1); + }, function(x){ err.textContent = gcWhy(x); gcBusy(open, false); }); + }); + document.querySelectorAll("[data-cx-keep]").forEach(function(b){ b.addEventListener("click", function(){ hide(d1); hide(d2); hide(d3); }); }); + document.getElementById("cx1go").addEventListener("click", function(){ hide(d1); show(info && info.offer ? d2 : d3); }); + document.getElementById("cx2no").addEventListener("click", function(){ hide(d2); show(d3); }); + var take = document.getElementById("cx2take"); + take.addEventListener("click", function(){ + text("cx2err", ""); gcBusy(take, true, "One moment..."); + gcPost("/api/billing/cancel/offer", body).then(function(j){ + kept = true; + text("cx2h", "You're staying, for " + j.percent_off + "% less"); + text("cx2p", "The discount comes off your next " + j.months + " months, starting with your next payment."); + document.getElementById("cx2act").hidden = true; document.getElementById("cx2done").hidden = false; + }, function(x){ text("cx2err", gcWhy(x)); gcBusy(take, false); }); + }); + document.getElementById("cx2close").addEventListener("click", function(){ hide(d2); }); + d2.addEventListener("close", function(){ if (kept) location.reload(); }); + var go = document.getElementById("cx3go"); + go.addEventListener("click", function(){ + text("cx3err", ""); gcBusy(go, true, "Cancelling..."); + gcPost("/api/billing/cancel", body).then(function(){ location.reload(); }, function(x){ text("cx3err", gcWhy(x)); gcBusy(go, false); }); + }); +}`; + function statusLine(v: BillingView, plan: Plan): string { const b = v.billing; const name = `${esc(plan.name)}`; @@ -150,7 +254,7 @@ function statusLine(v: BillingView, plan: Plan): string { const ended = retired ? b.cancel_at_period_end ? ` Your subscription to a plan GenClass no longer sells is cancelled and ends on ${day(b.current_period_end)}, without another charge.` - : ` Your subscription to a plan GenClass no longer sells is still open in Stripe and can bill again: cancel it in Manage billing, or email ${esc(CONTACT)}.` + : ` Your subscription to a plan GenClass no longer sells is still open in Stripe and can bill again: cancel it below, or email ${esc(CONTACT)}.` : overdue ? ` The last payment for your paid plan did not go through, so it has ended. Update your card in Manage billing to pay it and get the plan back, or email ${esc(CONTACT)}.` : b.subscription_id && b.current_period_end && b.subscription_status === "canceled" && Date.parse(b.current_period_end) > v.now.getTime() - GRACE_DAYS * 86_400_000 @@ -163,10 +267,10 @@ function statusLine(v: BillingView, plan: Plan): string { return `You are on the ${name} plan. The last payment did not go through; Stripe tries the card again over the next days. Update it in Manage billing to keep ${esc(plan.name)}: if it is still unpaid ${PAST_DUE_GRACE_DAYS} days after the failed payment, the account moves to the Free plan.`; } if (b.cancel_at_period_end) { - 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.`; + return `You are on the ${name} plan until ${day(b.current_period_end)}. It is cancelled and will not renew; you can resume it below 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, v.country ?? null))}). Cancel in Manage billing before then and nothing is charged; ${esc(plan.name)} then ends at once.`; + 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, v.country ?? null))}). Cancel 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; @@ -199,7 +303,7 @@ function planColumn(v: BillingView, p: Plan, current: Plan): string { const talk = `Talk to us`; let act = ""; if (cur) act = `${v.access.source === "comp" ? "Set up by GenClass" : v.access.source === "open" ? "This server" : "Your plan"}`; - else if (p.id === "free") act = subscribed && v.live ? 'To go back to Free, cancel in Manage billing.' : ""; + else if (p.id === "free") act = subscribed && v.live ? 'To go back to Free, cancel your plan.' : ""; else if (byAgreement(p)) act = talk; else if (v.live && !waiting) act = buy; const features = p.features @@ -283,6 +387,9 @@ export function projectPlanPage(nonce: string, v: ProjectPlanView): string { const offer = PAID_PLANS[0] ?? null; const a = v.access; const paid = a.source === "paid"; + // the app has a subscription of its own (bought per app, billing/plans.json version 4): cancelled and resumed here; + // an app the account's plan covers is cancelled with that plan, on the billing page + const ownSub = paid && v.live && CANCELLABLE.has(v.sub.status ?? ""); const name = esc(v.project.name); // version 5 (2026-11-13): Pro is the account's, per developer, for up to 3 apps; every new app sees this page, a // paying account included (Continue with Pro), and an app past what the plan covers waits here: more apps are @@ -295,7 +402,7 @@ export function projectPlanPage(nonce: string, v: ProjectPlanView): string { ? `Your ${esc(offer?.name ?? "paid")} plan covers up to ${a.apps ?? 0} apps, and ${name} is one more. More apps come with Enterprise, agreed by email.` : paid ? v.sub.cancels - ? `${name} is on ${esc(a.plan.name)} until ${day(v.sub.periodEnd)}. It is cancelled and will not renew; you can resume it in Manage billing.` + ? `${name} is on ${esc(a.plan.name)} until ${day(v.sub.periodEnd)}. It is cancelled and will not renew${ownSub ? "; you can resume it below" : ""}.` : v.sub.status === "past_due" ? `${name} is on ${esc(a.plan.name)}. The last payment did not go through: update your card in Manage billing.` : `Your ${esc(a.plan.name)} plan covers ${name}${a.apps ? ` (up to ${a.apps} apps on your account)` : ""}.` @@ -319,7 +426,7 @@ export function projectPlanPage(nonce: string, v: ProjectPlanView): string { // the card's lines: the first few, the rest folded (the owner, 2026-11-13: "too much written in the plan details") const features = offer ? pitchList(pitchLines(offer)) : ""; const action = covered - ? `

Your current plan.${paid ? ` Manage billing` : ""}

` + ? `

Your current plan.${paid ? ` Manage billing` : ""}${ownSub ? (v.sub.cancels ? ` Resume plan` : ` Cancel plan`) : paid ? ` Cancel plan` : ""}

` : proFull ? `Email us about Enterprise

Or remove an app you no longer use, and this one takes its place.

` : v.live @@ -352,8 +459,9 @@ export function projectPlanPage(nonce: string, v: ProjectPlanView): string { ${notice}${test}
${card} - +

All your projects and their plans

+ ${ownSub && !v.sub.cancels ? cancelDialogs() : ""}
`; @@ -390,6 +498,7 @@ ${notice}${test} }, function(e2){ err.textContent = gcWhy(e2); gcBusy(go, false); }); }); } + gcCancel(cfg.project); var portal = document.getElementById("portal"); if (portal) portal.addEventListener("click", function(e){ e.preventDefault(); @@ -428,9 +537,9 @@ ${notice}${test} user: { label, sub: orgName(label) }, ...orgRail("billing"), railLabel: "Organization", - css: DASH_CSS + ORG_CSS + BILLING_CSS + ".planpage .sb-ph{text-align:center}.planpage .sb-ph>div{margin:0 auto}.planpage #plan{background:none;border:0;box-shadow:none;padding:0;display:flex;flex-direction:column;align-items:center;gap:0}.planpage #plan .intro{margin:20px auto 0;text-align:center}.planpage #plan .err:empty{display:none}.planpage .notice{max-width:440px;margin-left:auto;margin-right:auto}.planpage .acct-form{justify-content:center}.plan.big{width:100%;max-width:440px;padding:24px 24px 22px;gap:8px}.plan.big h3{font-size:24px;letter-spacing:-.01em}.plan.big .price{font-size:15px;font-weight:600;margin-top:2px}.plan.big ul{margin-top:6px;gap:6px}.plan.big li{font-size:13.5px}.plan.big .pmore{font-size:12.5px}.plan.big .pmore ul{margin-top:6px}.plan.big .act{padding-top:12px}.plan.big .act .btn{width:100%;justify-content:center;padding:11px 16px;font-size:14.5px}.free{margin-top:12px;font-size:11px;width:100%;max-width:440px;text-align:center}.linkish{background:none;border:0;padding:0;font:inherit;font-size:11px;color:var(--ink3);text-decoration:underline;cursor:pointer}.linkish:disabled{opacity:.6;cursor:default}.planpage .linkish{display:inline-block;padding:6px 12px;margin:-6px -12px}.trialnote{margin:10px 0 0;font-size:13px;color:var(--ink3);text-align:center;width:100%}dialog.why{margin:auto;max-height:calc(100vh - 32px);overflow:auto;max-width:460px;width:calc(100% - 32px);border:1px solid var(--rule);border-radius:14px;background:var(--paper);color:var(--ink);padding:24px 24px 20px}dialog.why::backdrop{background:rgba(0,0,0,.62)}dialog.why h2{font-size:21px;margin:0 0 4px}dialog.why fieldset{border:0;padding:0;margin:14px 0 6px}dialog.why label{display:flex;gap:10px;align-items:center;padding:7px 0;font-size:15px;cursor:pointer}dialog.why textarea{margin-top:6px}.why-act{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}", + css: DASH_CSS + ORG_CSS + BILLING_CSS + ".planpage .sb-ph{text-align:center}.planpage .sb-ph>div{margin:0 auto}.planpage #plan{background:none;border:0;box-shadow:none;padding:0;display:flex;flex-direction:column;align-items:center;gap:0}.planpage #plan .intro{margin:20px auto 0;text-align:center}.planpage #plan .err:empty{display:none}.planpage .notice{max-width:440px;margin-left:auto;margin-right:auto}.planpage .acct-form{justify-content:center}.plan.big{width:100%;max-width:440px;padding:24px 24px 22px;gap:8px}.plan.big h3{font-size:24px;letter-spacing:-.01em}.plan.big .price{font-size:15px;font-weight:600;margin-top:2px}.plan.big ul{margin-top:6px;gap:6px}.plan.big li{font-size:13.5px}.plan.big .pmore{font-size:12.5px}.plan.big .pmore ul{margin-top:6px}.plan.big .act{padding-top:12px}.plan.big .act .btn{width:100%;justify-content:center;padding:11px 16px;font-size:14.5px}.free{margin-top:12px;font-size:11px;width:100%;max-width:440px;text-align:center}.linkish{background:none;border:0;padding:0;font:inherit;font-size:11px;color:var(--ink3);text-decoration:underline;cursor:pointer}.linkish:disabled{opacity:.6;cursor:default}.planpage .linkish{display:inline-block;padding:6px 12px;margin:-6px -12px}.trialnote{margin:10px 0 0;font-size:13px;color:var(--ink3);text-align:center;width:100%}dialog.why{margin:auto;max-height:calc(100vh - 32px);overflow:auto;max-width:460px;width:calc(100% - 32px);border:1px solid var(--rule);border-radius:14px;background:var(--paper);color:var(--ink);padding:24px 24px 20px}dialog.why::backdrop{background:rgba(0,0,0,.62)}dialog.why h2{font-size:21px;margin:0 0 4px}dialog.why fieldset{border:0;padding:0;margin:14px 0 6px}dialog.why label{display:flex;gap:10px;align-items:center;padding:7px 0;font-size:15px;cursor:pointer}dialog.why textarea{margin-top:6px}.why-act{display:flex;gap:10px;flex-wrap:wrap;margin-top:14px}.planpage #plan .cx .err:empty{display:none}" + CANCEL_CSS, body, - script: CLIENT_JS + script, + script: CLIENT_JS + CANCEL_JS + script, }); } @@ -500,6 +609,13 @@ export function billingPage(nonce: string, v: BillingView): string { const want = awaited(v, plan); const a = v.account; const manage = v.live && v.billing.stripe_customer_id; + // cancelling and resuming are GenClass's own (the popups below), for a subscription that still exists + const holds = !!manage && !!v.billing.subscription_id && CANCELLABLE.has(v.billing.subscription_status ?? ""); + const cancelBtn = !holds + ? "" + : v.billing.cancel_at_period_end + ? '' + : ''; let notice = ""; if (v.done) { const to = want && want !== "paid" ? planById(want) : null; @@ -546,9 +662,10 @@ ${ manage ? `

Manage billing

On Stripe
-

Card, invoices${PAID_PLANS.some((p) => p.per_seat === true) ? ", seats" : ""} and cancellation.

-
- +

Card${PAID_PLANS.some((p) => p.per_seat === true) ? ", invoices and seats" : " and invoices"}.${holds ? (v.billing.cancel_at_period_end ? " Your plan is set to end: resume it here." : " Cancel your plan here.") : ""}

+
${cancelBtn}
+ + ${holds && !v.billing.cancel_at_period_end ? cancelDialogs() : ""}
` : "" } @@ -608,6 +725,7 @@ ${teamSection(v)} gcBusy(portal, true, "Opening Stripe..."); gcPost("/api/billing/portal", {}).then(function(j){ location.href = j.url; }, function(e){ err.textContent = gcWhy(e); gcBusy(portal, false); }); }); + gcCancel(null); // back from a checkout started on a page check, the plan already showing: the report, which now opens with Pro if (cfg.next && cfg.done && !cfg.want) { location.replace(cfg.next); return; } if (cfg.want) { @@ -633,9 +751,9 @@ ${teamSection(v)} user: { label, sub: orgName(label) }, ...orgRail("billing"), railLabel: "Organization", - css: DASH_CSS + ORG_CSS + BILLING_CSS, + css: DASH_CSS + ORG_CSS + BILLING_CSS + CANCEL_CSS, body, - script: CLIENT_JS + script, + script: CLIENT_JS + CANCEL_JS + script, }); } diff --git a/telemetry-worker/src/billing.ts b/telemetry-worker/src/billing.ts index c241b96a..cbc05ae1 100644 --- a/telemetry-worker/src/billing.ts +++ b/telemetry-worker/src/billing.ts @@ -9,6 +9,13 @@ // POST /api/billing/trial 410: the trial of 2026-10 is gone; Pro's trial starts at Checkout // POST /api/billing/portal browser session + Origin; {url} of the Billing Portal // POST /api/billing/webhook Stripe only: signature, no session (src/stripe.ts) +// GET /api/billing/cancel[?project=] browser session; what cancelling means for the plan (the +// 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/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 // back to that report after the checkout (straight away with Pro) @@ -60,6 +67,8 @@ import { type Plan, } from "./plans.js"; import { + applyRetention, + cancelNow, checkCustomer, checkoutSession, ensureCustomer, @@ -73,6 +82,10 @@ import { notifyOwner, openTrialElsewhere, portalSession, + refreshSubscription, + resumeSubscription, + retentionOffer, + scheduleCancel, sharedCustomer, StripeError, stripeWebhook, @@ -187,6 +200,12 @@ export async function routeBilling(request: Request, url: URL, path: string, env return m === "POST" ? checkout(c, f) : method(); case "/api/billing/portal": return m === "POST" ? portal(c, f) : method(); + case "/api/billing/cancel": + return get ? cancelInfo(c, f, url.searchParams.get("project")) : m === "POST" ? cancelPlan(c, f) : method(); + case "/api/billing/cancel/offer": + return m === "POST" ? cancelOffer(c, f) : method(); + case "/api/billing/resume": + return m === "POST" ? resumePlan(c, f) : method(); case "/api/billing/pro": return get ? proAnswer(c) : method(); case "/api/billing/trial": @@ -460,7 +479,7 @@ async function checkout(c: C, f: Fetch): Promise { return fail(409, `the last payment for your ${planById(st.priced).name} plan did not go through; update your card in Manage billing to pay it, or email ${PLANS_FILE.contact}`); } if (st.priced === plan.id) { - return fail(409, `you are already on the ${plan.name} plan${st.cancelAtPeriodEnd ? "; to keep it after this period, resume it in Manage billing" : ""}`); + return fail(409, `you are already on the ${plan.name} plan${st.cancelAtPeriodEnd ? "; to keep it after this period, resume it on this page" : ""}`); } // a switch is paid on Checkout, never in the portal: a subscription sold through Managed Payments cannot take // another plan's price, and must not move onto another subscription outside it (src/stripe.ts header) @@ -524,6 +543,166 @@ async function portal(c: C, f: Fetch): Promise { } } +// --------------------------------------------------------------------------------------------- cancel, offer, resume + +// a Stripe subscription, read field by field +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Sub = Record; + +interface CancelTarget { + auth: Auth; + sub: Sub; + /** Every subscription of the account's customer, any status. */ + subs: Sub[]; + /** The plan's name as the pages say it ("Pro"; a plan GenClass no longer sells: "paid"). */ + name: string; + /** The app whose own subscription this is, or null for the account's. */ + project: { id: string; name: string } | null; +} + +/** + * The subscription a cancel, its offer or a resume is about: the account's, or with `projectId` that app's own (a + * plan bought per app under billing/plans.json version 4). Only the account that pays reaches it, and only a + * subscription Stripe lists now on the account's own GenClass customer, provably GenClass's, naming this account (and + * this app, or no app). Anything else is a 4xx and nothing is changed. + */ +async function cancelTarget(c: C, f: Fetch, a: Auth, projectId: string | null): Promise { + if (!canBuy(c.env, a.account)) return fail(503, "paid plans are not on sale yet"); + const b = await accountBilling(c.db, a.account.id, c.env); + let project: CancelTarget["project"] = null; + let subId = b.subscription_id; + if (projectId !== null) { + const p = await ownedProject(c, a.account.id, projectId); + if (!p || !p.id) return fail(404, "not found"); + const row = await c.db.prepare("SELECT subscription_id FROM projects WHERE id = ? AND account_id = ?").bind(p.id, a.account.id).first<{ subscription_id: string | null }>(); + project = { id: p.id, name: p.name }; + subId = row?.subscription_id ?? null; + } + if (!b.stripe_customer_id || !subId) return fail(409, project ? `${project.name} has no paid plan of its own` : "this account has no paid plan"); + if (await overBudget(c.env.AUTH_LIMIT, "cancel", a.account.id)) return tooMany(); + const own = await checkCustomer(c.env, f, a.account.id, b.stripe_customer_id); + if (own.state === "missing") return fail(409, `Stripe has no billing records for this account; email ${PLANS_FILE.contact}`); + if (own.state === "not_genclass") return refuseShared(c, f, a.account.id, b.stripe_customer_id, NOT_GENCLASS); + const sub = (own.subs as Sub[]).find((s) => s?.id === subId); + const named = sub?.metadata?.genclass_account; + if (!sub || !isGenClassSubscription(sub) || (named !== undefined && named !== null && named !== a.account.id) || projectOf(sub) !== (project?.id ?? null)) { + return fail(409, `this plan cannot be changed here; email ${PLANS_FILE.contact} and we will do it for you`); + } + const priced = subscriptionState(sub).priced; + return { auth: a, sub, subs: own.subs as Sub[], name: priced ? planById(priced).name : "paid", project }; +} + +/** 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); + +/** 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). + */ +async function cancelInfo(c: C, f: Fetch, projectId: string | null): Promise { + const a = await browserRead(c); + if (a instanceof Response) return a; + try { + const t = await cancelTarget(c, f, a, projectId || null); + if (t instanceof Response) return t; + const st = subscriptionState(t.sub); + if (!HOLDING_STATUSES.has(st.status)) return fail(409, `your ${t.name} plan has already ended`); + if (st.cancelAtPeriodEnd) return fail(409, `your ${t.name} plan is already cancelled and will not renew`); + const offer = await retentionOffer(c.env, f, t.sub, t.subs).catch(() => 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 }); + } catch (e) { + return stripeFail(e); + } +} + +/** + * POST /api/billing/cancel/offer: the person stays, with the offer's coupon on the subscription from its next invoice. + * 409 when this subscription cannot have it (retentionOffer). The owner is told. + */ +async function cancelOffer(c: C, f: Fetch): Promise { + const a = await browserWrite(c, "a plan is changed"); + if (a instanceof Response) return a; + const body = await readJson(c, 1024); + if (body instanceof Response) return body; + try { + const t = await cancelTarget(c, f, a, projectIn(body)); + if (t instanceof Response) return t; + const offer = await retentionOffer(c.env, f, t.sub, t.subs); + if (!offer) return fail(409, "this offer is not available for your plan"); + await applyRetention(c.env, f, t.sub.id as string, c.now); + await notifyOwner( + { env: c.env, fetch: f, now: c.now }, + { event: "retention_offer_taken", text: `${modeNote(c.env)}Stayed instead of cancelling ${t.name}, with ${offer.percent}% off for ${offer.months} months: ${cancelWho(t)}.`, account_id: a.account.id, subscription_id: t.sub.id }, + ).catch(() => false); + return json(200, { ok: true, percent_off: offer.percent, months: offer.months }); + } catch (e) { + return stripeFail(e); + } +} + +/** + * 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 + * 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 { + const a = await browserWrite(c, "a plan is cancelled"); + if (a instanceof Response) return a; + const body = await readJson(c, 1024); + if (body instanceof Response) return body; + try { + const t = await cancelTarget(c, f, a, projectIn(body)); + if (t instanceof Response) return t; + 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 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 }); + } catch (e) { + return stripeFail(e); + } +} + +/** POST /api/billing/resume: a plan set to end goes on as before (the same price; nothing is charged now). */ +async function resumePlan(c: C, f: Fetch): Promise { + const a = await browserWrite(c, "a plan is resumed"); + if (a instanceof Response) return a; + const body = await readJson(c, 1024); + if (body instanceof Response) return body; + try { + const t = await cancelTarget(c, f, a, projectIn(body)); + if (t instanceof Response) return t; + const st = subscriptionState(t.sub); + if (!LIVE_RESUME.has(st.status)) return fail(409, `your ${t.name} plan has ended; start it again on this page`); + if (!st.cancelAtPeriodEnd) return json(200, { ok: true }); + await resumeSubscription(c.env, f, t.sub); + await refreshSubscription({ env: c.env, db: c.db, fetch: f, now: c.now }, t.sub.id as string).catch(() => null); + return json(200, { ok: true }); + } catch (e) { + return stripeFail(e); + } +} +/** The statuses a plan set to end can be resumed in. */ +const LIVE_RESUME = new Set(["active", "trialing", "past_due"]); + /** * The days free a purchase of `plan` starts with: the plan's trial_days (Pro: 3) for an account that has never had a * subscription, none of its apps and not the account (D1), and none on its Stripe customer (`stripeSubs`, any diff --git a/telemetry-worker/src/stripe.ts b/telemetry-worker/src/stripe.ts index 853eedf8..49688d53 100644 --- a/telemetry-worker/src/stripe.ts +++ b/telemetry-worker/src/stripe.ts @@ -43,6 +43,12 @@ // 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. +// - 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). // - 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 @@ -488,7 +494,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, cancel at period end. It offers 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: scheduleCancel) 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). */ @@ -519,6 +525,88 @@ export async function cancelNow(env: Env, f: Fetch, subscriptionId: string): Pro } } +// --------------------------------------------------------------------------------------------- cancel, offer, resume + +/** The coupon offered once to someone about to cancel, by its id in each Stripe mode (scripts/stripe-setup.mjs makes it). */ +export const RETENTION_COUPON = "genclass_stay_15"; +/** The most an offer to stay may take off and for how long (the owner, 2026-11-18): a coupon beyond it is never offered. */ +export const RETENTION_MAX = { percent: 15, months: 6 }; +/** The subscription metadata key that says the offer was taken (its value: when). One offer per customer. */ +export const RETENTION_MARK = "genclass_retention"; + +export interface RetentionOffer { + percent: number; + months: number; +} + +/** + * The offer to stay for this subscription, as Stripe's coupon has it now, or null: only for a subscription that bills + * or is in its trial and is not set to end, that carries no discount (a promotion code's months free are not topped + * up), on a customer none of whose subscriptions (`subs`, any status) took the offer before, and only while the coupon + * is GenClass's (metadata genclass=1), valid, a percentage within RETENTION_MAX and for a set number of months. + */ +export async function retentionOffer(env: Env, f: Fetch, sub: Obj, subs: Obj[]): Promise { + if (sub?.status !== "active" && sub?.status !== "trialing") return null; + if (subscriptionState(sub).cancelAtPeriodEnd) return null; + if ((Array.isArray(sub?.discounts) && sub.discounts.length > 0) || sub?.discount) return null; + if (subs.some((s) => typeof s?.metadata?.[RETENTION_MARK] === "string" && s.metadata[RETENTION_MARK] !== "")) return null; + let c: Obj; + try { + c = await stripe(env, f, "GET", `/v1/coupons/${encodeURIComponent(RETENTION_COUPON)}`); + } catch (e) { + if (e instanceof StripeError && e.status === 404) return null; + throw e; + } + const percent = c?.percent_off; + const months = c?.duration_in_months; + if (c?.valid !== true || c?.metadata?.genclass !== GENCLASS_MARK || c?.duration !== "repeating") return null; + if (typeof percent !== "number" || !(percent > 0) || percent > RETENTION_MAX.percent) return null; + if (!Number.isInteger(months) || months < 1 || months > RETENTION_MAX.months) return null; + return { percent, months }; +} + +/** Put the offer's coupon on the subscription and mark it taken (RETENTION_MARK). The same call twice changes nothing more. */ +export async function applyRetention(env: Env, f: Fetch, subscriptionId: string, now: Date): Promise { + await stripe( + env, + f, + "POST", + `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, + { discounts: [{ coupon: RETENTION_COUPON }], metadata: { [RETENTION_MARK]: now.toISOString() } }, + `genclass-retention-${subscriptionId}`, + ); +} + +/** 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). + */ +export async function resumeSubscription(env: Env, f: Fetch, sub: Obj): Promise { + const id = idOf(sub?.id); + if (!id) throw new StripeError("not a subscription id", 400); + await stripe(env, f, "POST", `/v1/subscriptions/${encodeURIComponent(id)}`, sub?.cancel_at_period_end === true ? { cancel_at_period_end: false } : { cancel_at: "" }); +} + +/** + * After GenClass itself changed a subscription (a cancel, a resume): the subscription as Stripe has it now, written + * as the webhook writes it (the account's row, or its project's), so the page is right before Stripe's event arrives; + * that event then writes the same again. The same ownership checks as an event's. + */ +export async function refreshSubscription(x: EventContext, subscriptionId: string): Promise { + const event = { type: "genclass.refresh", id: subscriptionId }; + const sub = await fetchSubscription(x, subscriptionId); + const account = await accountByCustomer(x.db, idOf(sub?.customer)); + if (!account || !accountsSubscription(account, sub)) return ignored("the subscription is not the account's", event); + if (projectOf(sub)) return applyProjectSubscription(x, account, sub, event); + if (!isGenClassSubscription(sub) && idOf(sub?.id) !== account.subscription_id) return ignored("not a GenClass subscription", event, true); + return applySubscription(x, account, sub, event); +} + /** * Close the account's own open Checkout pages (metadata genclass=1 and genclass_account), so none can start a * subscription later: before an account is deleted. A page GenClass did not make is left alone. diff --git a/telemetry-worker/test/account-helpers.ts b/telemetry-worker/test/account-helpers.ts index 0436a167..57011d21 100644 --- a/telemetry-worker/test/account-helpers.ts +++ b/telemetry-worker/test/account-helpers.ts @@ -184,6 +184,10 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon const paymentIntents = new Map>(); const piKeys = new Map(); const portal: Record[] = PORTAL_CONFIGS.map((c) => ({ ...c, metadata: { ...c.metadata } })); + /** Coupons by id; the offer to stay (src/stripe.ts RETENTION_COUPON) is there as scripts/stripe-setup.mjs makes it. */ + const coupons = new Map>([ + ["genclass_stay_15", { id: "genclass_stay_15", object: "coupon", percent_off: 15, duration: "repeating", duration_in_months: 6, valid: true, metadata: { genclass: "1" } }], + ]); /** A subscription's latest invoice as an expansion returns it. */ const latest = (sub: Record) => typeof sub.latest_invoice === "string" @@ -334,12 +338,27 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon } return ok(pi); } + const cpn = /^\/v1\/coupons\/([^/]+)$/.exec(p); + if (method === "GET" && cpn) { + const c = coupons.get(decodeURIComponent(cpn[1]!)); + return c ? ok(c) : ok({ error: { code: "resource_missing", message: "No such coupon" } }, 404); + } const sub = /^\/v1\/subscriptions\/([^/]+)$/.exec(p); if (sub) { const s = subs.get(decodeURIComponent(sub[1]!)); if (!s) return ok({ error: { message: "No such subscription" } }, 404); if (method === "DELETE") s.status = "canceled"; - if (method === "POST") s.metadata = { ...(s.metadata ?? {}), ...formObject(form!, "metadata") }; + if (method === "POST") { + s.metadata = { ...(s.metadata ?? {}), ...formObject(form!, "metadata") }; + // a cancel at the period end and its undo, as Stripe shows them; a coupon put on the subscription + if (form!.get("cancel_at_period_end") === "true") Object.assign(s, { cancel_at_period_end: true, cancel_at: s.items?.data?.[0]?.current_period_end ?? null }); + if (form!.get("cancel_at_period_end") === "false" || form!.get("cancel_at") === "") Object.assign(s, { cancel_at_period_end: false, cancel_at: null }); + const coupon = form!.get("discounts[0][coupon]"); + if (coupon) { + if (!coupons.has(coupon)) return ok({ error: { code: "resource_missing", param: "discounts[0][coupon]", message: `No such coupon: '${coupon}'` } }, 400); + s.discounts = [`di_${coupon}`]; + } + } if (method === "GET") { const out: Record = { ...s }; if (expands(url).includes("customer")) { @@ -361,7 +380,7 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon const genclassCustomer = (id: string, accountId: string, email = "ada@example.com") => { customers.set(id, { id, object: "customer", email, description: "GenClass account", metadata: { genclass: "1", genclass_account: accountId } }); }; - return { fetch, calls, other, customers, subs, sessions, invoices, refunds, charges, paymentIntents, portal, genclassCustomer }; + return { fetch, calls, other, customers, subs, sessions, invoices, refunds, charges, paymentIntents, portal, coupons, genclassCustomer }; } /** The GenClass prices the fake Stripe knows by lookup key: the fixture's (Pro, Custom), the retired Individual, the real plans' Pro and a private price the tests give it. */ diff --git a/telemetry-worker/test/billing.test.ts b/telemetry-worker/test/billing.test.ts index df319c23..68e3afec 100644 --- a/telemetry-worker/test/billing.test.ts +++ b/telemetry-worker/test/billing.test.ts @@ -251,7 +251,7 @@ describe("POST /api/billing/checkout and /api/billing/portal", () => { // a cancelled-at-period-end plan says how to keep it s.subs.get("sub_late000001")!.cancel_at_period_end = true; expect(((await (await call(env, "POST", "/api/billing/checkout", { body: { plan: "pro" }, cookie, fetch: s.fetch })).json()) as any).error).toBe( - "you are already on the Pro plan; to keep it after this period, resume it in Manage billing", + "you are already on the Pro plan; to keep it after this period, resume it on this page", ); }); @@ -1139,7 +1139,7 @@ describe("Managed Payments for Pro, flexible billing mode, switching between Pro expect(page).toContain("Switching between Pro and Custom opens Stripe's checkout for the new plan."); expect(page).toContain("its unused days are refunded to the card or account that paid for it"); expect(page).not.toContain("switch between Pro and Custom, or cancel"); - expect(page).toContain("

Card, invoices and cancellation.

"); + expect(page).toContain("

Card and invoices. Cancel your plan here.

"); const r = await call(t.env, "POST", "/api/billing/checkout", { body: { plan: "custom" }, cookie: t.cookie, fetch: t.s.fetch }); expect(r.status).toBe(200); expect(await r.json()).toEqual({ url: "https://checkout.stripe.com/c/pay/cs_test_000001", switch: true }); diff --git a/telemetry-worker/test/cancel.test.ts b/telemetry-worker/test/cancel.test.ts new file mode 100644 index 00000000..85bbd8de --- /dev/null +++ b/telemetry-worker/test/cancel.test.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { resetTokenCache } from "../src/dashboard.js"; +import { resetOwnerCache } from "../src/paid.js"; +import { resetStripeCache, RETENTION_COUPON, RETENTION_MAX } from "../src/stripe.js"; +import { call, cliToken, createApp, fakeStripe, GENCLASS_PORTAL, resetClock, setPlan, setup, signedIn, subscription, WEBHOOK_SECRET } from "./account-helpers.js"; + +// 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 +// 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 })); + +const LIVE = { STRIPE_SECRET_KEY: "sk_live_fake", STRIPE_WEBHOOK_SECRET: WEBHOOK_SECRET, STRIPE_PORTAL_CONFIGURATION: GENCLASS_PORTAL, NOTIFY_WEBHOOK: "https://hooks.example.com/notify" }; +const CUS = "cus_ada0000001"; +const SUB = "sub_ada0000001"; +const END = 1_792_000_000; + +beforeEach(() => { + resetClock(); + resetTokenCache(); + resetOwnerCache(); + resetStripeCache(); +}); + +/** An account on Pro with its subscription in the fake Stripe (`status`, and anything else `over` sets on it). */ +async function paying(status = "active", over: Record = {}) { + const t = setup(LIVE); + const a = await signedIn(t.env); + const s = fakeStripe(); + s.genclassCustomer(CUS, a.account.id); + const sub: Record = subscription(SUB, a.account.id, CUS, "genclass_pro_monthly", status, { discounts: [], ...over }); + s.subs.set(SUB, sub); + setPlan(t.sql, a.account.id, "pro", { stripe_customer_id: CUS, subscription_id: SUB, subscription_status: status, stripe_mode: "live", current_period_end: new Date(END * 1000).toISOString() }); + const row = () => t.sql.rows("SELECT plan, subscription_status, cancel_at_period_end FROM accounts")[0]; + const writes = () => s.calls.filter((c) => c.method !== "GET").map((c) => `${c.method} ${c.url.pathname}`); + const get = (path = "/api/billing/cancel") => call(t.env, "GET", path, { cookie: a.cookie, fetch: s.fetch }); + const post = (path: string, body: Record = {}) => call(t.env, "POST", path, { body, cookie: a.cookie, fetch: s.fetch }); + const notices = () => s.other.filter((o) => o.url === LIVE.NOTIFY_WEBHOOK).map((o) => JSON.parse(o.body) as { event: string; text: string }); + return { ...t, ...a, s, sub, row, writes, get, post, notices }; +} + +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 () => { + 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(t.writes()).toEqual([]); + expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 0 }); + }); + + it("a trial: it would end at once", async () => { + const t = await paying("trialing", { trial_end: END }); + expect(await (await t.get()).json()).toMatchObject({ trial: true, offer: { percent_off: 15, months: 6 } }); + }); + + 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 }); + 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 }); + const late = await paying("past_due"); + expect(await (await late.get()).json()).toMatchObject({ ok: true, offer: null }); + }); + + it(`never more than ${RETENTION_MAX.percent}% for ${RETENTION_MAX.months} months: a coupon beyond that, not GenClass's, used up or missing is not offered, and cancelling still works`, async () => { + for (const edit of [ + (c: Record) => (c.percent_off = 20), + (c: Record) => (c.duration_in_months = 12), + (c: Record) => (c.duration = "forever"), + (c: Record) => (c.metadata = {}), + (c: Record) => (c.valid = false), + null, + ]) { + const t = await paying(); + if (edit) edit(t.s.coupons.get(RETENTION_COUPON)!); + else t.s.coupons.delete(RETENTION_COUPON); + expect(await (await t.get()).json()).toMatchObject({ ok: true, plan: "Pro", offer: null }); + expect((await t.post("/api/billing/cancel/offer")).status).toBe(409); + expect(t.writes()).toEqual([]); + expect((await t.post("/api/billing/cancel")).status).toBe(200); + } + }); + + it("a plan already set to end, or one that has ended, has nothing to cancel", async () => { + const set = await paying("active", { cancel_at_period_end: true }); + expect((await set.get()).status).toBe(409); + const ended = await paying("canceled"); + expect((await ended.get()).status).toBe(409); + expect((await ended.post("/api/billing/cancel")).status).toBe(409); + expect(ended.writes()).toEqual([]); + }); +}); + +describe("POST /api/billing/cancel/offer: staying, for 15% less over 6 months", () => { + it("puts GenClass's coupon on the subscription, marks it taken and tells the owner; the plan goes on", async () => { + const t = await paying(); + const r = await t.post("/api/billing/cancel/offer"); + expect(r.status).toBe(200); + expect(await r.json()).toEqual({ ok: true, percent_off: 15, months: 6 }); + const w = t.s.calls.filter((c) => c.method === "POST"); + expect(w.map((c) => c.url.pathname)).toEqual([`/v1/subscriptions/${SUB}`]); + expect(Object.fromEntries(w[0]!.form!)).toEqual({ "discounts[0][coupon]": RETENTION_COUPON, "metadata[genclass_retention]": expect.stringMatching(/^20\d\d-/) }); + expect(w[0]!.headers["idempotency-key"]).toBe(`genclass-retention-${SUB}`); + expect(t.sub.cancel_at_period_end).toBe(false); + expect(t.row()).toEqual({ plan: "pro", subscription_status: "active", cancel_at_period_end: 0 }); + expect(t.notices()).toEqual([expect.objectContaining({ event: "retention_offer_taken", text: expect.stringContaining("15% off for 6 months: ada@example.com") })]); + // once: a second cancel sees no offer, and asking for it again is refused + expect(await (await t.get()).json()).toMatchObject({ offer: null }); + expect((await t.post("/api/billing/cancel/offer")).status).toBe(409); + expect(t.s.calls.filter((c) => c.method === "POST")).toHaveLength(1); + }); +}); + +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 () => { + 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 + const page = await (await call(t.env, "GET", "/account/billing", { cookie: t.cookie })).text(); + expect(page).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); + expect(t.writes()).toHaveLength(1); + expect(t.notices()).toHaveLength(1); + }); + + 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 }); + 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("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"); + 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(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); + expect(Object.fromEntries(old.s.calls.find((c) => c.method === "POST")!.form!)).toEqual({ cancel_at: "" }); + expect(old.sub.cancel_at).toBe(null); + // nothing to resume: no write + const plain = await paying(); + expect((await plain.post("/api/billing/resume")).status).toBe(200); + expect(plain.writes()).toEqual([]); + }); + + it("an app's own subscription (bought per app) is cancelled with project_id, and only that one", async () => { + const t = await paying(); + const app = await createApp(t.env, t.cookie); + const own = subscription("sub_app0000001", t.account.id, CUS, "genclass_pro_monthly", "active", { discounts: [], metadata: { genclass: "1", genclass_account: t.account.id, genclass_project: app.id } }); + t.s.subs.set(own.id, own); + 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.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); + expect((await t.post("/api/billing/cancel", { project_id: app.id })).status).toBe(409); + expect((await t.post("/api/billing/cancel", { project_id: "nosuchproject0000" })).status).toBe(404); + }); +}); + +describe("who may cancel: the paying account, in the browser, and only GenClass's own subscription", () => { + it("signed out, another site's request and the genclass command are refused before any Stripe call", async () => { + const t = await paying(); + for (const path of ["/api/billing/cancel", "/api/billing/cancel/offer", "/api/billing/resume"]) { + expect((await call(t.env, "POST", path, { body: {}, fetch: t.s.fetch })).status).toBe(401); + expect((await call(t.env, "POST", path, { body: {}, cookie: t.cookie, origin: "https://evil.example", fetch: t.s.fetch })).status).toBe(403); + expect((await call(t.env, "POST", path, { body: {}, bearer: await cliToken(t.env, t.cookie), origin: null, fetch: t.s.fetch })).status).toBe(403); + } + expect((await call(t.env, "GET", "/api/billing/cancel", { fetch: t.s.fetch })).status).toBe(401); + expect((await call(t.env, "PUT", "/api/billing/cancel", { body: {}, cookie: t.cookie, fetch: t.s.fetch })).status).toBe(405); + expect(t.s.calls).toEqual([]); + }); + + it("an account with no plan, a customer that is not GenClass's, and a subscription that is not this account's change nothing", async () => { + const free = setup(LIVE); + const a = await signedIn(free.env); + const s0 = fakeStripe(); + expect((await call(free.env, "POST", "/api/billing/cancel", { body: {}, cookie: a.cookie, fetch: s0.fetch })).status).toBe(409); + expect(s0.calls).toEqual([]); + + const foreign = await paying(); + foreign.s.customers.set(CUS, { id: CUS, object: "customer", metadata: {} }); + expect((await foreign.post("/api/billing/cancel")).status).toBe(409); + expect(foreign.writes()).toEqual([]); + + const other = await paying(); + other.sub.items.data[0].price = { id: "price_other00001", object: "price", lookup_key: null, product: { id: "prod_other00001", object: "product", metadata: {} } }; + for (const path of ["/api/billing/cancel", "/api/billing/cancel/offer", "/api/billing/resume"]) expect((await other.post(path)).status).toBe(409); + expect(other.writes()).toEqual([]); + + const named = await paying("active", { metadata: { genclass: "1", genclass_account: "someone-else" } }); + expect((await named.post("/api/billing/cancel")).status).toBe(409); + expect(named.writes()).toEqual([]); + }); +}); + +describe("the billing page: Cancel plan opens the popups", () => { + it("a paying account gets the button and the three popups; a Free account gets neither", async () => { + 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"); + for (const id of ["cx1", "cx2", "cx3"]) expect(page).toContain(`cancel your plan.'); + expect(page).not.toContain("cancel in Manage billing"); + const free = setup(LIVE); + const a = await signedIn(free.env); + const none = await (await call(free.env, "GET", "/account/billing", { cookie: a.cookie })).text(); + expect(none).not.toContain('id="cancelplan"'); + expect(none).not.toContain(' { @@ -542,7 +542,7 @@ describe("Pro's trial: a cancel during the 3 free days ends the trial and Pro at } 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."); + expect(await text(call(b.env, "GET", "/account/billing", { cookie: b.cookie }))).toContain("It is cancelled and will not renew; you can resume it below 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"); @@ -810,7 +810,7 @@ describe("an app past what the plan covers waits on its plan page (Free: one app t.sql.db.prepare("UPDATE projects SET plan = 'team', stripe_mode = 'live', subscription_id = 'sub_s', subscription_status = 'active' WHERE id = ?").run(app.id); const r = await call(t.env, "DELETE", `/api/account/projects/${app.id}`, { body: { confirm: "delete" }, cookie: t.cookie }); expect(r.status).toBe(409); - expect((await r.json() as any).error).toContain("cancel it in Manage billing"); + expect((await r.json() as any).error).toContain("cancel it on its plan page"); t.sql.db.prepare("UPDATE projects SET subscription_status = 'canceled', plan = NULL WHERE id = ?").run(app.id); expect((await call(t.env, "DELETE", `/api/account/projects/${app.id}`, { body: { confirm: "delete" }, cookie: t.cookie })).status).toBe(204); }); diff --git a/telemetry-worker/test/stripe-setup-private.test.ts b/telemetry-worker/test/stripe-setup-private.test.ts index f0b9bdc2..e8e04e31 100644 --- a/telemetry-worker/test/stripe-setup-private.test.ts +++ b/telemetry-worker/test/stripe-setup-private.test.ts @@ -83,6 +83,8 @@ function account() { endpoints.set(x.id, x); return ok({ ...x, secret: "whsec_fresh" }); } + // the offer to stay's coupon (scripts/stripe-setup.mjs retention): missing, then made + if (method === "POST" && p === "/v1/coupons") return ok({ id: body.id, object: "coupon", valid: true, metadata: meta(body) }); if (method === "GET" && p === "/v1/billing_portal/configurations") { const d = q.get("is_default"); return ok({ data: [...portal.values()].filter((c) => d === null || String(c.is_default) === d), has_more: false }); diff --git a/telemetry-worker/test/stripe-setup.test.ts b/telemetry-worker/test/stripe-setup.test.ts index 3802c0b8..3689188f 100644 --- a/telemetry-worker/test/stripe-setup.test.ts +++ b/telemetry-worker/test/stripe-setup.test.ts @@ -46,6 +46,7 @@ function account() { // the other business's own API-made configuration (one per storefront, say): not the default, and not GenClass's ["bpc_otherstore01", { id: "bpc_otherstore01", object: "billing_portal.configuration", is_default: false, active: true, metadata: { storefront: "winter" }, business_profile: { headline: "the other business winter store" } }], ]); + const coupons = new Map(); const customers = new Map([["cus_other0000001", { id: "cus_other0000001", email: "ada@example.com", metadata: {} }]]); const calls: { method: string; url: URL; body: Obj }[] = []; let n = 0; @@ -120,6 +121,12 @@ function account() { if (body.disabled === "false") x.status = "enabled"; return ok(x); } + if ((m = /^\/v1\/coupons(?:\/([^/]+))?$/.exec(p))) { + if (method === "GET") return coupons.has(m[1]!) ? ok(coupons.get(m[1]!)) : missing("coupon"); + const x = { id: body.id, object: "coupon", name: body.name, percent_off: Number(body.percent_off), duration: body.duration, duration_in_months: Number(body.duration_in_months), valid: true, metadata: meta(body) }; + coupons.set(x.id, x); + return ok(x); + } if (method === "GET" && p === "/v1/billing_portal/configurations") { const d = q.get("is_default"); return ok({ data: [...portal.values()].filter((c) => d === null || String(c.is_default) === d), has_more: false }); @@ -139,7 +146,7 @@ function account() { } return ok({ error: { message: `fake Stripe has no ${method} ${p}` } }, 404); }; - return { products, prices, endpoints, portal, customers, calls, fetch, snapshot }; + return { products, prices, endpoints, portal, coupons, customers, calls, fetch, snapshot }; } async function run(a: ReturnType, o: { key?: string; argv?: string[] } = {}) { @@ -241,6 +248,11 @@ describe("scripts/stripe-setup.mjs on the shared Stripe account (shared with ano expect(f["features[subscription_update][enabled]"]).toBe("false"); expect(Object.keys(f).some((k) => /^features\[subscription_update\]\[(products|default_allowed_updates|proration_behavior)/.test(k))).toBe(false); expect(Object.keys(f).some((k) => /is_default/.test(k))).toBe(false); + // no cancelling in the portal: GenClass's billing page does it, behind its warning and its offer to stay + expect(f["features[subscription_cancel][enabled]"]).toBe("false"); + expect(Object.keys(f).filter((k) => k.startsWith("features[subscription_cancel]"))).toEqual(["features[subscription_cancel][enabled]"]); + // that offer's coupon: 15% off for 6 months, GenClass's own + expect([...a.coupons.values()]).toEqual([{ id: "genclass_stay_15", object: "coupon", name: "Thanks for staying: 15% off", percent_off: 15, duration: "repeating", duration_in_months: 6, valid: true, metadata: { genclass: "1" } }]); // a buyer may change the email and tax id of their GenClass customer, never an address (GenClass needs none) const updates = Object.entries(f).filter(([k]) => /^features\[customer_update\]\[allowed_updates\]\[\d+\]$/.test(k)).map(([, v]) => v); expect(updates).toEqual(["email", "tax_id"]);