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

The agent downloads every open deal's dates as one spreadsheet file, for the brokerage's compliance sheet or their own records #101

Merged opened this

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

Merged

mason/deal-clock:mason/90-the-agent-downloads-every-open-deal-s-da → main 2 commits fork

  • Merged. mason/90-the-agent-downloads-every-open-deal-s-da was merged into main as f80f96c.

Review

Sign in to review this change.
10 files changed +232 −7
README.md +1 −1
@@ -141,7 +141,7 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
141141 You get a calendar file with every date of the deal and two
142142 alarms for each: one as many days ahead as that date's Reminds N days
143143 before setting, and one the morning of. Open it in your own calendar app. On the clock,
144 Add all to calendar does the same for every open date of every open deal.
144 Add all to calendar does the same for every open date of every open deal. Download spreadsheet gives the same dates as one file that opens in Excel or Numbers; the Closed list links one with the closed deals too.
145145 13. **Print the client timeline.** On a sample deal's page, tap Client
146146 timeline: its dates in order, who owes each and whether it is done,
147147 upcoming or overdue, with no controls. Tap Print to make the one-page handout
contract/openapi.json +44
@@ -466,6 +466,50 @@
466466 }
467467 }
468468 },
469 "/api/deals.csv": {
470 "get": {
471 "summary": "Every date of every open deal as a spreadsheet (CSV): address, buyer, seller, date, due, done, owed_by, party, moved. closed=1 adds the closed deals.",
472 "operationId": "getApiDealsCsv",
473 "parameters": [
474 {
475 "name": "closed",
476 "in": "query",
477 "schema": {
478 "enum": [
479 "1"
480 ]
481 }
482 }
483 ],
484 "responses": {
485 "200": {
486 "description": "Every date of every open deal as a spreadsheet (CSV): address, buyer, seller, date, due, done, owed_by, party, moved. closed=1 adds the closed deals.",
487 "content": {
488 "text/csv": {
489 "schema": {
490 "type": "string"
491 }
492 }
493 }
494 },
495 "default": {
496 "description": "{ error, message }: why not",
497 "content": {
498 "application/json": {
499 "schema": {
500 "$ref": "#/components/schemas/Error"
501 }
502 }
503 }
504 }
505 },
506 "x-contract": {
507 "resource": "deal",
508 "verb": "list",
509 "least": "user"
510 }
511 }
512 },
469513 "/api/people": {
470514 "get": {
471515 "summary": "Each person on your deals once (parties with the same contact are one), with their roles and every open date they owe across deals, soonest first; people who owe nothing open come last.",
docs/TECHNICAL.md +4 −1
@@ -122,9 +122,11 @@ A deal is **closed** when its Closing date is marked done (derived, no column; `
122122
123123 **One clock per house.** `planFor` (`src/deals.ts`) refuses to open a deal at an address that already has an open one of the same author, comparing after trimming, collapsing spaces, ignoring case and a trailing period (`sameAddress`). A closed deal (see above) does not count, and the sample deals are another author's. The refusal is a `conflict` Result naming the deal (`existing`): the API and MCP answer 409 `{error: "conflict", message, existing_id}`; the New deal form re-renders with a link to that deal, everything typed kept, and an "Open a second deal anyway" checkbox (`open_anyway`); the terminal asks `yes` to go on. Send `openAnyway: true` (API/MCP: `open_anyway`) to open the second deal. The date preview shows the same notice. `insertDeal` is unguarded, so Restore the sample deals is unaffected. No new contract cell.
124124
125 **The spreadsheet.** `GET /deals/csv` and `GET /api/deals.csv` answer `text/csv` with `Content-Disposition: attachment; filename="deal-clock-YYYY-MM-DD.csv"`: one row per date of every open deal the person may read (the `deal` list cell, like the clock); `?closed=1` adds closed deals. A signed-out visitor gets the sign-in page (401), the API a JSON 401. Columns, in order: `address`, `buyer`, `seller` (party names, empty if none), `date` (label), `due` (YYYY-MM-DD), `done` (the day it was marked done, empty while open), `owed_by` (role label), `party` (that role's name, empty if none), `moved` (`yes` if the date was ever moved, else `no`). Cells with a comma, quote or line break are quoted; a cell starting with `=`, `+`, `-`, `@`, tab or carriage return is prefixed with `'` so it is never a formula (`src/csv.ts`). Lines end CRLF.
126
125127 `POST /tick` answers the reminders that go out today and are not yet
126128 marked sent, as JSON — call it each morning as a signed-in account (a
127 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. The JSON API is
129 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. `GET /deals/csv` (and `GET /api/deals.csv`, in openapi) is the spreadsheet, below. The JSON API is
128130 `/api/deals`, described at `/openapi.json`; the same operations are MCP
129131 tools at `POST /mcp` (`list_deals`, `get_deal`, `client_timeline`, `reminders_today`, `this_week`, `list_people`,
130132 `open_deal`, `add_date`, `update_address`, `add_party`, `edit_party`, `remove_party`,
@@ -183,6 +185,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
183185 | `src/deals.ts` | deals: open, read, move a date, set its reminder lead, mark done, parties, reminders sent |
184186 | `src/dates.ts`, `src/deadlines.ts` | calendar math; the standard contract dates and who owes them |
185187 | `src/reminders.ts`, `src/ics.ts` | reminder drafts and `/tick`; the calendar file |
188 | `src/csv.ts` | the spreadsheet file: rows shaped to CSV, formula guard |
186189 | `src/outbox.ts` | a sent reminder's mailto:/sms: link |
187190 | `src/sample.ts` | the four sample deals a new database starts with |
188191 | `src/result.ts` | what an action answers, and the audit habit they share |
src/contract.test.ts +18
@@ -22,6 +22,7 @@ import {
2222 import { actingAs, identities, table, type Verb } from "./can.ts";
2323 import { contract, permit } from "./contract.ts";
2424 import { openDb } from "./db.ts";
25 import { routes } from "./routes.ts";
2526 import { getProfile, setProfile, useDefaults } from "./profile.ts";
2627 import type { Who } from "./who.ts";
2728
@@ -177,3 +178,20 @@ test("the status update, at GET /api/deals/:id/status, its send and the two MCP
177178 expect(statusUpdates(db, { role: "anon" }, { dealId: dealBy("u1") }).ok).toBe(false);
178179 expect(sendStatusUpdate(db, { role: "anon" }, { dealId: dealBy("u1"), partyId: 1 }).ok).toBe(false);
179180 });
181
182 test("the spreadsheet, at GET /deals/csv and GET /api/deals.csv, answers as deal list says, as every identity", async () => {
183 for (const path of ["/deals/csv", "/api/deals.csv"]) {
184 const route = routes.find((r) => r.method === "GET" && r.path === path)!;
185 for (const identity of identities(contract)) {
186 const who = whoIs(identity);
187 const said = `${path} as ${identity}`;
188 const url = new URL(`http://app.test${path}`);
189 const res = await route.handle({ request: new Request(url), url, db, who, params: {} });
190 expect([said, res.status === 200]).toEqual([said, permit(who, "deal", "list") !== "no"]);
191 if (res.status === 200) expect(res.headers.get("content-type")).toContain("text/csv");
192 }
193 const url = new URL(`http://app.test${path}`);
194 const anon = await route.handle({ request: new Request(url), url, db, who: { role: "anon" }, params: {} });
195 expect(anon.status).toBe(401);
196 }
197 });
src/csv.test.ts added +44
@@ -0,0 +1,44 @@
1 import { expect, test } from "bun:test";
2 import { cell, COLUMNS, sheet } from "./csv.ts";
3 import type { DealView } from "./deals.ts";
4
5 const deal = (over: Partial<DealView> = {}): DealView =>
6 ({
7 id: 1,
8 address: '12 Elm St, Unit "4"',
9 closed: false,
10 parties: [
11 { id: 1, deal_id: 1, role: "buyer", name: "=HYPERLINK(\"x\")", contact: "" },
12 { id: 2, deal_id: 1, role: "seller", name: "Ruth", contact: "" },
13 { id: 3, deal_id: 1, role: "lender", name: "+Bank", contact: "" },
14 ],
15 deadlines: [
16 { id: 1, kind: "inspection", label: "Inspection", due: "2026-11-10", owes: "buyer", done_at: null, moves: [] },
17 { id: 2, kind: "financing", label: "Loan", due: "2026-11-20", owes: "lender", done_at: "2026-11-02T15:00:00Z", moves: [{}] },
18 ],
19 ...over,
20 }) as unknown as DealView;
21
22 test("header row, then one row per date", () => {
23 const lines = sheet([deal()]).split("\r\n");
24 expect(lines[0]).toBe(COLUMNS.join(","));
25 expect(lines[0]).toBe("address,buyer,seller,date,due,done,owed_by,party,moved");
26 expect(lines[1]).toBe(
27 `"12 Elm St, Unit ""4""","'=HYPERLINK(""x"")",Ruth,Inspection,2026-11-10,,Buyer,"'=HYPERLINK(""x"")",no`,
28 );
29 expect(lines[2]).toContain(",2026-11-20,2026-11-02,Lender,'+Bank,yes");
30 expect(lines).toHaveLength(4);
31 });
32
33 test("commas, quotes and newlines are quoted", () => {
34 expect(cell("a,b")).toBe('"a,b"');
35 expect(cell('say "hi"')).toBe('"say ""hi"""');
36 expect(cell("one\ntwo")).toBe('"one\ntwo"');
37 expect(cell("plain")).toBe("plain");
38 });
39
40 test("a cell a spreadsheet would run as a formula is defused", () => {
41 for (const c of ["=1+1", "+1", "-1", "@SUM(A1)", "\tx", "\rx"]) expect(cell(c).replace(/^"/, "").startsWith("'")).toBe(true);
42 expect(cell("=1,2")).toBe(`"'=1,2"`);
43 expect(cell("a=b")).toBe("a=b");
44 });
src/csv.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * The book as a spreadsheet file (RFC 4180): one row per date of every deal
3 * given. Every cell is quoted when it needs it, and a cell a spreadsheet
4 * would read as a formula is prefixed with `'`. Pure text out.
5 */
6
7 import { today } from "./dates.ts";
8 import { PARTY_LABEL } from "./deadlines.ts";
9 import type { DealView } from "./deals.ts";
10
11 export const COLUMNS = ["address", "buyer", "seller", "date", "due", "done", "owed_by", "party", "moved"] as const;
12
13 /** A cell starting with one of these is a formula to Excel and Numbers. */
14 const FORMULA = /^[=+\-@\t\r]/;
15
16 /** One cell: formula-guarded, then quoted when it holds a comma, quote or line break. */
17 export function cell(value: string): string {
18 const safe = FORMULA.test(value) ? `'${value}` : value;
19 return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
20 }
21
22 const nameOf = (deal: DealView, role: string): string => deal.parties.find((p) => p.role === role)?.name ?? "";
23
24 /** The rows of the given deals, header first, in the order given; lines end CRLF. */
25 export function sheet(deals: readonly DealView[]): string {
26 const rows: string[][] = [[...COLUMNS]];
27 for (const deal of deals)
28 for (const d of deal.deadlines)
29 rows.push([
30 deal.address,
31 nameOf(deal, "buyer"),
32 nameOf(deal, "seller"),
33 d.label,
34 d.due,
35 d.done_at === null ? "" : today(new Date(d.done_at)),
36 PARTY_LABEL[d.owes],
37 nameOf(deal, d.owes),
38 d.moves.length > 0 ? "yes" : "no",
39 ]);
40 return `${rows.map((r) => r.map(cell).join(",")).join("\r\n")}\r\n`;
41 }
src/openapi.ts +4 −4
@@ -34,15 +34,15 @@ const named = (schema: Schema): Schema => {
3434 ]),
3535 );
3636 };
37 const content = (schema: Schema) => ({
38 "application/json": { schema: named(schema) },
37 const content = (schema: Schema, mime = "application/json") => ({
38 [mime]: { schema: named(schema) },
3939 });
4040
4141 export function openapi(): Record<string, unknown> {
4242 const paths: Record<string, Record<string, unknown>> = {};
4343 for (const route of routes) {
4444 if (route.api === undefined) continue;
45 const { summary, body, answer, status, query, cell, conflict } = route.api;
45 const { summary, body, answer, status, query, cell, conflict, mime } = route.api;
4646 const path = route.path.replace(/:(\w+)/g, "{$1}");
4747 const params = [...route.path.matchAll(/:(\w+)/g)].map(([, name]) => ({
4848 name,
@@ -77,7 +77,7 @@ export function openapi(): Record<string, unknown> {
7777 responses: {
7878 [String(status ?? 200)]: {
7979 description: summary,
80 content: content(answer),
80 content: content(answer, mime),
8181 },
8282 ...(conflict === undefined
8383 ? {}
src/pages/clock.ts +2 −1
@@ -206,6 +206,7 @@ function render(input: {
206206 ? ""
207207 : `<section id="closed" class="card" data-live="deal.changed">
208208 <h2>Closed <span class="muted">· ${closed.length}</span></h2>
209 ${who.role === "anon" ? "" : `<p class="small"><a href="/deals/csv?closed=1" download>Download spreadsheet with closed deals</a></p>`}
209210 <ul class="closed">${closed.map((deal) => `<li><a href="/deals/${deal.id}">${escape(deal.address)}</a> <span class="muted">closed ${escape(spoken(deal.closing))}</span></li>`).join("")}</ul>
210211 </section>`;
211212 const restoreCard =
@@ -225,7 +226,7 @@ function render(input: {
225226 <h1>The clock</h1>
226227 <p class="summary"><span>${escape(spoken(on))}</span> · <span>${deals.length} ${deals.length === 1 ? "deal" : "deals"}</span>${overdue > 0 ? ` · <b class="u-overdue">${overdue} overdue</b>` : ""}${soon > 0 ? ` · <b class="u-soon">${soon} due within 3 days</b>` : ""}</p>
227228 </div>
228 ${who.role === "anon" ? "" : `<span class="actions"><a class="button button-quiet" href="/deals/ics">Add all to calendar</a> <a class="button" href="/deals/new">New deal</a></span>`}
229 ${who.role === "anon" ? "" : `<span class="actions"><a class="button button-quiet" href="/deals/ics">Add all to calendar</a> <a class="button button-quiet" href="/deals/csv" download>Download spreadsheet</a> <a class="button" href="/deals/new">New deal</a></span>`}
229230 </section>
230231 <form class="find" method="get" action="/" role="search">
231232 <label for="find-q">Find a deal</label>
src/routes.ts +45
@@ -71,6 +71,7 @@ import {
7171 updateDeal,
7272 type NewDeal,
7373 } from "./deals.ts";
74 import { sheet } from "./csv.ts";
7475 import { book, calendar } from "./ics.ts";
7576 import { agentOf, getProfile, setProfile, useDefaults, type Profile } from "./profile.ts";
7677 import { profilePage } from "./pages/profile.ts";
@@ -112,6 +113,8 @@ export interface Api {
112113 /** What it answers when it succeeds, and with which status (200). */
113114 readonly answer: Schema;
114115 readonly status?: number;
116 /** The media type it answers in, when not JSON. */
117 readonly mime?: string;
115118 /** The query parameters it reads. */
116119 readonly query?: Readonly<Record<string, Schema>>;
117120 /** Also answers 409 with this shape when what it makes is already there. */
@@ -120,6 +123,24 @@ export interface Api {
120123 readonly cell?: { readonly resource: string; readonly verb: Verb };
121124 }
122125
126 /** The spreadsheet of the deals this person may read; closed ones only when asked. */
127 function spreadsheet(c: Context): Result<Response> {
128 const deals = listDeals(c.db, c.who);
129 if (!deals.ok) return deals;
130 const withClosed = c.url.searchParams.get("closed") === "1";
131 return {
132 ok: true,
133 value: new Response(sheet(deals.value.filter((deal) => withClosed || !deal.closed)), {
134 headers: {
135 "content-type": "text/csv; charset=utf-8",
136 "content-disposition": `attachment; filename="deal-clock-${today()}.csv"`,
137 "cache-control": "no-store",
138 ...SECURITY,
139 },
140 }),
141 };
142 }
143
123144 export interface Route {
124145 readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
125146 readonly path: string;
@@ -599,6 +620,15 @@ export const routes: readonly Route[] = [
599620 });
600621 },
601622 },
623 {
624 method: "GET",
625 path: "/deals/csv",
626 handle: (c) => {
627 const got = spreadsheet(c);
628 if (got.ok) return got.value;
629 return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/deals/csv", heading: "Spreadsheet", error: got.error, message: got.message }), STATUS[got.error]);
630 },
631 },
602632 {
603633 method: "GET",
604634 path: "/deals/new",
@@ -1040,6 +1070,21 @@ export const routes: readonly Route[] = [
10401070 query: { q: { type: "string", maxLength: 100 } },
10411071 },
10421072 },
1073 {
1074 method: "GET",
1075 path: "/api/deals.csv",
1076 handle: (c) => {
1077 const got = spreadsheet(c);
1078 return got.ok ? got.value : answer(got);
1079 },
1080 api: {
1081 summary: "Every date of every open deal as a spreadsheet (CSV): address, buyer, seller, date, due, done, owed_by, party, moved. closed=1 adds the closed deals.",
1082 answer: { type: "string" },
1083 mime: "text/csv",
1084 query: { closed: { enum: ["1"] } },
1085 cell: { resource: "deal", verb: "list" },
1086 },
1087 },
10431088 {
10441089 method: "GET",
10451090 path: "/api/people",
src/server.test.ts +29
@@ -1028,6 +1028,11 @@ test("a deal whose Closing is marked done leaves the lanes for the Closed card,
10281028 expect(page).toContain("Inspection period ends");
10291029 const listed = (await (await api("/api/deals", {}, closer)).json()) as { id: number; closed: boolean }[];
10301030 expect(listed.find((d) => d.id === deal.id)!.closed).toBe(true);
1031 expect(await (await api("/deals/csv", {}, closer)).text()).not.toContain("77 Closing Court");
1032 expect(await (await api("/deals/csv?closed=1", {}, closer)).text()).toContain("77 Closing Court");
1033 expect(await (await api("/api/deals.csv", {}, closer)).text()).not.toContain("77 Closing Court");
1034 expect(await (await api("/api/deals.csv?closed=1", {}, closer)).text()).toContain("77 Closing Court");
1035 expect(clock).toContain('href="/deals/csv?closed=1"');
10311036 expect(await tickIds()).not.toContain(deal.id);
10321037 expect((await post("0")).status).toBe(303);
10331038 const back = await (await api("/", {}, closer)).text();
@@ -1281,3 +1286,27 @@ test("an unknown path is the product's 404 page for people and JSON for API clie
12811286 expect(asked.status).toBe(404);
12821287 expect(await asked.json()).toEqual({ error: "not_found" });
12831288 });
1289
1290 test("the spreadsheet: the open deals' dates as CSV, closed ones only on ask, signed-in only", async () => {
1291 const guest = await fetch(`${base}/deals/csv`);
1292 expect(guest.status).toBe(401);
1293 expect(await guest.text()).toContain("/__forge/signin?to=%2Fdeals%2Fcsv");
1294 expect((await fetch(`${base}/api/deals.csv`)).status).toBe(401);
1295
1296 const file = await api("/deals/csv", {}, alice);
1297 expect(file.status).toBe(200);
1298 expect(file.headers.get("content-type")).toContain("text/csv");
1299 expect(file.headers.get("content-disposition")).toBe(`attachment; filename="deal-clock-${today()}.csv"`);
1300 expect(file.headers.get("x-content-type-options")).toBe("nosniff");
1301 const body = await file.text();
1302 expect(body.startsWith("address,buyer,seller,date,due,done,owed_by,party,moved\r\n")).toBe(true);
1303 const same = await (await api("/api/deals.csv", {}, alice)).text();
1304 expect(same).toBe(body);
1305
1306 const deals = (await (await api("/api/deals", {}, alice)).json()) as { address: string; closed: boolean; deadlines: unknown[] }[];
1307 const open = deals.filter((d) => !d.closed);
1308 expect(body.trim().split("\r\n").length - 1).toBe(open.reduce((n, d) => n + d.deadlines.length, 0));
1309
1310 const clock = await (await api("/", {}, alice)).text();
1311 expect(clock).toContain('href="/deals/csv"');
1312 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs