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
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/16047-a-lapsed-forge-s-pay-again-link-opens-ch → main 0 commits fork 7 threads · 7 unresolved
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 | ||
| 8 | 8 | |
| 9 | 9 | ## What a visitor sees |
| 10 | 10 | |
| 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. | |
| 12 | 14 | |
| 13 | 15 | These sentences are public: anyone who opens the address reads that the subscription ended and the keep-until date. |
| 14 | 16 | |
| 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 | ||
| 15 | 21 | ## Paying |
| 16 | 22 | |
| 17 | 23 | 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. |
| 18 | 24 | |
| 19 | 25 | ## In the terminal |
| 20 | 26 | |
| 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 | ||
| 16 | 16 | /** Two plain sentences, for customers. */ |
| 17 | 17 | export const lapseRuleWords = (r: LapseRule): string => |
| 18 | 18 | `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 @@ | ||
| 1 | 1 | /** The sentences a lapsed forge (billing `none`, #11393) is told in, shared by the wake page and the terminal. */ |
| 2 | 2 | |
| 3 | 3 | import type { Lapse } from "./lapse.ts"; |
| 4 | import { graceDaysLeft, graceEnds, type LapseRule } from "./lapse_rule.ts"; | |
| 4 | 5 | |
| 5 | 6 | const day = (ms: number): string => new Date(ms).toISOString().slice(0, 10); |
| 6 | 7 | |
| @@ -15,12 +16,29 @@ export const exportSentence = (lapse: Extract<Lapse, { state: "none" }>, front: | ||
| 15 | 16 | const zoned = (ms: number): string => `${day(ms)} UTC`; |
| 16 | 17 | |
| 17 | 18 | /** |
| 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` | |
| 23 | * (UTC), the day the wake page names. Undefined for a forge that is not in | |
| 24 | * grace: nothing to announce. | |
| 22 | 25 | */ |
| 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 | ||
| 701 | 701 | const name = parseHostedChildName(request.headers.get("host") ?? "", childHost(parent)); |
| 702 | 702 | if (name === undefined) return undefined; |
| 703 | 703 | 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); | |
| 706 | 707 | } |
| 707 | 708 | |
| 708 | 709 | /** 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"; | ||
| 12 | 12 | import { getPlans } from "../../settings/plans.ts"; |
| 13 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 14 | 14 | import { lapseFor } from "../../billing/lapse.ts"; |
| 15 | import { lapseRule } from "../../billing/lapse_rule.ts"; | |
| 15 | 16 | import { lapseNotice } from "../../billing/lapse_words.ts"; |
| 16 | 17 | import { getStored } from "../../billing/store.ts"; |
| 17 | 18 | import { listPayments } from "../../billing/payments.ts"; |
| @@ -43,8 +44,9 @@ export function billingRows(f: Session): ListRow[] { | ||
| 43 | 44 | const p = customer === "" ? undefined : listPayments(f.app.db, customer, 1)[0]; |
| 44 | 45 | return p === undefined ? "" : ` · last payment ${p.status} ${p.amountMinor} ${p.currency} (minor units)`; |
| 45 | 46 | }; |
| 47 | const rule = lapseRule(f.app.db); | |
| 46 | 48 | 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); | |
| 48 | 50 | return { title: e.forge, secondary: e.plan, meta: `${e.status} · ${e.source}${lastPayment(getStored(f.app.db, e.forge)?.customerId ?? "")}`, ...(notice === undefined ? {} : { below: [notice] }) }; |
| 49 | 51 | }); |
| 50 | 52 | } |
src/tui/screens/lapsed.ts +15 −6
| @@ -8,8 +8,8 @@ | ||
| 8 | 8 | |
| 9 | 9 | import { readBilling } from "../../actions/billing.ts"; |
| 10 | 10 | 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"; | |
| 13 | 13 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 14 | 14 | import { childUrlOf } from "../../spawn/door.ts"; |
| 15 | 15 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -21,18 +21,26 @@ import { emptyState } from "../ui/widgets.ts"; | ||
| 21 | 21 | import { ListState } from "./common.ts"; |
| 22 | 22 | import type { PaletteEntry } from "./entries.ts"; |
| 23 | 23 | |
| 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 | ||
| 24 | 27 | const isAdmin = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent"; |
| 25 | 28 | |
| 26 | 29 | /** 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[] }[] { | |
| 28 | 31 | const read = readBilling(f.app, f.user); |
| 29 | 32 | if (!read.ok) return []; |
| 30 | 33 | 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[] }[] = []; | |
| 32 | 35 | for (const e of read.value.forges) { |
| 33 | 36 | const lapse = lapseFor(f.app.db, e.forge); |
| 34 | 37 | 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 }); | |
| 36 | 44 | } |
| 37 | 45 | return out; |
| 38 | 46 | } |
| @@ -62,7 +70,8 @@ export function lapsedScreen(f: Session, ctx: Ctx): Screen { | ||
| 62 | 70 | const rows = lapsedForges(f); |
| 63 | 71 | const target = rows[state.index]; |
| 64 | 72 | 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."; | |
| 66 | 75 | else { |
| 67 | 76 | note = "Making the checkout…"; |
| 68 | 77 | 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"; | ||
| 13 | 13 | import { REFUND_URL } from "../../billing/checkout.ts"; |
| 14 | 14 | import { changeLine, previewChange, same, seen } from "../../billing/plan_change.ts"; |
| 15 | 15 | import { lapseFor, type Lapse } from "../../billing/lapse.ts"; |
| 16 | import { lapseRule } from "../../billing/lapse_rule.ts"; | |
| 16 | 17 | import { lapseNotice } from "../../billing/lapse_words.ts"; |
| 17 | 18 | import { failedOrders } from "../../billing/orders.ts"; |
| 18 | 19 | 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): | ||
| 203 | 204 | const read = readBilling(ctx.app, ctx.auth.user); |
| 204 | 205 | if (!read.ok) return notFoundPage(ctx); |
| 205 | 206 | 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)])); | |
| 207 | 209 | const rows = b.forges.map( |
| 208 | 210 | (f) => html`<li class="row" data-forge="${f.forge}"> |
| 209 | 211 | <form class="row-fields" method="get" action="/settings/billing/change"> |
src/web/pages/lapsed.ts +21 −9
| @@ -9,8 +9,8 @@ | ||
| 9 | 9 | |
| 10 | 10 | import type { App } from "../../app.ts"; |
| 11 | 11 | 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"; | |
| 14 | 14 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 15 | 15 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 16 | import { takeDoor, tooManyStrangers } from "../../http/strangers.ts"; |
| @@ -27,8 +27,11 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse: | ||
| 27 | 27 | const url = new URL(request.url); |
| 28 | 28 | const front = publicOrigin(app.config.url, url.origin); |
| 29 | 29 | 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(" "); | |
| 30 | 33 | 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" } }); | |
| 32 | 35 | text.headers.set("cache-control", "no-store"); |
| 33 | 36 | return text; |
| 34 | 37 | } |
| @@ -43,10 +46,12 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse: | ||
| 43 | 46 | ${empty({ |
| 44 | 47 | icon: "history", |
| 45 | 48 | 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>`, | |
| 50 | 55 | })} |
| 51 | 56 | <p class="muted small" id="export">${exportLine}</p> |
| 52 | 57 | </div>`, |
| @@ -59,9 +64,12 @@ export function lapsedResponse(app: App, request: Request, name: string, lapse: | ||
| 59 | 64 | |
| 60 | 65 | /** |
| 61 | 66 | * 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. | |
| 63 | 71 | */ |
| 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> { | |
| 65 | 73 | const host = request.headers.get("host") ?? ""; |
| 66 | 74 | const from = request.headers.get("origin"); |
| 67 | 75 | let same = false; |
| @@ -71,6 +79,10 @@ export async function payAgainRoute(app: App, request: Request, name: string): P | ||
| 71 | 79 | same = false; |
| 72 | 80 | } |
| 73 | 81 | 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 | } | |
| 74 | 86 | // Anyone may press it, and each press calls the payment provider: count it per address. |
| 75 | 87 | const turn = takeDoor(app, "pay", request); |
| 76 | 88 | 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", () => { | ||
| 219 | 219 | const row = billingRows(open(alice).session).find((r) => r.title === "kid"); |
| 220 | 220 | putEntitlement(app.db, { forge: "kid", plan: was.plan, status: was.status, source: was.source, provider: was.provider }, "small", "u"); |
| 221 | 221 | 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/); | |
| 223 | 223 | }); |
test/billing.test.ts +1 −1
| @@ -195,7 +195,7 @@ describe("billing seam", () => { | ||
| 195 | 195 | putEntitlement(app.db, { forge: "kid", plan: was.plan, status: "grace", source: "stripe", provider: "stripe" }, "small", "u"); |
| 196 | 196 | const text = await (await send("GET", "/settings/billing", admin)).text(); |
| 197 | 197 | 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\./); | |
| 199 | 199 | }); |
| 200 | 200 | |
| 201 | 201 | 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"; | ||
| 4 | 4 | import { readFileSync } from "node:fs"; |
| 5 | 5 | import { join } from "node:path"; |
| 6 | 6 | import { lapseOf } from "../src/billing/lapse.ts"; |
| 7 | import type { LapseRule } from "../src/billing/lapse_rule.ts"; | |
| 7 | 8 | import { exportSentence, lapseNotice } from "../src/billing/lapse_words.ts"; |
| 8 | 9 | |
| 9 | 10 | const DAY = 86_400_000; |
| 11 | const rule: LapseRule = { graceDays: 7, lapse: "sleep" }; | |
| 10 | 12 | const past = { plan: "pro", status: "grace", source: "stripe", subscribed: true } as const; |
| 11 | 13 | |
| 12 | 14 | describe("lapse notice", () => { |
| 13 | 15 | test("one sentence with the UTC end date and the consequence", () => { |
| 14 | 16 | 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."); | |
| 17 | 19 | expect(s!.match(/\.(\s|$)/g)?.length).toBe(1); |
| 18 | 20 | }); |
| 19 | 21 | test("names the same keep-until day the wake page names once the grace is over", () => { |
| 20 | 22 | 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)!; | |
| 22 | 24 | const asleep = lapseOf({ ...past, since }, since + 8 * DAY, 7, 30); |
| 23 | 25 | if (asleep.state !== "none") throw new Error(asleep.state); |
| 24 | 26 | const kept = /kept until (\d{4}-\d\d-\d\d)/; |
| 25 | 27 | expect(kept.exec(notice)?.[1]).toBe(kept.exec(exportSentence(asleep, "https://forge.test"))![1]!); |
| 26 | 28 | }); |
| 27 | 29 | 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(); | |
| 30 | 32 | }); |
| 31 | 33 | }); |
| 32 | 34 |
Box 2: compute the days from lapseRule, not from raw graceUntil arithmetic, so the rule has one owner.