From 70edb43df8f15d76f1aa4096200d6c7b2364e869 Mon Sep 17 00:00:00 2001 From: Mehar Khanna Date: Wed, 18 Nov 2026 14:23:25 -0500 Subject: [PATCH] Billing: a cancel within 3 days of a renewal is refunded; shorter cancel popups The owner, 2026-11-18: "If they cancel genclass within the first 3 days of it being renewed let them get a refund", and the popups' "not on . Nothing is refunded for the days left." is extra and goes. POST /api/billing/cancel first gives the last payment back to the card, in full, when it was a renewal (the charge at the end of the trial and each month's after it; never the charge that starts a subscription, so subscribing again after a cancel is not a free plan) of the last 3 days, then ends the plan. A refund that fails never stops the cancel; the owner's notice says what went back or why nothing did. The popups say the plan ends as soon as you cancel, and name the refund only when there is one. Co-Authored-By: Claude Fable 5.2 --- telemetry-worker/README.md | 12 +++-- telemetry-worker/src/billing-pages.ts | 10 ++-- telemetry-worker/src/billing.ts | 26 ++++++--- telemetry-worker/src/stripe.ts | 63 +++++++++++++++++++--- telemetry-worker/test/cancel.test.ts | 77 +++++++++++++++++++++++---- 5 files changed, 152 insertions(+), 36 deletions(-) diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index 6621b36e..928a7ab1 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -557,8 +557,10 @@ app with a subscription of its own) opens up to three popups: a warning that the 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 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 +(the owner, 2026-11-15), and a discount or a promotion code's free months end with it. A cancel within 3 days of a +renewal (the charge at the end of the trial and each month's after it, never the charge that starts a subscription) +gives that payment back to the card in full (`src/stripe.ts` refundableOnCancel; the owner, 2026-11-18); any later, +nothing is refunded for the days left. 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). @@ -834,7 +836,7 @@ does about it. 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 (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 + refunded within 3 days of a renewal: `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: @@ -873,9 +875,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, 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 | +| `GET /api/billing/cancel[?project=]` | browser session: what the cancel popups say, `{ ok, plan, trial, ends, refund, discount, offer }` (the plan would end that day; `trial`: nothing was charged; `ends`: the day the paid month would have run to; `refund`: the last payment as text when a cancel now gives it back, else null; `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? }`: the plan ends that day, trial or paid, with no refund; `{ ok, ended: true, ends: null }` | +| `POST /api/billing/cancel` | browser session and `Origin`, `{ project_id? }`: the plan ends that day, trial or paid; a cancel within 3 days of a renewal is refunded first; `{ ok, ended: true, ends: null, refunded }` | | `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 acec973f..22729441 100644 --- a/telemetry-worker/src/billing-pages.ts +++ b/telemetry-worker/src/billing-pages.ts @@ -190,7 +190,6 @@ function gcCancel(project){ 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..."); @@ -203,16 +202,17 @@ function gcCancel(project){ 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); - 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); + var plan = j.plan || "paid"; + var lost = j.discount ? " Your discount or free months end too and do not come back." : ""; + var back = j.refund ? " Your last payment (" + j.refund + ") is refunded." : ""; + text("cx1p", (j.trial ? "Your " + plan + " trial ends as soon as you cancel. Nothing is charged." : plan + " ends as soon as you cancel.") + back + 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 + " 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); + text("cx3p", j.trial ? "This is the last step. Your trial ends now." : "This is the last step. " + plan + " ends now."); show(d1); }, function(x){ err.textContent = gcWhy(x); gcBusy(open, false); }); }); diff --git a/telemetry-worker/src/billing.ts b/telemetry-worker/src/billing.ts index 9350d999..3a1e3610 100644 --- a/telemetry-worker/src/billing.ts +++ b/telemetry-worker/src/billing.ts @@ -14,7 +14,7 @@ // 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; the plan ends that day, trial or -// paid; nothing is refunded +// paid; refunded within 3 days of a renewal // 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 @@ -69,6 +69,7 @@ import { import { applyRetention, cancelNow, + cancelRefundDue, checkCustomer, checkoutSession, ensureCustomer, @@ -83,6 +84,8 @@ import { openTrialElsewhere, portalSession, refreshSubscription, + money, + refundOnCancel, resumeSubscription, retentionOffer, sharedCustomer, @@ -604,7 +607,8 @@ const cancelWho = (t: CancelTarget): string => /** * 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 + * (the days up to it are lost). `refund`: the last payment, as text, when the cancel is within 3 days of a renewal and + * gives it back (src/stripe.ts refundableOnCancel), else null. `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). */ @@ -618,7 +622,8 @@ 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, discount: discounted(t.sub), offer: offer ? { percent_off: offer.percent, months: offer.months } : null }); + const due = await cancelRefundDue({ env: c.env, db: c.db, fetch: f, now: c.now }, t.sub).catch(() => null); + return json(200, { ok: true, plan: t.name, trial: st.status === "trialing", ends: st.periodEnd, refund: due ? money(due.amount, due.currency) : null, discount: discounted(t.sub), offer: offer ? { percent_off: offer.percent, months: offer.months } : null }); } catch (e) { return stripeFail(e); } @@ -651,8 +656,9 @@ async function cancelOffer(c: C, f: Fetch): Promise { /** * 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 + * 2026-11-18), a trial and a paid plan alike: nothing more is charged, and a discount or free months on it end too. A + * cancel within 3 days of a renewal first gives that payment back to the card (refundOnCancel); a refund that fails + * never stops the cancel, and the owner's notice says to make it by hand. 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 { @@ -666,18 +672,22 @@ 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"; + const x = { env: c.env, db: c.db, fetch: f, now: c.now }; + // the refund first (a second try finds it made); its failure is the owner's to settle, never a reason to keep billing + const back = trial ? null : await refundOnCancel(x, a.account, t.sub).catch((e) => ({ refund: null, amount: 0, currency: null, note: `the refund failed (${e instanceof Error ? e.message : String(e)}); refund by hand if one is due` })); + const refunded = back?.refund ? money(back.amount, back.currency ?? "usd") : null; 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); + await refreshSubscription(x, t.sub.id as string).catch(() => null); 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)}.`, + 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)}` : ""}; ${refunded ? `refunded ${refunded} to the card, ${back!.refund}` : `not refunded: ${back?.note ?? "nothing was due"}`}${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 }); + return json(200, { ok: true, ended: true, ends: null, refunded }); } catch (e) { return stripeFail(e); } diff --git a/telemetry-worker/src/stripe.ts b/telemetry-worker/src/stripe.ts index a2e32bff..26a54f11 100644 --- a/telemetry-worker/src/stripe.ts +++ b/telemetry-worker/src/stripe.ts @@ -47,8 +47,9 @@ // 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 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 +// the same day as they cancel it"), a trial and a paid plan alike (cancelNow), and a discount or a promotion code's +// free months end with it. A cancel within CANCEL_REFUND_DAYS (3) days of a renewal gives that payment back to the +// card in full (the owner, 2026-11-18; refundableOnCancel); any later, nothing is refunded for the days left. 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 @@ -1028,9 +1029,32 @@ async function chargeNotice(x: EventContext, event: Obj, obj: Obj): Promise `${(cents / 100).toFixed(2)} ${currency.toUpperCase()}`; +export const money = (cents: number, currency: string): string => `${(cents / 100).toFixed(2)} ${currency.toUpperCase()}`; -type SettleKind = "switch" | "duplicate"; +type SettleKind = "switch" | "duplicate" | "cancel"; + +/** A cancel within this many days of a renewal gives that renewal's payment back (the owner, 2026-11-18). */ +export const CANCEL_REFUND_DAYS = 3; + +/** The period a paid invoice's charge was for: its first charged line's. */ +const paidPeriod = (inv: Obj): { start: number; end: number } | null => { + const lines: Obj[] = Array.isArray(inv?.lines?.data) ? inv.lines.data : []; + const p = lines.find((l) => Number(l?.amount) > 0 && typeof l?.period?.start === "number" && typeof l?.period?.end === "number")?.period; + return p ? { start: p.start, end: p.end } : null; +}; + +/** + * Whether a cancel at `now` gives back what `inv`, the subscription's latest paid invoice, charged: it charged + * something, for a renewal (billing_reason subscription_cycle: the charge at the end of the trial and each month's + * after it; never the charge that starts a subscription, so subscribing, cancelling and subscribing again is not a + * free plan), and that renewal was at most CANCEL_REFUND_DAYS ago. Exported for tests. + */ +export function refundableOnCancel(inv: Obj, now: Date): boolean { + if (!(Number(inv?.amount_paid) > 0) || inv?.billing_reason !== "subscription_cycle") return false; + const start = paidPeriod(inv)?.start; + const at = now.getTime() / 1000; + return typeof start === "number" && start <= at && at - start <= CANCEL_REFUND_DAYS * 86_400; +} interface OneSubscription { /** The subscription the account keeps (fetched like fetchSubscription). */ @@ -1093,22 +1117,23 @@ interface Refunded { /** * Refund a subscription GenClass is about to cancel, to the payment method that paid it: for a switch, the unused part * of its latest paid invoice (its total times the share of the paid period left, counted from the current hour); for - * a duplicate, that invoice in full. Never a balance credit: a Managed Payments plan's invoices are issued through Link + * a duplicate, that invoice in full; for a cancel on GenClass's own page, that invoice in full when it was a renewal + * of the last CANCEL_REFUND_DAYS days (refundableOnCancel), else nothing. Never a balance credit: a Managed Payments plan's invoices are issued through Link * and the others' by GenClass, so a credit could be stranded or pay the other issuer's invoice. Idempotent: a refund * GenClass already made for it (metadata genclass_refund) is found and not made again, and the request carries an * idempotency key. A refusal (already refunded by Stripe or Link support, say) is reported, not retried. */ -async function refundFor(x: EventContext, account: BillingAccount, sub: Obj, kind: SettleKind): Promise { +async function refundFor(x: EventContext, account: { id: string }, sub: Obj, kind: SettleKind): Promise { const out: Refunded = { subscription: String(sub.id), kind, refund: null, amount: 0, currency: null }; const list = await stripe(x.env, x.fetch, "GET", "/v1/invoices", { subscription: sub.id, status: "paid", limit: 1 }); const inv: Obj | undefined = Array.isArray(list?.data) ? list.data[0] : undefined; if (!inv || typeof inv.id !== "string") return { ...out, note: "it has no paid invoice" }; const currency = typeof inv.currency === "string" ? inv.currency : "usd"; const paid = Number(inv.amount_paid) || 0; + if (kind === "cancel" && !refundableOnCancel(inv, x.now)) return { ...out, currency, note: `its last payment is not a renewal of the last ${CANCEL_REFUND_DAYS} days` }; let amount = paid; if (kind === "switch") { - const lines: Obj[] = Array.isArray(inv.lines?.data) ? inv.lines.data : []; - const period = lines.find((l) => Number(l?.amount) > 0 && typeof l?.period?.start === "number" && typeof l?.period?.end === "number")?.period; + const period = paidPeriod(inv); const at = Math.floor(x.now.getTime() / 3_600_000) * 3600; // the same amount for every retry within the hour amount = period && period.end > period.start ? Math.floor((paid * Math.min(Math.max(period.end - at, 0), period.end - period.start)) / (period.end - period.start)) : 0; } @@ -1137,6 +1162,28 @@ async function refundFor(x: EventContext, account: BillingAccount, sub: Obj, kin } } +/** + * A cancel on GenClass's own page, before the subscription is cancelled: its last payment back to the card when the + * cancel is within CANCEL_REFUND_DAYS days of a renewal (refundFor); `refund` null and a `note` when nothing is due or + * Stripe refused. Refund first, as in settleOthers: a second try finds the refund made. + */ +export const refundOnCancel = (x: EventContext, account: { id: string }, sub: Obj): Promise => refundFor(x, account, sub, "cancel"); + +/** + * What a cancel now would give back, for the popups: the amount of the subscription's last payment when + * refundOnCancel would refund it, else null. A subscription that is not active (a trial, an overdue one) or whose + * period began more than CANCEL_REFUND_DAYS days ago is answered without asking Stripe. + */ +export async function cancelRefundDue(x: EventContext, sub: Obj): Promise<{ amount: number; currency: string } | null> { + if (sub?.status !== "active") return null; + const start = sub?.items?.data?.[0]?.current_period_start ?? sub?.current_period_start; + if (typeof start === "number" && x.now.getTime() / 1000 - start > CANCEL_REFUND_DAYS * 86_400) return null; + const list = await stripe(x.env, x.fetch, "GET", "/v1/invoices", { subscription: sub.id, status: "paid", limit: 1 }); + const inv: Obj | undefined = Array.isArray(list?.data) ? list.data[0] : undefined; + if (!inv || !refundableOnCancel(inv, x.now)) return null; + return { amount: Number(inv.amount_paid), currency: typeof inv.currency === "string" ? inv.currency : "usd" }; +} + /** * Settle the subscriptions the account does not keep, after the kept one is on the account: each is refunded to its * payment method (refundFor: the unused time for a switch's old plan, the latest payment for a duplicate), then diff --git a/telemetry-worker/test/cancel.test.ts b/telemetry-worker/test/cancel.test.ts index 165965bc..be46b226 100644 --- a/telemetry-worker/test/cancel.test.ts +++ b/telemetry-worker/test/cancel.test.ts @@ -2,11 +2,11 @@ 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"; +import { call, cliToken, createApp, fakeStripe, GENCLASS_PORTAL, invoice, paymentIntentFor, resetClock, setPlan, setup, signedIn, subscription, T0, 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 (the plan ends that day, trial or paid, with no refund), the resume, and who may +// another discount), the cancel itself (the plan ends that day, trial or paid; refunded within 3 days of a renewal), 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 })); @@ -44,7 +44,7 @@ describe("GET /api/billing/cancel: what the popups say, before anything changes" 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(), discount: false, offer: { percent_off: 15, months: 6 } }); + expect(await r.json()).toEqual({ ok: true, plan: "Pro", trial: false, ends: new Date(END * 1000).toISOString(), refund: null, 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 }); }); @@ -118,12 +118,12 @@ describe("POST /api/billing/cancel and /api/billing/resume", () => { 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: true, ends: null }); - // one write: the cancel itself. No refund, no credit note, no end set for later + expect(await r.json()).toEqual({ ok: true, ended: true, ends: null, refunded: null }); + // one write: the cancel itself. No refund (no renewal in the last 3 days), 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/) })]); + 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; not refunded: it has no paid invoice\): 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).not.toContain('id="resumeplan"'); @@ -136,15 +136,70 @@ describe("POST /api/billing/cancel and /api/billing/resume", () => { 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(await (await t.post("/api/billing/cancel")).json()).toEqual({ ok: true, ended: true, ends: null, refunded: 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"); + expect(t.notices()[0]!.text).toContain("; its discount ended too"); + }); + + /** The subscription's latest paid invoice: `cents` charged for a period that began `daysAgo` days before T0. */ + const renewed = (t: Awaited>, daysAgo: number, cents = 5000, over: Record = {}) => { + const start = Math.floor(T0.getTime() / 1000) - Math.round(daysAgo * 86_400); + const inv: Record = { ...invoice("in_renewal0001", CUS, SUB, [["price_pro", cents]]), billing_reason: "subscription_cycle", ...over }; + for (const l of inv.lines.data) l.period = { start, end: start + 30 * 86_400 }; + t.s.invoices.set(inv.id, inv); + t.sub.items.data[0].current_period_start = start; + }; + + it("cancelled within 3 days of a renewal: the popups say the payment comes back, and it is refunded in full to the card before the plan ends", async () => { + const t = await paying(); + renewed(t, 2); + expect(await (await t.get()).json()).toMatchObject({ ok: true, refund: "50.00 USD" }); + expect(t.writes()).toEqual([]); + expect(await (await t.post("/api/billing/cancel")).json()).toEqual({ ok: true, ended: true, ends: null, refunded: "50.00 USD" }); + expect(t.writes()).toEqual(["POST /v1/refunds", `DELETE /v1/subscriptions/${SUB}`]); + const refund = [...t.s.refunds.values()][0]!; + expect(refund).toMatchObject({ amount: 5000, payment_intent: paymentIntentFor("in_renewal0001"), reason: "requested_by_customer", metadata: { genclass_refund: `cancel:${SUB}`, genclass_invoice: "in_renewal0001" } }); + expect(t.row()).toEqual({ plan: "free", subscription_status: "canceled", cancel_at_period_end: 0 }); + expect(t.notices()[0]!.text).toContain(`refunded 50.00 USD to the card, ${refund.id}`); + }); + + it("no refund after the third day, for the charge that starts a subscription, or when nothing was charged", async () => { + const late = await paying(); + renewed(late, 3.01); + expect(await (await late.get()).json()).toMatchObject({ refund: null }); + expect(await (await late.post("/api/billing/cancel")).json()).toMatchObject({ ended: true, refunded: null }); + expect(late.writes()).toEqual([`DELETE /v1/subscriptions/${SUB}`]); + expect(late.notices()[0]!.text).toContain("not refunded: its last payment is not a renewal of the last 3 days"); + // subscribing again right after a cancel is charged at once (no second trial): cancelling that is not a free plan + const first = await paying(); + renewed(first, 1, 5000, { billing_reason: "subscription_create" }); + expect(await (await first.get()).json()).toMatchObject({ refund: null }); + expect(await (await first.post("/api/billing/cancel")).json()).toMatchObject({ refunded: null }); + expect(first.writes()).toEqual([`DELETE /v1/subscriptions/${SUB}`]); + // free months: the renewal charged nothing + const free = await paying("active", { discounts: ["di_6monthsfree01"] }); + renewed(free, 1, 0); + expect(await (await free.get()).json()).toMatchObject({ refund: null }); + expect(await (await free.post("/api/billing/cancel")).json()).toMatchObject({ refunded: null }); + expect(free.writes()).toEqual([`DELETE /v1/subscriptions/${SUB}`]); + }); + + it("a refund Stripe refuses never stops the cancel: the plan ends and the owner is told why nothing went back", async () => { + const t = await paying(); + renewed(t, 1); + const real = t.s.fetch; + const f: typeof real = (input, init) => + String(input).endsWith("/v1/refunds") && init?.method === "POST" ? Promise.resolve(new Response(JSON.stringify({ error: { message: "This charge has already been refunded." } }), { status: 400 })) : real(input, init); + const r = await call(t.env, "POST", "/api/billing/cancel", { body: {}, cookie: t.cookie, fetch: f }); + expect(await r.json()).toEqual({ ok: true, ended: true, ends: null, refunded: null }); + expect(t.sub.status).toBe("canceled"); + expect(t.notices()[0]!.text).toContain("not refunded: Stripe refused the refund ("); }); 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(await (await t.post("/api/billing/cancel")).json()).toEqual({ ok: true, ended: true, ends: null, refunded: 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)"); @@ -226,7 +281,9 @@ describe("the billing page: Cancel plan opens the popups", () => { expect(page).toContain(''); 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."); + expect(page).toContain(" ends as soon as you cancel."); + expect(page).not.toContain("Nothing is refunded"); + expect(page).not.toContain(", not on "); for (const id of ["cx1", "cx2", "cx3"]) expect(page).toContain(`cancel your plan.'); expect(page).not.toContain("cancel in Manage billing");