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

An inspection or final walkthrough carries a time and a place, shown on the deal page, the client timeline, the calendar file and its reminder draft, so the buyer knows where to be and when #185

Merged opened this

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

Merged

mason/deal-clock:mason/180-an-inspection-or-final-walkthrough-carri → main 3 commits fork 4 threads · 4 unresolved

  • Merged. mason/180-an-inspection-or-final-walkthrough-carri was merged into main as 802dfbb.

Review

Sign in to review this change.
26 files changed +581 −36
README.md +7 −1
@@ -95,7 +95,13 @@ no lender is asked for anything; "Cash" shows beside the side. On a deal's page
9595 you can add a party (**Use someone from your other deals** fills in a person
9696 you already have), fix a typo with Edit, add a date the contract added (an HOA
9797 review), waive a contingency the buyer gave up, change who owes a date, correct
98 the address, and set the closing time and place. A date on a weekend or
98 the address, and set the closing time and place. An Inspection or Final
99 walkthrough row has **Set time and place** too (a time on a quarter hour and
100 one line for where, either optional; clear both to remove them): the buyer
101 sees them beside the date on the client timeline, your calendar file gives
102 that event the time (in your Profile time zone) and location, and the
103 reminder says "10:00 am at 12 Elm St". In the terminal press `@` on the date;
104 over MCP use `set_appointment`; both show it on the date. A date on a weekend or
99105 federal holiday says so and offers **Move to** the next business day. For an
100106 addendum that moves several dates, **Amend the contract** takes one reason and
101107 sends each party one notice. Every date also takes a short working note only
contract/openapi.json +29 −2
@@ -2442,7 +2442,7 @@
24422442 },
24432443 "/api/deals/{id}/deadlines/{deadline}": {
24442444 "patch": {
2445 "summary": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. Send any of them.",
2445 "summary": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. time and place set when and where an inspection or a final walkthrough is: time as HH:MM on a quarter hour from 07:00 to 20:00 (the agent's local time), place one line of 1 to 200 characters; a field left out stays, blank or null clears it, and any other kind of date is refused (422 with field time). Drafts, the client timeline and the calendar file say them. Send any of them.",
24462446 "operationId": "patchApiDealsIdDeadlinesDeadline",
24472447 "parameters": [
24482448 {
@@ -2486,6 +2486,21 @@
24862486 "note": {
24872487 "type": "string",
24882488 "maxLength": 200
2489 },
2490 "time": {
2491 "type": [
2492 "string",
2493 "null"
2494 ],
2495 "pattern": "^(0[7-9]|1[0-9]):(00|15|30|45)$|^20:00$",
2496 "description": "HH:MM on a quarter hour from 07:00 to 20:00, local time; null clears it. Inspection and walkthrough only."
2497 },
2498 "place": {
2499 "type": [
2500 "string",
2501 "null"
2502 ],
2503 "maxLength": 200
24892504 }
24902505 }
24912506 }
@@ -2494,7 +2509,7 @@
24942509 },
24952510 "responses": {
24962511 "200": {
2497 "description": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. Send any of them.",
2512 "description": "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. time and place set when and where an inspection or a final walkthrough is: time as HH:MM on a quarter hour from 07:00 to 20:00 (the agent's local time), place one line of 1 to 200 characters; a field left out stays, blank or null clears it, and any other kind of date is refused (422 with field time). Drafts, the client timeline and the calendar file say them. Send any of them.",
24982513 "content": {
24992514 "application/json": {
25002515 "schema": {
@@ -2517,6 +2532,18 @@
25172532 },
25182533 "note": {
25192534 "type": "string"
2535 },
2536 "time": {
2537 "type": [
2538 "string",
2539 "null"
2540 ]
2541 },
2542 "place": {
2543 "type": [
2544 "string",
2545 "null"
2546 ]
25202547 }
25212548 },
25222549 "required": [
docs/TECHNICAL.md +9 −1
@@ -175,7 +175,7 @@ A deal is **closed** when its Closing date is marked done (derived, no column; `
175175
176176 **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.
177177
178 **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).
178 **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, time, place, moves[]` of `from, to, reason, by, at`) and `messages[]` (`date, to, to_role, moment, due, by, sent_at, subject, body`: the words as approved).
179179
180180 **The import.** `POST /deals/import` (Profile's "Bring deals back from a file": a multipart form with a `file` field) and `POST /api/deals/import` (the file as the JSON body) read a file `src/export.ts` wrote, through `src/import.ts`: `version` must be 1, at most 2000 deals, at most 5 MB (413 past it, counted by the bytes read). Every deal passes `plan` (the checks opening a deal uses) and every party `partyText`; any refusal is a 422 naming the deal's place (`Deal 3 of the file: …`) and nothing is written (one transaction). Each deal is created as the signed-in agent's own whatever author the file names, asking `permit` for `deal` create; a deal of theirs (or a sample) with the same address and contract date is skipped. Sent and declined messages are never re-created. Audited as `deal.import`, one row per deal, written inside the same transaction as the deals. The terminal's `O` reads a bare `*.json` file name from `FORGE_APP_DATA/exports/` (the newest when none is typed, never a path) through `importText` and the same `importDeals`, gated by `mayOpen`; it refuses a file over 5 MB. There is no MCP tool: `/mcp` reads at most 64 KB, and widening that door's cap for one tool was not worth it.
181181
@@ -361,6 +361,14 @@ The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or
361361 characters) are nullable columns, read and written as `closing_time` and `closing_place` by
362362 `GET`/`PATCH /api/deals/:id`, the `update_closing` tool and `POST /deals/:id/closing`; `src/closing.ts`
363363 validates and words them. The calendar file writes a timed closing as floating local time.
364
365 An inspection or walkthrough date has the same pair, `deadline.time` and `deadline.place` (nullable
366 columns, same rules, validated by `src/appointment.ts` through `closing.ts`). `setAppointment` in
367 `src/deals.ts` writes them (an `update` of the deal, audited as `date.appointment`); doors:
368 `POST /deadlines/:id/appointment` (the form), MCP `set_appointment`, terminal `@` on a date, and `time`/`place` on `PATCH /api/deals/:id/deadlines/:deadline`
369 (any other kind of date is 422 with `field: "time"`). They appear on the deal page, timeline, broker
370 file, export (`dates[].time`, `dates[].place`), the terminal's date row, MCP `client_timeline` (`when_and_where`), the calendar file (`LOCATION`; `DTSTART`/`DTEND` in UTC, the wall time taken in the Profile zone, unlike the closing's floating time) and
371 the reminder draft for that date.
364372 ### Side
365373
366374 `deal.side` (`buyer`, `listing` or `both`; migration default `buyer`) says which side the agent represents. `src/side.ts` holds the words, `sideOf` (nothing or blank is `buyer`, anything but the three words is refused with 422 and `field: "side"`) and `onSide` (the narrowing: a `both` deal is on each side). It is an `update` of the deal, audited as one: `PATCH /api/deals/:id` with `side`, `POST /deals/:id/side`, MCP `set_side`. `GET /` and `GET /week` take `?side=buyer|listing|all` beside `?q=`; `GET /api/deals` and `list_deals` take `side` too. `GET /reminders/today` does not narrow by side. No new contract cell.
src/appointment.terminal.test.ts added +52
@@ -0,0 +1,52 @@
1 /** Setting an inspection's time and place from the terminal, as the page does. */
2 import { expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { addDays, DEFAULT_ZONE, today } from "./dates.ts";
7 import { createDeal, getDeal } from "./deals.ts";
8 import { openDb } from "./db.ts";
9 import { terminal, type Terminal } from "./terminal.ts";
10 import type { Who } from "./who.ts";
11
12 const db = openDb(mkdtempSync(join(tmpdir(), "app-appt-terminal-")));
13 const alice: Who = { role: "user", id: "u1", name: "alice" };
14 const context = { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" } };
15 const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "");
16 const lines = (t: Terminal): string[] => t.screen().map(plain);
17 const under = (t: Terminal): string => lines(t).find((l) => l.startsWith("▸")) ?? "";
18 const press = (t: Terminal, ...chunks: string[]) => chunks.forEach((c) => t.press(c));
19 function goTo(t: Terminal, text: string): void {
20 t.press("d");
21 for (let i = 0; i < 200 && !under(t).includes(text); i++) t.press("j");
22 expect(under(t)).toContain(text);
23 }
24
25 const made = createDeal(db, alice, { openAnyway: true, address: "9 Elm St", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 45) });
26 if (!made.ok) throw new Error(made.message);
27 const id = made.value.id;
28 const inspection = () => getDeal(db, alice, { id }).ok ? (getDeal(db, alice, { id }) as any).value.deadlines.find((d: any) => d.kind === "inspection") : undefined;
29
30 test("@ on an inspection asks the time and place, shows them on the row, and blank clears", () => {
31 const t = terminal(db, alice, context);
32 goTo(t, "Inspection period ends — 9 Elm St");
33 press(t, "@", "10:00\r", "9 Elm St\r");
34 expect(inspection()).toMatchObject({ time: "10:00", place: "9 Elm St" });
35 expect(under(t)).toContain("10:00 am · 9 Elm St");
36 press(t, "@", "10:07\r", "\r");
37 expect(lines(t).join("\n")).toContain("quarter hour");
38 expect(inspection().time).toBe("10:00");
39 press(t, "@", "\r", "\r");
40 expect(inspection()).toMatchObject({ time: null, place: null });
41 expect(under(t)).not.toContain("am");
42 });
43
44 test("@ on a closing says only an inspection or a walkthrough has them, and a guest may not", () => {
45 const t = terminal(db, alice, context);
46 goTo(t, "Closing — 9 Elm St");
47 press(t, "@");
48 expect(lines(t).join("\n")).toContain("Only an inspection or a walkthrough has a time and place.");
49 const guest = terminal(db, { role: "anon" } as Who, context);
50 press(guest, "d", "@", "11:00\r", "\r");
51 expect(inspection().time).toBeNull();
52 });
src/appointment.test.ts added +208
@@ -0,0 +1,208 @@
1 /** An inspection's or walkthrough's time and place: validated at every door, shown, said in drafts, in the calendar file, exported, escaped. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { openDb } from "./db.ts";
7 import { createDeal, getDeal, setAppointment } from "./deals.ts";
8 import { exportDeals } from "./export.ts";
9 import { calendar } from "./ics.ts";
10 import { fileRecord } from "./pages/file.ts";
11 import { dealPage } from "./pages/deal.ts";
12 import { timelinePage } from "./pages/timeline.ts";
13 import { drafts } from "./reminders.ts";
14 import { forgetRationing } from "./security.ts";
15 import { serve } from "./server.ts";
16 import { sign, type Who } from "./who.ts";
17
18 const KEY = "a-key-only-the-forge-holds";
19 const dir = mkdtempSync(join(tmpdir(), "app-appointment-"));
20 const db = openDb(dir);
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
23 const base = `http://${server.hostname}:${server.port}`;
24 afterAll(() => server.stop(true));
25 beforeEach(forgetRationing);
26
27 const identity = `u1|alice|user|${Date.now() + 600_000}`;
28 const user = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
29 const patch = (deal: number, date: number, body: object) =>
30 fetch(`${base}/api/deals/${deal}/deadlines/${date}`, { method: "PATCH", headers: { ...user, "content-type": "application/json" }, body: JSON.stringify(body) });
31 const agent = { name: "Dana", brokerage: "Harbor", phone: "555", email: "[email protected]" };
32
33 let n = 0;
34 const open = () => {
35 const made = createDeal(db, alice, { address: `${++n} Appointment Way`, buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-21", openAnyway: true });
36 if (!made.ok) throw new Error(made.message);
37 return made.value;
38 };
39 const dateOf = (deal: { deadlines: readonly { id: number; kind: string }[] }, kind: string) => deal.deadlines.find((d) => d.kind === kind)!;
40 const fresh = (id: number) => {
41 const got = getDeal(db, alice, { id });
42 if (!got.ok) throw new Error(got.message);
43 return got.value;
44 };
45
46 test("set, kept when only one is sent, and cleared", () => {
47 const deal = open();
48 const insp = dateOf(deal, "inspection");
49 const a = setAppointment(db, alice, { id: insp.id, time: "10:00", place: "12 Elm St" });
50 expect(a.ok && [a.value.time, a.value.place]).toEqual(["10:00", "12 Elm St"]);
51 const b = setAppointment(db, alice, { id: insp.id, place: "14 Oak Ave" });
52 expect(b.ok && [b.value.time, b.value.place]).toEqual(["10:00", "14 Oak Ave"]);
53 const c = setAppointment(db, alice, { id: insp.id, time: "", place: "" });
54 expect(c.ok && [c.value.time, c.value.place]).toEqual([null, null]);
55 const walk = setAppointment(db, alice, { id: dateOf(deal, "walkthrough").id, time: "16:30" });
56 expect(walk.ok && walk.value.time).toBe("16:30");
57 });
58
59 test("a bad time, an over-long place, or a closing or appraisal date is refused, naming the field", () => {
60 const deal = open();
61 const insp = dateOf(deal, "inspection");
62 for (const time of ["25:00", "2pm", "14:10", "06:45"]) {
63 const r = setAppointment(db, alice, { id: insp.id, time });
64 expect(!r.ok && r.field).toBe("time");
65 }
66 const long = setAppointment(db, alice, { id: insp.id, place: "x".repeat(201) });
67 expect(!long.ok && long.field).toBe("place");
68 for (const kind of ["closing", "appraisal", "title"]) {
69 const r = setAppointment(db, alice, { id: dateOf(deal, kind).id, time: "10:00" });
70 expect(r.ok).toBe(false);
71 expect(!r.ok && r.field).toBe("time");
72 }
73 expect(fresh(deal.id).deadlines.every((d) => d.time === null && d.place === null)).toBe(true);
74 });
75
76 test("the API takes time and place and describes them; other kinds are 422 naming time", async () => {
77 const deal = open();
78 const insp = dateOf(deal, "inspection");
79 const ok = await patch(deal.id, insp.id, { time: "10:00", place: "12 Elm St" });
80 expect(ok.status).toBe(200);
81 expect(await ok.json()).toMatchObject({ time: "10:00", place: "12 Elm St" });
82 expect((await patch(deal.id, insp.id, { time: "10:00", lead_days: 5 })).status).toBe(200);
83 expect(fresh(deal.id).deadlines.find((d) => d.id === insp.id)).toMatchObject({ time: "10:00", lead_days: 5 });
84 const bad = await patch(deal.id, insp.id, { time: "99:00" });
85 expect(bad.status).toBe(422);
86 expect(((await bad.json()) as any).field).toBe("time");
87 const closing = await patch(deal.id, dateOf(deal, "closing").id, { time: "10:00" });
88 expect(closing.status).toBe(422);
89 expect(((await closing.json()) as any).field).toBe("time");
90 const cleared = await patch(deal.id, insp.id, { time: null, place: null });
91 expect(await cleared.json()).toMatchObject({ time: null, place: null });
92 const spec = JSON.stringify(await (await fetch(`${base}/openapi.json`, { headers: user })).json());
93 expect(spec).toContain("when and where an inspection or a final walkthrough is");
94 });
95
96 test("the deal page form sets them, same-origin only, and a refusal re-renders with the text kept", async () => {
97 const deal = open();
98 const insp = dateOf(deal, "inspection");
99 const post = (body: Record<string, string>, headers: Record<string, string> = {}) =>
100 fetch(`${base}/deadlines/${insp.id}/appointment`, {
101 method: "POST",
102 body: Object.entries({ to: `/deals/${deal.id}`, ...body }).reduce((f, [k, v]) => (f.set(k, v), f), new FormData()),
103 headers: { ...user, ...headers },
104 redirect: "manual",
105 });
106 expect((await post({ time: "10:00", place: "12 Elm St" })).status).toBe(303);
107 expect(fresh(deal.id).deadlines.find((d) => d.id === insp.id)).toMatchObject({ time: "10:00", place: "12 Elm St" });
108 const refused = await post({ time: "10:07", place: "Typed <b>place</b>" });
109 expect(refused.status).toBe(422);
110 const page = await refused.text();
111 expect(page).toContain('aria-invalid="true"');
112 expect(page).toContain('value="Typed &lt;b&gt;place&lt;/b&gt;"');
113 const foreign = await post({ time: "11:00" }, { origin: "https://evil.example", "sec-fetch-site": "cross-site" });
114 expect(foreign.status).toBeGreaterThanOrEqual(400);
115 expect(fresh(deal.id).deadlines.find((d) => d.id === insp.id)!.time).toBe("10:00");
116 expect((await post({ time: "", place: "" })).status).toBe(303);
117 expect(fresh(deal.id).deadlines.find((d) => d.id === insp.id)).toMatchObject({ time: null, place: null });
118 });
119
120 test("shown on the deal page, the timeline and the file, escaped", () => {
121 const deal = open();
122 setAppointment(db, alice, { id: dateOf(deal, "inspection").id, time: "10:00", place: "<script>alert(1)</script>" });
123 setAppointment(db, alice, { id: dateOf(deal, "walkthrough").id, time: "16:30" });
124 const now = fresh(deal.id);
125 for (const html of [dealPage({ who: alice, deal: now, on: "2026-10-05" }), timelinePage({ who: alice, deal: now, on: "2026-10-05" })]) {
126 expect(html).toContain("10:00 am · &lt;script&gt;alert(1)&lt;/script&gt;");
127 expect(html).not.toContain("<script>alert(1)");
128 expect(html).toContain("4:30 pm");
129 }
130 expect(fileRecord(now).dates.map((d) => d.line).join("\n")).toContain("10:00 am · <script>alert(1)</script>");
131 expect(exportDeals([now], new Date("2026-10-05T00:00:00Z")).deals[0]).toMatchObject({ dates: expect.arrayContaining([expect.objectContaining({ kind: "inspection", time: "10:00", place: "<script>alert(1)</script>" })]) });
132 });
133
134 test("the calendar file carries the time in UTC from the Profile zone, with LOCATION", () => {
135 const deal = open();
136 setAppointment(db, alice, { id: dateOf(deal, "inspection").id, time: "10:00", place: "12 Elm St, Unit 2" });
137 const now = fresh(deal.id);
138 const insp = dateOf(now, "inspection") as { due: string };
139 const ics = calendar(now, "x.example", new Date("2026-10-02T00:00:00Z"), agent);
140 const day = insp.due.replaceAll("-", "");
141 // The deal's zone is the Profile's (America/New_York by default): 10:00 there on Oct 12 is 14:00 UTC.
142 expect(ics).toContain(`DTSTART:${day}T140000Z`);
143 expect(ics).toContain(`DTEND:${day}T150000Z`);
144 expect(ics).toContain("LOCATION:12 Elm St\\, Unit 2");
145 const walk = dateOf(now, "walkthrough") as { due: string };
146 expect(ics).toContain(`DTSTART;VALUE=DATE:${walk.due.replaceAll("-", "")}`);
147 });
148
149 test("the reminder draft says the time and place", () => {
150 const deal = open();
151 setAppointment(db, alice, { id: dateOf(deal, "inspection").id, time: "10:00", place: "12 Elm St" });
152 setAppointment(db, alice, { id: dateOf(deal, "walkthrough").id, place: "the property" });
153 const now = fresh(deal.id);
154 const bodies = (label: string) => drafts(now, agent).filter((r) => r.label === label && r.moment !== "late").map((r) => r.body);
155 expect(bodies("Inspection period ends").length).toBeGreaterThan(0);
156 for (const b of bodies("Inspection period ends")) expect(b).toContain(", 10:00 am at 12 Elm St");
157 for (const b of bodies("Final walkthrough")) expect(b).toContain(" at the property");
158 const plain = open();
159 for (const r of drafts(plain, agent).filter((r) => r.label === "Inspection period ends")) expect(r.body).not.toContain(" am");
160 });
161
162 test("a refused time leaves the note and lead of the same PATCH untouched", async () => {
163 const deal = open();
164 const insp = dateOf(deal, "inspection");
165 const before = fresh(deal.id).deadlines.find((d) => d.id === insp.id)!;
166 const refused = await patch(deal.id, insp.id, { note: "Inspector confirmed", lead_days: 9, time: "10:07" });
167 expect(refused.status).toBe(422);
168 const after = fresh(deal.id).deadlines.find((d) => d.id === insp.id)!;
169 expect([after.note, after.lead_days, after.time]).toEqual([before.note, before.lead_days, null]);
170 const kind = await patch(deal.id, dateOf(deal, "closing").id, { note: "kept out", place: "Title office" });
171 expect(kind.status).toBe(422);
172 expect(fresh(deal.id).deadlines.find((d) => d.kind === "closing")!.note).toBe("");
173 expect((await patch(deal.id, insp.id, { note: "Inspector confirmed", time: "10:00" })).status).toBe(200);
174 expect(fresh(deal.id).deadlines.find((d) => d.id === insp.id)).toMatchObject({ note: "Inspector confirmed", time: "10:00" });
175 });
176
177 test("the MCP tool set_appointment sets, keeps, clears and refuses, and the timeline tool says it", async () => {
178 const deal = open();
179 const insp = dateOf(deal, "inspection");
180 const call = async (name: string, args: object) =>
181 (await (await fetch(`${base}/mcp`, { method: "POST", headers: { ...user, "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) })).json()) as any;
182 const set = await call("set_appointment", { id: insp.id, time: "10:00", place: "12 Elm St" });
183 expect(JSON.parse(set.result.content[0].text)).toMatchObject({ time: "10:00", place: "12 Elm St" });
184 const kept = await call("set_appointment", { id: insp.id, place: null });
185 expect(JSON.parse(kept.result.content[0].text)).toMatchObject({ time: "10:00", place: null });
186 expect((await call("set_appointment", { id: insp.id, time: "8am" })).result.isError).toBe(true);
187 expect((await call("set_appointment", { id: insp.id })).result.isError).toBe(true);
188 expect((await call("set_appointment", { id: dateOf(deal, "closing").id, time: "10:00" })).result.isError).toBe(true);
189 const tl = JSON.parse((await call("client_timeline", { id: deal.id })).result.content[0].text);
190 expect(tl.dates.find((d: any) => d.label === "Inspection period ends").when_and_where).toBe("10:00 am");
191 });
192
193 test("the calendar file for an agent in a western zone is UTC from the Profile zone, so the day does not shift", () => {
194 const deal = open();
195 setAppointment(db, alice, { id: dateOf(deal, "inspection").id, time: "10:00", place: "12 Elm St" });
196 const insp = fresh(deal.id);
197 const due = insp.deadlines.find((d) => d.kind === "inspection")!.due.replaceAll("-", "");
198 const at = (zone: string) => calendar({ ...insp, zone }, "x.example", new Date("2026-10-02T00:00:00Z"), agent);
199 // Oct 12, 2026 is in daylight time: New York is UTC-4, Los Angeles UTC-7, Honolulu UTC-10.
200 expect(at("America/New_York")).toContain(`DTSTART:${due}T140000Z`);
201 expect(at("America/Los_Angeles")).toContain(`DTSTART:${due}T170000Z`);
202 expect(at("America/New_York")).toContain(`DTEND:${due}T150000Z`);
203 // 4:30 pm in Honolulu is 02:30 UTC the next day, which is still that same local day.
204 setAppointment(db, alice, { id: dateOf(deal, "inspection").id, time: "16:30" });
205 const late = fresh(deal.id);
206 const next = (d: string) => new Date(Date.parse(`${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10).replaceAll("-", "");
207 expect(calendar({ ...late, zone: "Pacific/Honolulu" }, "x.example", new Date("2026-10-02T00:00:00Z"))).toContain(`DTSTART:${next(due)}T023000Z`);
208 });
src/appointment.ts added +33
@@ -0,0 +1,33 @@
1 /**
2 * A time and place for an inspection or a final walkthrough: appointments the
3 * buyer has to be at, like the closing. The rules are the closing's (a quarter
4 * hour from 07:00 to 20:00, one line of up to 200 characters) and so are the
5 * words, said by `closing.ts`; this module only says which dates take them.
6 * Pure functions on plain data.
7 */
8
9 import { clock12, closingAfterDate, closingPlace, closingTime } from "./closing.ts";
10 import type { Result } from "./result.ts";
11
12 /** The kinds of date that are appointments. */
13 export const APPOINTMENT_KINDS: readonly string[] = ["inspection", "walkthrough"];
14
15 export const isAppointment = (kind: string): boolean => APPOINTMENT_KINDS.includes(kind);
16
17 export const appointmentTime = (value: unknown): Result<string | null> => closingTime(value, "time", "time");
18 export const appointmentPlace = (value: unknown): Result<string | null> => closingPlace(value, "place", "place");
19
20 interface Dated {
21 readonly kind: string;
22 readonly time: string | null;
23 readonly place: string | null;
24 }
25
26 const asClosing = (d: Dated) => ({ closing_time: isAppointment(d.kind) ? d.time : null, closing_place: isAppointment(d.kind) ? d.place : null });
27
28 /** How a draft says it after the date: ", 10:00 am at 12 Elm St" or " at 10:00 am"; "" when unset. */
29 export const appointmentAfterDate = (d: Dated): string => closingAfterDate(asClosing(d));
30

appointmentWhere is never used. Remove it (dead code).

31 /** "10:00 am · 12 Elm St" for a page; "" when neither is set. */
32 export const appointmentLine = (d: Dated): string =>
33 [d.time === null || !isAppointment(d.kind) ? "" : clock12(d.time), isAppointment(d.kind) ? (d.place ?? "") : ""].filter((p) => p !== "").join(" · ");
src/closing.ts +5 −5
@@ -18,23 +18,23 @@ export function clock12(time: string): string {
1818 }
1919
2020 /** The closing time from a form, a JSON body or a prompt: HH:MM on a quarter hour, 07:00 to 20:00. Blank or null is none. */
21 export function closingTime(value: unknown): Result<string | null> {
21 export function closingTime(value: unknown, field = "closing_time", noun = "closing time"): Result<string | null> {
2222 if (value === undefined || value === null) return ok(null);
2323 const text = typeof value === "string" ? value.trim() : undefined;
2424 if (text === "") return ok(null);
2525 if (text === undefined || !TIME.test(text) || text < "07:00" || text > "20:00")
26 return fail("invalid", "The closing time is HH:MM on a quarter hour, from 07:00 to 20:00.", "closing_time");
26 return fail("invalid", `The ${noun} is HH:MM on a quarter hour, from 07:00 to 20:00.`, field);
2727 return ok(text);
2828 }
2929
3030 /** The closing place from a form, a JSON body or a prompt: one line, 1 to 200 characters. Blank or null is none. */
31 export function closingPlace(value: unknown): Result<string | null> {
31 export function closingPlace(value: unknown, field = "closing_place", noun = "closing place"): Result<string | null> {
3232 if (value === undefined || value === null) return ok(null);
33 if (typeof value !== "string") return fail("invalid", "The closing place is 1 to 200 characters.", "closing_place");
33 if (typeof value !== "string") return fail("invalid", `The ${noun} is 1 to 200 characters.`, field);
3434 // Control characters have no place in a field: they would reach a calendar file or a terminal.
3535 const text = value.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
3636 if (text === "") return ok(null);
37 if (text.length > 200) return fail("invalid", "The closing place is 1 to 200 characters.", "closing_place");
37 if (text.length > 200) return fail("invalid", `The ${noun} is 1 to 200 characters.`, field);
3838 return ok(text);
3939 }
4040
src/contract.test.ts +17
@@ -12,6 +12,7 @@ import { getAudit, listAudit, mayRestore, restoreSamples } from "./actions.ts";
1212 import { record } from "./audit.ts";
1313 import {
1414 addDeadline,
15 setAppointment,
1516 createDeal,
1617 deleteDeal,
1718 getDeal,
@@ -281,3 +282,19 @@ test("bringing deals back, at POST /api/deals/import and POST /deals/import, ans
281282 }
282283 }
283284 });
285
286 test("an inspection's time and place, at POST /deadlines/:id/appointment, PATCH /api/deals/:id/deadlines/:deadline and set_appointment, answer as deal update says, as every identity", () => {
287 expect(routes.some((r) => r.method === "POST" && r.path === "/deadlines/:id/appointment")).toBe(true);
288 expect(routes.some((r) => r.method === "PATCH" && r.path === "/api/deals/:id/deadlines/:deadline")).toBe(true);
289 for (const identity of identities(contract)) {
290 const who = whoIs(identity);
291 const { mine, theirs } = actingAs(contract, identity);
292 for (const row of [mine, theirs]) {
293 const id = dealBy(String(row["author_id"]));
294 const date = db.query<{ id: number }, [number]>("INSERT INTO deadline (deal_id, kind, label, due, owes) VALUES (?1, 'inspection', 'Inspection', '2026-11-01', 'buyer') RETURNING id").get(id)!.id;
295 const said = `appointment as ${identity} on ${String(row["author_id"])}`;
296 const allowed = permit(who, "deal", "update", row) === "yes";
297 expect([said, setAppointment(db, who, { id: date, time: "10:00", place: "12 Elm St" }).ok]).toEqual([said, allowed]);
298 }
299 }
300 });
src/db.ts +3
@@ -569,6 +569,9 @@ export const migrations: string[] = [
569569 DROP TABLE reminder_hold;
570570 ALTER TABLE reminder_hold_new RENAME TO reminder_hold;
571571 CREATE INDEX reminder_hold_deal ON reminder_hold (deal_id)`,
572 // An inspection or a final walkthrough is an appointment: an optional time and place, like the closing's.
573 `ALTER TABLE deadline ADD COLUMN time TEXT CHECK (time IS NULL OR time GLOB '[0-2][0-9]:[0-5][0-9]')`,
574 `ALTER TABLE deadline ADD COLUMN place TEXT CHECK (place IS NULL OR length(place) BETWEEN 1 AND 200)`,
572575 ];
573576
574577 export function openDb(dir = dataDir): Database {
src/deals.ts +27
@@ -29,6 +29,7 @@ import {
2929 import { LENGTH_MAX, standard, validEmail, validPhone } from "./env.ts";
3030 import { agentOf, zoneOf } from "./profile.ts";
3131 import { emit } from "./live.ts";
32 import { appointmentPlace, appointmentTime, isAppointment } from "./appointment.ts";
3233 import { closingPlace, closingTime } from "./closing.ts";
3334 import { amount, rate } from "./money.ts";
3435 import { SIDE_REFUSAL, sideOf, type Side } from "./side.ts";
@@ -169,6 +170,9 @@ export interface Deadline {
169170 readonly note: string;
170171 /** Days before it is due that its first reminder goes out. */
171172 readonly lead_days: number;
173 /** An inspection's or walkthrough's time (HH:MM) and place; null while unset, and always null for any other kind. */
174 readonly time: string | null;
175 readonly place: string | null;
172176 }
173177 export interface DeadlineView extends Omit<Deadline, "owes_from" | "owes_by" | "owes_on"> {
174178 /** The day it was marked done, by the app's own calendar (`today()`); null while open or after a reopen. */
@@ -948,6 +952,29 @@ export function setReminderLead(
948952 return within(db, who, "date.lead", dealId, ok(reread(db, input.id)));
949953 }
950954
955 /**
956 * Set the time and place of an inspection or a walkthrough: a field left out
957 * stays, blank or null clears it. Any other kind of date is refused, naming time.
958 */
959 export function setAppointment(
960 db: Database,
961 who: Who,
962 input: { id: number; dealId?: number; time?: unknown; place?: unknown },
963 ): Result<Deadline> {
964 const WHAT = "date.appointment";
965 const { dealId, found } = deadlineFor(db, who, input.id, input.dealId);
966 if (!found.ok) return within(db, who, WHAT, dealId, found);
967 const { deadline } = found.value;
968 if (!isAppointment(deadline.kind))
969 return within(db, who, WHAT, dealId, fail("invalid", "Only an inspection or a walkthrough has a time and place.", "time"));
970 const time = input.time === undefined ? ok(deadline.time) : appointmentTime(input.time);
971 if (!time.ok) return within(db, who, WHAT, dealId, time);
972 const place = input.place === undefined ? ok(deadline.place) : appointmentPlace(input.place);
973 if (!place.ok) return within(db, who, WHAT, dealId, place);
974 db.query("UPDATE deadline SET time = ?1, place = ?2 WHERE id = ?3").run(time.value, place.value, deadline.id);
975 return within(db, who, WHAT, dealId, ok(reread(db, deadline.id)));
976 }
977
951978 /** Move one date, and only that one; the reason is kept beside it. */
952979 export function moveDeadline(
953980 db: Database,
src/export.ts +2
@@ -52,6 +52,8 @@ const dealOf = (deal: DealView): Record<string, unknown> => ({
5252 waived_by: d.waived_by,
5353 owed_by: d.owes,
5454 note: d.note,
55 time: d.time,
56 place: d.place,
5557 moves: d.moves.map((m) => ({ from: m.from_due, to: m.to_due, reason: m.reason, by: m.by_name, at: m.at })),
5658 })),
5759 messages: deal.sent.map((m) => ({
src/ics.ts +30 −4
@@ -5,6 +5,7 @@
55 * agent's own calendar keeps the clock too. Pure text out.
66 */
77
8 import { isAppointment } from "./appointment.ts";
89 import { addDays } from "./dates.ts";
910 import { isOpen, PARTY_LABEL } from "./deadlines.ts";
1011 import type { DealView } from "./deals.ts";
@@ -46,6 +47,29 @@ function endOfHour(date: string, time: string): string[] {
4647 return [`DTEND:${compact(day)}T${String(h % 24).padStart(2, "0")}${time.slice(3)}00`];
4748 }
4849
50 /** The instant a wall-clock `date` and `time` are in the IANA zone `zone`, as ms since the epoch; null for a zone this runtime does not know. */
51 function instantIn(date: string, time: string, zone: string): number | null {
52 try {
53 const wall = Date.parse(`${date}T${time}:00Z`);
54 const parts = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" });
55 const offset = (at: number): number => {
56 const p = Object.fromEntries(parts.formatToParts(new Date(at)).map((x) => [x.type, Number(x.value)]));
57 return Date.UTC(p["year"]!, p["month"]! - 1, p["day"]!, p["hour"]!, p["minute"]!, p["second"]!) - at;
58 };
59 // Twice, so a time near a change of clocks lands on the right side of it.
60 return wall - offset(wall - offset(wall));
61 } catch {
62 return null;
63 }
64 }
outdated

The issue asks for the time in the agent's Profile zone; this emits floating time. Use the zone or get the issue amended.

65
66 /** DTSTART and DTEND for an hour at `time` in the agent's zone, in UTC so no calendar reads the day in another zone; floating local time only when the zone is unknown. */
67 function appointmentSpan(date: string, time: string, zone: string): string[] {
68 const at = instantIn(date, time, zone);
69 if (at === null) return [`DTSTART:${compact(date)}T${time.replace(":", "")}00`, ...endOfHour(date, time)];
70 return [at, at + 3_600_000].map((ms, i) => `${i === 0 ? "DTSTART" : "DTEND"}:${stampOf(new Date(ms))}`);
71 }
72
4973 /** An alarm trigger, relative to the start, that fires at 9 a.m. the day of. */
5074 function nineAm(time: string): string {
5175 const delta = 540 - (Number(time.slice(0, 2)) * 60 + Number(time.slice(3)));
@@ -59,16 +83,18 @@ function events(deal: DealView, host: string, now: string, openOnly: boolean): s
5983 if (openOnly && !isOpen(d)) continue;
6084 const owner = deal.parties.find((p) => p.role === d.owes);
6185 const who = owner === undefined ? PARTY_LABEL[d.owes] : `${owner.name} (${PARTY_LABEL[d.owes]})`;
62 // Closing with a time is a timed hour in floating local time (no zone invented); otherwise all day.
63 const timed = d.kind === "closing" && deal.closing_time !== null ? deal.closing_time : null;
64 const place = d.kind === "closing" && deal.closing_place !== null ? deal.closing_place : null;
86 // Closing with a time is a timed hour in floating local time (no zone invented); an inspection or walkthrough with a time is one in UTC, from the agent's Profile zone; otherwise all day.
87 const timed = d.kind === "closing" ? deal.closing_time : isAppointment(d.kind) ? d.time : null;
88 const place = d.kind === "closing" ? deal.closing_place : isAppointment(d.kind) ? d.place : null;
6589 lines.push(
6690 "BEGIN:VEVENT",
6791 `UID:deadline-${d.id}@${host}`,
6892 `DTSTAMP:${now}`,
6993 ...(timed === null
7094 ? [`DTSTART;VALUE=DATE:${compact(d.due)}`, `DTEND;VALUE=DATE:${compact(addDays(d.due, 1))}`]
71 : [`DTSTART:${compact(d.due)}T${timed.replace(":", "")}00`, ...endOfHour(d.due, timed)]),
95 : d.kind === "closing"
96 ? [`DTSTART:${compact(d.due)}T${timed.replace(":", "")}00`, ...endOfHour(d.due, timed)]
97 : appointmentSpan(d.due, timed, deal.zone)),
7298 ...(place === null ? [] : [`LOCATION:${icsText(place)}`]),
7399 `SUMMARY:${icsText(`${d.waived_at !== null ? "Waived: " : d.done_at === null ? "" : "Done: "}${d.label} — ${deal.address}`)}`,
74100 `DESCRIPTION:${icsText(`${who} owes: ${d.what || d.label}`)}`,
src/import.test.ts +19 −1
@@ -4,7 +4,7 @@ import { mkdtempSync, writeFileSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { openDb } from "./db.ts";
7 import { getDeal, insertDeal, listDeals, markFellThrough, moveDeadline, plan, sendReminder, setNote, type NewDeal } from "./deals.ts";
7 import { getDeal, insertDeal, listDeals, markFellThrough, moveDeadline, plan, sendReminder, setAppointment, setNote, type NewDeal } from "./deals.ts";
88 import { exportDeals } from "./export.ts";
99 import { forgetRationing } from "./security.ts";
1010 import { serve } from "./server.ts";
@@ -200,3 +200,21 @@ test("the terminal's O brings deals back from the exports folder, gated like the
200200 expect(must(listDeals(db, hal)).filter((d) => d.author_id === "").length).toBe(0);
201201 db.close();
202202 });
203
204 test("an inspection's time and place survive export and import; a bad one refuses the file", () => {
205 const from = openDb(mkdtempSync(join(tmpdir(), "app-import-appt-from-")));
206 const id = open(from, alice as never, { ...base0, address: "5 Appointment Way" });
207 const date = must(getDeal(from, alice, { id })).deadlines.find((d) => d.kind === "inspection")!;
208 must(setAppointment(from, alice, { id: date.id, time: "10:00", place: "12 Elm St" }));
209 const file = exportDeals(must(listDeals(from, alice)), new Date("2026-10-02T00:00:00Z"));
210 const into = openDb(mkdtempSync(join(tmpdir(), "app-import-appt-into-")));
211 const carol: Who = { role: "user", id: "u3", name: "carol" };
212 must(importDeals(into, carol, JSON.parse(JSON.stringify(file))));
213 const back = must(listDeals(into, carol)).find((d) => d.address === "5 Appointment Way")!;
214 expect(back.deadlines.find((d) => d.kind === "inspection")).toMatchObject({ time: "10:00", place: "12 Elm St" });
215 expect(back.deadlines.find((d) => d.kind === "closing")).toMatchObject({ time: null, place: null });
216 const bad = JSON.parse(JSON.stringify(file));
217 bad.deals[0].dates.find((d: any) => d.kind === "inspection").time = "10:07";
218 const refused = importDeals(openDb(mkdtempSync(join(tmpdir(), "app-import-appt-bad-"))), carol, bad);
219 expect(refused.ok).toBe(false);
220 });
src/import.ts +13 −4
@@ -11,6 +11,7 @@ import type { Database } from "bun:sqlite";
1111 import { permit } from "./contract.ts";
1212 import { isDate } from "./dates.ts";
1313 import { KIND, KINDS, isPartyRole, leadOf, leadOfLabel, type Kind, type PartyRole } from "./deadlines.ts";
14 import { appointmentPlace, appointmentTime, isAppointment } from "./appointment.ts";
1415 import { closingPlace, closingTime } from "./closing.ts";
1516 import { NOTE_MAX, REASON_MAX, insertDeal, line, partyText, plan, sameAddress, type NewDeal, type Plan } from "./deals.ts";
1617 import { EXPORT_MAX, EXPORT_VERSION } from "./export.ts";
@@ -37,6 +38,8 @@ interface DateIn {
3738 due: string;
3839 owes: PartyRole;
3940 note: string;
41 time: string | null;
42 place: string | null;
4043 done: string | null;
4144 waived: string | null;
4245 waivedBy: string | null;
@@ -103,6 +106,12 @@ function readDeal(raw: unknown, n: number): Result<DealIn> {
103106 if (!isPartyRole(owes)) return refuse(n, `date ${i + 1} (${label}) says no valid party owes it.`, `${at}.owed_by`);
104107 const note = o.note === undefined || o.note === null || o.note === "" ? "" : line(o.note, 1, NOTE_MAX);
105108 if (note === undefined) return refuse(n, `the note on date ${i + 1} is up to ${NOTE_MAX} characters.`, `${at}.note`);
109 // An inspection's or walkthrough's time and place, as the export wrote them; any other kind carries none.
110 const appointment = isAppointment(o.kind as string);
111 const time = appointment ? appointmentTime(o.time) : ok(null);
112 if (!time.ok) return refuse(n, `the time on date ${i + 1} (${label}) is HH:MM on a quarter hour, 07:00 to 20:00.`, `${at}.time`);
113 const place = appointment ? appointmentPlace(o.place) : ok(null);
114 if (!place.ok) return refuse(n, `the place on date ${i + 1} (${label}) is 1 to 200 characters.`, `${at}.place`);
106115 const done = stamp(o.done);
107116 const waived = stamp(o.waived);
108117 if (done === undefined) return refuse(n, `date ${i + 1} (${label}) has a bad done time.`, `${at}.done`);
@@ -121,7 +130,7 @@ function readDeal(raw: unknown, n: number): Result<DealIn> {
121130 return refuse(n, `move ${j + 1} of date ${i + 1} (${label}) is not a from and to date, a reason and who moved it.`, `${at}.moves[${j}]`);
122131 moves.push({ from: m.from, to: m.to, reason, by, at: when });
123132 }
124 dates.push({ label, kind: o.kind as Kind, due: o.due, owes, note, done, waived, waivedBy, moves });
133 dates.push({ label, kind: o.kind as Kind, due: o.due, owes, note, time: time.value, place: place.value, done, waived, waivedBy, moves });
125134 }
126135
127136 const closing = dates.find((x) => x.kind === "closing");
@@ -214,10 +223,10 @@ function write(db: Database, who: Who & { role: "user" | "admin" }, deals: reado
214223 const lead = x.kind === "custom" ? leadOfLabel(x.label) : leadOf(x.kind);
215224 const what = x.kind === "custom" ? "" : KIND[x.kind].what;
216225 const row = db
217 .query<{ id: number }, [number, string, string, string, string, string, string, string | null, string | null, string | null, number]>(
218 "INSERT INTO deadline (deal_id, kind, label, due, owes, what, note, done_at, waived_at, waived_by, lead_days) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) RETURNING id",
226 .query<{ id: number }, [number, string, string, string, string, string, string, string | null, string | null, string | null, number, string | null, string | null]>(
227 "INSERT INTO deadline (deal_id, kind, label, due, owes, what, note, done_at, waived_at, waived_by, lead_days, time, place) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13) RETURNING id",
219228 )
220 .get(deal.id, x.kind, x.label, x.due, x.owes, what, x.note, x.done, x.waived, x.waivedBy, lead)!;
229 .get(deal.id, x.kind, x.label, x.due, x.owes, what, x.note, x.done, x.waived, x.waivedBy, lead, x.time, x.place)!;
221230 for (const m of x.moves)
222231 db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, at) VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))").run(row.id, m.from, m.to, m.reason, m.by, m.at);
223232 }
src/mcp.ts +19 −1
@@ -33,6 +33,7 @@ import {
3333 sendStatusUpdate,
3434 statusUpdates,
3535 setNote,
36 setAppointment,
3637 setReminderLead,
3738 setOwes,
3839 declineReminder,
@@ -99,7 +100,7 @@ export const tools: readonly Tool[] = [
99100 run: (db, who, args) => {
100101 const got = getDeal(db, who, { id: Number(args.id) });
101102 if (!got.ok) return got;
102 const dates = timelineRows(got.value, today(zoneOf(db))).map(({ label, due, role, name, status, todo }) => ({ label, due, owed_by: { role, name: name ?? null }, status, todo: todo.map((g) => (g.label === "" ? g.line : `${g.label}: ${g.line}`)) }));
103 const dates = timelineRows(got.value, today(zoneOf(db))).map(({ label, due, where, role, name, status, todo }) => ({ label, due, ...(where === "" ? {} : { when_and_where: where }), owed_by: { role, name: name ?? null }, status, todo: todo.map((g) => (g.label === "" ? g.line : `${g.label}: ${g.line}`)) }));
103104 return { ok: true, value: { address: got.value.address, sale_price: got.value.sale_price, earnest_amount: got.value.earnest_amount, closing_time: got.value.closing_time, closing_place: got.value.closing_place, agent: agentOf(db), dates } };
104105 },
105106 },
@@ -211,6 +212,23 @@ export const tools: readonly Tool[] = [
211212 },
212213 run: (db, who, args) => setNote(db, who, { id: Number(args.id), note: args.note }),
213214 },
215 {
216 name: "set_appointment",
217 description: "Set when and where an inspection or a final walkthrough is: time as HH:MM on a quarter hour from 07:00 to 20:00 (the agent's local time) and place of 1 to 200 characters. A field left out stays as it is; null clears it. Any other kind of date is refused. Drafts, the client timeline and the calendar file say them; reminders already sent keep their words.",
218 inputSchema: {
219 type: "object",
220 properties: {
221 id: { type: "integer" },
222 time: { type: ["string", "null"], pattern: "^(0[7-9]|1[0-9]):(00|15|30|45)$|^20:00$" },
223 place: { type: ["string", "null"], minLength: 1, maxLength: 200 },
224 },
225 required: ["id"],
226 },
227 run: (db, who, args) => {
228 if (args.time === undefined && args.place === undefined) return fail("invalid", "Give a time, a place, or null to clear one.");
229 return setAppointment(db, who, { id: Number(args.id), time: args.time, place: args.place });
230 },
231 },
214232 {
215233 name: "set_reminder_lead",
216234 description: "Set how many days before it is due a date's first reminder goes out (a whole number, 1 to 30). An unsent draft is drafted again for the new day; a sent one keeps its words.",
src/migrations.pin.json +3 −1
@@ -55,5 +55,7 @@
5555 "166c5e5ec18272d556b87786396c5c3a17da8b56185643e8efeeb83742cc2b5b",
5656 "3fbd9e1851d9bc86a3a4c5adfc9f2300712c450b66a87d253cfcb91586cbbe25",
5757 "7e011fb3dab2123101aa981ef9050d8f8d2c34fb3ba137ecc832f86d464b98a2",
58 "429a2adfb36ff61def2d1979556a9db87f4758663fa9c56b97e599b3bc13b773"
58 "429a2adfb36ff61def2d1979556a9db87f4758663fa9c56b97e599b3bc13b773",
59 "c5df0d263e04d4e07f9df383beb57f033966af540bb228d9bbbd7b57f3620408",
60 "4a52d9de76ede6d34d831d9bc6fc1d3d3a501a5d3652bf63695a9de49f2a7d39"
5961 ]
src/migrations.test.ts +1 −1
@@ -13,7 +13,7 @@ test("every migration is pinned by position; a pull may only append", () => {
1313 });
1414
1515 test("a database made before the Profile line gets the column and reads the agent", () => {
16 const before = migrations.filter((m) => !/profile ADD COLUMN line|commission_rate|profile ADD COLUMN zone|ADD COLUMN cash|'anniversary'/.test(m));
16 const before = migrations.filter((m) => !/profile ADD COLUMN line|commission_rate|profile ADD COLUMN zone|ADD COLUMN cash|'anniversary'|deadline ADD COLUMN (time|place)/.test(m));
1717 const db = new Database(":memory:");
1818 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
1919 before.forEach((sql, i) => {
src/pages/appointment.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * An inspection's or walkthrough's time and place on the deal page: the line
3 * that says them and the small form that sets them. Escaped here, once.
4 */
5
6 import { appointmentLine, isAppointment } from "../appointment.ts";
7 import type { DeadlineView } from "../deals.ts";
8 import { escape } from "../http.ts";
9
10 /** What was typed into an appointment form and why it was refused, to show beside the field. */
11 export interface AppointmentProblem {
12 readonly id: number;
13 readonly values: { readonly time: string; readonly place: string };
14 readonly field: string | undefined;
15 readonly message: string;
16 }
17
18 /** "10:00 am · 12 Elm St" under the date; nothing when unset or when the date is no appointment. */
19 export const appointmentText = (d: DeadlineView): string =>
20 appointmentLine(d) === "" ? "" : `<p class="small appointment"><b>${escape(appointmentLine(d))}</b></p>`;
21
22 /** "Set time and place" for an inspection or a walkthrough; the form stays open, with the agent's text, when it was refused. */
23 export function appointmentForm(d: DeadlineView, to: string, problem: AppointmentProblem | undefined): string {
24 if (!isAppointment(d.kind)) return "";
25 const mine = problem?.id === d.id ? problem : undefined;
26 const bad = (name: string): string => (mine?.field === name ? ` aria-invalid="true" aria-describedby="${name}-why-${d.id}"` : "");
27 const why = (name: string): string => (mine?.field === name ? `<span class="field-error" id="${name}-why-${d.id}" role="alert">${escape(mine.message)}</span>` : "");
28 const time = mine?.values.time ?? d.time ?? "";
29 const place = mine?.values.place ?? d.place ?? "";
30 return `<details class="address-edit"${mine === undefined ? "" : " open"}>
31 <summary class="button button-quiet button-small">Set time and place</summary>
32 <form class="stack" method="post" action="/deadlines/${d.id}/appointment">
33 <input type="hidden" name="to" value="${escape(to)}">
34 <div class="pair">
35 <label>Time <span class="muted">(optional)</span><input class="input" type="time" name="time" step="900" min="07:00" max="20:00" value="${escape(time)}"${bad("time")}>${why("time")}</label>
36 <label>Place <span class="muted">(optional)</span><input class="input" name="place" maxlength="200" autocomplete="off" placeholder="12 Elm St" value="${escape(place)}"${bad("place")}>${why("place")}</label>
37 </div>
38 <button class="button">Save</button>
39 </form>
40 </details>`;
41 }
src/pages/deal.ts +5 −1
@@ -22,6 +22,7 @@ import { layout } from "./layout.ts";
2222 import { sideOf } from "../side.ts";
2323 import { dealSideLabel, sideLabel, sideSelect } from "./side.ts";
2424 import { progressLine } from "./progress.ts";
25 import { appointmentForm, appointmentText, type AppointmentProblem } from "./appointment.ts";
2526 import { badge, conflictLines, nonBusinessLine, noteLine, owesChangedLine, rollForm, draftItem, dueLine, outboxLine, owedBy, releaseForm, sheet, sheetId } from "./sheet.ts";
2627
2728 const roleOptions = (selected?: string): string =>
@@ -246,6 +247,8 @@ export function dealPage(input: {
246247 figures?: FiguresProblem | undefined;
247248 /** A closing time or place that was refused: what was typed and why. */
248249 closing?: ClosingProblem | undefined;
250 /** An inspection or walkthrough time and place that was refused: what was typed and why. */
251 appointment?: AppointmentProblem | undefined;
249252 /** A party added or corrected and refused: what was typed and why, so the form keeps it. */
250253 party?: PartyProblem | undefined;
251254 /** People from other deals the add-party form offers, and the one picked to prefill it. */
@@ -290,10 +293,11 @@ export function dealPage(input: {
290293 <div>
291294 <p>${badge(d, on)} <b>${escape(d.label)}</b></p>
292295 <p class="muted small">${escape(dueLine(d, on))}${d.moves.length > 0 ? ` · moved ${d.moves.length}×` : ""}</p>
296 ${appointmentText(d)}
293297 <p class="small">${owedBy(deal, d)}</p>
294298 ${owesChangedLine(d)}
295299 ${noteLine(d)}
296 ${nonBusinessLine(d)}${may ? rollForm(d, path) : ""}
300 ${nonBusinessLine(d)}${may ? rollForm(d, path) : ""}${may ? appointmentForm(d, path, input.appointment) : ""}
297301 </div>
298302 <button class="button button-quiet" popovertarget="${sheetId(d)}">Open</button>
299303 </li>`,
src/pages/file.ts +2 −1
@@ -8,6 +8,7 @@
88 * this page and the terminal print from.
99 */
1010
11 import { appointmentLine } from "../appointment.ts";
1112 import { dayOfStamp, doneLine, short, spoken } from "../dates.ts";
1213 import { closedOn, fellOn, type DealView, type Party } from "../deals.ts";
1314 import { PARTY_LABEL } from "../deadlines.ts";
@@ -51,7 +52,7 @@ export function fileRecord(deal: DealView): FileRecord {
5152 : "Open";
5253 const live = new Set(deal.deadlines.map((d) => d.id));
5354 const live_dates = deal.deadlines.map((d) => ({
54 line: `${d.label} · due ${spoken(d.due)} · ${fileState(d)}`,
55 line: `${d.label} · due ${spoken(d.due)}${appointmentLine(d) === "" ? "" : ` · ${appointmentLine(d)}`} · ${fileState(d)}`,
5556 moves: d.moves.map((m) => `Moved ${short(m.from_due)} → ${short(m.to_due)}: ${m.reason} (${m.by_name}, ${short(dayOfStamp(deal.zone, m.at))})`),
5657 }));
5758 // A removed date leaves no row of its own; what remains of it is in the messages sent or declined about it.
src/pages/timeline.ts +1 −1
@@ -32,7 +32,7 @@ export function timelinePage(input: { who: Who; agent?: Agent | undefined; deal:
3232 const rows = timelineRows(deal, on)
3333 .map(
3434 (r) => `<li class="timeline-row" data-u="${r.urgency}">
35 <p class="timeline-date">${escape(r.spoken)}</p>
35 <p class="timeline-date">${escape(r.spoken)}${r.where === "" ? "" : ` · ${escape(r.where)}`}</p>
3636 <p class="timeline-label"><b>${escape(r.label)}</b></p>
3737 <p class="timeline-owner">${escape(r.role)}${r.name === undefined ? "" : ` · ${escape(r.name)}`}</p>
3838 <p class="timeline-status"><span aria-hidden="true">${r.mark}</span> ${r.doneLine === "" ? r.status : escape(r.doneLine)}</p>${todo(r.todo)}
src/reminders.ts +4 −3
@@ -9,6 +9,7 @@
99 */
1010
1111 import { addDays, daysBetween, dayOf, dayOfStamp, relative, short, spoken, today, weekday } from "./dates.ts";
12 import { appointmentAfterDate } from "./appointment.ts";
1213 import { closingAfterDate } from "./closing.ts";
1314 import { ANNIVERSARY_YEARS, anniversaryOn, anniversaryWords, checkinOn, checkinRoles, checkinWords } from "./checkin.ts";
1415 import { dollars } from "./money.ts";
@@ -162,7 +163,7 @@ function words(
162163 : `${party.role === "buyer" ? "Your" : "The buyer's"} ${dollars(sum)} earnest money deposit ${late ? "is still outstanding" : `is due ${short(deadline.due)}`}. `;
163164 if (moment === "moved" && notice !== undefined && notice.items.length > 1) {
164165 const changes = notice.items
165 .map(({ deadline: d, move }) => `• ${d.label}: from ${spoken(move.from_due)} to ${spoken(move.to_due)}${d.kind === "closing" ? closingAfterDate(deal) : ""}`)
166 .map(({ deadline: d, move }) => `• ${d.label}: from ${spoken(move.from_due)} to ${spoken(move.to_due)}${d.kind === "closing" ? closingAfterDate(deal) : appointmentAfterDate(d)}`)
166167 .join("\n");
167168 return {
168169 subject: `${deal.address} — dates changed`,
@@ -173,7 +174,7 @@ function words(
173174 const move = lastMove(deadline)!;
174175 return {
175176 subject: `${deadline.label} — ${deal.address} — date changed`,
176 body: `Hi ${first(party.name)}, a change of date: the ${deadline.label.toLowerCase()} for ${deal.address} has moved from ${spoken(move.from_due)} to ${spoken(move.to_due)}${deadline.kind === "closing" ? closingAfterDate(deal) : ""}. ${owed}Please work to the new date, and let me know if it causes a problem.\n\n${signOff(agent)}`,
177 body: `Hi ${first(party.name)}, a change of date: the ${deadline.label.toLowerCase()} for ${deal.address} has moved from ${spoken(move.from_due)} to ${spoken(move.to_due)}${deadline.kind === "closing" ? closingAfterDate(deal) : appointmentAfterDate(deadline)}. ${owed}Please work to the new date, and let me know if it causes a problem.\n\n${signOff(agent)}`,
177178 };
178179 }
179180 if (moment === "late") {
@@ -182,7 +183,7 @@ function words(
182183 body: `Hi ${first(party.name)}, the ${deadline.label.toLowerCase()} for ${deal.address} was due ${spoken(deadline.due)} and has passed without being marked done. ${deposit(true)}${owed}Could you send me an update today on where it stands and when it will be done?\n\n${signOff(agent)}`,
183184 };
184185 }
185 const when = `${moment === "before" ? `in ${days(deadline.lead_days)}, on ${spoken(deadline.due)}` : `today, ${spoken(deadline.due)}`}${deadline.kind === "closing" ? closingAfterDate(deal) : ""}`;
186 const when = `${moment === "before" ? `in ${days(deadline.lead_days)}, on ${spoken(deadline.due)}` : `today, ${spoken(deadline.due)}`}${deadline.kind === "closing" ? closingAfterDate(deal) : appointmentAfterDate(deadline)}`;
186187 // The walk-through is the day before the keys change hands: it says where and when that is.
187188 const closes = deadline.kind === "walkthrough" && closingAfterDate(deal) !== "" ? `Closing follows on ${spoken(deal.closing)}${closingAfterDate(deal)}. ` : "";
188189 const yours = party.role === deadline.owes;
src/routes.ts +28 −3
@@ -72,6 +72,7 @@ import {
7272 sendStatusUpdate,
7373 statusUpdates,
7474 setReminderLead,
75 setAppointment,
7576 setNote,
7677 line,
7778 NOTE_MAX,
@@ -1270,6 +1271,23 @@ export const routes: readonly Route[] = [
12701271 return done(set, backTo(f.to));
12711272 },
12721273 },
1274 {
1275 method: "POST",
1276 path: "/deadlines/:id/appointment",
1277 handle: async (c) => {
1278 const f = await form(c);
1279 if (f instanceof Response) return f;
1280 const id = Number(c.params.id);
1281 const set = setAppointment(c.db, c.who, { id, time: f.time ?? "", place: f.place ?? "" });
1282 if (set.ok) return done(set, backTo(f.to), `Time and place saved on ${set.value.label}.`);
1283 const deal = c.db.query<{ deal_id: number }, [number]>("SELECT deal_id FROM deadline WHERE id = ?1").get(id)?.deal_id;
1284 const found = deal === undefined ? undefined : getDeal(c.db, c.who, { id: deal });
1285 // A refused time or place comes back as that deal's page, naming the field, with what was typed.
1286 if (found?.ok && set.error === "invalid")
1287 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), appointment: { id, values: { time: String(f.time ?? ""), place: String(f.place ?? "") }, field: set.field, message: set.message } }), STATUS.invalid);
1288 return done(set, backTo(f.to));
1289 },
1290 },
12731291 {
12741292 method: "POST",
12751293 path: "/deadlines/:id/lead",
@@ -1792,6 +1810,13 @@ export const routes: readonly Route[] = [
17921810 // A note outside its rule is refused before anything else in the request is applied.
17931811 if ("note" in sent && line(sent.note, 0, NOTE_MAX) === undefined)
17941812 return json({ error: "invalid", message: `The note is one line of up to ${NOTE_MAX} characters.`, field: "note" }, 400);
1813 // Time and place are checked and written first, so a 422 on them leaves nothing else changed.
1814 if ("time" in sent || "place" in sent) {
1815 const placed = setAppointment(c.db, c.who, { ...target, time: sent.time, place: sent.place });
1816 // A time or place outside its rule, or on a date that takes none, is a 422 naming the field.
1817 if (!placed.ok) return json({ error: placed.error, message: placed.message, ...(placed.field === undefined ? {} : { field: placed.field }) }, STATUS[placed.error]);
1818 if (!("owes" in sent || "note" in sent || "lead_days" in sent)) return answer(placed);
1819 }
17951820 if ("owes" in sent) {
17961821 const handed = setOwes(c.db, c.who, { ...target, owes: sent.owes });
17971822 if (!handed.ok || !("lead_days" in sent || "note" in sent)) return answer(handed);
@@ -1807,9 +1832,9 @@ export const routes: readonly Route[] = [
18071832 },
18081833 api: {
18091834 summary:
1810 "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. Send any of them.",
1811 body: { type: "object", properties: { lead_days: { type: "integer", minimum: 1, maximum: 30 }, owes: ROLE, note: { type: "string", maxLength: 200 } } },
1812 answer: { type: "object", properties: { id: { type: "integer" }, lead_days: { type: "integer" }, owes: ROLE, note: { type: "string" } }, required: ["id", "lead_days", "owes", "note"] },
1835 "Change a date: lead_days sets how many days before it is due its first reminder goes out (a whole number, 1 to 30; 400 with field lead_days otherwise; an unsent draft is drafted again for the new day, a sent one keeps its words), and owes changes which party owes it (one of the party roles; 422 otherwise, 409 for a date already done or waived). Today's and later reminders are drafted to the new party; ones already sent stay as they were. note sets the agent's working note on the date, one line of up to 200 characters, empty to clear it (400 with field note otherwise); it is internal and never reaches a client timeline, reminder or status update. time and place set when and where an inspection or a final walkthrough is: time as HH:MM on a quarter hour from 07:00 to 20:00 (the agent's local time), place one line of 1 to 200 characters; a field left out stays, blank or null clears it, and any other kind of date is refused (422 with field time). Drafts, the client timeline and the calendar file say them. Send any of them.",
1836 body: { type: "object", properties: { lead_days: { type: "integer", minimum: 1, maximum: 30 }, owes: ROLE, note: { type: "string", maxLength: 200 }, time: { type: ["string", "null"], pattern: "^(0[7-9]|1[0-9]):(00|15|30|45)$|^20:00$", description: "HH:MM on a quarter hour from 07:00 to 20:00, local time; null clears it. Inspection and walkthrough only." }, place: { type: ["string", "null"], maxLength: 200 } } },
1837 answer: { type: "object", properties: { id: { type: "integer" }, lead_days: { type: "integer" }, owes: ROLE, note: { type: "string" }, time: { type: ["string", "null"] }, place: { type: ["string", "null"] } }, required: ["id", "lead_days", "owes", "note"] },
18131838 },
18141839 },
18151840 {
src/server.test.ts +1
@@ -185,6 +185,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
185185 "waive_date",
186186 "move_date",
187187 "set_date_note",
188 "set_appointment",
188189 "set_reminder_lead",
189190 "amend_deal",
190191 "send_reminder",
src/terminal.ts +18 −5
@@ -14,7 +14,7 @@
1414 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, C sets the closing time and place, M amends the contract, S drafts a status update for the party under the cursor, D removes it, F marks it fell through (or brings it back), Y changes the side (buyer, listing or both)
1515 *
1616 * On a date (dates or deal view): x marks it done, W waives it (the buyer gave it up), u reopens it or un-waives it, m moves it
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
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, @ sets an inspection's or walkthrough's time and place. o or enter opens its deal; n opens a new
1818 * deal (address, buyer, seller, contract and closing dates, side); d, r and b move
1919 * between views; esc cancels a prompt; q leaves. / finds a deal by address or
2020 * party and narrows dates, week and reminders to it; / then enter clears it. E writes every deal you may read to one JSON file
@@ -23,6 +23,7 @@
2323
2424 import type { Database } from "bun:sqlite";
2525 import { bookLine, tally } from "./book.ts";
26 import { appointmentLine, isAppointment } from "./appointment.ts";
2627 import { closingLine } from "./closing.ts";
2728 import { timelineRows } from "./timeline.ts";
2829 import { fileRecord } from "./pages/file.ts";
@@ -52,6 +53,7 @@ import {
5253 withConflicts,
5354 removeDeadline,
5455 setNote,
56 setAppointment,
5557 setReminderLead,
5658 removeParty,
5759 sendReminder,
@@ -209,7 +211,7 @@ export function terminal(
209211
210212 function onDate(key: string): boolean {
211213 const row = dateRows()[cursor];
212 if (!["x", "u", "W", "m", "N", "l", "T", "o", "\r"].includes(key)) return false;
214 if (!["x", "u", "W", "m", "N", "l", "T", "@", "o", "\r"].includes(key)) return false;
213215 if (row === undefined) {
214216 said = "No date here.";
215217 return true;
@@ -248,6 +250,16 @@ export function terminal(
248250 const set = setNote(db, me, { id: date.id, note });
249251 return report(set, () => (set.ok && set.value.note === "" ? `Note cleared on ${date.label}.` : `Note saved on ${date.label}.`));
250252 });
253 if (key === "@")
254 if (!isAppointment(date.kind)) said = "Only an inspection or a walkthrough has a time and place.";
255 else
256 ask(deal, [`Time for ${date.label} (HH:MM, now ${date.time ?? "none"}; blank clears)`, `Place (now ${date.place ?? "none"}; blank clears)`], ([time, place]) =>
257 report(setAppointment(db, me, { id: date.id, time, place }), () => {
258 const set = getDeal(db, me, { id: deal.id });
259 const now = set.ok ? set.value.deadlines.find((d) => d.id === date.id) : undefined;
260 return `${date.label}: ${now === undefined || appointmentLine(now) === "" ? "the day only" : appointmentLine(now)}.`;
261 }),
262 );
251263 if ((key === "o" || key === "\r") && view === "dates") {
252264 view = "deal";
253265 dealId = deal.id;
@@ -749,7 +761,8 @@ export function terminal(
749761 const flag = date.nonBusinessDay === null ? "" : dim(` not a business day · next is ${spoken(date.nonBusinessDay.next)} (N moves it)`);
750762 const lead = isOpen(date) ? dim(` reminds ${date.lead_days}d before`) : "";
751763 const note = date.note === "" ? "" : dim(` note: ${date.note}`);
752 return `${i === cursor ? "▸" : " "} ${when} ${i === cursor ? bold(text) : text}${flag}${lead}${moved}${note}`;
764 const where = appointmentLine(date) === "" ? "" : dim(` ${appointmentLine(date)}`);
765 return `${i === cursor ? "▸" : " "} ${when} ${i === cursor ? bold(text) : text}${where}${flag}${lead}${moved}${note}`;
753766 };
754767
755768 function screen(): string[] {
@@ -946,8 +959,8 @@ export function terminal(
946959 : view === "timeline" || view === "file"
947960 ? "b back to the deal · d dates · q quit"
948961 : view === "deal"
949 ? "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"
950 : `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 · O bring deals back · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · E export · L activity · q quit`;
962 ? "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 · @ time and place (inspection, walkthrough) · 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"
963 : `j/k move · x done · W waive · u reopen · m move · N next business day · l lead · T note · @ time and place · o open deal · n new deal · c check dates · / find · R restore samples · O bring deals back · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · E export · L activity · q quit`;
951964 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
952965 }
953966 return lines;
src/timeline.ts +4 −1
@@ -5,6 +5,7 @@
55 * internal — no notes, drafts, reasons or contacts.
66 */
77
8 import { appointmentLine } from "./appointment.ts";
89 import { doneLine, spoken, urgencyOf, type Urgency } from "./dates.ts";
910 import type { DealView } from "./deals.ts";
1011 import { guidance, type Guidance } from "./guidance.ts";
@@ -27,6 +28,8 @@ export interface TimelineRow {
2728 readonly due: string;
2829 /** "Thu, Oct 15, 2026". */
2930 readonly spoken: string;
31 /** "10:00 am · 12 Elm St" for an inspection or walkthrough with a time or place, else empty. */
32 readonly where: string;
outdated

The where field splits the role doc comment from role. Move it below the role comment or give role its comment back.

3033 /** The role that owes it, and the deal's party in that role if it has one. */
3134 readonly role: string;
3235 readonly name: string | undefined;
@@ -43,6 +46,6 @@ export function timelineRows(deal: DealView, on: string): TimelineRow[] {
4346 return deal.deadlines.map((d) => {
4447 const u = urgencyOf(d, on);
4548 const { name, role } = owner(deal, d);
46 return { label: d.label, due: d.due, spoken: spoken(d.due), role, name, status: STATUS[u].word, doneLine: u === "done" && d.done_on !== null ? doneLine(d.due, d.done_on) : "", mark: STATUS[u].mark, urgency: u, todo: guidance(d.kind, deal.side, u !== "done" && u !== "waived") };
49 return { label: d.label, due: d.due, spoken: spoken(d.due), where: appointmentLine(d), role, name, status: STATUS[u].word, doneLine: u === "done" && d.done_on !== null ? doneLine(d.due, d.done_on) : "", mark: STATUS[u].mark, urgency: u, todo: guidance(d.kind, deal.side, u !== "done" && u !== "waived") };
4750 });
4851 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs