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

A deal whose closing is marked done leaves the clock for a Closed list, and can be reopened #28

Merged opened this

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

Merged

mason/deal-clock:mason/20-a-deal-whose-closing-is-marked-done-leav → main 5 commits fork 1 thread · 1 unresolved

  • Merged. mason/20-a-deal-whose-closing-is-marked-done-leav was merged into main as 4f83b8c.

Review

Sign in to review this change.
15 files changed +171 −15
README.md +5 −1
@@ -78,7 +78,11 @@ for the same list; over MCP, an agent asks for the `this_week` tool.
7878 reason beside its field. In the terminal, press c instead of n for the same
7979 list. Tap Open deal. You land on the new
8080 deal's page with every date worked out, and it has its own lane on the clock.
81 11. **Download the calendar file.** On a deal's page, tap Add to calendar.
81 11. **Close a deal.** Open a deal's page, tap Open on its Closing date and
82 mark it done. The deal steps off the clock into the Closed card below it,
83 its reminders stop, and its page says "Closed on …". Everything on it still
84 opens; reopen the Closing date and the deal is back on the clock.
85 12. **Download the calendar file.** On a deal's page, tap Add to calendar.
8286 You get a calendar file with every date of the deal and an alarm three days
8387 before and the morning of, to open in your own calendar app.
8488
contract/openapi.json +5
@@ -952,6 +952,10 @@
952952 "type": "string",
953953 "format": "date"
954954 },
955 "closed": {
956 "type": "boolean",
957 "description": "The Closing date is marked done; the deal is off the clock."
958 },
955959 "business_days": {
956960 "enum": [
957961 0,
@@ -1143,6 +1147,7 @@
11431147 "address",
11441148 "contract_date",
11451149 "closing",
1150 "closed",
11461151 "parties",
11471152 "deadlines"
11481153 ]
docs/TECHNICAL.md +2
@@ -36,6 +36,8 @@ sent until undone. Over the API: `POST /api/deals/:id/reminders/decline` and
3636 `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the
3737 reason on the reminders list, and `u` to undo. Each is an update of the deal.
3838
39 A deal is **closed** when its Closing date is marked done (derived, no column; `closed` on `GET /api/deals` and `list_deals`). It leaves the clock for the Closed card, sends no reminders (`/tick`, `reminders_today`, the terminal `r` list), and the terminal date list shows its dates only after `h`. Reopening the Closing date reopens the deal.
40
3941 `POST /tick` answers the reminders that go out today and are not yet
4042 marked sent, as JSON — call it each morning as a signed-in account (a
4143 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. The JSON API is
src/deadlines.ts +4
@@ -36,6 +36,10 @@ export const KINDS = [
3636 ] as const;
3737 export type Kind = (typeof KINDS)[number];
3838
39 /** A deal is closed when its Closing date is marked done; reopening that date reopens the deal. */
40 export const isClosed = (deadlines: readonly { kind: Kind; done_at: string | null }[]): boolean =>
41 deadlines.some((d) => d.kind === "closing" && d.done_at !== null);
42
3943 export interface KindInfo {
4044 readonly label: string;
4145 /** Two or three letters for a marker on the clock. */
src/deals.test.ts +21
@@ -25,6 +25,7 @@ import {
2525 undoDecline,
2626 type DealView,
2727 } from "./deals.ts";
28 import { isClosed } from "./deadlines.ts";
2829 import { openDb } from "./db.ts";
2930 import { calendar, fold, icsText } from "./ics.ts";
3031 import { drafts, dueOn, recipients } from "./reminders.ts";
@@ -417,3 +418,23 @@ test("a decline needs a reason of 1 to 200 characters, a real unsent reminder, a
417418 sendReminder(db, alice, ask);
418419 expect(declineReminder(db, alice, { ...ask, reason: "Too late" }).ok).toBe(false);
419420 });
421
422 test("a deal is closed when its Closing date is marked done, and open again when it is reopened", () => {
423 const deal = open({ address: "31 Closed Ct" });
424 expect(deal.closed).toBe(false);
425 expect(isClosed(deal.deadlines)).toBe(false);
426 const beforeClosing = drafts(deal, agent).length;
427 expect(beforeClosing).toBeGreaterThan(0);
428 // Another date done does not close it.
429 markDone(db, alice, { id: due(deal, "inspection").id, done: true });
430 expect(fresh(deal.id).closed).toBe(false);
431 markDone(db, alice, { id: due(deal, "closing").id, done: true });
432 const closed = fresh(deal.id);
433 expect(closed.closed).toBe(true);
434 expect(drafts(closed, agent)).toEqual([]);
435 expect(dueOn([closed], due(closed, "inspection").due, agent)).toEqual([]);
436 markDone(db, alice, { id: due(deal, "closing").id, done: false });
437 expect(fresh(deal.id).closed).toBe(false);
438 expect(isClosed([{ kind: "closing", done_at: "2026-11-02T10:00:00.000Z" }])).toBe(true);
439 expect(isClosed([{ kind: "closing", done_at: null }, { kind: "custom", done_at: "x" }])).toBe(false);
440 });
src/deals.ts +11 −1
@@ -8,9 +8,10 @@
88
99 import type { Database } from "bun:sqlite";
1010 import { permit } from "./contract.ts";
11 import { isDate } from "./dates.ts";
11 import { isDate, today } from "./dates.ts";
1212 import {
1313 DEFAULT_LENGTHS,
14 isClosed,
1415 isPartyRole,
1516 KIND,
1617 LENGTH_MAX,
@@ -95,10 +96,18 @@ export interface Deadline {
9596 export interface DeadlineView extends Deadline {
9697 readonly moves: readonly Move[];
9798 }
99 /** The day the Closing date was marked done, by the app's own calendar (the one `today()` keeps). */
100 export const closedOn = (deal: { deadlines: readonly { kind: Kind; done_at: string | null }[]; closing: string }): string => {
101 const at = deal.deadlines.find((d) => d.kind === "closing")?.done_at;
102 return at == null ? deal.closing : today(new Date(at));
103 };
104
98105 /** A deal with everything hanging off it: what every page and door shows. */
99106 export interface DealView extends Deal {
100107 /** The `closing` deadline's date, wherever it has moved. */
101108 readonly closing: string;
109 /** Its Closing date is marked done: the deal has stepped off the clock. */
110 readonly closed: boolean;
102111 readonly parties: readonly Party[];
103112 readonly deadlines: readonly DeadlineView[];
104113 readonly sent: readonly Sent[];
@@ -167,6 +176,7 @@ function view(db: Database, deal: Deal): DealView {
167176 ...deal,
168177 closing:
169178 deadlines.find((d) => d.kind === "closing")?.due ?? deal.contract_date,
179 closed: isClosed(deadlines),
170180 parties: db
171181 .query<Party, [number]>(
172182 "SELECT * FROM party WHERE deal_id = ?1 ORDER BY id",
src/pages/clock.ts +17 −3
@@ -116,7 +116,11 @@ export function clock(input: {
116116 on: string;
117117 notice?: string | undefined;
118118 }): string {
119 const { who, deals, on, notice } = input;
119 const { who, on, notice } = input;
120 const deals = input.deals.filter((deal) => !deal.closed);
121 const closed = input.deals
122 .filter((deal) => deal.closed)
123 .sort((a, b) => b.closing.localeCompare(a.closing) || b.id - a.id);
120124 const open = deals.flatMap((deal) => deal.deadlines.filter((d) => d.done_at === null));
121125 const overdue = open.filter((d) => urgency(d.due, on, false) === "overdue").length;
122126 const soon = open.filter((d) => urgency(d.due, on, false) === "soon").length;
@@ -128,15 +132,24 @@ export function clock(input: {
128132 );
129133 const toSend = today.filter(({ r }) => unsent(r)).length;
130134 const timeline =
131 deals.length === 0
135 deals.length === 0 && closed.length === 0
132136 ? `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`
133 : `<div class="clock-scroll" tabindex="0" role="region" aria-label="Timeline of every deal's dates">
137 : deals.length === 0
138 ? `<p class="empty">Every deal is closed.</p>`
139 : `<div class="clock-scroll" tabindex="0" role="region" aria-label="Timeline of every deal's dates">
134140 <div class="clock-inner" style="width:${at(days)}">
135141 <div class="axis" aria-hidden="true">${axis(start, days, on)}</div>
136142 <ol class="lanes">${deals.map((deal) => lane(deal, start, on)).join("")}</ol>
137143 </div>
138144 </div>
139145 ${deals.flatMap((deal) => deal.deadlines.map((d) => sheet(deal, d, who, on, "/"))).join("")}`;
146 const closedCard =
147 closed.length === 0
148 ? ""
149 : `<section id="closed" class="card" data-live="deal.changed">
150 <h2>Closed <span class="muted">· ${closed.length}</span></h2>
151 <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 </section>`;
140153 const body = `<section class="intro">
141154 <div>
142155 <h1>The clock</h1>
@@ -153,6 +166,7 @@ export function clock(input: {
153166 <li><span class="dot" data-u="done"></span>Done</li>
154167 </ul>
155168 </section>
169 ${closedCard}
156170 ${deals.length === 0 ? "" : weekCard(deals, on)}
157171 <section id="today" class="card" data-live="deal.changed">
158172 <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2>
src/pages/deal.ts +2 −2
@@ -5,7 +5,7 @@
55 */
66
77 import { addDays, relative, short, spoken } from "../dates.ts";
8 import { canChange, canRemove, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
8 import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
99 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1010 import { escape } from "../http.ts";
1111 import { MOMENT_LABEL } from "../reminders.ts";
@@ -108,7 +108,7 @@ export function dealPage(input: {
108108 <section class="intro">
109109 <div>
110110 <h1>${escape(deal.address)}</h1>
111 <p class="summary">Under contract ${escape(spoken(deal.contract_date))} · closes ${escape(spoken(deal.closing))}, ${escape(relative(deal.closing, on))}${deal.business_days ? " · business days" : ""}</p>
111 <p class="summary">${deal.closed ? `<b>Closed on ${escape(spoken(closedOn(deal)))}</b> · ` : ""}Under contract ${escape(spoken(deal.contract_date))} · closes ${escape(spoken(deal.closing))}, ${escape(relative(deal.closing, on))}${deal.business_days ? " · business days" : ""}</p>
112112 </div>
113113 <a class="button button-quiet" href="${path}/ics" download>Add to calendar</a>
114114 </section>
src/reminders.ts +2 −1
@@ -72,8 +72,9 @@ function words(
7272 };
7373 }
7474
75 /** Every reminder an open date of this deal has, sent or not. */
75 /** Every reminder an open date of this deal has, sent or not; a closed deal reminds no one. */
7676 export function drafts(deal: DealView, agent: Agent): Draft[] {
77 if (deal.closed) return [];
7778 return deal.deadlines
7879 .filter((d) => d.done_at === null)
7980 .flatMap((deadline) => draftsFor(deal, deadline, agent));
src/routes.ts +2 −1
@@ -125,6 +125,7 @@ export const DEAL: Schema = {
125125 address: { type: "string" },
126126 contract_date: DATE,
127127 closing: DATE,
128 closed: { type: "boolean", description: "The Closing date is marked done; the deal is off the clock." },
128129 business_days: { enum: [0, 1] },
129130 author_id: { type: "string" },
130131 author_name: { type: "string" },
@@ -188,7 +189,7 @@ export const DEAL: Schema = {
188189 },
189190 },
190191 },
191 required: ["id", "address", "contract_date", "closing", "parties", "deadlines"],
192 required: ["id", "address", "contract_date", "closing", "closed", "parties", "deadlines"],
192193 };
193194 const NEW_DEAL: Schema = {
194195 type: "object",
src/server.test.ts +40
@@ -2,6 +2,7 @@ import { afterAll, expect, test } from "bun:test";
22 import { mkdtempSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import { addDays, spoken, today } from "./dates.ts";
56 import { agent, env } from "./env.ts";
67 import { drafts } from "./reminders.ts";
78 import { serve } from "./server.ts";
@@ -792,6 +793,45 @@ test("Check the dates refuses a guest and writes nothing; a refusal with no fiel
792793 expect(page).not.toContain("-why");
793794 });
794795
796 // Its own person: writes are rationed per person across the whole run.
797 const closer = as("u20", "closer");
798 test("a deal whose Closing is marked done leaves the lanes for the Closed card, and sends nothing", async () => {
799 // The inspection ends in three days, so a reminder for this deal goes out today.
800 const made = await api(
801 "/api/deals",
802 { method: "POST", ...jsonBody({ address: "77 Closing Court", buyer: "B", seller: "S", contract_date: addDays(today(), -7), closing_date: addDays(today(), 25) }) },
803 closer,
804 );
805 expect(made.status).toBe(201);
806 const deal = (await made.json()) as { id: number; address: string; closed: boolean; deadlines: { id: number; kind: string }[] };
807 expect(deal.closed).toBe(false);
808 const tickIds = async () =>
809 ((await (await api("/tick", { method: "POST" }, closer)).json()) as { reminders: { deal_id: number }[] }).reminders.map((r) => r.deal_id);
810 expect(await tickIds()).toContain(deal.id);
811 const closing = deal.deadlines.find((d) => d.kind === "closing")!;
812 const post = (done: string) => {
813 const body = new FormData();
814 body.set("done", done);
815 return api(`/deadlines/${closing.id}/done`, { method: "POST", body, redirect: "manual" }, closer);
816 };
817 expect((await api("/", {}, closer).then((r) => r.text()))).toContain(`<a href="/deals/${deal.id}">${deal.address}</a> <small`);
818 expect((await post("1")).status).toBe(303);
819 const clock = await (await api("/", {}, closer)).text();
820 expect(clock).not.toContain(`<a href="/deals/${deal.id}">${deal.address}</a> <small`);
821 expect(clock).toContain('id="closed"');
822 expect(clock).toContain(`<a href="/deals/${deal.id}">${deal.address}</a> <span class="muted">closed`);
823 const page = await (await api(`/deals/${deal.id}`, {}, closer)).text();
824 expect(page).toContain(`Closed on ${spoken(today())}`);
825 expect(page).toContain("Inspection period ends");
826 const listed = (await (await api("/api/deals", {}, closer)).json()) as { id: number; closed: boolean }[];
827 expect(listed.find((d) => d.id === deal.id)!.closed).toBe(true);
828 expect(await tickIds()).not.toContain(deal.id);
829 expect((await post("0")).status).toBe(303);
830 const back = await (await api("/", {}, closer)).text();
831 expect(back).toContain(`<a href="/deals/${deal.id}">${deal.address}</a> <small`);
832 expect(back).not.toContain('id="closed"');
833 });
834
795835 test("This week lists the sample's overdue inspection and this week's closing, and nothing done", async () => {
796836 const page = await (await api("/", {}, alice)).text();
797837 const week = page.slice(page.indexOf('id="week"'), page.indexOf('id="today"'));
src/terminal.test.ts +38 −2
@@ -6,8 +6,8 @@ import { expect, test } from "bun:test";
66 import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
9 import { addDays, today } from "./dates.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, sendReminder, type DealView } from "./deals.ts";
9 import { addDays, spoken, today } from "./dates.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, markDone, sendReminder, type DealView } from "./deals.ts";
1111 import { openDb } from "./db.ts";
1212 import { terminal, type Terminal } from "./terminal.ts";
1313 import type { Who } from "./who.ts";
@@ -265,6 +265,42 @@ test("n declines a reminder with a reason, u undoes it; anon is not asked to typ
265265 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before);
266266 });
267267
268 test("a closed deal's dates leave the date list and reminders, it is listed under Closed, and u reopens it", () => {
269 // The inspection ends in three days, so its "3 days before" reminder goes out today.
270 const other = createDeal(db, alice, {
271 address: "88 Shut Ave",
272 buyer: "B",
273 seller: "S",
274 contractDate: addDays(today(), -7),
275 closingDate: addDays(today(), 20),
276 });
277 if (!other.ok) throw new Error(other.message);
278 const closing = other.value.deadlines.find((d) => d.kind === "closing")!;
279 const t = terminal(db, alice, context);
280 t.press("r");
281 expect(lines(t).join("\n")).toContain("88 Shut Ave");
282 t.press("d");
283 expect(lines(t).join("\n")).toContain("88 Shut Ave");
284 expect(lines(t).join("\n")).not.toContain("Closed (");
outdated

Vacuous unless a reminder for this deal is due today. Make one due, assert it appears in r before markDone, and is absent after.

285 markDone(db, alice, { id: closing.id, done: true });
286 t.press("d");
287 const dates = lines(t).join("\n");
288 expect(dates).not.toContain("Inspection period ends — 88 Shut Ave");
289 expect(dates).toContain("Closed (1)");
290 expect(dates).toContain(`88 Shut Ave — closed ${spoken(today())}`);
291 t.press("r");
292 expect(lines(t).join("\n")).not.toContain("88 Shut Ave");
293 t.press("d");
294 t.press("h");
295 expect(lines(t).join("\n")).toContain("Inspection period ends — 88 Shut Ave");
296 expect(lines(t).join("\n")).toContain("(closed)");
297 goTo(t, "Closing — 88 Shut Ave");
298 t.press("u");
299 t.press("h");
300 expect(lines(t).join("\n")).not.toContain("Closed (");
301 expect(lines(t).join("\n")).toContain("Inspection period ends — 88 Shut Ave");
302 });
303
268304 test("w lists the dates overdue or due within seven days, by day, with who owes each; x works there", () => {
269305 const soon = addDeadline(db, alice, { dealId: id, label: "Week check", due: addDays(today(), 2), owes: "buyer" });
270306 if (!soon.ok) throw new Error(soon.message);
src/terminal.ts +13 −3
@@ -25,6 +25,7 @@ import {
2525 createDeal,
2626 deleteDeal,
2727 getDeal,
28 closedOn,
2829 listDeals,
2930 markDone,
3031 mayOpen,
@@ -109,7 +110,7 @@ export function terminal(
109110 if (view === "week") return thisWeek(deals(), on()).map(({ deal, deadline }) => ({ deal, date: deadline }));
110111 return deals()
111112 .flatMap((deal) =>
112 deal.deadlines.filter((d) => showDone || d.done_at === null).map((date) => ({ deal, date })),
113 (deal.closed && !showDone ? [] : deal.deadlines.filter((d) => showDone || d.done_at === null)).map((date) => ({ deal, date })),
113114 )
114115 .sort((a, b) => a.date.due.localeCompare(b.date.due) || a.date.id - b.date.id);
115116 };
@@ -388,7 +389,8 @@ export function terminal(
388389 const u = urgency(date.due, on(), date.done_at !== null);
389390 const when = tint(u, `${spoken(date.due).padEnd(12)} ${(date.done_at === null ? relative(date.due, on()) : "done").padEnd(12)}`);
390391 const who = owner(deal, date);
391 const text = view === "week" ? `${date.label} — ${deal.address} · ${who.name ?? who.role}` : withDeal ? `${date.label} — ${deal.address}` : date.label;
392 const label = view === "week" ? `${date.label} — ${deal.address} · ${who.name ?? who.role}` : withDeal ? `${date.label} — ${deal.address}` : date.label;
393 const text = label + (deal.closed && withDeal ? dim(" (closed)") : "");
392394 const moved = date.moves.length > 0 ? dim(` moved: ${date.moves.at(-1)!.reason}`) : "";
393395 return `${i === cursor ? "▸" : " "} ${when} ${i === cursor ? bold(text) : text}${moved}`;
394396 };
@@ -408,6 +410,14 @@ export function terminal(
408410 if (!listed.ok) lines.push(listed.message);
409411 else if (rows.length === 0) lines.push(dim("Nothing open. Every date is done."));
410412 rows.forEach((row, i) => lines.push(dateLine(row, i, true)));
413 const closed = all.filter((d) => d.closed);
414 if (closed.length > 0)
415 lines.push(
416 "",
417 bold(`Closed (${closed.length})`),
418 ...closed.map((d) => dim(` ${d.address} — closed ${spoken(closedOn(d))}`)),
419 dim(showDone ? " Their dates are listed above; u on the Closing date reopens the deal." : " h shows their dates; u on the Closing date reopens the deal."),
420 );
411421 } else if (view === "week") {
412422 const rows = dateRows();
413423 const listed = listDeals(db, me);
@@ -437,7 +447,7 @@ export function terminal(
437447 const deal = openDeal();
438448 if (deal === undefined) lines.push(dim("That deal is gone."));
439449 else {
440 lines.push(bold(deal.address), dim(`under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
450 lines.push(bold(deal.address), ...(deal.closed ? [bold(`Closed on ${spoken(closedOn(deal))}`)] : []), dim(`under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
441451 deal.deadlines.forEach((date, i) => lines.push(dateLine({ deal, date }, i, false)));
442452 lines.push("", bold("Parties"));
443453 deal.parties.forEach((p, i) => {
src/week.test.ts +5
@@ -31,3 +31,8 @@ test("overdue first, then by due date, then by address", () => {
3131 test("nothing in the window is an empty list", () => {
3232 expect(thisWeek([], on)).toEqual([]);
3333 });
34
35 test("a closed deal's dates are left out", () => {
36 const shut = { address: "C Street", closed: true, deadlines: [d("2026-11-03")] };
37 expect(thisWeek([...deals, shut], on).some((i) => i.deal.address === "C Street")).toBe(false);
38 });
src/week.ts +4 −1
@@ -1,5 +1,5 @@
11 /**
2 * The dates to chase this week: every open date that is overdue or falls
2 * The dates to chase this week: every open date of an open deal that is overdue or falls
33 * within the next seven days, oldest first, then by address.
44 */
55
@@ -11,6 +11,8 @@ export const WEEK = 7;
1111
1212 export interface WeekDeal<D> {
1313 readonly address: string;
14 /** A closed deal is off the clock, so none of its dates are chased. */
15 readonly closed?: boolean;
1416 readonly deadlines: readonly D[];
1517 }
1618
@@ -25,6 +27,7 @@ export function thisWeek<D extends { due: string; done_at: string | null }, Deal
2527 ): WeekItem<Deal, D>[] {
2628 const last = addDays(on, WEEK);
2729 return deals
30 .filter((deal) => deal.closed !== true)
2831 .flatMap((deal) =>
2932 deal.deadlines.filter((d) => d.done_at === null && d.due <= last).map((deadline) => ({ deal, deadline })),
3033 )

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs