Public: anyone can read this; the crew can change it.

Changing a forge's plan shows the change in one line before it is made #13169

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/13132-changing-a-forge-s-plan-shows-the-change → main 8 commits fork 3 threads · 3 unresolved

  • Merged. torque/13132-changing-a-forge-s-plan-shows-the-change was merged into main as e2dd278.

Review

Sign in to review this change.
11 files changed +254 −22
docs/design/audit.md +1
@@ -117,6 +117,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
117117 - `/settings/appearance` — `pages/account.ts` · every theme as a card that wears its own colours · the Theme row of the account menu (Auto, Light, Dark only) · none seen.
118118 - `/settings/everyday` — `pages/everyday.ts` · an admin makes the everyday account with a passkey, or keeps working as admin · `/settings` (the pair, once made) · none seen.
119119 - `/settings/billing` — `pages/billing.ts` · each forge's plan, granted by hand · `/settings/economics` · none seen.
120 - `/settings/billing/change` — `pages/billing.ts` · one forge's plan change before it is confirmed: from, to, the cents a month and the day it starts · `/settings/billing` · none seen.
120121 - `/settings/economics` — `pages/economics.ts` · the profit slider's position and the margin, with the policy in words · `/admin/limits`, `/settings/capacity` · none seen.
121122 - `/settings/hosted-forges` — `pages/hosted-forges.ts` · what the forges hosted here may reach: one sentence with a switch, the names for every forge, each forge's grants and asks · `/forges` (the same asks and grants, on each forge's row) · none seen.
122123 - `/settings/capacity` — `pages/capacity.ts` · how many runs and checks go at once · `/admin/limits`, `/settings/usage` · none seen.
docs/features/billing.md +1
@@ -4,6 +4,7 @@ Billing records the plan each forge is on (`src/billing/`): a store of entitleme
44
55 - **Plans:** small, medium or large, the sizes. A forge never granted a plan reads as `active` on its size, source `granted`.
66 - **Grant by hand (admin, a person):** the Billing page, the terminal screen, `PUT /api/v1/forges/{name}/plan` with `{ "plan": "large" }` (`GET` reads it), or the MCP `forges` tool with `{ forge, plan }` (planned first; `dryRun: false` grants).
7 - **Preview first:** the page's *Review change* opens `/settings/billing/change?forge=&plan=`, which says in one line `small → medium: $49.00 a month, starts 2026-11-15` (from, to, whole cents a month from the plans setting, the UTC day it starts) and carries those numbers in its *Confirm change* form. A confirm whose numbers differ from what the preview would say now (a price edited, the day rolled over) changes nothing and shows the new preview (409). The terminal's yes/no shows the same line; no Stripe call is made (`src/billing/plan_change.ts`).
78 - **Audit:** every grant is a row in `entitlement_change` and a `billing.plan` event.
89 - **Terminal:** the palette's *Billing* (admins), `src/tui/screens/billing.ts`: `j`/`k` pick a forge, `s`, `m` or `l` grants that plan after a yes/no; `c` connects Stripe (key shown as dots), `w` saves a signing secret, `x` disconnects after a yes/no.
910 - **Stripe (#11136):** Settings → Billing → Provider takes one key (`src/billing/stripe.ts`, `connection.ts`); how to connect it is in `docs/PROFIT.md`. Not yet: the `/hooks/stripe` receiver, and checkout, portal and reconcile, which come with the pull that calls them.
src/billing/plan_change.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * The preview of a hand plan change, in one line before it is made (#13132):
3 * from plan, to plan, the amount a month and the day it starts. Pure: plain
4 * data in, plain data out, no store and no Stripe call. Money is integer
5 * cents (a plan's `priceUsd` times 100, rounded once); a hand grant takes
6 * effect at once, so it starts today, a UTC day.
7 */
8
9 import type { Plan } from "../settings/plans.ts";
10
11 export interface PlanChange {
12 readonly forge: string;
13 readonly from: string;
14 readonly to: string;
15 /** What the forge pays a month on the new plan, in cents; 0 is free. */
16 readonly cents: number;
17 /** The UTC day the new plan starts, YYYY-MM-DD. */
18 readonly starts: string;
19 }
20
21 /** The price in cents of a plan named by key, or by the size it sits on; unknown reads as 0. */
22 export function centsFor(plans: readonly Plan[], name: string): number {
23 const p = plans.find((q) => q.key === name) ?? plans.find((q) => q.size === name);
24 return p === undefined ? 0 : Math.round(p.priceUsd * 100);
25 }
26
27 export function previewChange(plans: readonly Plan[], forge: string, from: string, to: string, now: Date): PlanChange {
28 return { forge, from, to, cents: centsFor(plans, to), starts: now.toISOString().slice(0, 10) };
29 }
30
31 /** Whole cents as "$19.00 a month" or "Free". */
32 export function perMonth(cents: number): string {
33 return cents === 0 ? "Free" : `$${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")} a month`;
34 }
35
36 /** The one line: "small → medium: $49.00 a month, starts 2026-11-15". */
37 export function changeLine(c: PlanChange): string {
38 return `${c.from} → ${c.to}: ${perMonth(c.cents)}, starts ${c.starts}`;
39 }
40
41 export interface Seen {
42 readonly from: string;
43 readonly to: string;
44 readonly cents: number;
45 readonly starts: string;
46 }
47
48 /** What a confirm carried, as the numbers it saw; undefined when one is missing or not whole. */
49 export function seen(raw: { from: string; to: string; cents: string; starts: string }): Seen | undefined {
50 if (!/^\d{1,9}$/.test(raw.cents) || !/^\d{4}-\d{2}-\d{2}$/.test(raw.starts)) return undefined;
51 return { from: raw.from, to: raw.to, cents: Number(raw.cents), starts: raw.starts };
52 }
53
54 /** True when what the confirm saw is exactly what the preview would say now. */
55 export function same(now: PlanChange, s: Seen | undefined): boolean {
56 return s !== undefined && s.from === now.from && s.to === now.to && s.cents === now.cents && s.starts === now.starts;
57 }
src/http/route_marks.ts +13 −3
@@ -16,7 +16,10 @@ import { Router } from "./router.ts";
1616
1717 export type Mark = "admin" | "open";
1818
19 /** Every head of a registered route: one mark for all of it, or `mixed` when each route is listed below. */
19 /**
20 * Every head of a registered route: one mark for all of it, or `mixed` when each route is listed
21 * below.
22 */
2023 export const HEADS: Readonly<Record<string, Mark | "mixed">> = {
2124 "/": "open",
2225 "/-": "open",
@@ -311,6 +314,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
311314 "/settings/hosted-forges/reach/remove": "admin",
312315 "/settings/economics": "admin",
313316 "/settings/billing": "admin",
317 "/settings/billing/change": "admin",
314318 "/settings/billing/grant": "admin",
315319 "/settings/billing/links": "admin",
316320 "/settings/billing/portal": "admin",
@@ -422,7 +426,10 @@ export function markOf(pattern: string): Mark | undefined {
422426 }
423427
424428 let listed: Router<Mark> | undefined;
425 /** ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as `/packs/:name`. */
429 /**
430 * ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as
431 * `/packs/:name`.
432 */
426433 function listedRoutes(): Router<Mark> {
427434 if (listed !== undefined) return listed;
428435 const params = (p: string) => p.split("/").filter((s) => s.startsWith(":") || s.startsWith("*")).length;
@@ -432,7 +439,10 @@ function listedRoutes(): Router<Mark> {
432439 return (listed = matcher);
433440 }
434441
435 /** Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as `admin`. */
442 /**
443 * Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as
444 * `admin`.
445 */
436446 export function isAdminRoute(path: string): boolean {
437447 const own = listedRoutes().match("*", path);
438448 if (own !== undefined) return own.handler === "admin";
src/http/settings_routes.ts +9 −5
@@ -19,7 +19,7 @@ import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts
1919 import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts";
2020 import { flagsPage, flagsSet } from "../web/pages/flags.ts";
2121 import { appTemplatesPage, appTemplatesSet } from "../web/pages/app_templates.ts";
22 import { billingPage, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
22 import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
2323 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2424 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
2525 import { usagePage } from "../web/pages/usage.ts";
@@ -228,6 +228,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
228228 router.add("GET", "/settings/economics", economicsPage);
229229 router.add("POST", "/settings/economics", economicsSet);
230230 router.add("GET", "/settings/billing", billingPage);
231 router.add("GET", "/settings/billing/change", billingChange);
231232 router.add("POST", "/settings/billing/grant", billingGrant);
232233 router.add("POST", "/settings/billing/links", billingSetLinks);
233234 router.add("POST", "/settings/billing/portal", billingSetPortal);
@@ -330,8 +331,9 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
330331 // and not an API one: it is a browser redirect, possibly from a phone, and
331332 // the only thing it carries is a `state` this forge issued minutes ago.
332333 router.add("GET", "/settings/origins/callback", async (ctx) => {
333 // A sign-in this forge runs for a child (`spawn/origin_broker.ts`) comes back here, since the provider
334 // has this one address registered; its state is not a person's, so it is told apart before the session.
334 // A sign-in this forge runs for a child (`spawn/origin_broker.ts`) comes back here, since the
335 // provider has this one address registered; its state is not a person's, so it is told apart
336 // before the session.
335337 const brokered = await brokerCallback(ctx);
336338 if (brokered !== undefined) return brokered;
337339 const done = await completeOAuthCallback(ctx.app, ctx.auth.user, {
@@ -355,7 +357,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
355357 return new Response(null, {
356358 status: 303,
357359 headers: {
358 // Signed out, the code is not carried through the sign-in page: it dies unredeemed in a minute.
360 // Signed out, the code is not carried through the sign-in page: it dies unredeemed in a
361 // minute.
359362 location: !done.ok && done.error === "unauthorized" ? "/settings/origins" : callbackLanding(ctx, done),
360363 "referrer-policy": "no-referrer",
361364 "cache-control": "no-store",
@@ -367,7 +370,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
367370 router.add("GET", "/settings/origins", originsPage);
368371 router.add("POST", "/settings/origins/token", originConnectToken);
369372 router.add("POST", "/settings/origins/oauth", originOAuthStart);
370 // A hosted forge asks its host to let it reach one more name (`web/pages/origin-reach.ts`); how the asks stand is read from the API.
373 // A hosted forge asks its host to let it reach one more name (`web/pages/origin-reach.ts`); how
374 // the asks stand is read from the API.
371375 router.add("POST", "/settings/origins/reach", originReachAsk);
372376 router.add("POST", "/settings/origins/reach/dismiss", originReachDismiss);
373377 router.add("POST", "/settings/origins/apps", originAppCreate);
src/tui/screens/billing.ts +9 −2
@@ -7,7 +7,9 @@
77 * signing secret, `x` disconnects after a yes/no: the same actions as the page.
88 */
99
10 import { grantPlan, readBilling, connectStripe, disconnectStripe, saveSigningSecret, BILLING_WORDS, STRIPE_WORDS } from "../../actions/billing.ts";
10 import { grantPlan, planGrant, readBilling, connectStripe, disconnectStripe, saveSigningSecret, BILLING_WORDS, STRIPE_WORDS } from "../../actions/billing.ts";
11 import { changeLine, previewChange } from "../../billing/plan_change.ts";
12 import { getPlans } from "../../settings/plans.ts";
1113 import type { Ctx, Screen } from "../app/app.ts";
1214 import { binding } from "../app/keys.ts";
1315 import { fill, len, split } from "../ui/layout.ts";
@@ -21,6 +23,11 @@ import type { PaletteEntry } from "./entries.ts";
2123 const isAdmin = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent";
2224 const stripeWords = (e: keyof typeof STRIPE_WORDS | "not_found" | "no_such_forge" | "bad_plan"): string =>
2325 e === "not_found" ? "Not found." : e in STRIPE_WORDS ? `${STRIPE_WORDS[e as keyof typeof STRIPE_WORDS]}.` : `${BILLING_WORDS[e as keyof typeof BILLING_WORDS]}.`;
26 /** The same one line the page shows before its confirm: from, to, amount a month, start day. */
27 function previewLine(f: Session, forge: string, plan: string): string[] {

Tests: the terminal now shows the preview line in the grant confirmation, but no test would fail without it. Add a tui test that opens the confirm and asserts the line (from → to: amount, starts day).

28 const planned = planGrant(f.app, f.user, forge, plan);
29 return planned.ok ? [changeLine(previewChange(getPlans(f.app.db), forge, planned.value.from.plan, planned.value.to.plan, new Date()))] : [];
30 }
2431 const PLANS: Record<string, string> = { s: "small", m: "medium", l: "large" };
2532
2633 export function billingRows(f: Session): ListRow[] {
@@ -93,7 +100,7 @@ export function billingScreen(f: Session, ctx: Ctx): Screen {
93100 };
94101 const ask = confirmScreen(ctx, screen, {
95102 title: "Grant a plan",
96 body: [`Put ${target.title} on ${plan}?`],
103 body: [`Put ${target.title} on ${plan}?`, ...previewLine(f, target.title, plan)],
97104 actions: [{ label: "Grant" }, { label: "Cancel" }],
98105 onChoose: grant,
99106 });
src/web/pages/billing.ts +57 −10
@@ -6,9 +6,10 @@
66 */
77
88 import { ledBlock } from "./visitors.ts";
9 import { BILLING_WORDS, STRIPE_WORDS, connectStripe, disconnectStripe, grantPlan, readBilling, saveSigningSecret, type BillingError, type StripeWords } from "../../actions/billing.ts";
9 import { BILLING_WORDS, STRIPE_WORDS, connectStripe, disconnectStripe, grantPlan, planGrant, readBilling, saveSigningSecret, type BillingError, type StripeWords } from "../../actions/billing.ts";
1010 import { retryOrder } from "../../actions/order.ts";
1111 import { REFUND_URL } from "../../billing/checkout.ts";
12 import { changeLine, previewChange, same, seen } from "../../billing/plan_change.ts";
1213 import { lapseFor, type Lapse } from "../../billing/lapse.ts";
1314 import { failedOrders } from "../../billing/orders.ts";
1415 import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../actions/codes.ts";
@@ -36,6 +37,8 @@ interface Shown {
3637 readonly link: string;
3738 }
3839
40 const isPerson = (ctx: Ctx): boolean => ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent";
41
3942 const day = (iso: string): string => iso.slice(0, 10);
4043
4144 /** The Codes section: make one, copy it once, then one line per code with its one action. */
@@ -151,7 +154,10 @@ export async function billingSetLinks(ctx: Ctx): Promise<Response> {
151154 return billingView(ctx, undefined, {}, undefined, 422, { values: next, error });
152155 }
153156
154 /** Last 7 days, from visit to paid: one `dl` row per step with its share of the step before; clicks by plan and where they came from as rows under it. */
157 /**
158 * Last 7 days, from visit to paid: one `dl` row per step with its share of the step before; clicks
159 * by plan and where they came from as rows under it.
160 */
155161 function funnelRow(r: FunnelReport): Html {
156162 const row = (label: string, value: string): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`;
157163 return html`<section class="settings-block" id="funnel">
@@ -185,14 +191,14 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
185191 const b = read.value;
186192 const rows = b.forges.map(
187193 (f) => html`<li class="row" data-forge="${f.forge}">
188 <form class="row-fields" method="post" action="${PATH}/grant">
194 <form class="row-fields" method="get" action="/settings/billing/change">
189195 <input type="hidden" name="forge" value="${f.forge}" />
190196 <span class="mono">${f.forge}</span>
191197 <span class="muted small">${f.status} · ${f.source}${lapseWords(lapseFor(ctx.app.db, f.forge))}</span>
192198 <select class="input" name="plan" aria-label="Plan for ${f.forge}">
193199 ${Object.keys(SIZES).map((p) => html`<option value="${p}" ${p === f.plan ? html`selected` : null}>${p}</option>`)}
194200 </select>
195 ${btn("Grant")}
201 ${btn("Review change")}
196202 </form>
197203 </li>`,
198204 );
@@ -283,12 +289,54 @@ export async function billingRevokeCode(ctx: Ctx): Promise<Response> {
283289 return flashTo(ctx, `${PATH}#codes`, done.ok ? { message: "Code revoked. Forges already made keep their plan." } : { tone: "danger", message: `${codeWords(done.error)}.` });
284290 }
285291
286 // POST /settings/billing/grant
292 /** The preview and its confirm form: the change in one line, then the button posting its numbers */
293 function changeView(ctx: Ctx, forge: string, plan: string, refused = false): Response {
294 const planned = planGrant(ctx.app, ctx.auth.user, forge, plan);
295 if (!planned.ok) return planned.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, PATH, { tone: "danger", message: `${words(planned.error)}.` });
296 const c = previewChange(getPlans(ctx.app.db), planned.value.to.forge, planned.value.from.plan, planned.value.to.plan, new Date());
297 const response = page({
298 ctx,
299 title: "Change plan",
300 body: html`<div class="page-head"><h1>Change plan</h1></div>
301 ${refused ? html`<p class="notice danger" role="alert">That changed while you looked. Nothing was made; the numbers below are the new ones.</p>` : null}
302 <section class="settings-block" data-plan-change>
303 <p data-change-line><span class="mono">${c.forge}</span>: ${changeLine(c)}</p>

Principle 1 (nothing explains itself twice): the one-line change above is repeated as a four-row dl (from, to, amount, starts) right below it. Keep the line and drop the dl, or keep the dl and drop the line; the hidden inputs already carry the values.

304 <p class="muted small">Starts today. Nothing is charged.</p>
305 <form class="row-fields" method="post" action="${PATH}/grant">
306 <input type="hidden" name="forge" value="${c.forge}" />
307 <input type="hidden" name="plan" value="${c.to}" />
308 <input type="hidden" name="from" value="${c.from}" />
309 <input type="hidden" name="cents" value="${String(c.cents)}" />
outdated

Principles 1 and 8: the Assumptions paragraph is a second explanation of what the line and the page already say, in non-plain words. Cut it, or reduce it to one short plain sentence (Starts today. Nothing is charged).

310 <input type="hidden" name="starts" value="${c.starts}" />
311 ${btn("Confirm change")}
312 <a href="${PATH}">Cancel</a>
313 </form>
314 </section>`,
315 }, refused ? 409 : 200);
316 response.headers.set("cache-control", "no-store");
317 return response;
318 }
319
320 // GET /settings/billing/change?forge=&plan= — the preview, before the confirm.
321 export function billingChange(ctx: Ctx): Response {
322 if (!ctx.auth.user) return signInFirst(ctx);
323 if (!isPerson(ctx)) return notFoundPage(ctx);
324 return changeView(ctx, ctx.url.searchParams.get("forge") ?? "", ctx.url.searchParams.get("plan") ?? "");
325 }
326
327 // POST /settings/billing/grant — the confirm: it must carry what the preview showed.
287328 export async function billingGrant(ctx: Ctx): Promise<Response> {
288 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
329 if (!isPerson(ctx)) return notFoundPage(ctx);
289330 const form = await readForm(ctx, "admin");
290331 if (form instanceof Response) return form;
291 const set = grantPlan(ctx.app, ctx.auth.user, field(form, "forge"), field(form, "plan"));
332 const forge = field(form, "forge");
333 const plan = field(form, "plan");
334 const planned = planGrant(ctx.app, ctx.auth.user, forge, plan);
335 if (!planned.ok) return planned.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, PATH, { tone: "danger", message: `${words(planned.error)}.` });
336 const now = previewChange(getPlans(ctx.app.db), forge, planned.value.from.plan, planned.value.to.plan, new Date());
337 const carried = seen({ from: field(form, "from"), to: plan, cents: field(form, "cents"), starts: field(form, "starts") });
338 if (!same(now, carried)) return changeView(ctx, forge, plan, true);
339 const set = grantPlan(ctx.app, ctx.auth.user, forge, plan);
292340 if (!set.ok && set.error === "not_found") return notFoundPage(ctx);
293341 return flashTo(ctx, PATH, set.ok ? { message: `${set.value.entitlement.forge} is on ${set.value.entitlement.plan}.` } : { tone: "danger", message: `${words(set.error)}.` });
294342 }
@@ -296,8 +344,6 @@ export async function billingGrant(ctx: Ctx): Promise<Response> {
296344 const back = (ctx: Ctx, r: { ok: true; message: string } | { ok: false; error: BillingError | StripeWords }): Response | Promise<Response> =>
297345 r.ok ? flashTo(ctx, PATH, { message: r.message }) : r.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, PATH, { tone: "danger", message: `${words(r.error)}.` });
298346
299 const isPerson = (ctx: Ctx): boolean => ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent";
300
301347 // POST /settings/billing/stripe/connect
302348 export async function stripeConnect(ctx: Ctx): Promise<Response> {
303349 if (!isPerson(ctx)) return notFoundPage(ctx);
@@ -325,7 +371,8 @@ export async function stripeDisconnect(ctx: Ctx): Promise<Response> {
325371 return back(ctx, r.ok ? { ok: true, message: "Stripe is disconnected." } : r);
326372 }
327373
328 // POST /settings/billing/orders/retry — an admin who is a person retries a paid order whose forge was not made.
374 // POST /settings/billing/orders/retry — an admin who is a person retries a paid order whose forge
375 // was not made.
329376 export async function orderRetry(ctx: Ctx): Promise<Response> {
330377 if (!isPerson(ctx)) return notFoundPage(ctx);
331378 const form = await readForm(ctx, "admin");
test/billing-plan-change.test.ts added +28
@@ -0,0 +1,28 @@
1 /** The plan-change preview, by hand (#13132): integer cents, the UTC day, the one line. */
2 import { expect, test } from "bun:test";
3 import { centsFor, changeLine, perMonth, previewChange, same, seen } from "../src/billing/plan_change.ts";
4 import { DEFAULT_PLANS, type Plan } from "../src/settings/plans.ts";
5
6 test("price is whole cents: $19 → 1900, $19.99 → 1999, free → 0", () => {
7 expect(centsFor(DEFAULT_PLANS, "small")).toBe(1900);
8 expect(centsFor(DEFAULT_PLANS, "free")).toBe(0);
9 const odd: Plan[] = [{ ...DEFAULT_PLANS[1]!, key: "odd", priceUsd: 19.99 }];
10 expect(centsFor(odd, "odd")).toBe(1999);
11 expect(centsFor(DEFAULT_PLANS, "nope")).toBe(0);
12 });
13
14 test("the line says from, to, dollars and cents a month, and the UTC day", () => {
15 const c = previewChange(DEFAULT_PLANS, "kid", "small", "medium", new Date("2026-11-15T23:59:59Z"));
16 expect(changeLine(c)).toBe("small → medium: $49.00 a month, starts 2026-11-15");
17 expect(perMonth(1905)).toBe("$19.05 a month");
18 expect(perMonth(0)).toBe("Free");
19 });
20
21 test("a confirm matches only the exact numbers", () => {
22 const c = previewChange(DEFAULT_PLANS, "kid", "small", "medium", new Date("2026-11-15T00:00:00Z"));
23 expect(same(c, seen({ from: "small", to: "medium", cents: "4900", starts: "2026-11-15" }))).toBe(true);
24 expect(same(c, seen({ from: "small", to: "medium", cents: "4901", starts: "2026-11-15" }))).toBe(false);
25 expect(same(c, seen({ from: "small", to: "medium", cents: "4900", starts: "2026-11-16" }))).toBe(false);
26 expect(same(c, seen({ from: "small", to: "medium", cents: "49.00", starts: "2026-11-15" }))).toBe(false);
27 expect(same(c, undefined)).toBe(false);
28 });
test/billing-tui.test.ts +19 −1
@@ -1,4 +1,7 @@
1 /** Billing in the terminal (#11134): the admin sees each forge's plan and grants one; no one else is offered it. */
1 /**
2 * Billing in the terminal (#11134): the admin sees each forge's plan and grants one; no one else is
3 * offered it.
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
@@ -85,6 +88,21 @@ test("the admin sees the forge's plan and grants another after a yes", async ()
8588 tui.stop?.();
8689 });
8790
91 test("the confirm shows the change in one line: from, to, amount a month, start day", async () => {
92 const { tui, session } = open(alice);
93 tui.ctx.push(billingScreen(session, tui.ctx));
94 await settleApp(tui);
95 const from = entitlementOf(app.db, "kid", "small").plan;
96 const to = from === "medium" ? "small" : "medium";
97 tui.dispatch(key(to === "medium" ? "m" : "s"));
98 await settleApp(tui);
99 const price = to === "medium" ? "$49.00" : "$19.00";
100 expect(tui.screen.toText()).toContain(`${from} → ${to}: ${price} a month, starts ${new Date().toISOString().slice(0, 10)}`);
101 tui.dispatch(key("n"));
102 await settleApp(tui);
103 tui.stop?.();
104 });
105
88106 test("a no changes nothing", async () => {
89107 const { tui, session } = open(alice);
90108 const screen = billingScreen(session, tui.ctx);
test/billing.test.ts +55
@@ -142,6 +142,61 @@ describe("billing seam", () => {
142142 expect((await send("GET", "/settings/billing", bob)).status).toBe(403);
143143 });
144144
145 describe("a plan change is previewed (#13132)", () => {
146 const post = (token: string, fields: Record<string, string>) =>
147 fetch(`${servers.url}/settings/billing/grant`, {
148 method: "POST",
149 headers: { authorization: `Bearer ${token}`, "content-type": "application/x-www-form-urlencoded" },
150 body: new URLSearchParams(fields),
151 });
152 const today = () => new Date().toISOString().slice(0, 10);
153
154 test("the preview says from, to, the amount a month in cents-exact dollars and the day it starts", async () => {
155 const from = entitlementOf(app.db, "kid", "small").plan;
156 const to = from === "medium" ? "large" : "medium";
157 const res = await send("GET", `/settings/billing/change?forge=kid&plan=${to}`, admin);
158 expect(res.status).toBe(200);
159 const text = await res.text();
160 const price = to === "medium" ? "$49.00 a month" : "$149.00 a month";
161 expect(text).toContain(`${from} → ${to}: ${price}, starts ${today()}`);
162 expect(text.split(`${from} → ${to}`).length).toBe(2); // said once
163 expect(text).not.toContain("Assumptions");
164 expect(text).toContain(`name="cents" value="${to === "medium" ? 4900 : 14900}"`);
165 expect(entitlementOf(app.db, "kid", "small").plan).toBe(from);
166 expect((await send("GET", `/settings/billing/change?forge=kid&plan=${to}`, bob)).status).toBe(403);
167 expect(await (await send("GET", "/settings/billing/change?forge=kid&plan=huge", admin)).text()).not.toContain("data-plan-change");
168 });
169
170 test("the confirm with the previewed numbers makes the change", async () => {
171 const from = entitlementOf(app.db, "kid", "small").plan;
172 const to = from === "medium" ? "large" : "medium";
173 const cents = to === "medium" ? "4900" : "14900";
174 const res = await post(admin, { forge: "kid", plan: to, from, cents, starts: today() });
175 expect(res.status).toBe(200);
176 expect(entitlementOf(app.db, "kid", "small").plan).toBe(to);
177 });
178
179 test("a confirm with other numbers, or none, refuses with the new ones and changes nothing", async () => {
180 const from = entitlementOf(app.db, "kid", "small").plan;
181 const to = from === "small" ? "medium" : "small";
182 const stale = await post(admin, { forge: "kid", plan: to, from, cents: "1", starts: today() });
183 expect(stale.status).toBe(409);
184 const text = await stale.text();
185 expect(text).toContain("That changed while you looked");
186 expect(text).toContain(`name="cents" value="${to === "small" ? 1900 : 4900}"`);
187 expect(entitlementOf(app.db, "kid", "small").plan).toBe(from);
188 expect((await post(admin, { forge: "kid", plan: to })).status).toBe(409);
189 expect((await post(admin, { forge: "kid", plan: to, from, cents: to === "small" ? "1900" : "4900", starts: "2000-01-01" })).status).toBe(409);
190 expect(entitlementOf(app.db, "kid", "small").plan).toBe(from);
191 });
192
193 test("the Billing page's row leads to the preview, not straight to the grant", async () => {
194 const text = await (await send("GET", "/settings/billing", admin)).text();
195 expect(text).toContain('action="/settings/billing/change"');
196 expect(text).not.toContain('action="/settings/billing/grant"');
197 });
198 });
199
145200 test("the Billing page says the last Stripe event and the refused signatures, or that none came", async () => {
146201 const before = await (await send("GET", "/settings/billing", admin)).text();
147202 expect(before).toContain("No event yet");
test/server-timing-sweep.test.ts +5 −1
@@ -36,7 +36,10 @@ const NOT_PAGES = new Set([
3636 "/:owner/:name/stream",
3737 ]);
3838
39 /** Routes that answer 3xx for the sweep's signed-in user: not pages, no phases. A page may not join by redirecting. */
39 /**
40 * Routes that answer 3xx for the sweep's signed-in user: not pages, no phases. A page may not join
41 * by redirecting.
42 */
4043 const REDIRECTS = new Set([
4144 "/.well-known/change-password",
4245 "/alice/forge/changes",
@@ -50,6 +53,7 @@ const REDIRECTS = new Set([
5053 "/big",
5154 "/home",
5255 "/login",
56 "/settings/billing/change",
5357 "/settings/origins/callback",
5458 "/settings/resilience",
5559 "/sign-in",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs