Public: anyone can read this; the crew can change it.
After a demo, one Restore the sample deals action brings back the four sample deals exactly as the README describes, leaving every real deal untouched #40
Check · Review · Land · Live done — Landed and live in production.
mason/deal-clock:mason/34-after-a-demo-one-restore-the-sample-deal → main 3 commits fork
13 files
changed +301
−40
README.md +4
| @@ -94,6 +94,10 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture | ||
| 94 | 94 | upcoming or overdue, with no controls. Print it with your browser's print |
| 95 | 95 | to hand to a buyer or seller. In the terminal, open the deal with o and press |
| 96 | 96 | t; over MCP, an agent asks for the `client_timeline` tool. |
| 97 | 14. **Put the samples back.** After the walk-through, an admin taps Sample | |
| 98 | deals below the clock, then Restore the sample deals and confirms: the four | |
| 99 | samples return as they were, dated from today, and the deals you opened are | |
| 100 | left alone. Only an admin sees it. In the terminal press R; over MCP, the `restore_samples` tool. | |
| 97 | 101 | |
| 98 | 102 | ## What is real, and what is not yet |
| 99 | 103 |
docs/TECHNICAL.md +2 −1
| @@ -53,7 +53,8 @@ tools at `POST /mcp` (`list_deals`, `get_deal`, `client_timeline`, `reminders_to | ||
| 53 | 53 | `open_deal`, `add_date`, `add_party`, `edit_party`, `remove_party`, |
| 54 | 54 | `remove_date` — custom dates only — `remove_deal` — its author or an admin — |
| 55 | 55 | `mark_done` — with `done: false` to |
| 56 | reopen a date — `move_date`, `send_reminder`). `send_reminder` takes an | |
| 56 | reopen a date — `move_date`, `send_reminder`, `restore_samples` — admin only: puts the | |
| 57 | four sample deals back and leaves every other deal alone). `send_reminder` takes an | |
| 57 | 58 | optional `subject` and `body` to send edited words; without them the draft |
| 58 | 59 | goes as it is. |
| 59 | 60 |
src/actions.ts +34 −1
| @@ -9,7 +9,9 @@ | ||
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import type { AuditRow } from "./audit.ts"; |
| 11 | 11 | import { permit } from "./contract.ts"; |
| 12 | import { fail, ok, refuse, type Result } from "./result.ts"; | |
| 12 | import { emit } from "./live.ts"; | |
| 13 | import { audited, fail, ok, refuse, type Result } from "./result.ts"; | |
| 14 | import { restore, SAMPLE } from "./sample.ts"; | |
| 13 | 15 | import type { Who } from "./who.ts"; |
| 14 | 16 | |
| 15 | 17 | export type { Failure, Result } from "./result.ts"; |
| @@ -69,3 +71,34 @@ export function getAudit( | ||
| 69 | 71 | return fail("invalid", "An audit id is a whole number."); |
| 70 | 72 | return fail("not_found", "No such audit row."); |
| 71 | 73 | } |
| 74 | ||
| 75 | /** | |
| 76 | * Whether `who` may put the samples back, as `restoreSamples` would refuse. | |
| 77 | * Restoring removes the deals the sample identity wrote and writes them | |
| 78 | * again, so the table is asked for both cells it exercises: `deal` `delete`, | |
| 79 | * on a row the sample authored, and `deal` `create`. Today that is an admin; | |
| 80 | * no cell is loosened for it. | |
| 81 | */ | |
| 82 | export const mayRestore = (who: Who): Result<null> => | |
| 83 | permit(who, "deal", "delete", { author_id: SAMPLE.id }) === "yes" && | |
| 84 | permit(who, "deal", "create") === "yes" | |
| 85 | ? ok(null) | |
| 86 | : refuse(who, "Sign in to restore the sample deals.", "Only an admin may restore the sample deals."); | |
| 87 | ||
| 88 | /** | |
| 89 | * Put the four sample deals back as the README describes them, anchored to | |
| 90 | * today, for the next demo. Only deals the sample identity wrote are removed; | |
| 91 | * every deal a person made is left as it is. Audited as a delete: the | |
| 92 | * samples are removed and written again. | |
| 93 | */ | |
| 94 | export function restoreSamples(db: Database, who: Who): Result<{ id: number; ids: number[] }> { | |
| 95 | const may = mayRestore(who); | |
| 96 | let out: Result<{ id: number; ids: number[] }>; | |
| 97 | if (!may.ok) out = may; | |
| 98 | else { | |
| 99 | const ids = restore(db); | |
| 100 | emit("deal.changed", { id: ids[0] }); | |
| 101 | out = ok({ id: ids[0]!, ids }); | |
| 102 | } | |
| 103 | return audited(db, who, "deal", "delete", out.ok ? out.value.id : undefined, out); | |
| 104 | } |
src/contract.test.ts +17 −2
| @@ -8,7 +8,7 @@ import { expect, test } from "bun:test"; | ||
| 8 | 8 | import { mkdtempSync } from "node:fs"; |
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| 11 | import { getAudit, listAudit } from "./actions.ts"; | |
| 11 | import { getAudit, listAudit, mayRestore, restoreSamples } from "./actions.ts"; | |
| 12 | 12 | import { record } from "./audit.ts"; |
| 13 | 13 | import { |
| 14 | 14 | createDeal, |
| @@ -18,7 +18,7 @@ import { | ||
| 18 | 18 | updateDeal, |
| 19 | 19 | } from "./deals.ts"; |
| 20 | 20 | import { actingAs, identities, table, type Verb } from "./can.ts"; |
| 21 | import { contract } from "./contract.ts"; | |
| 21 | import { contract, permit } from "./contract.ts"; | |
| 22 | 22 | import { openDb } from "./db.ts"; |
| 23 | 23 | import type { Who } from "./who.ts"; |
| 24 | 24 | |
| @@ -121,3 +121,18 @@ test("every door answers as the table says, as every identity", () => { | ||
| 121 | 121 | } |
| 122 | 122 | expect(asked).toBeGreaterThan(0); |
| 123 | 123 | }); |
| 124 | ||
| 125 | test("restoring the samples answers as the table says for the cells it exercises, as every identity", () => { | |
| 126 | for (const identity of identities(contract)) { | |
| 127 | const who = whoIs(identity); | |
| 128 | const said = `restore as ${identity}`; | |
| 129 | // It removes what the sample authored and writes deals again: delete on that row, and create. | |
| 130 | const allowed = permit(who, "deal", "delete", { author_id: "sample" }) === "yes" && permit(who, "deal", "create") === "yes"; | |
| 131 | expect([said, mayRestore(who).ok]).toEqual([said, allowed]); | |
| 132 | expect([said, restoreSamples(db, who).ok]).toEqual([said, allowed]); | |
| 133 | } | |
| 134 | expect(whoIs("anon")).toEqual({ role: "anon" }); | |
| 135 | expect(mayRestore({ role: "anon" }).ok).toBe(false); | |
| 136 | expect(mayRestore({ role: "admin", id: "a", name: "a" }).ok).toBe(true); | |
| 137 | expect(mayRestore({ role: "user", id: "u", name: "u" }).ok).toBe(false); | |
| 138 | }); |
src/mcp.ts +7 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import type { Result } from "./actions.ts"; | |
| 10 | import { restoreSamples, type Result } from "./actions.ts"; | |
| 11 | 11 | import { today } from "./dates.ts"; |
| 12 | 12 | import { PARTY_ROLES } from "./deadlines.ts"; |
| 13 | 13 | import { |
| @@ -278,6 +278,12 @@ export const tools: readonly Tool[] = [ | ||
| 278 | 278 | inputSchema: { type: "object", properties: { deal_id: { type: "integer" } }, required: ["deal_id"] }, |
| 279 | 279 | run: (db, who, a) => deleteDeal(db, who, { id: Number(a.deal_id) }), |
| 280 | 280 | }, |
| 281 | { | |
| 282 | name: "restore_samples", | |
| 283 | description: "Put the four sample deals back as the README describes them, anchored to today; deals people made are untouched.", | |
| 284 | inputSchema: { type: "object", properties: {} }, | |
| 285 | run: (db, who) => restoreSamples(db, who), | |
| 286 | }, | |
| 281 | 287 | ]; |
| 282 | 288 | |
| 283 | 289 | /** One JSON-RPC message in, an HTTP status and a body out (a notification gets 202 and no body). */ |
src/pages/clock.ts +14
| @@ -14,6 +14,7 @@ import { drafts, pending, unsent } from "../reminders.ts"; | ||
| 14 | 14 | import type { Who } from "../who.ts"; |
| 15 | 15 | import { thisWeek } from "../week.ts"; |
| 16 | 16 | import { layout } from "./layout.ts"; |
| 17 | import { mayRestore } from "../actions.ts"; | |
| 17 | 18 | import { badge, draftItem, owedBy, sheet, sheetId, URGENCY_LABEL } from "./sheet.ts"; |
| 18 | 19 | import { canChange } from "../deals.ts"; |
| 19 | 20 | |
| @@ -150,6 +151,18 @@ export function clock(input: { | ||
| 150 | 151 | <h2>Closed <span class="muted">· ${closed.length}</span></h2> |
| 151 | 152 | <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> |
| 152 | 153 | </section>`; |
| 154 | const restoreCard = | |
| 155 | !mayRestore(who).ok | |
| 156 | ? "" | |
| 157 | : `<section id="samples" class="card"> | |
| 158 | <h2>Sample deals</h2> | |
| 159 | <p class="muted small">After a demo, put the four sample deals back as the README describes them. Deals you opened are not touched.</p> | |
| 160 | <details class="confirm"> | |
| 161 | <summary class="button button-quiet">Restore the sample deals</summary> | |
| 162 | <p>Any change made to the sample deals is lost. Your own deals are kept.</p> | |
| 163 | <form method="post" action="/samples/restore"><button class="button">Yes, restore them</button></form> | |
| 164 | </details> | |
| 165 | </section>`; | |
| 153 | 166 | const body = `<section class="intro"> |
| 154 | 167 | <div> |
| 155 | 168 | <h1>The clock</h1> |
| @@ -167,6 +180,7 @@ export function clock(input: { | ||
| 167 | 180 | </ul> |
| 168 | 181 | </section> |
| 169 | 182 | ${closedCard} |
| 183 | ${restoreCard} | |
| 170 | 184 | ${deals.length === 0 ? "" : weekCard(deals, on)} |
| 171 | 185 | <section id="today" class="card" data-live="deal.changed"> |
| 172 | 186 | <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2> |
src/restore.test.ts added +81
| @@ -0,0 +1,81 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { restoreSamples } from "./actions.ts"; | |
| 6 | import { addDays, today } from "./dates.ts"; | |
| 7 | import { openDb } from "./db.ts"; | |
| 8 | import { addParty, createDeal, listDeals, markDone, moveDeadline, type DealView } from "./deals.ts"; | |
| 9 | import type { Who } from "./who.ts"; | |
| 10 | ||
| 11 | const db = openDb(mkdtempSync(join(tmpdir(), "app-restore-"))); | |
| 12 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 13 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 14 | const on = today(); | |
| 15 | ||
| 16 | const all = (): DealView[] => { | |
| 17 | const got = listDeals(db, alice); | |
| 18 | if (!got.ok) throw new Error(got.message); | |
| 19 | return got.value; | |
| 20 | }; | |
| 21 | const samples = () => all().filter((d) => d.author_id === "sample"); | |
| 22 | const sample = (address: string) => samples().find((d) => d.address.includes(address))!; | |
| 23 | const date = (deal: DealView, kind: string) => deal.deadlines.find((d) => d.kind === kind)!; | |
| 24 | ||
| 25 | const mine = createDeal(db, alice, { address: "12 Elm St", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: on, closingDate: addDays(on, 45) }); | |
| 26 | if (!mine.ok) throw new Error(mine.message); | |
| 27 | ||
| 28 | /** What a demo does to the samples. */ | |
| 29 | function demo(): void { | |
| 30 | for (const d of sample("Harbor View").deadlines) markDone(db, alice, { id: d.id, done: true }); | |
| 31 | for (const d of sample("Alder Lane").deadlines) markDone(db, alice, { id: d.id, done: true }); | |
| 32 | moveDeadline(db, alice, { id: date(sample("Juniper"), "inspection").id, due: addDays(on, 30), reason: "demo" }); | |
| 33 | addParty(db, alice, { dealId: sample("Juniper").id, role: "title", name: "Demo Title", contact: "" }); | |
| 34 | } | |
| 35 | ||
| 36 | test("restoring brings the README walk-through back and leaves a person's deal byte for byte alone", () => { | |
| 37 | const before = JSON.stringify(all().find((d) => d.id === mine.value.id)); | |
| 38 | demo(); | |
| 39 | expect(date(sample("Harbor View"), "inspection").done_at).not.toBeNull(); | |
| 40 | const restored = restoreSamples(db, root); | |
| 41 | expect(restored.ok).toBe(true); | |
| 42 | expect(samples().length).toBe(4); | |
| 43 | expect(JSON.stringify(all().find((d) => d.id === mine.value.id))).toBe(before); | |
| 44 | ||
| 45 | const harbor = date(sample("Harbor View"), "inspection"); | |
| 46 | expect(harbor.done_at).toBeNull(); | |
| 47 | expect(harbor.due < on).toBe(true); | |
| 48 | const alder = sample("Alder Lane"); | |
| 49 | expect(alder.closing >= on && alder.closing <= addDays(on, 7)).toBe(true); | |
| 50 | const appraisal = date(sample("Orchard Row"), "appraisal"); | |
| 51 | expect(appraisal.moves.length).toBe(1); | |
| 52 | expect(sample("Juniper").deadlines.every((d) => d.done_at === null && d.due >= on)).toBe(true); | |
| 53 | expect(sample("Juniper").parties.some((p) => p.name === "Demo Title")).toBe(false); | |
| 54 | }); | |
| 55 | ||
| 56 | test("restoring twice leaves what once did, and the seeded guard is not tripped", () => { | |
| 57 | const shape = () => samples().map((d) => [d.address, d.closing, d.parties.length, d.deadlines.map((x) => [x.kind, x.due, x.done_at])]); | |
| 58 | restoreSamples(db, root); | |
| 59 | const once = JSON.stringify(shape()); | |
| 60 | restoreSamples(db, root); | |
| 61 | expect(JSON.stringify(shape())).toBe(once); | |
| 62 | expect(samples().length).toBe(4); | |
| 63 | expect(db.query("SELECT count(*) AS n FROM app_meta WHERE key = 'seeded'").get()).toEqual({ n: 1 }); | |
| 64 | }); | |
| 65 | ||
| 66 | test("only an admin may restore: the table's delete cell on a sample row, and a refusal changes nothing", () => { | |
| 67 | demo(); | |
| 68 | const strangers = restoreSamples(db, { role: "anon" }); | |
| 69 | expect(strangers.ok).toBe(false); | |
| 70 | if (!strangers.ok) expect(strangers.error).toBe("signin_required"); | |
| 71 | const user = restoreSamples(db, alice); | |
| 72 | expect(user.ok).toBe(false); | |
| 73 | if (!user.ok) expect(user.error).toBe("forbidden"); | |
| 74 | expect(date(sample("Harbor View"), "inspection").done_at).not.toBeNull(); | |
| 75 | const rows = db.query("SELECT verb, outcome FROM audit ORDER BY id DESC LIMIT 2").all(); | |
| 76 | expect(rows).toEqual([ | |
| 77 | { verb: "delete", outcome: "forbidden" }, | |
| 78 | { verb: "delete", outcome: "signin_required" }, | |
| 79 | ]); | |
| 80 | expect(restoreSamples(db, root).ok).toBe(true); | |
| 81 | }); |
src/routes.ts +6
| @@ -16,6 +16,7 @@ import { existsSync, readFileSync } from "node:fs"; | ||
| 16 | 16 | import { |
| 17 | 17 | getAudit, |
| 18 | 18 | listAudit, |
| 19 | restoreSamples, | |
| 19 | 20 | type Failure, |
| 20 | 21 | type Result, |
| 21 | 22 | } from "./actions.ts"; |
| @@ -442,6 +443,11 @@ export const routes: readonly Route[] = [ | ||
| 442 | 443 | return done(addParty(c.db, c.who, { dealId: id, role: f.role, name: f.name, contact: f.contact }), backTo(`/deals/${id}`), "Party added."); |
| 443 | 444 | }, |
| 444 | 445 | }, |
| 446 | { | |
| 447 | method: "POST", | |
| 448 | path: "/samples/restore", | |
| 449 | handle: (c) => done(restoreSamples(c.db, c.who), "/", "Sample deals restored."), | |
| 450 | }, | |
| 445 | 451 | { |
| 446 | 452 | method: "POST", |
| 447 | 453 | path: "/deals/:id/delete", |
src/sample.ts +54 −34
| @@ -10,7 +10,7 @@ import { addDays, daysBetween, today } from "./dates.ts"; | ||
| 10 | 10 | import { DEFAULT_LENGTHS, type PartyRole } from "./deadlines.ts"; |
| 11 | 11 | import { insertDeal } from "./deals.ts"; |
| 12 | 12 | |
| 13 | const SAMPLE = { id: "sample", name: "Sample data" }; | |
| 13 | export const SAMPLE = { id: "sample", name: "Sample data" }; | |
| 14 | 14 | |
| 15 | 15 | interface Sample { |
| 16 | 16 | readonly address: string; |
| @@ -203,44 +203,64 @@ export function refresh(db: Database, on = today()): void { | ||
| 203 | 203 | }).immediate(); |
| 204 | 204 | } |
| 205 | 205 | |
| 206 | /** Write the four samples, anchored to `on`. The caller holds the write transaction. */ | |
| 207 | function writeSamples(db: Database, on: string): void { | |
| 208 | for (const s of SAMPLES) { | |
| 209 | const deal = insertDeal(db, SAMPLE, { | |
| 210 | address: s.address, | |
| 211 | buyer: s.buyer, | |
| 212 | seller: s.seller, | |
| 213 | contractDate: addDays(on, s.contract), | |
| 214 | closingDate: addDays(on, s.closing), | |
| 215 | lengths: { ...DEFAULT_LENGTHS, ...s.lengths }, | |
| 216 | businessDays: false, | |
| 217 | }); | |
| 218 | for (const [role, name, contact] of s.parties) | |
| 219 | db.query("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4)").run(deal.id, role, name, contact); | |
| 220 | for (const kind of s.done ?? []) | |
| 221 | db.query("UPDATE deadline SET done_at = ?1 WHERE deal_id = ?2 AND kind = ?3").run(`${addDays(on, -1)}T17:00:00.000Z`, deal.id, kind); | |
| 222 | for (const [label, days, owes, what] of s.custom ?? []) | |
| 223 | db.query("INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5)").run(deal.id, label, addDays(on, days), owes, what); | |
| 224 | if (s.sent !== undefined) { | |
| 225 | const [kind, role, moment, subject, body] = s.sent; | |
| 226 | const d = db.query<{ id: number; label: string; due: string }, [number, string]>("SELECT id, label, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!; | |
| 227 | const p = db.query<{ id: number; name: string }, [number, string]>("SELECT id, name FROM party WHERE deal_id = ?1 AND role = ?2").get(deal.id, role)!; | |
| 228 | const at = `${moment === "before" ? addDays(d.due, -3) : d.due}T08:30:00.000Z`; | |
| 229 | db.query("INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, by_name, subject, body, sent_at, sample) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, 1)").run(deal.id, d.id, p.id, d.label, p.name, role, moment, d.due, SAMPLE.name, subject, body, at); | |
| 230 | } | |
| 231 | if (s.moved !== undefined) { | |
| 232 | const [kind, days, reason] = s.moved; | |
| 233 | const d = db.query<{ id: number; due: string }, [number, string]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!; | |
| 234 | const to = addDays(on, days); | |
| 235 | db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(to, d.id); | |
| 236 | db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)").run(d.id, d.due, to, reason, SAMPLE.name); | |
| 237 | } | |
| 238 | } | |
| 239 | db.query("INSERT OR REPLACE INTO app_meta (key, value) VALUES ('seeded', ?1)").run(on); | |
| 240 | db.query("INSERT OR REPLACE INTO app_meta (key, value) VALUES ('sample_anchor', ?1)").run(on); | |
| 241 | } | |
| 242 | ||
| 206 | 243 | /** Write the samples into an empty database, once; a database that has had them never gets them again. */ |
| 207 | 244 | export function seed(db: Database, on = today()): void { |
| 208 | 245 | // Asked and written in one write transaction, taken before the question: |
| 209 | 246 | // the server and a terminal opening a new file at once seed it once. |
| 210 | 247 | db.transaction(() => { |
| 211 | 248 | if (db.query("SELECT 1 FROM app_meta WHERE key = 'seeded'").get() !== null) return; |
| 212 | for (const s of SAMPLES) { | |
| 213 | const deal = insertDeal(db, SAMPLE, { | |
| 214 | address: s.address, | |
| 215 | buyer: s.buyer, | |
| 216 | seller: s.seller, | |
| 217 | contractDate: addDays(on, s.contract), | |
| 218 | closingDate: addDays(on, s.closing), | |
| 219 | lengths: { ...DEFAULT_LENGTHS, ...s.lengths }, | |
| 220 | businessDays: false, | |
| 221 | }); | |
| 222 | for (const [role, name, contact] of s.parties) | |
| 223 | db.query("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4)").run(deal.id, role, name, contact); | |
| 224 | for (const kind of s.done ?? []) | |
| 225 | db.query("UPDATE deadline SET done_at = ?1 WHERE deal_id = ?2 AND kind = ?3").run(`${addDays(on, -1)}T17:00:00.000Z`, deal.id, kind); | |
| 226 | for (const [label, days, owes, what] of s.custom ?? []) | |
| 227 | db.query("INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5)").run(deal.id, label, addDays(on, days), owes, what); | |
| 228 | if (s.sent !== undefined) { | |
| 229 | const [kind, role, moment, subject, body] = s.sent; | |
| 230 | const d = db.query<{ id: number; label: string; due: string }, [number, string]>("SELECT id, label, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!; | |
| 231 | const p = db.query<{ id: number; name: string }, [number, string]>("SELECT id, name FROM party WHERE deal_id = ?1 AND role = ?2").get(deal.id, role)!; | |
| 232 | const at = `${moment === "before" ? addDays(d.due, -3) : d.due}T08:30:00.000Z`; | |
| 233 | db.query("INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, by_name, subject, body, sent_at, sample) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, 1)").run(deal.id, d.id, p.id, d.label, p.name, role, moment, d.due, SAMPLE.name, subject, body, at); | |
| 234 | } | |
| 235 | if (s.moved !== undefined) { | |
| 236 | const [kind, days, reason] = s.moved; | |
| 237 | const d = db.query<{ id: number; due: string }, [number, string]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!; | |
| 238 | const to = addDays(on, days); | |
| 239 | db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(to, d.id); | |
| 240 | db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)").run(d.id, d.due, to, reason, SAMPLE.name); | |
| 241 | } | |
| 242 | } | |
| 243 | db.query("INSERT INTO app_meta (key, value) VALUES ('seeded', ?1)").run(on); | |
| 244 | db.query("INSERT INTO app_meta (key, value) VALUES ('sample_anchor', ?1)").run(on); | |
| 249 | writeSamples(db, on); | |
| 250 | }).immediate(); | |
| 251 | } | |
| 252 | ||
| 253 | /** | |
| 254 | * Put the samples back as `seed` wrote them: every deal authored by the sample | |
| 255 | * identity (and nothing else) is removed with its dates, moves, parties and | |
| 256 | * reminders, and the four are written again anchored to `on`. One immediate | |
| 257 | * transaction, so two restores at once leave four, not eight. Answers the ids | |
| 258 | * of the deals written. | |
| 259 | */ | |
| 260 | export function restore(db: Database, on = today()): number[] { | |
| 261 | return db.transaction(() => { | |
| 262 | db.query("DELETE FROM deal WHERE author_id = ?1").run(SAMPLE.id); | |
| 263 | writeSamples(db, on); | |
| 264 | return db.query<{ id: number }, [string]>("SELECT id FROM deal WHERE author_id = ?1 ORDER BY id").all(SAMPLE.id).map((r) => r.id); | |
| 245 | 265 | }).immediate(); |
| 246 | 266 | } |
src/server.test.ts +34
| @@ -180,6 +180,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 180 | 180 | "remove_party", |
| 181 | 181 | "remove_date", |
| 182 | 182 | "remove_deal", |
| 183 | "restore_samples", | |
| 183 | 184 | ]); |
| 184 | 185 | const call = (name: string, args: unknown, who = {}) => |
| 185 | 186 | rpc( |
| @@ -353,6 +354,39 @@ test("refuses a cross-site post", async () => { | ||
| 353 | 354 | expect(posted.status).toBe(403); |
| 354 | 355 | }); |
| 355 | 356 | |
| 357 | const rita = as("u-rita", "rita"); | |
| 358 | test("the clock offers to restore the samples to an admin only, and the post is same-origin", async () => { | |
| 359 | expect(await (await api("/", {}, rita)).text()).not.toContain("Restore the sample deals"); | |
| 360 | const page = await (await api("/", {}, root)).text(); | |
| 361 | expect(page).toContain("Restore the sample deals"); | |
| 362 | expect(page).toContain('action="/samples/restore"'); | |
| 363 | const cross = await api("/samples/restore", { method: "POST", redirect: "manual", headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site" } }, root); | |
| 364 | expect(cross.status).toBe(403); | |
| 365 | const notice = async (r: Response) => decodeURIComponent(r.headers.get("set-cookie") ?? ""); | |
| 366 | expect(await notice(await fetch(base + "/samples/restore", { method: "POST", redirect: "manual" }))).toContain("Sign in to restore"); | |
| 367 | expect(await notice(await api("/samples/restore", { method: "POST", redirect: "manual" }, rita))).toContain("Only an admin"); | |
| 368 | const ok = await api("/samples/restore", { method: "POST", redirect: "manual" }, root); | |
| 369 | expect(ok.status).toBe(303); | |
| 370 | expect(await notice(ok)).toContain("Sample deals restored."); | |
| 371 | }); | |
| 372 | ||
| 373 | test("restore_samples over MCP: an admin restores, anyone else is refused and nothing changes", async () => { | |
| 374 | const call = (who = {}) => rpc({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "restore_samples", arguments: {} } }, who); | |
| 375 | const sampleIds = async () => | |
| 376 | ((await (await api("/api/deals", {}, root)).json()) as { id: number; author_id: string }[]).filter((d) => d.author_id === "sample").map((d) => d.id); | |
| 377 | const before = await sampleIds(); | |
| 378 | expect(before.length).toBe(4); | |
| 379 | expect((await call()).result.isError).toBe(true); | |
| 380 | expect((await call(rita)).result.isError).toBe(true); | |
| 381 | expect(await sampleIds()).toEqual(before); | |
| 382 | const restored = await call(root); | |
| 383 | expect(restored.result.isError).toBeUndefined(); | |
| 384 | const after = await sampleIds(); | |
| 385 | expect(after.length).toBe(4); | |
| 386 | const trail = (await (await api("/api/audit", {}, root)).json()) as { verb: string; outcome: string }[]; | |
| 387 | expect(trail.some((r) => r.verb === "delete" && r.outcome === "ok")).toBe(true); | |
| 388 | }); | |
| 389 | ||
| 356 | 390 | test("static files are cached for a year when linked by content", async () => { |
| 357 | 391 | const page = await (await fetch(base + "/")).text(); |
| 358 | 392 | const href = /href="(\/static\/app\.css\?v=[0-9a-f]{8})"/.exec(page)?.[1]; |
src/terminal.test.ts +20
| @@ -369,3 +369,23 @@ test("r lists an overdue follow-up as late, as the clock page does, until it is | ||
| 369 | 369 | again.press("r"); |
| 370 | 370 | expect(lines(again).some((l) => l.includes("Appraisal back") && l.includes("overdue follow-up"))).toBe(false); |
| 371 | 371 | }); |
| 372 | ||
| 373 | test("R is refused to someone who is not an admin", () => { | |
| 374 | const t = terminal(db, alice, context); | |
| 375 | press(t, "R"); | |
| 376 | expect(lines(t).join("\n")).toContain("Only an admin may restore the sample deals."); | |
| 377 | }); | |
| 378 | ||
| 379 | test("R then yes puts the sample deals back, leaving a person's deal alone", () => { | |
| 380 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 381 | const t = terminal(db, root, context); | |
| 382 | const harbor = () => listDeals(db, alice).value!.find((d) => d.address.includes("Harbor View"))!; | |
| 383 | const first = harbor().deadlines.find((d) => d.done_at === null)!; | |
| 384 | markDone(db, alice, { id: first.id, done: true }); | |
| 385 | press(t, "R", "no\r"); | |
| 386 | expect(harbor().deadlines.find((d) => d.id === first.id)!.done_at).not.toBeNull(); | |
| 387 | press(t, "R", "yes\r"); | |
| 388 | expect(lines(t).join("\n")).toContain("Sample deals restored."); | |
| 389 | expect(harbor().deadlines.every((d) => d.done_at === null)).toBe(true); | |
| 390 | expect(getDeal(db, alice, { id }).ok).toBe(true); | |
| 391 | }); |
src/terminal.ts +17 −1
| @@ -44,6 +44,7 @@ import { | ||
| 44 | 44 | type DealView, |
| 45 | 45 | type DeadlineView, |
| 46 | 46 | } from "./deals.ts"; |
| 47 | import { mayRestore, restoreSamples } from "./actions.ts"; | |
| 47 | 48 | import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts"; |
| 48 | 49 | import { drafts, MOMENT_LABEL, pending, unsent, type Agent, type Draft } from "./reminders.ts"; |
| 49 | 50 | import type { Result } from "./result.ts"; |
| @@ -361,6 +362,21 @@ export function terminal( | ||
| 361 | 362 | view = "reminders"; |
| 362 | 363 | cursor = 0; |
| 363 | 364 | reading = undefined; |
| 365 | } else if (key === "R" && (view === "dates" || view === "week")) { | |
| 366 | const may = mayRestore(me); | |
| 367 | if (!may.ok) said = may.message; | |
| 368 | else | |
| 369 | prompt = { | |
| 370 | steps: ["Type yes to put the sample deals back (your own deals are kept)"], | |
| 371 | answers: [], | |
| 372 | text: "", | |
| 373 | finish: ([yes]) => { | |
| 374 | if (yes !== "yes") return "Kept."; | |
| 375 | const restored = restoreSamples(db, me); | |
| 376 | cursor = 0; | |
| 377 | return restored.ok ? "Sample deals restored." : restored.message; | |
| 378 | }, | |
| 379 | }; | |
| 364 | 380 | } else if ((key === "n" && view !== "reminders") || key === "c") { |
| 365 | 381 | const may = mayOpen(me); |
| 366 | 382 | if (!may.ok) said = may.message; |
| @@ -496,7 +512,7 @@ export function terminal( | ||
| 496 | 512 | ? "b back to the deal · d dates · q quit" |
| 497 | 513 | : view === "deal" |
| 498 | 514 | ? "j/k move · t client timeline · s messages · x done · u reopen · m move · a add date · p add party · e edit party · X remove date/party · D remove deal · b back · q quit" |
| 499 | : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · h ${showDone ? "hide" : "show"} done · w this week · r reminders · q quit`; | |
| 515 | : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · q quit`; | |
| 500 | 516 | lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys)); |
| 501 | 517 | } |
| 502 | 518 | return lines; |
static/app.css +11
| @@ -827,6 +827,17 @@ textarea.input { | ||
| 827 | 827 | } |
| 828 | 828 | } |
| 829 | 829 | |
| 830 | .confirm summary { | |
| 831 | list-style: none; | |
| 832 | width: max-content; | |
| 833 | } | |
| 834 | .confirm summary::-webkit-details-marker { | |
| 835 | display: none; | |
| 836 | } | |
| 837 | .confirm[open] summary { | |
| 838 | margin-bottom: var(); | |
| 839 | } | |
| 840 | ||
| 830 | 841 | /* On paper: only the client timeline changes — black on white, no tools, no row split. */ |
| 831 | 842 | @media print { |
| 832 | 843 | .timeline-page { |
new above
offline