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

A lapsed forge's pay-again link opens checkout with its plan already chosen and says how many days of grace remain #16076

Merged opened this

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

Merged

mason/forge:mason/16047-a-lapsed-forge-s-pay-again-link-opens-ch → main 0 commits fork 7 threads · 7 unresolved

  • Merged. mason/16047-a-lapsed-forge-s-pay-again-link-opens-ch was merged into main as 8f5555b.

Review

Sign in to review this change.
12 files changed +262 −36
docs/features/lapsed-forge.md +8 −2
@@ -8,14 +8,20 @@ When a forge's subscription ends and the grace days pass, its billing reads `non
88
99 ## What a visitor sees
1010
11 Its address answers 402 with one page: a sentence on what happened, a **Pay again** button, and a line that says until when the data is kept and how to ask for an export. A client that does not ask for HTML gets the same sentences as plain text. The button posts to `/pay-again` on that address, same origin only; it makes a checkout for the last paid plan and sends the payer to it. Each address may press it five times a minute, and sixty together; past that the answer is 429 with `Retry-After`.
11 Its address answers 402 with one page: a sentence on what happened that also names the plan checkout opens with ("Paying again opens checkout for Medium, $49 a month."), a **Pay again** button, and a line that says until when the data is kept and how to ask for an export. A client that does not ask for HTML gets the same sentences as plain text. The button posts to `/pay-again` on that address, same origin only; it makes a checkout for the last paid plan and sends the payer to it. Each address may press it five times a minute, and sixty together; past that the answer is 429 with `Retry-After`.
12
13 Once the day the data is kept until has passed, the link has expired: the page says so and offers no button (the plain-text answer says the same), and a post to `/pay-again` is refused with 410 and that sentence, so no checkout is made for data that may be gone. The plan is the forge's own paid plan, else the last paid one it had.
1214
1315 These sentences are public: anyone who opens the address reads that the subscription ended and the keep-until date.
1416
17 ## Grace days
18
19 A forge still in grace is awake, so it never meets this page. Where it is seen, on the billing page and screen, the lapse notice says how many whole days of grace remain and the day they end (UTC), both counted by the lapse rule (`billing/lapse_rule.ts`, the `billing.grace_days` setting /pricing states).
20
1521 ## Paying
1622
1723 The provider's webhook records the payment as for any subscription; the next request to the address wakes the forge as it was. Nothing on this page marks a forge paid.
1824
1925 ## In the terminal
2026
21 Palette entry **Lapsed forges** (forge admins who are people): each sleeping forge with the same sentences; `p` starts the checkout and prints the address to hand to the payer. `j`/`k` move, `esc` goes back.
27 Palette entry **Lapsed forges** (forge admins who are people): each sleeping forge with the same sentences (the plan line, or the expired line; `p` on an expired one starts nothing); `p` starts the checkout and prints the address to hand to the payer. `j`/`k` move, `esc` goes back.
src/billing/lapse_rule.ts +11
@@ -16,3 +16,14 @@ export const lapseRule = (db: Database): LapseRule => ({ graceDays: limitValue(d
1616 /** Two plain sentences, for customers. */
1717 export const lapseRuleWords = (r: LapseRule): string =>
1818 `If a payment lapses, you have ${r.graceDays} ${r.graceDays === 1 ? "day" : "days"} of grace. After that your forge sleeps and keeps its data.`;
19
20 const DAY = 86_400_000;
21
22 /** The day grace ends for a forge whose grace began at `since`, by the rule. */
23 export const graceEnds = (r: LapseRule, since: number): number => since + r.graceDays * DAY;
24
25 /**
26 * Whole days of grace left at `now` for grace begun at `since`, by the rule: rounded up, never
27 * below none.
28 */
29 export const graceDaysLeft = (r: LapseRule, since: number, now: number): number => Math.max(0, Math.ceil((graceEnds(r, since) - now) / DAY));
src/billing/lapse_words.ts +26 −8
@@ -1,6 +1,7 @@
11 /** The sentences a lapsed forge (billing `none`, #11393) is told in, shared by the wake page and the terminal. */
22
33 import type { Lapse } from "./lapse.ts";
4 import { graceDaysLeft, graceEnds, type LapseRule } from "./lapse_rule.ts";
45
56 const day = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
67
@@ -15,12 +16,29 @@ export const exportSentence = (lapse: Extract<Lapse, { state: "none" }>, front:
1516 const zoned = (ms: number): string => `${day(ms)} UTC`;
1617
1718 /**
18 * The lapse notice, one plain sentence: the day the grace period ends (UTC,
19 * the zone named) and what happens then: the forge sleeps, and its data is
20 * kept until `keepUntil` (UTC), the same day the wake page names. Undefined
21 * for a forge that is not in grace: nothing to announce.
19 * The lapse notice, one plain sentence, shown where a forge in grace is seen
20 * (the billing page and screen): the whole days of grace left and the day
21 * they end (UTC, the zone named), both by the lapse rule (`lapse_rule.ts`),
22 * then what follows: the forge sleeps, and its data is kept until `keepUntil`
outdated

Box 2: compute the days from lapseRule, not from raw graceUntil arithmetic, so the rule has one owner.

23 * (UTC), the day the wake page names. Undefined for a forge that is not in
24 * grace: nothing to announce.
2225 */
23 export const lapseNotice = (lapse: Lapse): string | undefined =>
24 lapse.state === "grace"
25 ? `Your payment lapsed: the grace period ends on ${zoned(lapse.graceUntil)}, and then your forge sleeps; its data is kept until ${zoned(lapse.keepUntil)}.`
26 : undefined;
26 export function lapseNotice(lapse: Lapse, rule: LapseRule, now = Date.now()): string | undefined {
27 if (lapse.state !== "grace") return undefined;
28 const left = Math.max(1, graceDaysLeft(rule, lapse.since, now));
29 const days = left === 1 ? "1 day of grace remains" : `${left} days of grace remain`;
30 return `Your payment lapsed: ${days}, ending on ${zoned(graceEnds(rule, lapse.since))}, and then your forge sleeps; its data is kept until ${zoned(lapse.keepUntil)}.`;
31 }
32
33 /** The plan checkout opens with when paying again. */
34 export const payAgainSentence = (plan: { name: string; priceUsd: number }): string =>
35 `Paying again opens checkout for ${plan.name}, $${plan.priceUsd} a month.`;
36
outdated

Dead on the one live path: lapsedResponse only receives state none, so this is always 0. Show grace where a forge in grace can see it, and test that.

37 /** Whether the time the data is kept has passed: the pay-again link has expired. */
38 export const linkExpired = (lapse: Extract<Lapse, { state: "none" }>, now: number): boolean => now > lapse.keepUntil;
39
40 /**
41 * Said in place of the button, and as the refusal of a pay-again post, once the keep-until day has
42 * passed, so nobody pays blind. The day itself is the export line's to say.
43 */
44 export const expiredSentence = (front: string): string => `This link has expired. Ask this forge's operator at ${front} before paying.`;
src/spawn/host.ts +3 −2
@@ -701,8 +701,9 @@ export async function payAgainGate(parent: App, request: Request): Promise<Respo
701701 const name = parseHostedChildName(request.headers.get("host") ?? "", childHost(parent));
702702 if (name === undefined) return undefined;
703703 const ledger = readLedgerSync(parent, name);
704 if (ledger === undefined || !ledger.done || lapsedNone(parent, name) === undefined) return undefined;
705 return payAgainRoute(parent, request, name);
704 const lapse = lapsedNone(parent, name);
705 if (ledger === undefined || !ledger.done || lapse === undefined) return undefined;
706 return payAgainRoute(parent, request, name, lapse);
706707 }
707708
708709 /** Drop every hosted child App this parent has open (call when the parent stops). */
src/tui/screens/billing.ts +3 −1
@@ -12,6 +12,7 @@ import { changeLine, previewChange } from "../../billing/plan_change.ts";
1212 import { getPlans } from "../../settings/plans.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
1414 import { lapseFor } from "../../billing/lapse.ts";
15 import { lapseRule } from "../../billing/lapse_rule.ts";
1516 import { lapseNotice } from "../../billing/lapse_words.ts";
1617 import { getStored } from "../../billing/store.ts";
1718 import { listPayments } from "../../billing/payments.ts";
@@ -43,8 +44,9 @@ export function billingRows(f: Session): ListRow[] {
4344 const p = customer === "" ? undefined : listPayments(f.app.db, customer, 1)[0];
4445 return p === undefined ? "" : ` · last payment ${p.status} ${p.amountMinor} ${p.currency} (minor units)`;
4546 };
47 const rule = lapseRule(f.app.db);
4648 return read.value.forges.map((e) => {
47 const notice = lapseNotice(lapseFor(f.app.db, e.forge));
49 const notice = lapseNotice(lapseFor(f.app.db, e.forge), rule);
4850 return { title: e.forge, secondary: e.plan, meta: `${e.status} · ${e.source}${lastPayment(getStored(f.app.db, e.forge)?.customerId ?? "")}`, ...(notice === undefined ? {} : { below: [notice] }) };
4951 });
5052 }
src/tui/screens/lapsed.ts +15 −6
@@ -8,8 +8,8 @@
88
99 import { readBilling } from "../../actions/billing.ts";
1010 import { lapseFor } from "../../billing/lapse.ts";
11 import { exportSentence, lapsedSentence } from "../../billing/lapse_words.ts";
12 import { canPayAgain, startPayAgain } from "../../billing/pay_again.ts";
11 import { exportSentence, expiredSentence, lapsedSentence, linkExpired, payAgainSentence } from "../../billing/lapse_words.ts";
12 import { canPayAgain, payAgainPlan, startPayAgain } from "../../billing/pay_again.ts";
1313 import { publicOrigin } from "../../core/public_origin.ts";
1414 import { childUrlOf } from "../../spawn/door.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
@@ -21,18 +21,26 @@ import { emptyState } from "../ui/widgets.ts";
2121 import { ListState } from "./common.ts";
2222 import type { PaletteEntry } from "./entries.ts";
2323
24 /** Said when `p` is pressed on a forge whose link has expired: no checkout is made. */
25 export const EXPIRED_NOTE = "This link has expired; ask the operator before paying.";
26
2427 const isAdmin = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent";
2528
2629 /** The forges asleep for want of payment, with the lines that say why and how to export. */
27 export function lapsedForges(f: Session): { name: string; lines: string[] }[] {
30 export function lapsedForges(f: Session): { name: string; expired: boolean; lines: string[] }[] {
2831 const read = readBilling(f.app, f.user);
2932 if (!read.ok) return [];
3033 const front = publicOrigin(f.app.config.url, `http://${f.app.config.host ?? "localhost"}`);
31 const out: { name: string; lines: string[] }[] = [];
34 const out: { name: string; expired: boolean; lines: string[] }[] = [];
3235 for (const e of read.value.forges) {
3336 const lapse = lapseFor(f.app.db, e.forge);
3437 if (lapse.state !== "none") continue;
35 out.push({ name: e.forge, lines: [lapsedSentence(e.forge), exportSentence(lapse, front)] });
38 const plan = payAgainPlan(f.app, e.forge);
39 const expired = linkExpired(lapse, Date.now());
40 const lines = [lapsedSentence(e.forge), exportSentence(lapse, front)];
41 if (expired) lines.push(expiredSentence(front));
42 else if (plan !== undefined) lines.push(payAgainSentence(plan));
43 out.push({ name: e.forge, expired, lines });
3644 }
3745 return out;
3846 }
@@ -62,7 +70,8 @@ export function lapsedScreen(f: Session, ctx: Ctx): Screen {
6270 const rows = lapsedForges(f);
6371 const target = rows[state.index];
6472 if (e.key === "p" && target !== undefined) {
65 if (!canPayAgain(f.app, target.name)) note = "Paying is not set up on this forge yet.";
73 if (target.expired) note = EXPIRED_NOTE;
74 else if (!canPayAgain(f.app, target.name)) note = "Paying is not set up on this forge yet.";
6675 else {
6776 note = "Making the checkout…";
6877 void startPayAgain(f.app, target.name, childUrlOf(f.app, target.name).replace(/\/+$/, "")).then((made) => {
src/web/pages/billing.ts +3 −1
@@ -13,6 +13,7 @@ import { retryOrder } from "../../actions/order.ts";
1313 import { REFUND_URL } from "../../billing/checkout.ts";
1414 import { changeLine, previewChange, same, seen } from "../../billing/plan_change.ts";
1515 import { lapseFor, type Lapse } from "../../billing/lapse.ts";
16 import { lapseRule } from "../../billing/lapse_rule.ts";
1617 import { lapseNotice } from "../../billing/lapse_words.ts";
1718 import { failedOrders } from "../../billing/orders.ts";
1819 import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../actions/codes.ts";
@@ -203,7 +204,8 @@ function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused):
203204 const read = readBilling(ctx.app, ctx.auth.user);
204205 if (!read.ok) return notFoundPage(ctx);
205206 const b = read.value;
206 const notices = new Map(b.forges.map((f) => [f.forge, lapseNotice(lapseFor(ctx.app.db, f.forge))]));
207 const rule = lapseRule(ctx.app.db);
208 const notices = new Map(b.forges.map((f) => [f.forge, lapseNotice(lapseFor(ctx.app.db, f.forge), rule)]));
207209 const rows = b.forges.map(
208210 (f) => html`<li class="row" data-forge="${f.forge}">
209211 <form class="row-fields" method="get" action="/settings/billing/change">
src/web/pages/lapsed.ts +21 −9
@@ -9,8 +9,8 @@
99
1010 import type { App } from "../../app.ts";
1111 import type { Lapse } from "../../billing/lapse.ts";
12 import { exportSentence, lapsedSentence } from "../../billing/lapse_words.ts";
13 import { canPayAgain, startPayAgain } from "../../billing/pay_again.ts";
12 import { exportSentence, expiredSentence, lapsedSentence, linkExpired, payAgainSentence } from "../../billing/lapse_words.ts";
13 import { canPayAgain, payAgainPlan, startPayAgain } from "../../billing/pay_again.ts";
1414 import { publicOrigin } from "../../core/public_origin.ts";
1515 import type { Ctx } from "../../http/context.ts";
1616 import { takeDoor, tooManyStrangers } from "../../http/strangers.ts";
@@ -27,8 +27,11 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse:
2727 const url = new URL(request.url);
2828 const front = publicOrigin(app.config.url, url.origin);
2929 const exportLine = exportSentence(lapse, front);
30 const plan = payAgainPlan(app, name);
31 const expired = linkExpired(lapse, Date.now());

High: expiry is decided only to hide the button. The POST /pay-again handler must check linkExpired too and refuse, with a test; otherwise a direct post still opens checkout blind.

32 const said = [lapsedSentence(name), ...(plan === undefined || expired ? [] : [payAgainSentence(plan)])].join(" ");
3033 if (!(request.headers.get("accept") ?? "").includes("text/html")) {
31 const text = new Response(`${lapsedSentence(name)}\n${exportLine}\n`, { status: 402, headers: { "content-type": "text/plain; charset=utf-8" } });
34 const text = new Response(`${said}\n${expired ? `${expiredSentence(front)}\n` : ""}${exportLine}\n`, { status: 402, headers: { "content-type": "text/plain; charset=utf-8" } });
3235 text.headers.set("cache-control", "no-store");
3336 return text;
3437 }
@@ -43,10 +46,12 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse:
4346 ${empty({
4447 icon: "history",
4548 title: "This forge is asleep",
46 note: lapsedSentence(name),
47 action: pay
48 ? html`<form method="post" action="${PAY_AGAIN_PATH}">${btn("Pay again", { variant: "primary" })}</form>`
49 : html`<p class="muted">Paying is not set up on this forge yet; ask its operator.</p>`,
49 note: said,
50 action: expired
51 ? html`<p class="muted">${expiredSentence(front)}</p>`
52 : pay
53 ? html`<form method="post" action="${PAY_AGAIN_PATH}">${btn("Pay again", { variant: "primary" })}</form>`
outdated

Principle 1/7: up to three stacked muted paragraphs. Fold the plan into the empty() note and keep the expired sentence next to the button. The plain-text 402 above still omits these lines.

54 : html`<p class="muted">Paying is not set up on this forge yet; ask its operator.</p>`,
5055 })}
5156 <p class="muted small" id="export">${exportLine}</p>
5257 </div>`,
@@ -59,9 +64,12 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse:
5964
6065 /**
6166 * POST /pay-again on a lapsed forge's address: make the checkout and send the
62 * payer to it. Refused unless the request comes from this very address.
67 * payer to it. Refused unless the request comes from this very address, and
68 * refused with 410 and the expired sentence once the keep-until day has passed
69 * (the same `linkExpired` that hides the button), so a direct post never opens
70 * checkout for data that may be gone.
6371 */
64 export async function payAgainRoute(app: App, request: Request, name: string): Promise<Response> {
72 export async function payAgainRoute(app: App, request: Request, name: string, lapse: Extract<Lapse, { state: "none" }>): Promise<Response> {
6573 const host = request.headers.get("host") ?? "";
6674 const from = request.headers.get("origin");
6775 let same = false;
@@ -71,6 +79,10 @@ export async function payAgainRoute(app: App, request: Request, name: string): P
7179 same = false;
7280 }
7381 if (!same) return new Response("not allowed", { status: 403, headers: { "cache-control": "no-store" } });
82 if (linkExpired(lapse, Date.now())) {
83 const front = publicOrigin(app.config.url, new URL(request.url).origin);
84 return new Response(`${expiredSentence(front)}\n`, { status: 410, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } });
85 }
7486 // Anyone may press it, and each press calls the payment provider: count it per address.
7587 const turn = takeDoor(app, "pay", request);
7688 if (!turn.allowed) return tooManyStrangers({ retryAfter: turn.retryAfter, why: "too many attempts to pay again; retry shortly" });
test/billing-pay-again-plan.test.ts added +163
@@ -0,0 +1,163 @@
1 /**
2 * The pay-again page and screen name the plan, an expired link, and the grace days where grace is
3 * seen (#16047).
4 */
5
6 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
11 import { useCheckout, type CheckoutRequest } from "../src/billing/checkout.ts";
12 import { graceDaysLeft, type LapseRule } from "../src/billing/lapse_rule.ts";
13 import { lapseNotice } from "../src/billing/lapse_words.ts";
14 import { startPayAgain } from "../src/billing/pay_again.ts";
15 import { putEntitlement } from "../src/billing/store.ts";
16 import { ok } from "../src/kernel/result.ts";
17 import { childUrlOf } from "../src/spawn/door.ts";
18 import { payAgainGate } from "../src/spawn/host.ts";
19 import { EXPIRED_NOTE, lapsedForges, lapsedScreen } from "../src/tui/screens/lapsed.ts";
20 import type { Ctx } from "../src/tui/app/app.ts";
21 import type { Session } from "../src/tui/session.ts";
22 import type { KeyEvent } from "../src/tui/term/input.ts";
23 import { Screen as Surface } from "../src/tui/term/screen.ts";
24 import { theme } from "../src/tui/ui/theme.ts";
25 import { lapsedResponse } from "../src/web/pages/lapsed.ts";
26
27 const DAY = 86_400_000;
28 const pressed = (key: string): KeyEvent => ({ type: "key", key, ctrl: false, alt: false, shift: false });
29 const PLAN_LINE = "Paying again opens checkout for Medium, $49 a month.";
30 let dir = "";
31 let app: App;
32 let asked: CheckoutRequest[] = [];
33
outdated

Only the helper is tested. Add a page test and a TUI test that fail without the change, and one for the plan the checkout opens with.

34 const asleep = (keepUntil: number) => ({ state: "none" as const, since: 0, keepUntil });
35 const visit = (accept: string) => new Request("https://kid.forge.test/", { headers: { accept, host: "kid.forge.test" } });
36 const admin = () => ({ app, user: { id: "x", username: "alice", isAdmin: true, kind: "person" } }) as unknown as Session;
37 const press = (name: string): Request => {
38 const url = childUrlOf(app, name).replace(/\/+$/, "");
39 return new Request(`${url}/pay-again`, { method: "POST", headers: { host: new URL(url).host, origin: url } });
40 };
41 /** `old` lapsed in 2000: its keep-until day is long past, so its link has expired. */
42 async function lapseLongAgo(): Promise<void> {
43 await writeFile(join(dir, "spawn", "old.json"), JSON.stringify({ name: "old", bodyId: "body-old", done: true }));
44 putEntitlement(app.db, { forge: "old", plan: "medium", status: "none", payer: "[email protected]", source: "stripe" }, "free", "system");
45 const then = "2000-01-01T00:00:00.000Z";
46 app.db.run("UPDATE entitlement_change SET at = ?1 WHERE forge = 'old'", [then]);
47 app.db.run("UPDATE entitlement SET updated_at = ?1 WHERE forge = 'old'", [then]);
48 }
49
50 beforeAll(async () => {
51 dir = await mkdtemp(join(tmpdir(), "pay-again-plan-"));
52 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
53 await mkdir(join(dir, "spawn"), { recursive: true });
54 await writeFile(join(dir, "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: "body-kid", done: true }));
55 putEntitlement(app.db, { forge: "kid", plan: "medium", status: "none", payer: "[email protected]", source: "stripe" }, "free", "system");
56 useCheckout(app, {
57 name: "fake",
58 create: async (req) => {
59 asked.push(req);
60 return ok({ id: "cs_1", url: "https://pay.example/cs_1" });
61 },
62 state: async () => ok({ paid: false, customer: "", subscription: "" }),
63 });
64 });
65 afterAll(async () => {
66 app.db.close();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 describe("the lapsed page", () => {
71 test("names the plan the checkout opens with, and the checkout opens with that plan", async () => {
72 const res = lapsedResponse(app, visit("text/html"), "kid", asleep(Date.now() + DAY));
73 const body = await res.text();
74 expect(res.status).toBe(402);
75 expect(body).toContain(PLAN_LINE);
76 expect(body).toContain("Pay again");
77 expect(body).not.toContain("grace");
78 await startPayAgain(app, "kid", "https://kid.forge.test");
79 expect(asked[0]).toMatchObject({ plan: "medium", planName: "Medium", priceUsd: 49 });
80 });
81
82 test("once the keep-until day has passed it says the link expired and offers no button", async () => {
83 const body = await lapsedResponse(app, visit("text/html"), "kid", asleep(Date.now() - DAY)).text();
84 expect(body).toContain("This link has expired");
85 expect(body).not.toContain('action="/pay-again"');
86 expect(body).not.toContain(PLAN_LINE);
87 });
88
89 test("the plain-text answer carries the same lines", async () => {
90 const live = await lapsedResponse(app, visit("application/json"), "kid", asleep(Date.now() + DAY)).text();
91 expect(live).toContain(PLAN_LINE);
92 const gone = await lapsedResponse(app, visit("application/json"), "kid", asleep(Date.now() - DAY)).text();
93 expect(gone).toContain("This link has expired");
94 });
95 });
96
97 describe("a pay-again post", () => {
98 test("opens checkout while the data is kept", async () => {
99 asked = [];
100 const res = await payAgainGate(app, press("kid"));
101 expect(res?.status).toBe(303);
102 expect(asked).toHaveLength(1);
103 });
104
105 test("past the keep-until day is refused with the expired sentence, and no checkout is made", async () => {
106 await lapseLongAgo();
107 asked = [];
108 const res = await payAgainGate(app, press("old"));
109 expect(res?.status).toBe(410);
110 expect(await res!.text()).toContain("This link has expired");
111 expect(asked).toHaveLength(0);
112 });
113 });
114
115 describe("the lapsed screen", () => {
116 test("lists the plan line, or the expired line once the data may be gone", () => {
117 const rows = lapsedForges(admin()).filter((r) => r.name !== "old");
118 expect(rows.map((r) => r.name)).toEqual(["kid"]);
119 // putEntitlement made the forge lapsed just now: its keep-until day is ahead.
120 expect(rows[0]!.lines).toContain(PLAN_LINE);
121 expect(rows[0]!.expired).toBe(false);
122 });
123 });
124
125 describe("the lapsed screen, expired", () => {
126 test("an expired forge's row says the link expired and names no plan", async () => {
127 await lapseLongAgo();
128 const row = lapsedForges(admin()).find((r) => r.name === "old")!;
129 expect(row.expired).toBe(true);
130 expect(row.lines.some((l) => l.startsWith("This link has expired."))).toBe(true);
131 expect(row.lines).not.toContain(PLAN_LINE);
132 });
133
134 test("p on an expired forge says so and starts no checkout (the refusal is synchronous)", async () => {
135 await lapseLongAgo();
136 asked = [];
137 const ctx = { theme: theme("dark"), invalidate: () => {} } as unknown as Ctx;
138 const screen = lapsedScreen(admin(), ctx);
139 const at = lapsedForges(admin()).findIndex((r) => r.name === "old");
140 for (let i = 0; i < at; i++) screen.key!(pressed("j"));
141 screen.key!(pressed("p"));
142 const s = new Surface(200, 40);
143 screen.render({ x: 0, y: 0, w: 200, h: 40 }, s);
144 expect(s.toText()).toContain(EXPIRED_NOTE);
145 expect(asked).toHaveLength(0);
146 });
147 });
148
149 describe("the grace days", () => {
150 const rule: LapseRule = { graceDays: 3, lapse: "sleep" };
151 const g = { state: "grace" as const, since: 0, graceUntil: 3 * DAY, keepUntil: 10 * DAY };
152 test("are counted by the lapse rule", () => {
153 expect(graceDaysLeft(rule, 0, DAY + 1)).toBe(2);
154 expect(graceDaysLeft(rule, 0, 4 * DAY)).toBe(0);
155 // The rule's setting, not a stored graceUntil, decides: five days of grace leave four after
156 // one.
157 expect(graceDaysLeft({ graceDays: 5, lapse: "sleep" }, 0, DAY)).toBe(4);
158 });
159 test("show in the lapse notice, where a forge in grace is seen", () => {
160 expect(lapseNotice(g, rule, DAY + 1)).toContain("2 days of grace remain, ending on 1970-01-04 UTC");
161 expect(lapseNotice(g, rule, 2 * DAY + 1)).toContain("1 day of grace remains");
162 });
163 });
test/billing-tui.test.ts +1 −1
@@ -219,5 +219,5 @@ test("a forge in grace shows the lapse notice on its terminal row", () => {
219219 const row = billingRows(open(alice).session).find((r) => r.title === "kid");
220220 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: was.status, source: was.source, provider: was.provider }, "small", "u");
221221 expect(row?.meta).not.toContain("lapsed");
222 expect(row?.below?.[0]).toMatch(/Your payment lapsed: the grace period ends on \d{4}-\d\d-\d\d UTC/);
222 expect(row?.below?.[0]).toMatch(/Your payment lapsed: \d+ days? of grace remain, ending on \d{4}-\d\d-\d\d UTC/);
223223 });
test/billing.test.ts +1 −1
@@ -195,7 +195,7 @@ describe("billing seam", () => {
195195 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: "grace", source: "stripe", provider: "stripe" }, "small", "u");
196196 const text = await (await send("GET", "/settings/billing", admin)).text();
197197 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: was.status, source: was.source, provider: was.provider }, "small", "u");
198 expect(text).toMatch(/data-lapse-notice>Your payment lapsed: the grace period ends on \d{4}-\d\d-\d\d UTC, and then your forge sleeps; its data is kept until \d{4}-\d\d-\d\d UTC\./);
198 expect(text).toMatch(/data-lapse-notice>Your payment lapsed: \d+ days? of grace remain, ending on \d{4}-\d\d-\d\d UTC, and then your forge sleeps; its data is kept until \d{4}-\d\d-\d\d UTC\./);
199199 });
200200
201201 test("the Billing page's row leads to the preview, not straight to the grant", async () => {
test/lapse-words.test.ts +7 −5
@@ -4,29 +4,31 @@ import { describe, expect, test } from "bun:test";
44 import { readFileSync } from "node:fs";
55 import { join } from "node:path";
66 import { lapseOf } from "../src/billing/lapse.ts";
7 import type { LapseRule } from "../src/billing/lapse_rule.ts";
78 import { exportSentence, lapseNotice } from "../src/billing/lapse_words.ts";
89
910 const DAY = 86_400_000;
11 const rule: LapseRule = { graceDays: 7, lapse: "sleep" };
1012 const past = { plan: "pro", status: "grace", source: "stripe", subscribed: true } as const;
1113
1214 describe("lapse notice", () => {
1315 test("one sentence with the UTC end date and the consequence", () => {
1416 const since = Date.parse("2026-03-01T23:30:00Z");
15 const s = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30));
16 expect(s).toBe("Your payment lapsed: the grace period ends on 2026-03-08 UTC, and then your forge sleeps; its data is kept until 2026-04-07 UTC.");
17 const s = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30), rule, since + DAY);
18 expect(s).toBe("Your payment lapsed: 6 days of grace remain, ending on 2026-03-08 UTC, and then your forge sleeps; its data is kept until 2026-04-07 UTC.");
1719 expect(s!.match(/\.(\s|$)/g)?.length).toBe(1);
1820 });
1921 test("names the same keep-until day the wake page names once the grace is over", () => {
2022 const since = Date.parse("2026-03-01T23:30:00Z");
21 const notice = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30))!;
23 const notice = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30), rule, since + DAY)!;
2224 const asleep = lapseOf({ ...past, since }, since + 8 * DAY, 7, 30);
2325 if (asleep.state !== "none") throw new Error(asleep.state);
2426 const kept = /kept until (\d{4}-\d\d-\d\d)/;
2527 expect(kept.exec(notice)?.[1]).toBe(kept.exec(exportSentence(asleep, "https://forge.test"))![1]!);
2628 });
2729 test("says nothing for an active or already-asleep forge", () => {
28 expect(lapseNotice({ state: "active" })).toBeUndefined();
29 expect(lapseNotice(lapseOf({ ...past, since: 0 }, 99 * DAY, 7, 30))).toBeUndefined();
30 expect(lapseNotice({ state: "active" }, rule)).toBeUndefined();
31 expect(lapseNotice(lapseOf({ ...past, since: 0 }, 99 * DAY, 7, 30), rule)).toBeUndefined();
3032 });
3133 });
3234

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs