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

The wallet's spends download as one CSV through the data export door #13412

Merged opened this

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

Merged

scout/forge:scout/13386-the-wallet-s-spends-download-as-one-csv → main 9 commits fork 1 thread · 1 unresolved

  • Merged. scout/13386-the-wallet-s-spends-download-as-one-csv was merged into main as ce1f2f0.

Review

Sign in to review this change.
6 files changed +68 −3
docs/features/wallet.md +5
@@ -12,6 +12,11 @@ did not end well says so beside what it paid for.
1212 - **Where:** a link beside the statement in the app's settings → App; at the
1313 terminal, `owner/name — Wallet` in the `:` palette while the repository is
1414 open (`j`/`k` move).
15 - **CSV:** `/owner/name/wallet.csv` downloads those same rows (`date_utc,dollars,paid_for,outcome,run`)
16 through the shared formula-safe writer (`actions/wallet_csv.ts`: a cell starting `=`, `+`, `-` or `@`
17 is written as text). It reads `readWallet`, so the gate and the 20-row cap are the page's: anyone
18 else gets 404. The page links it; the terminal's wallet screen prints the path. It does not go
19 through `exportRows`, which reads a table of an app's own database; the ledger is the forge's.
1520 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
1621 scan and no sort, so it does not grow with the ledger
1722 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
src/actions/wallet_csv.ts added +12
@@ -0,0 +1,12 @@
1 /**
2 * The wallet's spends as one CSV (#13386): the rows the wallet page shows (`readWallet`, so the
3 * same gate and the same 20-row cap), written by the one formula-safe writer (`text/csv_write.ts`).
4 * Dollars are numbers to the cent; what it paid for is text, so a cell starting `=` is neutralised.
5 */
6 import { toCsv } from "../text/csv_write.ts";
7 import type { WalletSpend } from "./wallet.ts";
8
9 export const WALLET_CSV_HEADER = ["date_utc", "dollars", "paid_for", "outcome", "run"] as const;
10
11 export const walletCsv = (spends: readonly WalletSpend[]): string =>
12 toCsv(WALLET_CSV_HEADER, spends.map((s) => [s.date, Number(s.costUsd.toFixed(2)), s.paidFor, s.outcome, s.runPath]));
src/http/server.ts +2 −1
@@ -489,7 +489,7 @@ import {
489489 crewSettingsPage,
490490 crewSubscriptionsSave,
491491 } from "../web/pages/crew-settings.ts";
492 import { walletPage, walletSave } from "../web/pages/wallet.ts";
492 import { walletCsvDownload, walletPage, walletSave } from "../web/pages/wallet.ts";
493493 import {
494494 promptSourceAdd,
495495 promptSourceDelete,
@@ -1769,6 +1769,7 @@ export function buildRouter(): Router<Handler> {
17691769 promptSourceDelete,
17701770 );
17711771 router.add("GET", "/:owner/:name/wallet", walletPage);
1772 router.add("GET", "/:owner/:name/wallet.csv", walletCsvDownload);
17721773 router.add("POST", "/:owner/:name/wallet", walletSave);
17731774 router.add("GET", "/:owner/:name/settings/crew", crewSettingsPage);
17741775 router.add("POST", "/:owner/:name/settings/crew", crewAdd);
src/tui/screens/money.ts +4 −1
@@ -132,7 +132,10 @@ export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
132132 const c = ctx.theme.c;
133133 const r = rows();
134134 const [head, list] = split(area, "v", [len(1), fill(1)]);
135 const said = r.length === 0 ? "nothing spent yet" : "last 20 spends · US dollars · days are UTC";
135 const said =
136 r.length === 0
137 ? "nothing spent yet"
138 : `last 20 spends · US dollars · days are UTC · as CSV: /${repo.ownerName}/${repo.name}/wallet.csv`;
136139 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
137140 drawList(s, list!, c, state, r);
138141 },
src/web/pages/wallet.ts +20 −1
@@ -6,6 +6,7 @@
66 * Server-rendered, no script; anyone else gets the not-found page.
77 */
88
9 import { walletCsv } from "../../actions/wallet_csv.ts";
910 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1011 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1112 import { canAdmin } from "../../core/repos.ts";
@@ -55,7 +56,8 @@ export function walletPage(ctx: Ctx): Response {
5556 const body = html`<section class="settings-block" data-wallet>
5657 <h2>Wallet</h2>
5758 ${capBlock}
58 <p class="small">What ${w.app}'s last 20 spends paid for, newest first, each with the run behind it.</p>
59 <p class="small">What ${w.app}'s last 20 spends paid for, newest first, each with the run behind it.
60 ${w.spends.length === 0 ? null : html`<a href="${base}/wallet.csv" download>Download as CSV</a>`}</p>
5961 ${w.spends.length === 0
6062 ? html`<p class="small">Nothing spent yet: the crew's runs on ${w.app} appear here as they report their cost.</p>`
6163 : html`<div class="table-scroll">
@@ -79,6 +81,23 @@ export function walletPage(ctx: Ctx): Response {
7981 return response;
8082 }
8183
84 // GET /:owner/:name/wallet.csv: the rows above as a download, behind the page's own gate.
85 export function walletCsvDownload(ctx: Ctx): Response {
86 const repo = loadRepo(ctx);
87 if (!repo) return repoNotFound(ctx);
88 const read = readWallet(ctx.app, ctx.auth.user, repo);
89 if (!read.ok) return repoNotFound(ctx);
90 const name = `${repo.name}-wallet`.replace(/[^A-Za-z0-9._-]/g, "_");
91 return new Response(walletCsv(read.value.spends), {
92 headers: {
93 "content-type": "text/csv; charset=utf-8",
94 "content-disposition": `attachment; filename="${name}.csv"`,
95 "x-content-type-options": "nosniff",
96 "cache-control": "private, no-store",
97 },
98 });
99 }
100
82101 // POST /:owner/:name/wallet
83102 export async function walletSave(ctx: Ctx): Promise<Response> {
84103 const gate = await adminForm(ctx);
test/wallet.test.ts +25
@@ -8,6 +8,7 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { readWallet, LAST_SPENDS_SQL } from "../src/actions/wallet.ts";
11 import { walletCsv } from "../src/actions/wallet_csv.ts";
1112 import { createIssue } from "../src/core/issues.ts";
1213 import { createRepo as initRepo, type Repo } from "../src/core/repos.ts";
1314 import { createRun } from "../src/core/runs.ts";
@@ -165,3 +166,27 @@ test("with 10,000 ledger rows the page costs a few statements, not one per row",
165166 expectWork(await requestStatements(app.db, url, { headers }), { max: 40 });
166167 expectWork(await statements(app.db, () => void readWallet(app, bob, repo)), { max: 2 });
167168 });
169
170 test("the CSV download is the page's rows, neutralises a formula cell, and is the writer's alone", async () => {
171 const res = await fetch(`${servers.url}/bob/wallet-app/wallet.csv`, { headers: { cookie: await cookieOf("bob") } });
172 expect(res.status).toBe(200);
173 expect(res.headers.get("content-type")).toContain("text/csv");
174 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
175 expect(res.headers.get("content-disposition")).toContain("wallet-app-wallet.csv");
176 const lines = (await res.text()).split("\r\n").filter((l) => l !== "");
177 const w = readWallet(app, bob, repo);
178 if (!w.ok) throw new Error("refused");
179 expect(lines).toHaveLength(21);
180 expect(lines[0]).toBe("date_utc,dollars,paid_for,outcome,run");
181 expect(lines.slice(1)).toEqual(walletCsv(w.value.spends).split("\r\n").filter((l) => l !== "").slice(1));
182 expect(lines[1]).toBe(`2026-10-07,1.5,build #1 Fix <b>the</b> login,ok,/bob/wallet-app/runs/${issueRun}`);
183 const page = await (await fetch(`${servers.url}/bob/wallet-app/wallet`, { headers: { cookie: await cookieOf("bob") } })).text();
184 expect(page).toContain("/bob/wallet-app/wallet.csv");
185 const evil = { ...w.value.spends[0]!, paidFor: "=HYPERLINK(1)" };
186 expect(walletCsv([evil]).split("\r\n")[1]).toContain(",'=HYPERLINK(1),");
187 for (const headers of [{}, { cookie: await cookieOf("carol") }]) {
188 const no = await fetch(`${servers.url}/bob/wallet-app/wallet.csv`, { headers, redirect: "manual" });
189 expect(no.status).toBe(404);
190 expect(await no.text()).not.toContain("1.5");
191 }
192 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs