Public: anyone can read this; the crew can change it.
The agent downloads all their deals as one file (dates, parties, notes, moves and every approved message) from the Profile page, so leaving the app never means losing a deal #172
Check · Review · Land · Live done — Landed and live in production.
mason/deal-clock:mason/164-the-agent-downloads-all-their-deals-as-o → main 2 commits fork 2 threads · 2 unresolved
11 files
changed +402
−5
README.md +5
| @@ -142,6 +142,11 @@ anytime, I answer within the hour"). Whoever runs the app can set your usual | ||
| 142 | 142 | contract lengths once; see the technical page. On your phone, choose Add to |
| 143 | 143 | Home Screen: the deal-clock mark sits beside the name and it opens full screen. |
| 144 | 144 | |
| 145 | **Keep your deals.** On the Profile, **Download all my deals** saves one file | |
| 146 | with every deal you can read: addresses, figures, dates, parties, notes, every | |
| 147 | move with its reason, closed and fell-through deals, and the exact words of | |
| 148 | every message you sent. In the terminal, press `E` to save the same file. If you ever stop using the app, you keep them. | |
| 149 | ||
| 145 | 150 | **Put the samples back.** After the tour, an admin taps **Sample deals** below |
| 146 | 151 | the clock, then **Restore the sample deals** and confirms: the seven samples |
| 147 | 152 | return as they were, dated from today, and the deals you opened are left alone. |
contract/openapi.json +51
| @@ -758,6 +758,57 @@ | ||
| 758 | 758 | } |
| 759 | 759 | } |
| 760 | 760 | }, |
| 761 | "/api/deals/export": { | |
| 762 | "get": { | |
| 763 | "summary": "All the deals you may read as one JSON file: version, exported_at, and per deal its address, side, figures, closing time and place, state (open, closed or fell_through with reason), parties with phone and email, each date with due, done, waived, owed_by, note and moves, and the sent messages with the exact approved words. Never the audit log.", | |
| 764 | "operationId": "getApiDealsExport", | |
| 765 | "responses": { | |
| 766 | "200": { | |
| 767 | "description": "All the deals you may read as one JSON file: version, exported_at, and per deal its address, side, figures, closing time and place, state (open, closed or fell_through with reason), parties with phone and email, each date with due, done, waived, owed_by, note and moves, and the sent messages with the exact approved words. Never the audit log.", | |
| 768 | "content": { | |
| 769 | "application/json": { | |
| 770 | "schema": { | |
| 771 | "type": "object", | |
| 772 | "properties": { | |
| 773 | "version": { | |
| 774 | "type": "integer" | |
| 775 | }, | |
| 776 | "exported_at": { | |
| 777 | "type": "string", | |
| 778 | "format": "date-time" | |
| 779 | }, | |
| 780 | "truncated": { | |
| 781 | "type": "boolean" | |
| 782 | }, | |
| 783 | "deals": { | |
| 784 | "type": "array", | |
| 785 | "items": { | |
| 786 | "type": "object" | |
| 787 | } | |
| 788 | } | |
| 789 | } | |
| 790 | } | |
| 791 | } | |
| 792 | } | |
| 793 | }, | |
| 794 | "default": { | |
| 795 | "description": "{ error, message }: why not", | |
| 796 | "content": { | |
| 797 | "application/json": { | |
| 798 | "schema": { | |
| 799 | "$ref": "#/components/schemas/Error" | |
| 800 | } | |
| 801 | } | |
| 802 | } | |
| 803 | } | |
| 804 | }, | |
| 805 | "x-contract": { | |
| 806 | "resource": "deal", | |
| 807 | "verb": "read", | |
| 808 | "least": "user" | |
| 809 | } | |
| 810 | } | |
| 811 | }, | |
| 761 | 812 | "/api/deals/{id}": { |
| 762 | 813 | "get": { |
| 763 | 814 | "summary": "One deal, with its progress: dates done, total, overdue and days to closing.", |
docs/TECHNICAL.md +3
| @@ -167,6 +167,8 @@ A deal is **closed** when its Closing date is marked done (derived, no column; ` | ||
| 167 | 167 | |
| 168 | 168 | **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. |
| 169 | 169 | |
| 170 | **The export.** `GET /deals/export.json` (Profile's "Download all my deals") and `GET /api/deals/export`, the MCP tool `export_deals` and `E` in the terminal (which writes the same file under `FORGE_APP_DATA/exports/`), answer every deal the person may read (the `deal` list cell; a stranger gets 401), built from `listDeals` so contacts are blanked exactly as the deal page blanks them. The audit log is never in it. The file is `application/json` with `Content-Disposition: attachment; filename="deal-clock-YYYY-MM-DD.json"`, `Cache-Control: no-store` and the security headers. Shape (`src/export.ts`): `{ version: 1, exported_at, truncated, deals: [...] }`, at most 2000 deals (`truncated` is true past that). Each deal: `id, address, side, contract_date, closing, closing_time, closing_place, business_days, sale_price, earnest_amount, commission_rate, opened_by, created_at, state` (`open`, `closed` or `fell_through`), `reason` (null unless fell through, which also has `fell_at` and `by`), `parties[]` (`role, name, phone, email`), `dates[]` (`label, kind, due, done, waived, waived_by, owed_by, note, moves[]` of `from, to, reason, by, at`) and `messages[]` (`date, to, to_role, moment, due, by, sent_at, subject, body`: the words as approved). | |
| 171 | ||
| 170 | 172 | **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. |
| 171 | 173 | |
| 172 | 174 | `POST /tick` answers the reminders that go out today and are not yet |
| @@ -230,6 +232,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it. | ||
| 230 | 232 | | `src/deals.ts` | deals: open, read, move a date, set its reminder lead, mark done, parties, reminders sent | |
| 231 | 233 | | `src/dates.ts`, `src/deadlines.ts` | calendar math; the standard contract dates and who owes them | |
| 232 | 234 | | `src/reminders.ts`, `src/ics.ts` | reminder drafts and `/tick`; the calendar file | |
| 235 | | `src/export.ts` | the all-my-deals JSON file: deal views shaped to plain data | | |
| 233 | 236 | | `src/csv.ts` | the spreadsheet file: rows shaped to CSV, formula guard | |
| 234 | 237 | | `src/outbox.ts` | a sent reminder's mailto:/sms: link | |
| 235 | 238 | | `src/sample.ts` | the seven sample deals a new database starts with | |
src/export.test.ts added +183
| @@ -0,0 +1,183 @@ | ||
| 1 | /** The export: every field the issue lists, nothing of the audit, refused to strangers, fast with 200 deals. */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { existsSync, mkdtempSync, readFileSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { record } from "./audit.ts"; | |
| 7 | import { openDb } from "./db.ts"; | |
| 8 | import { getDeal, insertDeal, listDeals, markFellThrough, moveDeadline, plan, sendReminder, setNote, type NewDeal } from "./deals.ts"; | |
| 9 | import { EXPORT_MAX, exportDeals } from "./export.ts"; | |
| 10 | import { forgetRationing } from "./security.ts"; | |
| 11 | import { serve } from "./server.ts"; | |
| 12 | import { terminal } from "./terminal.ts"; | |
| 13 | import { sign, type Who } from "./who.ts"; | |
| 14 | ||
| 15 | interface Filed { | |
| 16 | id: number; | |
| 17 | state: string; | |
| 18 | reason: string | null; | |
| 19 | address: string; | |
| 20 | parties: { role: string; name: string; phone: string; email: string }[]; | |
| 21 | dates: { kind: string; note: string; moves: { to: string; reason: string; by: string }[] }[]; | |
| 22 | messages: { to: string; subject: string; body: string; by: string }[]; | |
| 23 | } | |
| 24 | interface File { | |
| 25 | version: number; | |
| 26 | exported_at: string; | |
| 27 | truncated: boolean; | |
| 28 | deals: Filed[]; | |
| 29 | } | |
| 30 | ||
| 31 | const KEY = "a-key-only-the-forge-holds"; | |
| 32 | const dir = mkdtempSync(join(tmpdir(), "app-export-")); | |
| 33 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 34 | const bob: Who = { role: "user", id: "u2", name: "bob" }; | |
| 35 | const AUDIT_WORDS = "zebra-secret-audit-words"; | |
| 36 | ||
| 37 | let dealId = 0; | |
| 38 | let fellId = 0; | |
| 39 | let server: ReturnType<typeof serve>; | |
| 40 | let base = ""; | |
| 41 | let headers: Record<string, string> = {}; | |
| 42 | ||
| 43 | const open = (db: ReturnType<typeof openDb>, who: Who, input: NewDeal): number => { | |
| 44 | const planned = plan(input); | |
| 45 | if (!planned.ok) throw new Error(planned.message); | |
| 46 | return insertDeal(db, { id: "id" in who ? who.id : "", name: "name" in who ? who.name : "" }, planned.value).id; | |
| 47 | }; | |
| 48 | const must = <T>(r: { ok: true; value: T } | { ok: false; message: string }): T => { | |
| 49 | if (!r.ok) throw new Error(r.message); | |
| 50 | return r.value; | |
| 51 | }; | |
| 52 | const listed = (db: ReturnType<typeof openDb>, who: Who) => must(listDeals(db, who)); | |
| 53 | ||
| 54 | beforeAll(() => { | |
| 55 | const db = openDb(dir); | |
| 56 | const input = (address: string, closingDate = "2026-11-25") => ({ address, buyer: "Bea Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate }); | |
| 57 | dealId = open(db, alice, input("9 Export Way", "2026-11-20")); | |
| 58 | fellId = open(db, alice, input("3 Fell Court")); | |
| 59 | for (let i = 0; i < 200; i++) open(db, alice, input(`${100 + i} Bulk Lane`)); | |
| 60 | open(db, bob, input("77 Bob's Own Road")); | |
| 61 | db.query("UPDATE party SET phone = '555 0100', email = '[email protected]' WHERE deal_id = ?1 AND role = 'buyer'").run(dealId); | |
| 62 | const first = must(getDeal(db, alice, { id: dealId })); | |
| 63 | const insp = first.deadlines.find((d) => d.kind === "inspection")!; | |
| 64 | must(setNote(db, alice, { dealId, id: insp.id, note: "Call the inspector" })); | |
| 65 | must(moveDeadline(db, alice, { dealId, id: insp.id, due: "2026-10-20", reason: "Seller asked" })); | |
| 66 | must(markFellThrough(db, alice, { id: fellId, fell: true, reason: "Financing fell apart" })); | |
| 67 | const buyer = first.parties.find((p) => p.role === "buyer")!; | |
| 68 | must(sendReminder(db, alice, { deadlineId: insp.id, partyId: buyer.id, moment: "before", subject: "Inspection soon", body: "Hi Bea, the inspection is near." })); | |
| 69 | record(db, { who: alice, resource: "deal", verb: "update", outcome: "ok", what: AUDIT_WORDS }); | |
| 70 | db.close(); | |
| 71 | server = serve({ port: 0, dataDir: dir, identityKey: KEY }); | |
| 72 | base = `http://${server.hostname}:${server.port}`; | |
| 73 | const identity = `u1|alice|user|${Date.now() + 600_000}`; | |
| 74 | headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 75 | }); | |
| 76 | afterAll(() => server.stop(true)); | |
| 77 | ||
| 78 | test("the file holds every field, with moves, notes, state, parties and messages", () => { | |
| 79 | const db = openDb(dir); | |
| 80 | const file = JSON.parse(JSON.stringify(exportDeals(listed(db, alice), new Date("2026-11-08T10:00:00Z")))) as File; | |
| 81 | db.close(); | |
| 82 | expect(file.version).toBe(1); | |
| 83 | expect(file.exported_at).toBe("2026-11-08T10:00:00.000Z"); | |
| 84 | const mine = file.deals.find((d) => d.id === dealId)!; | |
| 85 | expect(mine.address).toBe("9 Export Way"); | |
| 86 | expect(mine.state).toBe("open"); | |
| 87 | expect(mine.parties.find((p) => p.role === "buyer")).toEqual({ role: "buyer", name: "Bea Buyer", phone: "555 0100", email: "[email protected]" }); | |
| 88 | const date = mine.dates.find((d) => d.kind === "inspection")!; | |
| 89 | expect(date.note).toBe("Call the inspector"); | |
| 90 | expect(date.moves[0]).toMatchObject({ to: "2026-10-20", reason: "Seller asked", by: "alice" }); | |
| 91 | for (const key of ["due", "done", "waived", "owed_by"]) expect(key in date).toBe(true); | |
| 92 | for (const key of ["side", "closing_time", "closing_place", "sale_price"]) expect(key in mine).toBe(true); | |
| 93 | expect(mine.messages[0]).toMatchObject({ to: "Bea Buyer", subject: "Inspection soon", body: "Hi Bea, the inspection is near.", by: "alice" }); | |
| 94 | const lost = file.deals.find((d) => d.id === fellId)!; | |
| 95 | expect(lost.state).toBe("fell_through"); | |
| 96 | expect(lost.reason).toBe("Financing fell apart"); | |
| 97 | }); | |
| 98 | ||
| 99 | test("another user gets exactly what listDeals gives them, and no audit content", async () => { | |
| 100 | const db = openDb(dir); | |
| 101 | const expected = listed(db, bob).map((d) => d.id); | |
| 102 | db.close(); | |
| 103 | const identity = `u2|bob|user|${Date.now() + 600_000}`; | |
| 104 | const theirs = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 105 | forgetRationing(); | |
| 106 | const text = await (await fetch(`${base}/api/deals/export`, { headers: theirs })).text(); | |
| 107 | expect((JSON.parse(text) as File).deals.map((d) => d.id)).toEqual(expected); | |
| 108 | expect(text).not.toContain(AUDIT_WORDS); | |
| 109 | expect(text).not.toContain("who_name"); | |
| 110 | const auditText = await (await fetch(`${base}/deals/export.json`, { headers })).text(); | |
| 111 | expect(auditText).not.toContain(AUDIT_WORDS); | |
| 112 | }); | |
| 113 | ||
| 114 | test("the export holds only the deals it is given, so a narrowed list narrows the file", () => { | |
| 115 | const db = openDb(dir); | |
| 116 | const all = listed(db, alice); | |
| 117 | db.close(); | |
| 118 | const bobs = all.filter((d) => d.author_id === bob.id); | |
| 119 | expect(bobs.length).toBe(1); | |
| 120 | const file = exportDeals(all.filter((d) => d.author_id !== bob.id), new Date()) as unknown as File; | |
| 121 | expect(file.deals.some((d) => d.address === "77 Bob's Own Road")).toBe(false); | |
| 122 | }); | |
| 123 | ||
| 124 | test("the cap bounds the file", () => { | |
| 125 | const db = openDb(dir); | |
| 126 | const first = listed(db, alice)[0]!; | |
| 127 | db.close(); | |
| 128 | const file = exportDeals(Array.from({ length: EXPORT_MAX + 1 }, () => first), new Date()); | |
| 129 | expect(file.deals).toHaveLength(EXPORT_MAX); | |
| 130 | expect(file.truncated).toBe(true); | |
| 131 | }); | |
| 132 | ||
| 133 | test("the page and the API download it with the headers; 200+ deals in under 200 ms", async () => { | |
| 134 | forgetRationing(); | |
| 135 | for (const path of ["/deals/export.json", "/api/deals/export"]) { | |
| 136 | const t = performance.now(); | |
| 137 | const res = await fetch(base + path, { headers }); | |
| 138 | const body = (await res.json()) as File; | |
| 139 | expect(performance.now() - t).toBeLessThan(200); | |
| 140 | expect(res.status).toBe(200); | |
| 141 | expect(res.headers.get("content-type")).toContain("application/json"); | |
| 142 | expect(res.headers.get("content-disposition")).toMatch(/^attachment; filename="deal-clock-\d{4}-\d\d-\d\d\.json"$/); | |
| 143 | expect(res.headers.get("cache-control")).toBe("no-store"); | |
| 144 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 145 | expect(body.deals.length).toBeGreaterThan(200); | |
| 146 | } | |
| 147 | expect(await (await fetch(`${base}/profile`, { headers })).text()).toContain('href="/deals/export.json"'); | |
| 148 | }); | |
| 149 | ||
| 150 | test("a stranger is refused exactly like the clock", async () => { | |
| 151 | forgetRationing(); | |
| 152 | const clock = await fetch(`${base}/deals/csv`); | |
| 153 | const gone = await fetch(`${base}/deals/export.json`); | |
| 154 | expect(gone.status).toBe(clock.status); | |
| 155 | expect(gone.status).toBe(401); | |
| 156 | expect(await gone.text()).toContain("Sign in"); | |
| 157 | expect((await fetch(`${base}/api/deals/export`)).status).toBe(401); | |
| 158 | }); | |
| 159 | ||
| 160 | test("MCP's export_deals gives the same file", async () => { | |
| 161 | const res = await fetch(`${base}/mcp`, { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "export_deals", arguments: {} } }) }); | |
| 162 | expect(await res.text()).toContain("exported_at"); | |
| 163 | }); | |
| 164 | ||
| 165 | test("E in the terminal writes the same file, and refuses a guest", () => { | |
| 166 | const db = openDb(dir); | |
| 167 | const out = join(mkdtempSync(join(tmpdir(), "app-export-out-")), "exports"); | |
| 168 | const context = { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" }, exportDir: out }; | |
| 169 | const t = terminal(db, alice, context); | |
| 170 | t.press("E"); | |
| 171 | const files = new Bun.Glob("*.json").scanSync(out); | |
| 172 | const name = [...files][0]!; | |
| 173 | expect(name).toMatch(/^deal-clock-\d{4}-\d\d-\d\d\.json$/); | |
| 174 | const written = JSON.parse(readFileSync(join(out, name), "utf8")) as File; | |
| 175 | expect(written.deals.map((d) => d.id)).toEqual(listed(db, alice).map((d) => d.id)); | |
| 176 | expect(t.screen().join("\n")).toContain("Wrote"); | |
| 177 | const guestOut = join(out, "guest"); | |
| 178 | const guest = terminal(db, { role: "anon" }, { ...context, exportDir: guestOut }); | |
| 179 | guest.press("E"); | |
| 180 | expect(guest.screen().join("\n")).toContain("Sign in"); | |
| 181 | expect(existsSync(guestOut)).toBe(false); | |
| 182 | db.close(); | |
| 183 | }); |
src/export.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
No terminal door: add the export command in src/tty.ts using exportDeals, gated by permit like the page. |
||
| 2 | * The agent's deals as one JSON file they can keep: plain data in (the deals | |
| 3 | * as the deal page reads them), plain data out. Nothing is read from a | |
| 4 | * database or a clock here, and nothing is invented: every field is one the | |
| 5 | * deal view already carries. | |
| 6 | */ | |
| 7 | ||
| 8 | import { today } from "./dates.ts"; | |
| 9 | import type { DealView } from "./deals.ts"; | |
| 10 | ||
| 11 | export const EXPORT_VERSION = 1; | |
| 12 | /** The most deals one file holds, so the work cannot be made slow on purpose. */ | |
| 13 | export const EXPORT_MAX = 2000; | |
| 14 | ||
| 15 | export interface Export { | |
| 16 | readonly version: number; | |
| 17 | readonly exported_at: string; | |
| 18 | /** True when more deals were readable than the file holds. */ | |
| 19 | readonly truncated: boolean; | |
| 20 | readonly deals: readonly unknown[]; | |
| 21 | } | |
| 22 | ||
| 23 | function stateOf(deal: DealView): Record<string, unknown> { | |
| 24 | if (deal.fell_through) | |
| 25 | return { state: "fell_through", fell_at: deal.fell_at, reason: deal.fell_reason, by: deal.fell_by }; | |
| 26 | return { state: deal.closed ? "closed" : "open", reason: null }; | |
| 27 | } | |
| 28 | ||
| 29 | const dealOf = (deal: DealView): Record<string, unknown> => ({ | |
| 30 | id: deal.id, | |
| 31 | address: deal.address, | |
| 32 | side: deal.side, | |
| 33 | contract_date: deal.contract_date, | |
| 34 | closing: deal.closing, | |
| 35 | closing_time: deal.closing_time, | |
| 36 | closing_place: deal.closing_place, | |
| 37 | business_days: deal.business_days === 1, | |
| 38 | sale_price: deal.sale_price, | |
| 39 | earnest_amount: deal.earnest_amount, | |
| 40 | commission_rate: deal.commission_rate, | |
| 41 | opened_by: deal.author_name, | |
| 42 | created_at: deal.created_at, | |
| 43 | ...stateOf(deal), | |
| 44 | parties: deal.parties.map((p) => ({ role: p.role, name: p.name, phone: p.phone, email: p.email })), | |
| 45 | dates: deal.deadlines.map((d) => ({ | |
| 46 | label: d.label, | |
| 47 | kind: d.kind, | |
| 48 | due: d.due, | |
| 49 | done: d.done_at, | |
| 50 | waived: d.waived_at, | |
| 51 | waived_by: d.waived_by, | |
| 52 | owed_by: d.owes, | |
| 53 | note: d.note, | |
| 54 | moves: d.moves.map((m) => ({ from: m.from_due, to: m.to_due, reason: m.reason, by: m.by_name, at: m.at })), | |
| 55 | })), | |
| 56 | messages: deal.sent.map((m) => ({ | |
| 57 | date: m.label, | |
| 58 | to: m.party_name, | |
| 59 | to_role: m.party_role, | |
| 60 | moment: m.moment, | |
| 61 | due: m.due, | |
| 62 | by: m.by_name, | |
| 63 | sent_at: m.sent_at, | |
| 64 | subject: m.subject, | |
| 65 | body: m.body, | |
| 66 | })), | |
| 67 | }); | |
| 68 | ||
| 69 | /** The file for the given deals, in the order given, capped at EXPORT_MAX. */ | |
| 70 | export function exportDeals(deals: readonly DealView[], now: Date): Export { | |
| 71 | return { | |
| 72 | version: EXPORT_VERSION, | |
| 73 | exported_at: now.toISOString(), | |
| 74 | truncated: deals.length > EXPORT_MAX, | |
| 75 | deals: deals.slice(0, EXPORT_MAX).map(dealOf), | |
| 76 | }; | |
| 77 | } | |
| 78 | ||
| 79 | export const exportName = (now: Date): string => `deal-clock-${today(now)}.json`; |
src/mcp.ts +10
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import { restoreSamples, type Result } from "./actions.ts"; |
| 11 | 11 | import { today } from "./dates.ts"; |
| 12 | import { exportDeals } from "./export.ts"; | |
| 12 | 13 | import { fail, ok } from "./result.ts"; |
| 13 | 14 | import { DEFAULT_LENGTHS, PARTY_ROLES, SUGGESTED_DATES } from "./deadlines.ts"; |
| 14 | 15 | import { |
| @@ -76,6 +77,15 @@ export const tools: readonly Tool[] = [ | ||
| 76 | 77 | return deals.ok ? { ok: true, value: onSide(find(deals.value, q), side) } : deals; |
| 77 | 78 | }, |
| 78 | 79 | }, |
| 80 | { | |
| 81 | name: "export_deals", | |
| 82 | description: "Every deal you may read as one file to keep: version, exported_at, and per deal its address, side, figures, closing time and place, state (open, closed, fell_through with reason), parties with phone and email, each date with due, done, waived, owed_by, note and moves, and every sent message with its exact words. Never the audit log.", | |
| 83 | inputSchema: { type: "object", properties: {} }, | |
| 84 | run: (db, who) => { | |
| 85 | const deals = listDeals(db, who); | |
| 86 | return deals.ok ? { ok: true, value: exportDeals(deals.value, new Date()) } : deals; | |
| 87 | }, | |
| 88 | }, | |
| 79 | 89 | { |
| 80 | 90 | name: "get_deal", |
| 81 | 91 | description: "One deal by id. conflicts lists the open dates due on or after closing (a slipped contingency); empty when in order.", |
src/pages/profile.ts +1
| @@ -65,6 +65,7 @@ export function profilePage(input: { | ||
| 65 | 65 | <h1>Profile</h1> |
| 66 | 66 | <p class="muted">${profile.saved ? "Saved by you." : "These are the defaults the app was started with."} The header, the client timeline and the sign-off of every unsent reminder carry them. Reminders already sent keep the words that went out.</p> |
| 67 | 67 | ${mayChange ? form : readOnly} |
| 68 | <p class="small"><a href="/deals/export.json" download>Download all my deals</a> <span class="muted">One file with every deal you can read: dates, parties, notes, moves and the words of every message sent.</span></p> | |
| 68 | 69 | </section>`; |
| 69 | 70 | return layout({ body, who, agent, path: "/profile", heading: "Profile", notice, waiting: input.waiting, live: false }); |
| 70 | 71 | } |
src/routes.ts +41
| @@ -83,6 +83,7 @@ import { | ||
| 83 | 83 | type NewDeal, |
| 84 | 84 | } from "./deals.ts"; |
| 85 | 85 | import { activitySheet, sheet } from "./csv.ts"; |
| 86 | import { exportDeals, exportName } from "./export.ts"; | |
| 86 | 87 | import { book, calendar } from "./ics.ts"; |
| 87 | 88 | import { agentOf, getProfile, setProfile, useDefaults, type Profile } from "./profile.ts"; |
| 88 | 89 | import { profilePage } from "./pages/profile.ts"; |
| @@ -156,6 +157,24 @@ function spreadsheet(c: Context): Result<Response> { | ||
| 156 | 157 | }; |
| 157 | 158 | } |
| 158 | 159 | |
| 160 | /** Every deal this person may read, as one JSON file to keep. */ | |
| 161 | function everything(c: Context): Result<Response> { | |
| 162 | const deals = listDeals(c.db, c.who); | |
| 163 | if (!deals.ok) return deals; | |
| 164 | const now = new Date(); | |
| 165 | return { | |
| 166 | ok: true, | |
| 167 | value: new Response(JSON.stringify(exportDeals(deals.value, now), null, 2) + "\n", { | |
| 168 | headers: { | |
| 169 | "content-type": "application/json; charset=utf-8", | |
| 170 | "content-disposition": `attachment; filename="${exportName(now)}"`, | |
| 171 | "cache-control": "no-store", | |
| 172 | ...SECURITY, | |
| 173 | }, | |
| 174 | }), | |
| 175 | }; | |
| 176 | } | |
| 177 | ||
| 159 | 178 | export interface Route { |
| 160 | 179 | readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; |
| 161 | 180 | readonly path: string; |
| @@ -813,6 +832,15 @@ export const routes: readonly Route[] = [ | ||
| 813 | 832 | return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/deals/csv", heading: "Spreadsheet", error: got.error, message: got.message }), STATUS[got.error]); |
| 814 | 833 | }, |
| 815 | 834 | }, |
| 835 | { | |
| 836 | method: "GET", | |
| 837 | path: "/deals/export.json", | |
| 838 | handle: (c) => { | |
| 839 | const got = everything(c); | |
| 840 | if (got.ok) return got.value; | |
| 841 | return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/deals/export.json", heading: "Download all my deals", error: got.error, message: got.message }), STATUS[got.error]); | |
| 842 | }, | |
| 843 | }, | |
| 816 | 844 | { |
| 817 | 845 | method: "GET", |
| 818 | 846 | path: "/deals/new", |
| @@ -1453,6 +1481,19 @@ export const routes: readonly Route[] = [ | ||
| 1453 | 1481 | conflict: CONFLICT, |
| 1454 | 1482 | }, |
| 1455 | 1483 | }, |
| 1484 | { | |
| 1485 | method: "GET", | |
| 1486 | path: "/api/deals/export", | |
| 1487 | handle: (c) => { | |
| 1488 | const got = everything(c); | |
| 1489 | return got.ok ? got.value : answer(got); | |
| 1490 | }, | |
| 1491 | api: { | |
| 1492 | summary: "All the deals you may read as one JSON file: version, exported_at, and per deal its address, side, figures, closing time and place, state (open, closed or fell_through with reason), parties with phone and email, each date with due, done, waived, owed_by, note and moves, and the sent messages with the exact approved words. Never the audit log.", | |
| 1493 | answer: { type: "object", properties: { version: { type: "integer" }, exported_at: { type: "string", format: "date-time" }, truncated: { type: "boolean" }, deals: { type: "array", items: { type: "object" } } } }, | |
| 1494 | cell: { resource: "deal", verb: "list" }, | |
| 1495 | }, | |
| 1496 | }, | |
| 1456 | 1497 | { |
| 1457 | 1498 | method: "GET", |
| 1458 | 1499 | path: "/api/deals/:id", |
src/server.test.ts +1
| @@ -172,6 +172,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 172 | 172 | const listed = await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" }); |
| 173 | 173 | expect(listed.result.tools.map((t: { name: string }) => t.name)).toEqual([ |
| 174 | 174 | "list_deals", |
| 175 | "export_deals", | |
| 175 | 176 | "get_deal", |
| 176 | 177 | "client_timeline", |
| 177 | 178 | "reminders_today", |
src/terminal.ts +25 −3
| @@ -17,7 +17,8 @@ | ||
| 17 | 17 | * (a new date, then the reason), N moves one flagged "not a business day" to the next business day, l sets how many days before it reminds. o or enter opens its deal; n opens a new |
| 18 | 18 | * deal (address, buyer, seller, contract and closing dates, side); d, r and b move |
| 19 | 19 | * between views; esc cancels a prompt; q leaves. / finds a deal by address or |
| 20 | * party and narrows dates, week and reminders to it; / then enter clears it. | |
| 20 | * party and narrows dates, week and reminders to it; / then enter clears it. E writes every deal you may read to one JSON file | |
| 21 | * under the app's exports folder (the page's Download all my deals). | |
| 21 | 22 | */ |
| 22 | 23 | |
| 23 | 24 | import type { Database } from "bun:sqlite"; |
| @@ -71,6 +72,9 @@ import { conflictLine } from "./order.ts"; | ||
| 71 | 72 | import { isOpen, PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts"; |
| 72 | 73 | import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts"; |
| 73 | 74 | import { permit } from "./contract.ts"; |
| 75 | import { exportDeals, exportName } from "./export.ts"; | |
| 76 | import { mkdirSync, writeFileSync } from "node:fs"; | |
| 77 | import { join } from "node:path"; | |
| 74 | 78 | import { drafts, heldFrom, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts"; |
| 75 | 79 | import type { AuditRow } from "./audit.ts"; |
| 76 | 80 | import type { Result } from "./result.ts"; |
| @@ -115,7 +119,7 @@ export interface Terminal { | ||
| 115 | 119 | export function terminal( |
| 116 | 120 | db: Database, |
| 117 | 121 | me: Who, |
| 118 | context: { title: string; where: string; ssh?: string | undefined; agent?: Agent; on?: () => string }, | |
| 122 | context: { title: string; where: string; ssh?: string | undefined; agent?: Agent; on?: () => string; exportDir?: string }, | |
| 119 | 123 | ): Terminal { |
| 120 | 124 | const on = context.on ?? today; |
| 121 | 125 | /** The saved profile unless a caller fixed one: read when drawn, so a save elsewhere shows at once. */ |
| @@ -588,6 +592,8 @@ export function terminal( | ||
| 588 | 592 | } else if (key === "P") { |
| 589 | 593 | view = "people"; |
| 590 | 594 | cursor = 0; |
| 595 | } else if (key === "E") { | |
| 596 | said = exportAll(); | |
| 591 | 597 | } else if (key === "I") { |
| 592 | 598 | view = "profile"; |
| 593 | 599 | cursor = 0; |
| @@ -680,6 +686,22 @@ export function terminal( | ||
| 680 | 686 | cursor = Math.min(cursor, Math.max(0, rowCount() - 1)); |
| 681 | 687 | } |
| 682 | 688 | |
| 689 | /** E: the page's Download all my deals, written as a file; the same `listDeals` gate and the same `exportDeals`. */ | |
| 690 | function exportAll(): string { | |
| 691 | if (context.exportDir === undefined) return "Export is not available here."; | |
| 692 | const listed = listDeals(db, me); | |
| 693 | if (!listed.ok) return listed.message; | |
| 694 | const now = new Date(); | |
| 695 | const path = join(context.exportDir, exportName(now)); | |
| 696 | try { | |
| 697 | mkdirSync(context.exportDir, { recursive: true }); | |
| 698 | writeFileSync(path, JSON.stringify(exportDeals(listed.value, now), null, 2) + "\n"); | |
| 699 | } catch { | |
| 700 | return "Could not write the export file."; | |
| 701 | } | |
| 702 | return `Wrote ${listed.value.length} deals to ${path}.`; | |
| 703 | } | |
| 704 | ||
| 683 | 705 | const dateLine = (row: Row, i: number, withDeal: boolean): string => { |
| 684 | 706 | const { date, deal } = row; |
| 685 | 707 | const u = urgencyOf(date, on()); |
| @@ -881,7 +903,7 @@ export function terminal( | ||
| 881 | 903 | ? "b back to the deal · d dates · q quit" |
| 882 | 904 | : view === "deal" |
| 883 | 905 | ? "j/k move · t client timeline · f broker file · s messages · x done · W waive · u reopen/un-waive · m move · N next business day · l remind lead · T note · a add date · p add party · e edit party · A edit address · C closing time and place · M amend the contract · S status update to the party · X remove date/party · D remove deal · b back · q quit" |
| 884 | : `j/k move · x done · W waive · u reopen · m move · N next business day · l lead · T note · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · L activity · q quit`; | |
| 906 | : `j/k move · x done · W waive · u reopen · m move · N next business day · l lead · T note · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · E export · L activity · q quit`; | |
| 885 | 907 | lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys)); |
| 886 | 908 | } |
| 887 | 909 | return lines; |
src/tty.ts +3 −2
| @@ -6,12 +6,13 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { openDb } from "./db.ts"; |
| 9 | import { ssh, title, where } from "./env.ts"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { dataDir, ssh, title, where } from "./env.ts"; | |
| 10 | 11 | import { terminal } from "./terminal.ts"; |
| 11 | 12 | import { whoAtTty } from "./who.ts"; |
| 12 | 13 | |
| 13 | 14 | const esc = "\x1b["; |
| 14 | const term = terminal(openDb(), whoAtTty(), { title, where, ssh }); | |
| 15 | const term = terminal(openDb(), whoAtTty(), { title, where, ssh, exportDir: join(dataDir, "exports") }); | |
| 15 | 16 | const draw = (): void => { |
| 16 | 17 | process.stdout.write(`${esc}2J${esc}H${term.screen().join("\r\n")}`); |
| 17 | 18 | }; |
new above
offline
Missing: another user's private deal absent, and audit content absent (the current check only looks for the word audit). Also merge the duplicate listDeals import and move the top-level expect calls into setup that throws.