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

/settings/payments downloads as a CSV, one row per payment #15626

Merged opened this

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

Merged

scout/forge:scout/15624-settings-payments-downloads-as-a-csv-one → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15624-settings-payments-downloads-as-a-csv-one was merged into main as 07280c0.

Review

Sign in to review this change.
11 files changed +208 −14
docs/features/payments.md added +20
@@ -0,0 +1,20 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Your payments, on a page, in the terminal and as a CSV
4 ---
5 # Your payments, on a page, in the terminal and as a CSV (#13093, #15624)
6
7 What was charged for the forges you claimed, newest first.
8
9 - **Page:** `/settings/payments` lists the newest 100. **Download CSV**
10 (under the sentence) fetches `/settings/payments.csv`.
11 - **Terminal:** `Payments` in the palette (`src/tui/screens/payments.ts`)
12 shows the same rows; `c` switches to the file's text to read or copy, `c`
13 again goes back.
14 - **The file:** header `date,forge,plan,amount,currency,status,order_id`,
15 UTC ISO dates, decimal amounts, only your own payments. A cell starting
16 with `=`, `+`, `-` or `@` is prefixed with `'` so a spreadsheet reads text.
17 - **The cap:** the file holds the newest 10,000 rows; past that the response
18 carries an `X-Truncated` header, and the data holds nothing but rows.
19 - **Rate:** one file per person every 2 seconds; a quicker request gets `429`
20 with `Retry-After`.
scripts/unused-exports-allow.json +1
@@ -206,6 +206,7 @@
206206 "src/web/og/raster.ts useLoader",
207207 "src/web/pages/flow-waiting.ts forgetUnproposed",
208208 "src/web/pages/repo.ts clearReadmeCache",
209 "src/web/pages/payments.ts forgetCsvTimes",
209210 "src/web/pages/site.ts signupAllowed",
210211 "src/web/pages/tree_cache.ts clearTreeCache",
211212 "src/web/pinned.ts deployToHref",
src/actions/forge_bill.ts +5 −3
@@ -83,21 +83,23 @@ export const billNames = (app: App, user: User): string[] =>
8383 export interface PaymentLine extends Payment {
8484 /** The forge's plan now: the store keeps no plan per payment. */
8585 readonly plan: string;
86 /** The claimed forge whose customer paid. */
87 readonly forge: string;
8688 }
8789
8890 /** The most rows listed; a person with more is told so. */
8991 export const PAYMENTS_CAP = 100;
9092
9193 /** This person's payments, newest first: those of every forge they claimed, once each. */
92 export function paymentsFor(app: App, user: User | undefined): { rows: PaymentLine[]; more: boolean } {
94 export function paymentsFor(app: App, user: User | undefined, cap = PAYMENTS_CAP): { rows: PaymentLine[]; more: boolean } {
9395 if (user === undefined) return { rows: [], more: false };
9496 const seen = new Map<string, PaymentLine>();
9597 for (const forge of billNames(app, user)) {
9698 const e = getStored(app.db, forge);
9799 if (e === undefined || e.customerId === "") continue;
98100 const plan = getPlan(app.db, e.plan)?.name ?? e.plan;
99 for (const p of listPayments(app.db, e.customerId, PAYMENTS_CAP + 1)) if (!seen.has(p.id)) seen.set(p.id, { ...p, plan });
101 for (const p of listPayments(app.db, e.customerId, cap + 1, Math.max(500, cap + 1))) if (!seen.has(p.id)) seen.set(p.id, { ...p, plan, forge });
100102 }
101103 const all = [...seen.values()].sort((a, b) => (a.at === b.at ? (a.id < b.id ? 1 : -1) : a.at < b.at ? 1 : -1));
102 return { rows: all.slice(0, PAYMENTS_CAP), more: all.length > PAYMENTS_CAP };
104 return { rows: all.slice(0, cap), more: all.length > cap };
103105 }
src/billing/payments.ts +2 −2
@@ -100,9 +100,9 @@ interface Row {
100100 }
101101
102102 /** One customer's payments, newest first. */
103 export function listPayments(db: Database, customerId: string, limit = 100): Payment[] {
103 export function listPayments(db: Database, customerId: string, limit = 100, ceiling = 500): Payment[] {
104104 return db
105105 .query<Row, [string, number]>("SELECT * FROM payment WHERE customer_id = ?1 ORDER BY at DESC, id DESC LIMIT ?2")
106 .all(customerId, Math.max(1, Math.min(500, Math.floor(limit))))
106 .all(customerId, Math.max(1, Math.min(ceiling, Math.floor(limit))))
107107 .map((r) => ({ id: r.id, subscriptionId: r.subscription_id ?? undefined, customerId: r.customer_id, amountMinor: r.amount_minor, currency: r.currency, status: r.status, at: r.at }));
108108 }
src/http/marks/settings.json +1
@@ -29,6 +29,7 @@
2929 "/settings/everyday/to-admin": "open",
3030 "/settings/everyday/keep": "open",
3131 "/settings/payments": "open",
32 "/settings/payments.csv": "open",
3233 "/settings/shells": "open",
3334 "/settings/shells/stop-idle": "open",
3435 "/settings/shells/:id/stop": "open",
src/http/settings_routes.ts +2 −1
@@ -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 { paymentsPage } from "../web/pages/payments.ts";
22 import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts";
2323 import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
2424 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2525 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
@@ -191,6 +191,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
191191 router.add("POST", "/settings/everyday/keep", everydayKeep);
192192 router.add("GET", "/settings/appearance", appearancePage);
193193 router.add("GET", "/settings/payments", paymentsPage);
194 router.add("GET", "/settings/payments.csv", paymentsCsv);
194195 router.add("GET", "/settings/shells", shellsPage);
195196 router.add("POST", "/settings/shells/stop-idle", shellsStopIdle);
196197 router.add("POST", "/settings/shells/:id/stop", shellStop);
src/tui/screens/payments.ts +22 −3
@@ -5,7 +5,7 @@
55 */
66
77 import { paymentsFor, PAYMENTS_CAP } from "../../actions/forge_bill.ts";
8 import { amountWords } from "../../web/pages/payments.ts";
8 import { amountWords, paymentsCsvText } from "../../web/pages/payments.ts";
99 import type { Ctx, Screen } from "../app/app.ts";
1010 import { binding } from "../app/keys.ts";
1111 import { style } from "../term/style.ts";
@@ -23,12 +23,26 @@ export function paymentLines(session: Session): string[] {
2323 return more ? [...lines, `Showing the newest ${PAYMENTS_CAP}; older payments are kept but not listed.`] : lines;
2424 }
2525
26 /**
27 * The file `/settings/payments.csv` serves, line by line, to read or copy; the last line says when
28 * it is cut.
29 */
30 export function csvLines(session: Session): string[] {
31 const user = session.user?.kind === "user" ? session.user : undefined;
32 if (user === undefined) return [];
33 const { csv, more } = paymentsCsvText(session.app, user);
34 const lines = csv.split("\r\n").filter((l) => l !== "");
35 return more ? [...lines, "(only the newest payments are shown; the file on /settings/payments.csv says the same)"] : lines;
36 }
37
2638 export function paymentsScreen(session: Session, ctx: Ctx): Screen {
2739 const scroll = new Scroll();
28 const lines = paymentLines(session);
40 const paged = paymentLines(session);
41 let lines = paged;
42 let asFile = false;
2943 return {
3044 title: "Payments",
31 keys: [binding(["j", "k"], "scroll"), binding(["esc"], "back")],
45 keys: [binding(["j", "k"], "scroll"), binding(["c"], "CSV / list"), binding(["esc"], "back")],
3246 render(area, s) {
3347 const c = ctx.theme.c;
3448 const from = scroll.window(area.h, lines.length);
@@ -38,6 +52,11 @@ export function paymentsScreen(session: Session, ctx: Ctx): Screen {
3852 }
3953 },
4054 key(e) {
55 if (e.key === "c") {
56 asFile = !asFile;
57 lines = asFile ? csvLines(session) : paged;
58 return true;
59 }
4160 if (e.key === "esc" || e.key === "q") {
4261 ctx.pop();
4362 return true;
src/web/pages/payments.ts +67 −1
@@ -9,6 +9,10 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
99 import { signInFirst } from "../chrome.ts";
1010 import { html, type Html } from "../html.ts";
1111 import { page } from "../layout.ts";
12 import type { App } from "../../app.ts";
13 import type { User } from "../../core/users.ts";
14 import { toCsv } from "../../text/csv_write.ts";
15 import { securityFloor } from "../../http/respond.ts";
1216 import { EXPORT_PATH, EXPORT_WORDS } from "../../core/account_export.ts";
1317 import { paymentsFor, PAYMENTS_CAP, type PaymentLine } from "../../actions/forge_bill.ts";
1418
@@ -28,6 +32,68 @@ export function amountWords(minor: number, currency: string): string {
2832 }
2933 }
3034
35 /** The most rows the file holds; a person with more gets the newest and X-Truncated says so. */
36 export const PAYMENTS_CSV_CAP = 10_000;
37
38 /** The least gap between one person's downloads: the file is built in memory. */
39 const CSV_GAP_MS = 2000;
40 const csvTimes = new WeakMap<App, Map<string, number>>();
41 const lastCsvOf = (app: App): Map<string, number> => {
42 let m = csvTimes.get(app);
43 if (m === undefined) csvTimes.set(app, (m = new Map()));
44 return m;
45 };
46 /** Forget every person's last download on this forge (tests). */
47 export const forgetCsvTimes = (app: App): void => lastCsvOf(app).clear();
48
49 /**
50 * "19.99" from 1999 and "usd": the currency's own minor-unit digits, no symbol; plain minor units
51 * when unknown.
52 */
53 function decimal(minor: number, currency: string): string | number {
54 try {
55 const digits = new Intl.NumberFormat("en-US", { style: "currency", currency: currency.toUpperCase() }).resolvedOptions().maximumFractionDigits ?? 2;
56 return (minor / 10 ** digits).toFixed(digits);
57 } catch {
58 return minor;
59 }
60 }
61
outdated

Issue box 4 says no cap. A 10,000-row cap, plus the listPayments clamp raised for every caller, departs from it. Remove the cap or have the issue amended.

62 /**
63 * The file's text for a person, newest first, at most `cap` rows; `more` when older ones were left
64 * out.
65 */
66 export function paymentsCsvText(app: App, user: User | undefined, cap = PAYMENTS_CSV_CAP): { csv: string; more: boolean } {
67 const { rows, more } = paymentsFor(app, user, cap);
68 const csv = toCsv(
69 ["date", "forge", "plan", "amount", "currency", "status", "order_id"],
70 rows.map((p) => [p.at, p.forge, p.plan, decimal(p.amountMinor, p.currency), p.currency.toUpperCase(), p.status, p.id]),
71 );
72 return { csv, more };
73 }
74
75 // GET /settings/payments.csv: the page's rows, same order, up to `cap`; one build per person per
76 // CSV_GAP_MS.
77 export function paymentsCsv(ctx: Ctx, cap = PAYMENTS_CSV_CAP): Response {
outdated

Both doors: the terminal has no way to get this file, and there is no docs/features/ how-to. Add a src/tui/ entry and docs/features/payments.md.

78 const user = ctx.auth.user;
79 if (user === undefined) return signInFirst(ctx);
80 const now = Date.now();
81 const lastCsv = lastCsvOf(ctx.app);
82 if (now - (lastCsv.get(user.id) ?? 0) < CSV_GAP_MS) {
83 return securityFloor(new Response("Too many downloads; try again in a moment.\n", { status: 429, headers: { "retry-after": "2", "content-type": "text/plain; charset=utf-8" } }));
84 }
outdated

A '# truncated' line inside the CSV is not a data row and corrupts the file for parsers. Signal truncation out of band (a header) and add a test for it.

85 if (lastCsv.size > 1000) for (const [k, t] of lastCsv) if (now - t >= CSV_GAP_MS) lastCsv.delete(k);
86 lastCsv.set(user.id, now);
87 const { csv, more } = paymentsCsvText(ctx.app, user, cap);
88 const headers: Record<string, string> = {
89 "content-type": "text/csv; charset=utf-8",
90 "content-disposition": 'attachment; filename="payments.csv"',
91 "cache-control": "private, no-store",
92 };
93 if (more) headers["x-truncated"] = `only the newest ${cap} payments are in this file`;
94 return securityFloor(new Response(csv, { headers }));
95 }
96
3197 const line = (p: PaymentLine): Html =>
3298 html`<tr data-payment="${p.status}"><td>${STATUS_WORDS[p.status]}</td><td><time datetime="${p.at}">${p.at.slice(0, 10)}</time></td><td>${amountWords(p.amountMinor, p.currency)}</td><td>${p.plan}</td></tr>`;
3399
@@ -56,7 +122,7 @@ export function paymentsPage(ctx: Ctx): Response {
56122 // A lean shell: a person comes here from Settings and goes back to it, so the bar holds that
57123 // one link.
58124 tools: html`<a class="small" href="/settings">Settings</a>`,
59 body: html`<div class="page-head"><h1>Payments</h1></div><p>What was charged for the forges you claimed, newest first. Plan now is the forge's plan today.</p>${body}${exportRow()}`,
125 body: html`<div class="page-head"><h1>Payments</h1></div><p>What was charged for the forges you claimed, newest first. Plan now is the forge's plan today.</p>${rows.length === 0 ? null : html`<p><a href="/settings/payments.csv" download>Download CSV</a></p>`}${body}${exportRow()}`,
60126 });
61127 notePhase(ctx.request, "render", performance.now() - rendering);
62128 return res;
test/design-audit.test.ts +1 −1
@@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1717
1818 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1919 const NOT_PAGES =
20 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
20 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2121
2222 const getRoutes = [
2323 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/payments-page.test.ts +77 −2
@@ -7,9 +7,11 @@ import { createApp } from "../src/app.ts";
77 import { putEntitlement } from "../src/billing/store.ts";
88 import { recordPayment } from "../src/billing/payments.ts";
99 import { createSession } from "../src/core/sessions.ts";
10 import { createUser } from "../src/core/users.ts";
10 import { createUser, getUserById } from "../src/core/users.ts";
1111 import { serve } from "../src/http/server.ts";
12 import { amountWords } from "../src/web/pages/payments.ts";
12 import { amountWords, forgetCsvTimes, paymentsCsv } from "../src/web/pages/payments.ts";
13 import { listPayments } from "../src/billing/payments.ts";
14 import type { Ctx } from "../src/http/context.ts";
1315 import { servedRows, dropServed } from "../src/spawn/clients.ts";
1416
1517 let dir = "", app: ReturnType<typeof createApp>, servers: Awaited<ReturnType<typeof serve>>;
@@ -112,3 +114,76 @@ test("the settings page links to it for a person with no forge too, and a curren
112114 expect(amountWords(1999, "usd")).toBe("$19.99");
113115 expect(amountWords(5, "zzzz")).toBe("5 ZZZZ (minor units)");
114116 });
117
118 // /settings/payments.csv (#15624)
119 const csv = (cookie?: string) => {
120 forgetCsvTimes(app);
121 return fetch(`${servers.url}/settings/payments.csv`, { headers: cookie ? { cookie } : {}, redirect: "manual" });
122 };
123
124 test("csv: header, newest first, decimal amounts, only my payments, a link on the page", async () => {
125 const res = await csv(bob);
126 expect(res.status).toBe(200);
127 expect(res.headers.get("content-type")).toStartWith("text/csv");
128 expect(res.headers.get("x-truncated")).toBeNull();
129 const text = await res.text();
130 const lines = text.trimEnd().split("\r\n");
131 expect(lines[0]).toBe("date,forge,plan,amount,currency,status,order_id");
132 expect(lines[1]).toMatch(/^2026-11-01T00:00:00.000Z,acme,.+,5.00,EUR,refunded,in_2$/);
133 expect(lines[2]).toMatch(/,19.99,USD,paid,in_1$/);
134 expect(lines[3]).toMatch(/,1500,JPY,failed,in_3$/);
135 expect(lines).toHaveLength(4);
136 expect(text).not.toContain("in_4");
137 expect(await (await get(bob)).text()).toContain('href="/settings/payments.csv"');
138 });
139
140 test("csv: past the page's 100 the file holds all, the cap cuts it with a header, other callers keep 500", async () => {
141 for (let i = 0; i < 102; i++) pay(`in_big${i}`, "cus_big", 100, "usd", "paid", new Date(Date.UTC(2025, 0, 1 + i)).toISOString());
142 await claimed("bigshop", "b5", "[email protected]", "u");
143 putEntitlement(app.db, { forge: "bigshop", plan: "small", status: "active", customerId: "cus_big", source: "stripe" }, "small", "u");
144 const faye = await person("fay");
145 const fay = faye.cookie;
146 dropServed(app);
147 await servedRows(app);
148 const res = await csv(fay);
149 expect(res.headers.get("x-truncated")).toBeNull();
150 expect((await res.text()).trimEnd().split("\r\n")).toHaveLength(103);
151 expect(listPayments(app.db, "cus_big", 10_000)).toHaveLength(102);
152 for (let i = 102; i < 520; i++) pay(`in_big${i}`, "cus_big", 100, "usd", "paid", new Date(Date.UTC(2025, 0, 1 + i)).toISOString());
153 expect(listPayments(app.db, "cus_big", 10_000)).toHaveLength(500);
154 expect(listPayments(app.db, "cus_big", 10_000, 10_000)).toHaveLength(520);
155
156 // Past the cap the file is cut to the newest, and a header says so, not a line of the data.
157 const user = getUserById(app.db, faye.id)!;
158 forgetCsvTimes(app);
159 const cut = paymentsCsv({ app, auth: { user }, request: new Request("http://x/settings/payments.csv") } as unknown as Ctx, 5);
160 expect(cut.headers.get("x-truncated")).toContain("newest 5");
161 const lines = (await cut.text()).trimEnd().split("\r\n");
162 expect(lines).toHaveLength(6);
163 expect(lines.some((l) => l.startsWith("#"))).toBe(false);
164 expect(lines[1]).toContain("in_big519");
165 });
166
167 test("csv: a second download within the gap is refused with 429", async () => {
168 forgetCsvTimes(app);
169 const url = `${servers.url}/settings/payments.csv`;
170 expect((await fetch(url, { headers: { cookie: bob } })).status).toBe(200);
171 const again = await fetch(url, { headers: { cookie: bob } });
172 expect(again.status).toBe(429);
173 expect(again.headers.get("retry-after")).toBe("2");
174 });
175
176 test("csv: another person's payments are never in the file; a formula-like plan is neutralised", async () => {
177 await claimed("gamma", "b4", "[email protected]", "u");
178 putEntitlement(app.db, { forge: "gamma", plan: "=SUM(1)", status: "active", customerId: "cus_gina", source: "stripe" }, "=SUM(1)", "u");
179 pay("in_g1", "cus_gina", 100, "usd", "paid", "2026-10-20T00:00:00.000Z");
180 const gina = (await person("gina")).cookie;
181 dropServed(app);
182 await servedRows(app);
183 const text = await (await csv(gina)).text();
184 expect(text).toContain("in_g1");
185 expect(text).not.toContain("in_1,");
186 expect(text).toContain(",'=SUM(1),");
187 expect(text).not.toContain(",=SUM(1),");
188 expect((await csv()).status).toBe(303);
189 });
test/payments-tui.test.ts +10 −1
@@ -10,7 +10,7 @@ import { createUser, getUserByName } from "../src/core/users.ts";
1010 import { serve } from "../src/http/server.ts";
1111 import { dropServed, servedRows } from "../src/spawn/clients.ts";
1212 import { Session } from "../src/tui/session.ts";
13 import { entry, paymentLines } from "../src/tui/screens/payments.ts";
13 import { csvLines, entry, paymentLines } from "../src/tui/screens/payments.ts";
1414
1515 let dir = "", app: ReturnType<typeof createApp>, servers: Awaited<ReturnType<typeof serve>>;
1616
@@ -62,3 +62,12 @@ test("the owner sees only their rows, and a guest sees nothing", () => {
6262 expect(entry.offered(guest)).toBe(false);
6363 expect(entry.offered(as("bob"))).toBe(true);
6464 });
65
66 test("the file's text is offered in the terminal: bob's rows only, a guest none", () => {
67 const lines = csvLines(as("bob"));
68 expect(lines[0]).toBe("date,forge,plan,amount,currency,status,order_id");
69 expect(lines).toHaveLength(2);
70 expect(lines[1]).toContain("19.99,USD,paid,in_1");
71 expect(lines.join("\n")).not.toContain("in_4");
72 expect(csvLines(new Session(app, { user: undefined, sshUsername: "guest", remoteAddress: "127.0.0.1" }))).toEqual([]);
73 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs