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

A payment that fails shows one line on the plan row with the day the forge will sleep #16012

Merged opened this

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

Merged

scout/forge:scout/15997-a-payment-that-fails-shows-one-line-on-t → main 5 commits fork 2 threads · 2 unresolved

  • Merged. scout/15997-a-payment-that-fails-shows-one-line-on-t was merged into main as 452ce28.

Review

Sign in to review this change.
9 files changed +120 −27
docs/features/plan-row.md +3 −2
@@ -4,11 +4,12 @@ row: The Plan row in a forge's settings
44 ---
55 # The Plan row in a forge's settings (#11141)
66
7 A forge's admins see one `status-rows` `dl` row (`Plan`) at the top of `/settings`: the plan's name and size, the crew credit used this month, and the status (`Active`, or in grace `Payment due — paused on <day> · Pay`, #11394). With a billing portal set and a Stripe payer, **Manage billing** links to the provider's customer-portal sign-in (the buyer signs in with the email they paid with); **Change size** links to the host's `/pricing`. A forge with no notice (never told, or a host that is not its parent) shows no row.
7 A forge's admins see one `status-rows` `dl` row (`Plan`) at the top of `/settings`: the plan's name and size, the crew credit used this month, and the status (`Active`, or in grace `Payment failed; your forge sleeps on <day> · Pay`, #11394). With a billing portal set and a Stripe payer, **Manage billing** links to the provider's customer-portal sign-in (the buyer signs in with the email they paid with); **Change size** links to the host's `/pricing`. A forge with no notice (never told, or a host that is not its parent) shows no row.
88
9 - **Grace (#11394):** while a payment is late the row says `Payment due — paused on <day>` (the day grace ends, UTC) followed by one **Pay** link: the provider's portal when one is set, else the host's `/pricing`. Pay takes the place of Manage billing, and when Pay already goes to `/pricing`, Change size is dropped so the row never offers two links to one place. Home and board carry no notice.
9 - **Grace (#11394):** while a payment is late the row says `Payment failed; your forge sleeps on <day>` (the day grace ends, UTC) followed by one **Pay** link: the provider's portal when one is set, else the host's `/pricing`. Pay takes the place of Manage billing, and when Pay already goes to `/pricing`, Change size is dropped so the row never offers two links to one place. Home and board carry no notice.
1010 - **Operator:** on the host's `/forges` (operator only) a forge in grace shows `grace until <YYYY-MM-DD>` in its row (`graceWords` in `src/spawn/clients.ts`); the terminal's forges screen says the same.
1111 - **Host:** Settings → Billing → *Billing portal* sets `billing.portal_url` (https only, empty clears). Changing it tells every forge sent from here.
1212 - **How a forge learns its plan:** the host writes a notice (`src/billing/notice.ts`) into that one forge's own `plan.json` (never `parent.json`) when the forge is made, a gift is redeemed, a plan is granted, or Stripe changes the subscription. The forge reads only its own file and calls nothing on the host, so it cannot read another forge's plan; the notice has no forge name, customer or subscription id.
1313 - **Terminal:** the palette entry *Plan* (`src/tui/screens/planrow.ts`, any admin) shows the same plan line (`planLine`) and, for an admin who is a person, sets the billing portal address with Enter through `changePortalUrl`, as the page does.
1414 - **Preview (#11549):** a preview is seeded in grace (`seedGrace` in `src/spawn/preview-seed.ts`, only when `FORGE_APP_ENV=preview`): its own `plan.json` says payment is late and one client forge is in grace, so the forge's looks of `/settings` (the Plan row) and `/forges` (`grace until <date>`), light and dark, desk and phone, are on every pull's looks page (`PREVIEW_OWNER_LOOKS`).
15 - **Grace over:** once the day the row names has passed, the forge stops saying "Payment failed" on its own (it reads its notice against the clock; nothing re-tells it) and the row says `No active plan`, with no Pay link. A host that tells the forge `none` gets the same row.
src/billing/notice.ts +6 −4
@@ -89,7 +89,7 @@ export function keepNotice(dataDir: string, notice: PlanNotice): boolean {
8989 }
9090
9191 /** Tell one forge its plan as the host holds it now. Never throws: a forge that cannot be reached is told at the next change. */
92 export function tellPlan(app: App, forge: string): boolean {
92 export function tellPlan(app: App, forge: string, now: number = Date.now()): boolean {
9393 try {
9494 const child = listChildrenNow(app).find((c) => c.name === forge && c.done);
outdated

Only evaluated when tellPlan runs. Nothing re-tells at grace expiry, so the forge keeps status grace and the past day. Add a trigger when grace ends, and a test for it.

9595 if (child === undefined) return false;
@@ -97,8 +97,10 @@ export function tellPlan(app: App, forge: string): boolean {
9797 const plan = getPlan(app.db, e.plan);
9898 const portal = getPortalUrl(app.db);
9999 // In grace the forge is told the day it pauses (the end of grace), not the provider's period end.
100 const lapse = e.status === "grace" ? lapseFor(app.db, forge) : undefined;
100 const lapse = e.status === "grace" ? lapseFor(app.db, forge, now) : undefined;
101101 const periodEnd = lapse?.state === "grace" ? Math.floor(lapse.graceUntil / 1000) : e.periodEnd;
102 // Grace spent: the forge is told so, not the provider's period end as a day it sleeps.
103 const status: EntitlementStatus = lapse?.state === "none" ? "none" : e.status;
102104 const paysAtProvider = getStored(app.db, forge)?.provider === "stripe";
103105 return keepNotice(childDirOf(app, child.bodyId), {
104106 name: plan?.name ?? e.plan,
@@ -106,8 +108,8 @@ export function tellPlan(app: App, forge: string): boolean {
106108 priceUsd: plan?.priceUsd ?? 0,
107109 creditUsd: plan?.creditUsd ?? 0,
108110 askUsd: limitValue(app.db, "billing.ask_cents") / 100,
109 status: e.status,
110 ...(periodEnd === undefined ? {} : { periodEnd }),
111 status,
112 ...(periodEnd === undefined || status === "none" ? {} : { periodEnd }),
111113 ...(paysAtProvider && portal !== "" ? { portalUrl: portal } : {}),
112114 });
113115 } catch {
src/spawn/preview-seed.ts +4 −1
@@ -532,7 +532,10 @@ export const PREVIEW_GRACE_CLIENT = "preview-grace-client";
532532 */
533533 function seedGrace(app: App): void {
534534 const dir = app.config.dataDir;
535 if (noticeOf(dir) === undefined) {
535 // Absent, or still the seeded grace: the day is five days from this boot, so a preview that
536 // restarts on each push never lapses into "No active plan".
537 const held = noticeOf(dir);
538 if (held === undefined || held.status === "grace") {
536539 keepNotice(dir, {
537540 name: "Medium",
538541 size: "medium",
src/web/plan_row.ts +16 −9
@@ -1,7 +1,7 @@
11 /**
22 * The Plan row in a forge's settings (#11141), one `dl` row for its admins: the
33 * plan's name and size, the crew credit used this month, and the status (in
4 * grace, "Payment due — paused on <day> · Pay"). Everything is what the host
4 * grace, "Payment failed; your forge sleeps on <day> · Pay"). Everything is what the host
55 * told this forge (`billing/notice.ts`) and its own funding file; nothing is
66 * asked of the host. "Manage billing" is the provider's portal sign-in, shown
77 * only when the host set one and this forge pays through it, and not in grace,
@@ -25,9 +25,16 @@ export const dayWords = (secs: number): string => {
2525 return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`;
2626 };
2727
28 /** "Active", or "Payment due — paused on 18 Nov". */
28 /**
29 * The status as this forge sees it now: a notice in grace whose day has passed is spent, whatever
30 * the host last told, since nothing re-tells a forge when grace ends.
31 */
32 export const statusNow = (n: Pick<PlanNotice, "status" | "periodEnd">, now: number = Date.now()): PlanNotice["status"] =>
33 n.status === "grace" && n.periodEnd !== undefined && n.periodEnd * 1000 <= now ? "none" : n.status;
34
35 /** "Active", or "Payment failed; your forge sleeps on 18 Nov". */
2936 export function statusWords(n: Pick<PlanNotice, "status" | "periodEnd">): string {
30 if (n.status === "grace") return n.periodEnd === undefined ? "Payment due" : `Payment due — paused on ${dayWords(n.periodEnd)}`;
37 if (n.status === "grace") return n.periodEnd === undefined ? "Payment failed" : `Payment failed; your forge sleeps on ${dayWords(n.periodEnd)}`;
3138 return n.status === "none" ? "No active plan" : "Active";
3239 }
3340
@@ -35,7 +42,7 @@ export function statusWords(n: Pick<PlanNotice, "status" | "periodEnd">): string
3542 * The plan as one plain line of text, or undefined when this forge was told none; the page and the
3643 * terminal say the same.
3744 */
38 export function planLine(dataDir: string): string | undefined {
45 export function planLine(dataDir: string, now: number = Date.now()): string | undefined {
3946 const n = noticeOf(dataDir);
4047 if (n === undefined) return undefined;
4148 const f = fundingOf(dataDir);
@@ -45,23 +52,23 @@ export function planLine(dataDir: string): string | undefined {
4552 const cap = f?.capUsd ?? n.creditUsd;
4653 const credit = cap > 0 && f?.spentUsd != null ? ` ${usdWords(f.spentUsd)} of ${usdWords(cap)} crew credit used this month.${uncountedWords(f.uncountedUsd ?? 0)}` : "";
4754 const buys = n.priceUsd > 0 && n.creditUsd > 0 ? ` ${creditWords(n, 0, n.askUsd)}` : "";
48 return `${n.name}${size}. ${statusWords(n)}.${credit}${buys}`;
55 return `${n.name}${size}. ${statusWords({ ...n, status: statusNow(n, now) })}.${credit}${buys}`;
4956 }
5057
5158 /**
5259 * One `dl` row for a forge's admins; null for anyone else or a forge told nothing. `more` is a row
5360 * to share the same `dl` (the Cores row), so the facts read as one list.
5461 */
55 export function planRow(dataDir: string, parentOrigin: string | undefined, admin: boolean, more: Html | null = null): Html | null {
62 export function planRow(dataDir: string, parentOrigin: string | undefined, admin: boolean, more: Html | null = null, now: number = Date.now()): Html | null {
5663 if (!admin) return null;
57 const line = planLine(dataDir);
64 const line = planLine(dataDir, now);
5865 if (line === undefined) return more === null ? null : html`<dl class="status-rows">${more}</dl>`;
5966 const n = noticeOf(dataDir);
6067 const portal = n?.portalUrl;
6168 // In grace the one link that matters is Pay: the provider's portal, else the host's pricing page.
62 const pay = n?.status === "grace" ? (portal ?? (parentOrigin === undefined ? undefined : `${parentOrigin}/pricing`)) : undefined;
69 const pay = n !== undefined && statusNow(n, now) === "grace" ? (portal ?? (parentOrigin === undefined ? undefined : `${parentOrigin}/pricing`)) : undefined;
6370 return html`<dl class="status-rows"><div class="status-row"><dt>Plan</dt><dd>${line}${
64 pay === undefined ? "" : html` · <a href="${pay}" rel="noopener noreferrer">Pay</a>`
71 pay === undefined ? "" : html` · <a href="${pay}" rel="noopener noreferrer" aria-label="Pay the overdue plan">Pay</a>`
6572 }${
6673 portal === undefined || pay !== undefined ? "" : html` <a href="${portal}" rel="noopener noreferrer" target="_blank">Manage billing</a>`
6774 }${
test/grace-calm.test.ts +6 −5
@@ -1,6 +1,6 @@
11 /**
22 * Grace is one line where it belongs (#11394): the forge's own /settings Plan
3 * line says "Payment due — paused on <day> · Pay", the operator's /forges row
3 * line says "Payment failed; your forge sleeps on <day> · Pay", the operator's /forges row
44 * says "grace until <date>", and the home and the board carry no notice.
55 */
66 import { afterAll, beforeAll, expect, test } from "bun:test";
@@ -40,7 +40,7 @@ beforeAll(async () => {
4040 cookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
4141 // This forge is itself told it is in grace (its own plan.json), and as a host it holds a child in grace.
4242 await writeFile(join(dir, "parent.json"), JSON.stringify({ upstream: "https://host.example" }));
43 keepNotice(dir, { name: "Medium", size: "medium", priceUsd: 49, creditUsd: 10, status: "grace", periodEnd: Date.UTC(2026, 10, 18) / 1000, portalUrl: PORTAL });
43 keepNotice(dir, { name: "Medium", size: "medium", priceUsd: 49, creditUsd: 10, status: "grace", periodEnd: Date.UTC(2099, 10, 18) / 1000, portalUrl: PORTAL });
4444 await mkdir(join(dir, "spawn"), { recursive: true });
4545 await writeFile(join(dir, "spawn", "alpha.json"), JSON.stringify({ name: "alpha", bodyId: "body-alpha", done: true, size: "small", org: "alpha", apps: [] }));
4646 await mkdir(childDirOf(app, "body-alpha"), { recursive: true });
@@ -61,10 +61,11 @@ const get = async (path: string): Promise<string> => {
6161 };
6262
6363 test("the plan line says when it pauses, and settings carries it with a Pay link", async () => {
64 expect(planLine(dir)).toContain("Payment due — paused on 18 Nov");
64 expect(planLine(dir)).toContain("Payment failed; your forge sleeps on 18 Nov");
6565 const body = await get("/settings");
66 expect(body).toContain("Payment due — paused on 18 Nov");
66 expect(body).toContain("Payment failed; your forge sleeps on 18 Nov");
6767 expect(body).toMatch(new RegExp(`· <a href="${PORTAL}"[^>]*>Pay</a>`));
68 expect(body).toContain('aria-label="Pay the overdue plan"');
6869 });
6970
7071 test("a told forge learns the day grace ends, not the provider's period end", () => {
@@ -86,7 +87,7 @@ test("in grace, the home and the board carry no notice and none of the words", a
8687 for (const path of ["/", "/board"]) {
8788 const body = await get(path);
8889 expect({ path, found: standing(body) }).toEqual({ path, found: [] });
89 expect(body).not.toContain("Payment due");
90 expect(body).not.toContain("Payment failed");
9091 expect(body).not.toContain("grace until");
9192 }
9293 });
test/payment-failed-line.test.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * A failed payment is one line on the plan row (#15997): "Payment failed; your forge sleeps on
3 * <day>", the day computed from the `billing.grace_days` setting, on day 0, the last day and after
4 * grace.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { childDirOf } from "../src/actions/spawn.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { lapseFor } from "../src/billing/lapse.ts";
13 import { tellPlan } from "../src/billing/notice.ts";
14 import { putEntitlement } from "../src/billing/store.ts";
15 import { setLimit } from "../src/settings/limits.ts";
16 import { dayWords, planLine, planRow } from "../src/web/plan_row.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const DAY = 86_400_000;
22 let dir = "";
23 let app: App;
24 let child = "";
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-payfail-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 await mkdir(join(dir, "spawn"), { recursive: true });
30 await writeFile(join(dir, "spawn", "alpha.json"), JSON.stringify({ name: "alpha", bodyId: "body-alpha", done: true, size: "small", org: "alpha", apps: [] }));
31 child = childDirOf(app, "body-alpha");
32 await mkdir(child, { recursive: true });
33 await writeFile(join(child, "parent.json"), JSON.stringify({ upstream: "https://host.example" }));
34 putEntitlement(app.db, { forge: "alpha", plan: "medium", status: "grace", periodEnd: 1_796_000_000, provider: "stripe", customerId: "cus_x", subscriptionId: "sub_x", source: "stripe" }, "small", "");
35 });
36
37 afterAll(async () => {
38 app.close();
39 await rm(dir, { recursive: true, force: true });
40 });
41
42 const lineAt = (now: number): string => {
43 expect(tellPlan(app, "alpha", now)).toBe(true);
44 return planLine(child) ?? "";
45 };
46
47 test("the line names the day grace ends, read from the setting, on day 0 and the last day", () => {
48 for (const days of [7, 3]) {
49 setLimit(app.db, "billing.grace_days", days, "test");
50 const lapse = lapseFor(app.db, "alpha");
51 if (lapse.state !== "grace") throw new Error("the forge is not in grace");
outdated

The : 0 fallback hides a forge that is not in grace. Assert the state is grace first. The after-grace test also only proves a manual tellPlan call, not what the forge shows once the clock passes.

52 const since = lapse.since;
53 const expected = `Payment failed; your forge sleeps on ${dayWords((since + days * DAY) / 1000)}`;
54 expect(lineAt(since)).toContain(expected);
55 expect(lineAt(since + days * DAY - 1)).toContain(expected);
56 }
57 });
58
59 test("after grace the line no longer promises a day", () => {
60 setLimit(app.db, "billing.grace_days", 7, "test");
61 const lapse = lapseFor(app.db, "alpha");
62 if (lapse.state !== "grace") throw new Error("the forge is not in grace");
63 const since = lapse.since;
64 expect(lapseFor(app.db, "alpha", since + 7 * DAY).state).toBe("none");
65 expect(lineAt(since + 7 * DAY)).not.toContain("Payment failed");
66 });
67
68 test("a forge told grace once and never again stops saying it when the day passes", () => {
69 setLimit(app.db, "billing.grace_days", 7, "test");
70 const lapse = lapseFor(app.db, "alpha");
71 if (lapse.state !== "grace") throw new Error("the forge is not in grace");
72 expect(tellPlan(app, "alpha", lapse.since)).toBe(true);
73 // No second tell: only the clock moves.
74 expect(planLine(child, lapse.since + 7 * DAY - 1000)).toContain("Payment failed; your forge sleeps on");
75 const after = planLine(child, lapse.since + 7 * DAY) ?? "";
76 expect(after).not.toContain("Payment failed");
77 expect(after).toContain("No active plan");
78 expect(planRow(child, "https://host.example", true, null, lapse.since + 7 * DAY)!.toString()).not.toContain(">Pay<");
79 });
test/plan-notice.test.ts +3 −3
@@ -87,7 +87,7 @@ describe("plan notice", () => {
8787 expect(row).toContain("<dt>Plan</dt>");
8888 expect(row).toContain(" · <a href=\"" + PORTAL + "\"");
8989 expect(row).toContain("Medium");
90 expect(row).toContain("Payment due — paused on ");
90 expect(row).toContain("Payment failed; your forge sleeps on ");
9191 expect(row).toContain('href="https://host.example/pricing"');
9292 expect(planRow(a, "https://host.example", false)).toBeNull();
9393 // No portal URL for a forge that does not pay through Stripe: the plan, no link.
@@ -102,9 +102,9 @@ describe("plan notice", () => {
102102 test("in grace with no portal, Pay goes to the host's pricing and Change size is not repeated", async () => {
103103 const cd = await mkdtemp(join(tmpdir(), "forge-grace-row-"));
104104 try {
105 await writeFile(join(cd, "plan.json"), JSON.stringify({ name: "Plan", size: "small", status: "grace", periodEnd: Date.UTC(2026, 10, 18) / 1000 }));
105 await writeFile(join(cd, "plan.json"), JSON.stringify({ name: "Plan", size: "small", status: "grace", periodEnd: Date.UTC(2099, 10, 18) / 1000 }));
106106 const row = planRow(cd, "https://host.example", true)!.toString();
107 expect(row).toContain('Payment due — paused on 18 Nov. · <a href="https://host.example/pricing"');
107 expect(row).toContain('Payment failed; your forge sleeps on 18 Nov. · <a href="https://host.example/pricing"');
108108 expect(row.match(/href="https:\/\/host\.example\/pricing"/g)?.length).toBe(1);
109109 expect(row).not.toContain("Change size");
110110 // With a portal, Pay goes there and Change size still offers the host's pricing.
test/preview-grace.test.ts +2 −2
@@ -33,12 +33,12 @@ const get = async (path: string): Promise<string> => {
3333 };
3434
3535 test("a seeded preview shows the Plan row in grace and the grace row on /forges", async () => {
36 expect(await get("/settings")).toMatch(/Payment due — paused on \d+ \w+/);
36 expect(await get("/settings")).toMatch(/Payment failed; your forge sleeps on \d+ \w+/);
3737 expect(await get("/forges")).toMatch(/grace until \d{4}-\d{2}-\d{2}/);
3838 });
3939
4040 test("home carries no notice, and a second seed changes nothing", async () => {
41 expect(await get("/")).not.toContain("Payment due");
41 expect(await get("/")).not.toContain("Payment failed");
4242 const again = await seedPreview(app, { FORGE_APP_ENV: "preview" });
4343 expect(again.ok && again.value.seeded).toBe(false);
4444 });
test/tui-plan-row.test.ts +1 −1
@@ -64,7 +64,7 @@ test("an admin reads the plan line and sets the portal; a bad address keeps noth
6464 const h = boot("alice");
6565 await h.open();
6666 expect(h.text()).toContain("Medium");
67 expect(h.text()).toContain("Payment due — paused on ");
67 expect(h.text()).toContain("Payment failed; your forge sleeps on ");
6868 await h.press("enter");
6969 for (const ch of "http://insecure.test") await h.press(ch);
7070 await h.press("enter");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs