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

When a date moves, every party it reminds gets a drafted "date changed" notice the agent approves, so nobody works to the old date #60

Merged opened this

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

Merged

mason/deal-clock:mason/57-when-a-date-moves-every-party-it-reminds → main 2 commits fork

  • Merged. mason/57-when-a-date-moves-every-party-it-reminds was merged into main as 5cf5853.

Review

Sign in to review this change.
13 files changed +382 −51
README.md +4 −1
@@ -70,7 +70,10 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
7070 5. **Move a date, with a reason.** Open the same marker again and use Move
7171 this date: pick a new date and say why ("Inspector delayed"). The marker
7272 jumps to the new date, and the sheet lists the move, the reason and who
73 made it. No other date moves.
73 made it. No other date moves. A *Date changed* notice is drafted for each
74 party the date reminds, naming the old and the new date (not the reason);
75 it waits under Reminders for today like any other, and you send, edit or
76 decline it. Move the date again and an unsent notice is replaced.
7477 6. **See a date that was moved.** On 9 Orchard Row, open the appraisal
7578 marker. The sheet shows where it moved from and to, with the reason
7679 the appraiser gave.
contract/openapi.json +10 −5
@@ -620,7 +620,8 @@
620620 "enum": [
621621 "before",
622622 "day_of",
623 "late"
623 "late",
624 "moved"
624625 ]
625626 },
626627 "reason": {
@@ -714,7 +715,8 @@
714715 "enum": [
715716 "before",
716717 "day_of",
717 "late"
718 "late",
719 "moved"
718720 ]
719721 }
720722 },
@@ -1162,7 +1164,8 @@
11621164 "enum": [
11631165 "before",
11641166 "day_of",
1165 "late"
1167 "late",
1168 "moved"
11661169 ]
11671170 },
11681171 "due": {
@@ -1212,7 +1215,8 @@
12121215 "enum": [
12131216 "before",
12141217 "day_of",
1215 "late"
1218 "late",
1219 "moved"
12161220 ]
12171221 },
12181222 "due": {
@@ -1288,7 +1292,8 @@
12881292 "enum": [
12891293 "before",
12901294 "day_of",
1291 "late"
1295 "late",
1296 "moved"
12921297 ]
12931298 },
12941299 "on": {
docs/TECHNICAL.md +9
@@ -22,6 +22,15 @@ Removing a party or a date drops the reminders not yet sent; reminders already
2222 marked sent stay on record. Over the API: `PATCH` or `DELETE
2323 /api/deals/:id/parties/:party` and `DELETE /api/deals/:id/deadlines/:deadline`.
2424
25 Reminder moments (`MOMENTS`, `src/reminders.ts`): `before`, `day_of`, `late`
26 and `moved` (*Date changed*). `moved` is drafted for the latest move of an open
27 date, to the parties a `day_of` reminder goes to, dated the day of the move; its
28 words name the old and new dates, never the move's reason. Sent and declined
29 rows are keyed by `due` (a plain date) and `move_id` (the latest move for `moved`, else 0; see `moveKey`), so
30 an earlier notice stays sent and a date moved back and forth is told afresh.
31 `deadline_move.notify` is 1 only for moves made after the moment existed.
32 `send_reminder` and the decline and undo doors take `moment: "moved"`.
33
2534 Sending is simulated: *Send* records that a reminder went out and the
2635 words approved with it; nothing leaves the app. The record is shown on the
2736 page (the **Messages** section of `/deals/:id`, newest first, each entry
src/db.test.ts +19
@@ -113,3 +113,22 @@ test("the migration that accepts the late moment keeps the rows of the old schem
113113 // The migrations after it ran too: sample deals are keyed by the address they were written with.
114114 expect(raw.query("SELECT count(*) AS n FROM sample_deal").get()).toEqual({ n: 0 });
115115 });
116
117 test("the migration that accepts the moved moment keeps old moves quiet and takes new notices", () => {
118 const dir = mkdtempSync(join(tmpdir(), "app-db-moved-"));
119 const raw = new Database(join(dir, "app.db"));
120 raw.exec("PRAGMA foreign_keys = ON");
121 const at = migrations.findIndex((sql) => sql.includes("'before', 'day_of', 'late', 'moved'"));
122 raw.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
123 migrations.slice(0, at).forEach((sql, i) => {
124 raw.exec(sql);
125 raw.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1);
126 });
127 raw.exec(`INSERT INTO deal (id, address, contract_date, author_id, author_name) VALUES (1, 'A St', '2026-01-01', 'u', 'U');
128 INSERT INTO deadline (id, deal_id, kind, label, due, owes) VALUES (1, 1, 'inspection', 'Inspection', '2026-01-10', 'buyer');
129 INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (1, '2026-01-05', '2026-01-10', 'r', 'Dana')`);
130 migrate(raw);
131 expect(raw.query("SELECT notify FROM deadline_move").all()).toEqual([{ notify: 0 }]);
132 raw.exec("INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, moment, due, by_name) VALUES (1, 1, 1, 'I', 'Ann', 'moved', '2026-01-10', 'D')");
133 expect(raw.query("SELECT due, move_id FROM reminder").all()).toEqual([{ due: "2026-01-10", move_id: 0 }]);
134 });
src/db.ts +96
@@ -210,6 +210,102 @@ export const migrations: string[] = [
210210 // are looked up by the deal or date they hang off.
211211 `CREATE INDEX IF NOT EXISTS party_deal ON party (deal_id);
212212 CREATE INDEX IF NOT EXISTS deadline_move_deadline ON deadline_move (deadline_id)`,
213 // A moved date is a fourth moment, `moved`. SQLite cannot alter a
214 // CHECK, so both tables are rebuilt with their rows kept; the old tables
215 // are named only inside this one migration, and schema_version means it runs
216 // once.
217 `CREATE TABLE reminder_new (
218 id INTEGER PRIMARY KEY,
219 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
220 deadline_id INTEGER NOT NULL,
221 party_id INTEGER NOT NULL,
222 label TEXT NOT NULL,
223 party_name TEXT NOT NULL,
224 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')),
225 due TEXT NOT NULL,
226 by_name TEXT NOT NULL,
227 subject TEXT NOT NULL DEFAULT '',
228 body TEXT NOT NULL DEFAULT '',
229 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
230 party_role TEXT NOT NULL DEFAULT '',
231 sample INTEGER NOT NULL DEFAULT 0,
232 UNIQUE (deadline_id, party_id, moment, due)
233 );
234 INSERT INTO reminder_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body, sent_at, party_role, sample)
235 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body, sent_at, party_role, sample FROM reminder;
236 DROP TABLE reminder;
237 ALTER TABLE reminder_new RENAME TO reminder;
238 CREATE INDEX reminder_deal ON reminder (deal_id);
239 CREATE TABLE reminder_declined_new (
240 id INTEGER PRIMARY KEY,
241 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
242 deadline_id INTEGER NOT NULL,
243 party_id INTEGER NOT NULL,
244 label TEXT NOT NULL,
245 party_name TEXT NOT NULL,
246 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')),
247 due TEXT NOT NULL,
248 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
249 by_name TEXT NOT NULL,
250 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
251 UNIQUE (deadline_id, party_id, moment, due)
252 );
253 INSERT INTO reminder_declined_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at)
254 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at FROM reminder_declined;
255 DROP TABLE reminder_declined;
256 ALTER TABLE reminder_declined_new RENAME TO reminder_declined;
257 CREATE INDEX reminder_declined_deal ON reminder_declined (deal_id)`,
258 // Whether a move owes the parties a "date changed" notice: only a move made
259 // by a person from here on does, so a deal's earlier moves do not sprout drafts.
260 `ALTER TABLE deadline_move ADD COLUMN notify INTEGER NOT NULL DEFAULT 0`,
261 // Which move a "date changed" notice was about gets its own column, so `due`
262 // stays a plain date; the rows are rebuilt (the key changes) and any made
263 // with the move id inside `due` are split.
264 `CREATE TABLE reminder_new (
265 id INTEGER PRIMARY KEY,
266 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
267 deadline_id INTEGER NOT NULL,
268 party_id INTEGER NOT NULL,
269 label TEXT NOT NULL,
270 party_name TEXT NOT NULL,
271 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')),
272 due TEXT NOT NULL,
273 by_name TEXT NOT NULL,
274 subject TEXT NOT NULL DEFAULT '',
275 body TEXT NOT NULL DEFAULT '',
276 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
277 party_role TEXT NOT NULL DEFAULT '',
278 sample INTEGER NOT NULL DEFAULT 0,
279 move_id INTEGER NOT NULL DEFAULT 0,
280 UNIQUE (deadline_id, party_id, moment, due, move_id)
281 );
282 INSERT INTO reminder_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body, sent_at, party_role, sample, move_id)
283 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, substr(due, 1, 10), by_name, subject, body, sent_at, party_role, sample,
284 CASE WHEN instr(due, '#') > 0 THEN CAST(substr(due, instr(due, '#') + 1) AS INTEGER) ELSE 0 END FROM reminder;
285 DROP TABLE reminder;
286 ALTER TABLE reminder_new RENAME TO reminder;
287 CREATE INDEX reminder_deal ON reminder (deal_id);
288 CREATE TABLE reminder_declined_new (
289 id INTEGER PRIMARY KEY,
290 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
291 deadline_id INTEGER NOT NULL,
292 party_id INTEGER NOT NULL,
293 label TEXT NOT NULL,
294 party_name TEXT NOT NULL,
295 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')),
296 due TEXT NOT NULL,
297 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
298 by_name TEXT NOT NULL,
299 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
300 move_id INTEGER NOT NULL DEFAULT 0,
301 UNIQUE (deadline_id, party_id, moment, due, move_id)
302 );
303 INSERT INTO reminder_declined_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at, move_id)
304 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, substr(due, 1, 10), reason, by_name, at,
305 CASE WHEN instr(due, '#') > 0 THEN CAST(substr(due, instr(due, '#') + 1) AS INTEGER) ELSE 0 END FROM reminder_declined;
306 DROP TABLE reminder_declined;
307 ALTER TABLE reminder_declined_new RENAME TO reminder_declined;
308 CREATE INDEX reminder_declined_deal ON reminder_declined (deal_id)`,
213309 ];
214310
215311 export function openDb(dir = dataDir): Database {
src/deals.test.ts +78 −2
@@ -7,7 +7,7 @@ import { expect, test } from "bun:test";
77 import { mkdtempSync } from "node:fs";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { addDays, today } from "./dates.ts";
10 import { addDays, spoken, today } from "./dates.ts";
1111 import {
1212 addDeadline,
1313 addParty,
@@ -29,7 +29,7 @@ import {
2929 import { isClosed } from "./deadlines.ts";
3030 import { openDb } from "./db.ts";
3131 import { book, calendar, fold, icsText } from "./ics.ts";
32 import { drafts, dueOn, pending, recipients } from "./reminders.ts";
32 import { drafts, dueOn, pending, recipients, signOff } from "./reminders.ts";
3333 import type { Who } from "./who.ts";
3434
3535 const db = openDb(mkdtempSync(join(tmpdir(), "app-deals-")));
@@ -548,3 +548,79 @@ test("correcting an address rewrites the drafts not yet sent and leaves the word
548548 expect(after.sent[0]!.body).toContain("40 Typo Rd");
549549 expect(after.sent[0]!.subject).not.toContain("Unit 1");
550550 });
551
552 test("moving a date drafts a Date changed notice to the parties a day-of reminder goes to, with both dates", () => {
553 const deal = open({ address: "5 Moved Ln" });
554 const insp = due(deal, "inspection");
555 const from = insp.due;
556 expect(moveDeadline(db, alice, { id: insp.id, due: "2026-11-20", reason: "Inspector sick (internal)" }).ok).toBe(true);
557 const after = fresh(deal.id);
558 const notes = drafts(after, agent).filter((d) => d.moment === "moved");
559 const day = drafts(after, agent).filter((d) => d.moment === "day_of" && d.deadline_id === insp.id);
560 expect(notes.map((n) => n.party_id).sort()).toEqual(day.map((n) => n.party_id).sort());
561 expect(notes.length).toBeGreaterThan(0);
562 const n = notes[0]!;
563 expect(n.on).toBe(today());
564 expect(n.body).toContain("5 Moved Ln");
565 expect(n.body).toContain(spoken(from));
566 expect(n.body).toContain(spoken("2026-11-20"));
567 expect(n.body).toContain(signOff(agent));
568 expect(n.body).not.toContain("Inspector sick");
569 expect(n.sent_at).toBeNull();
570 expect(pending(n, today())).toBe(true);
571 });
572
573 test("a second move replaces the unsent notice and leaves a sent one as sent", () => {
574 const deal = open({ address: "6 Moved Ln" });
575 const insp = due(deal, "inspection");
576 const first = insp.due;
577 moveDeadline(db, alice, { id: insp.id, due: "2026-11-20", reason: "a" });
578 const one = drafts(fresh(deal.id), agent).filter((d) => d.moment === "moved");
579 const sentTo = one[0]!;
580 const sent = sendReminder(db, alice, { deadlineId: insp.id, partyId: sentTo.party_id, moment: "moved", agent });
581 expect(sent.ok).toBe(true);
582 if (sent.ok) expect(sent.value.body).toBe(sentTo.body);
583 moveDeadline(db, alice, { id: insp.id, due: "2026-11-25", reason: "b" });
584 const after = fresh(deal.id);
585 const now = drafts(after, agent).filter((d) => d.moment === "moved");
586 expect(now.length).toBe(one.length);
587 expect(now.every((d) => d.sent_at === null)).toBe(true);
588 expect(now[0]!.body).toContain(spoken("2026-11-20"));
589 expect(now[0]!.body).toContain(spoken("2026-11-25"));
590 expect(now[0]!.body).not.toContain(spoken(first));
591 expect(after.sent.filter((s) => s.moment === "moved").length).toBe(1);
592 });
593
594 test("a notice can be edited, declined, undone; marking done stops it", () => {
595 const deal = open({ address: "7 Moved Ln" });
596 const insp = due(deal, "inspection");
597 moveDeadline(db, alice, { id: insp.id, due: "2026-11-20", reason: "a" });
598 const [a, b] = drafts(fresh(deal.id), agent).filter((d) => d.moment === "moved");
599 const edited = sendReminder(db, alice, { deadlineId: insp.id, partyId: a!.party_id, moment: "moved", subject: "New date", body: "Moved, sorry — Dana", agent });
600 expect(edited.ok && edited.value.body).toBe("Moved, sorry — Dana");
601 const word = drafts(fresh(deal.id), agent).find((d) => d.moment === "moved" && d.party_id === a!.party_id)!;
602 expect(word.body).toBe("Moved, sorry — Dana");
603 expect(word.sent_at).not.toBeNull();
604 if (b !== undefined) {
605 const no = declineReminder(db, alice, { deadlineId: insp.id, partyId: b.party_id, moment: "moved", reason: "told by phone", agent });
606 expect(no.ok).toBe(true);
607 expect(drafts(fresh(deal.id), agent).find((d) => d.moment === "moved" && d.party_id === b.party_id)!.declined).not.toBeNull();
608 expect(undoDecline(db, alice, { deadlineId: insp.id, partyId: b.party_id, moment: "moved", agent }).ok).toBe(true);
609 expect(drafts(fresh(deal.id), agent).find((d) => d.moment === "moved" && d.party_id === b.party_id)!.declined).toBeNull();
610 }
611 markDone(db, alice, { id: insp.id, done: true });
612 expect(drafts(fresh(deal.id), agent).filter((d) => d.deadline_id === insp.id)).toEqual([]);
613 });
614
615 test("a date moved away and back is told of each move afresh", () => {
616 const deal = open({ address: "8 Moved Ln" });
617 const insp = due(deal, "inspection");
618 const home = insp.due;
619 moveDeadline(db, alice, { id: insp.id, due: "2026-11-20", reason: "a" });
620 const p = drafts(fresh(deal.id), agent).find((d) => d.moment === "moved")!;
621 sendReminder(db, alice, { deadlineId: insp.id, partyId: p.party_id, moment: "moved", agent });
622 moveDeadline(db, alice, { id: insp.id, due: home, reason: "b" });
623 moveDeadline(db, alice, { id: insp.id, due: "2026-11-20", reason: "c" });
624 const again = drafts(fresh(deal.id), agent).find((d) => d.moment === "moved" && d.party_id === p.party_id)!;
625 expect(again.sent_at).toBeNull();
626 });
src/deals.ts +34 −24
@@ -21,7 +21,7 @@ import {
2121 } from "./deadlines.ts";
2222 import { agent as defaultAgent, LENGTH_MAX, standard } from "./env.ts";
2323 import { emit } from "./live.ts";
24 import { draftsFor, type Agent, type Draft } from "./reminders.ts";
24 import { draftsFor, moveKey, type Agent, type Draft } from "./reminders.ts";
2525 import { audited, fail, ok, refuse, type Result } from "./result.ts";
2626 import type { Who } from "./who.ts";
2727
@@ -50,6 +50,8 @@ export interface Declined {
5050 readonly party_name: string;
5151 readonly moment: Moment;
5252 readonly due: string;
53 /** The move a "date changed" notice was about; 0 for every other moment. */
54 readonly move_id: number;
5355 /** Why the agent chose not to send it. */
5456 readonly reason: string;
5557 readonly by_name: string;
@@ -63,6 +65,8 @@ export interface Move {
6365 readonly reason: string;
6466 readonly by_name: string;
6567 readonly at: string;
68 /** 1 when the move owes the parties a "date changed" notice; 0 for a move made before notices existed. */
69 readonly notify: 0 | 1;
6670 }
6771 export interface Sent {
6872 readonly id: number;
@@ -76,6 +80,8 @@ export interface Sent {
7680 readonly party_role: PartyRole | "";
7781 readonly moment: Moment;
7882 readonly due: string;
83 /** The move a "date changed" notice was about; 0 for every other moment. */
84 readonly move_id: number;
7985 readonly by_name: string;
8086 readonly sent_at: string;
8187 /** The words that went out, as approved; '' on a reminder sent before they were kept. */
@@ -113,9 +119,9 @@ export interface DealView extends Deal {
113119 readonly declined: readonly Declined[];
114120 }
115121
116 export type Moment = "before" | "day_of" | "late";
122 export type Moment = "before" | "day_of" | "late" | "moved";
117123 export const isMoment = (v: unknown): v is Moment =>
118 v === "before" || v === "day_of" || v === "late";
124 v === "before" || v === "day_of" || v === "late" || v === "moved";
119125
120126 /** Text from a person: trimmed, one line, within bounds — or undefined. */
121127 export function line(value: unknown, min: number, max: number): string | undefined {
@@ -580,7 +586,7 @@ export function moveDeadline(
580586 db.transaction(() => {
581587 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(input.due as string, deadline.id);
582588 db.query(
583 "INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)",
589 "INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, notify) VALUES (?1, ?2, ?3, ?4, ?5, 1)",
584590 ).run(deadline.id, deadline.due, input.due as string, reason, authorOf(who).name);
585591 })();
586592 return within(db, who, dealId, ok(reread(db, deadline.id)));
@@ -734,7 +740,7 @@ export function sendReminder(
734740 const { dealId, found } = deadlineFor(db, who, input.deadlineId);
735741 if (!found.ok) return within(db, who, dealId, found);
736742 if (!isMoment(input.moment))
737 return within(db, who, dealId, fail("invalid", "A reminder is for three days before, the day of, or the day after (overdue)."));
743 return within(db, who, dealId, fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed."));
738744 const party = Number.isInteger(input.partyId)
739745 ? db
740746 .query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2")
@@ -743,11 +749,14 @@ export function sendReminder(
743749 if (party === null)
744750 return within(db, who, dealId, fail("not_found", "No such party on this deal."));
745751 const { deadline } = found.value;
752 const seen = view(db, found.value.deal);
746753 const draft = draftsFor(
747 view(db, found.value.deal),
748 { ...deadline, moves: [] },
754 seen,
755 seen.deadlines.find((d) => d.id === deadline.id)!,
749756 input.agent ?? defaultAgent,
750757 ).find((r) => r.party_id === party.id && r.moment === input.moment);
758 if (draft === undefined && input.moment === "moved")
759 return within(db, who, dealId, fail("not_found", "No such reminder on this date."));
751760 if (draft?.declined != null)
752761 return within(db, who, dealId, fail("invalid", "This reminder was declined; undo that first to send it."));
753762 const subject =
@@ -758,11 +767,11 @@ export function sendReminder(
758767 if (body === undefined)
759768 return within(db, who, dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`));
760769 const sent = db
761 .query<Sent, [number, number, number, string, string, string, string, string, string, string, string]>(
762 `INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
763 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET sent_at = sent_at RETURNING *`,
770 .query<Sent, [number, number, number, string, string, string, string, string, number, string, string, string]>(
771 `INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, move_id, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
772 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
764773 )
765 .get(found.value.deal.id, deadline.id, party.id, deadline.label, party.name, party.role, input.moment, deadline.due, authorOf(who).name, subject, body)!;
774 .get(found.value.deal.id, deadline.id, party.id, deadline.label, party.name, party.role, input.moment, deadline.due, moveKey(seen.deadlines.find((d) => d.id === deadline.id)!, input.moment), authorOf(who).name, subject, body)!;
766775 return within(db, who, dealId, ok(sent));
767776 }
768777
@@ -771,24 +780,25 @@ function draftOf(
771780 db: Database,
772781 who: Who,
773782 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent },
774 ): { dealId?: number; found: Result<{ draft: Draft; deal: Deal; deadline: Deadline; party: Party }> } {
783 ): { dealId?: number; found: Result<{ draft: Draft; deal: Deal; deadline: DeadlineView; party: Party }> } {
775784 const { dealId, found } = deadlineFor(db, who, input.deadlineId, input.dealId);
776785 if (!found.ok) return { dealId, found };
777786 if (!isMoment(input.moment))
778 return { dealId, found: fail("invalid", "A reminder is for three days before, the day of, or the day after (overdue).") };
787 return { dealId, found: fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed.") };
779788 const { deal, deadline } = found.value;
780789 const party = Number.isInteger(input.partyId)
781790 ? db.query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2").get(input.partyId, deal.id)
782791 : null;
792 const seen = view(db, deal).deadlines.find((d) => d.id === deadline.id)!;
783793 const draft =
784794 party === null
785795 ? undefined
786 : draftsFor(view(db, deal), { ...deadline, moves: [] }, input.agent ?? defaultAgent).find(
796 : draftsFor(view(db, deal), seen, input.agent ?? defaultAgent).find(
787797 (r) => r.party_id === party.id && r.moment === input.moment,
788798 );
789799 if (party === null || draft === undefined)
790800 return { dealId, found: fail("not_found", "No such reminder on this date.") };
791 return { dealId, found: ok({ draft, deal, deadline, party }) };
801 return { dealId, found: ok({ draft, deal, deadline: seen, party }) };
792802 }
793803
794804 /**
@@ -805,15 +815,15 @@ export function declineReminder(
805815 const reason = line(input.reason, 1, REASON_MAX);
806816 if (reason === undefined)
807817 return within(db, who, dealId, fail("invalid", `Say why in 1 to ${REASON_MAX} characters.`));
808 const { draft, deal } = found.value;
818 const { draft, deal, deadline } = found.value;
809819 if (draft.sent_at !== null)
810820 return within(db, who, dealId, fail("invalid", "This reminder was already sent."));
811821 const declined = db
812 .query<Declined, [number, number, number, string, string, string, string, string, string]>(
813 `INSERT INTO reminder_declined (deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
814 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET reason = excluded.reason, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`,
822 .query<Declined, [number, number, number, string, string, string, string, number, string, string]>(
823 `INSERT INTO reminder_declined (deal_id, deadline_id, party_id, label, party_name, moment, due, move_id, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
824 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET reason = excluded.reason, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`,
815825 )
816 .get(deal.id, draft.deadline_id, draft.party_id, draft.label, draft.party_name, draft.moment, draft.due, reason, authorOf(who).name)!;
826 .get(deal.id, draft.deadline_id, draft.party_id, draft.label, draft.party_name, draft.moment, draft.due, moveKey(deadline, draft.moment), reason, authorOf(who).name)!;
817827 return within(db, who, dealId, ok(declined));
818828 }
819829
@@ -825,12 +835,12 @@ export function undoDecline(
825835 ): Result<{ id: number }> {
826836 const { dealId, found } = draftOf(db, who, input);
827837 if (!found.ok) return within(db, who, dealId, found);
828 const { draft } = found.value;
838 const { draft, deadline } = found.value;
829839 const gone = db
830 .query<{ id: number }, [number, number, string, string]>(
831 "DELETE FROM reminder_declined WHERE deadline_id = ?1 AND party_id = ?2 AND moment = ?3 AND due = ?4 RETURNING id",
840 .query<{ id: number }, [number, number, string, string, number]>(
841 "DELETE FROM reminder_declined WHERE deadline_id = ?1 AND party_id = ?2 AND moment = ?3 AND due = ?4 AND move_id = ?5 RETURNING id",
832842 )
833 .get(draft.deadline_id, draft.party_id, draft.moment, draft.due);
843 .get(draft.deadline_id, draft.party_id, draft.moment, draft.due, moveKey(deadline, draft.moment));
834844 if (gone === null)
835845 return within(db, who, dealId, fail("invalid", "This reminder was not declined."));
836846 return within(db, who, dealId, ok({ id: gone.id }));
src/mcp.ts +3 −3
@@ -146,7 +146,7 @@ export const tools: readonly Tool[] = [
146146 properties: {
147147 deadline_id: { type: "integer" },
148148 party_id: { type: "integer" },
149 moment: { enum: ["before", "day_of", "late"] },
149 moment: { enum: ["before", "day_of", "late", "moved"] },
150150 subject: { type: "string", minLength: 1, maxLength: 150 },
151151 body: { type: "string", minLength: 1, maxLength: 2000 },
152152 },
@@ -164,7 +164,7 @@ export const tools: readonly Tool[] = [
164164 properties: {
165165 deadline_id: { type: "integer" },
166166 party_id: { type: "integer" },
167 moment: { enum: ["before", "day_of", "late"] },
167 moment: { enum: ["before", "day_of", "late", "moved"] },
168168 reason: { type: "string", minLength: 1, maxLength: 200 },
169169 },
170170 required: ["deadline_id", "party_id", "moment", "reason"],
@@ -177,7 +177,7 @@ export const tools: readonly Tool[] = [
177177 description: "Take back a decline: the reminder is a draft again, to send or decline.",
178178 inputSchema: {
179179 type: "object",
180 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late"] } },
180 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
181181 required: ["deadline_id", "party_id", "moment"],
182182 },
183183 run: (db, who, args) =>
src/reminders.ts +35 −9
@@ -7,10 +7,10 @@
77 * sent one, with the words approved; a sent draft reads back those words.
88 */
99
10 import { addDays, spoken } from "./dates.ts";
10 import { addDays, spoken, today } from "./dates.ts";
1111 import { memoizer, print } from "./memo.ts";
1212 import { KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
13 import type { DealView, DeadlineView, Moment, Party } from "./deals.ts";
13 import type { DealView, DeadlineView, Move, Moment, Party } from "./deals.ts";
1414
1515 export interface Agent {
1616 readonly name: string;
@@ -44,14 +44,30 @@ export interface Draft {
4444 readonly declined: { readonly reason: string; readonly by_name: string } | null;
4545 }
4646
47 export const MOMENTS: readonly Moment[] = ["before", "day_of", "late"];
47 export const MOMENTS: readonly Moment[] = ["before", "day_of", "late", "moved"];
4848 export const MOMENT_LABEL: Readonly<Record<Moment, string>> = {
4949 before: "3 days before",
5050 day_of: "Morning of",
5151 late: "Overdue follow-up",
52 moved: "Date changed",
5253 };
53 const OFFSET: Readonly<Record<Moment, number>> = { before: -3, day_of: 0, late: 1 };
54 export const sendOn = (due: string, moment: Moment): string => addDays(due, OFFSET[moment]);
54 const OFFSET: Readonly<Record<Exclude<Moment, "moved">, number>> = { before: -3, day_of: 0, late: 1 };
55 /** The morning a reminder goes out; a "date changed" notice goes the day of the move instead. */
56 export const sendOn = (due: string, moment: Exclude<Moment, "moved">): string => addDays(due, OFFSET[moment]);
57
58 /** The move a "date changed" notice is about: the latest, if the agent is to tell people of it. */
59 const lastMove = (deadline: DeadlineView): Move | undefined => {
60 const move = deadline.moves[deadline.moves.length - 1];
61 return move !== undefined && move.notify === 1 ? move : undefined;
62 };
63
64 /**
65 * Which move a sent or declined row is about: the id of the latest move for a
66 * "date changed" notice, 0 for every other moment. A date that moves back and
67 * forth is told of each move afresh.
68 */
69 export const moveKey = (deadline: DeadlineView, moment: Moment): number =>
70 moment === "moved" ? (lastMove(deadline)?.id ?? 0) : 0;
5571
5672 /**
5773 * The parties a moment tells: whoever owes the date, then whoever its kind
@@ -75,6 +91,13 @@ function words(
7591 ): { subject: string; body: string } {
7692 const owner = deal.parties.find((p) => p.role === deadline.owes);
7793 const owed = deadline.what === "" ? "" : `${deadline.what}. `;
94 if (moment === "moved") {
95 const move = lastMove(deadline)!;
96 return {
97 subject: `${deadline.label} — ${deal.address} — date changed`,
98 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)}. ${owed}Please work to the new date, and let me know if it causes a problem.\n\n${signOff(agent)}`,
99 };
100 }
78101 if (moment === "late") {
79102 return {
80103 subject: `${deadline.label} — ${deal.address} — overdue`,
@@ -106,21 +129,24 @@ const remembered = memoizer<Draft[]>(400);
106129
107130 /** The reminders one date has, sent or not. */
108131 export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent): Draft[] {
109 return MOMENTS.flatMap((moment) =>
132 return MOMENTS.filter((moment) => moment !== "moved" || lastMove(deadline) !== undefined).flatMap((moment) =>
110133 recipients(deal, deadline, moment).map((party) => {
134 const key = moveKey(deadline, moment);
111135 const sent = deal.sent.find(
112136 (s) =>
113137 s.deadline_id === deadline.id &&
114138 s.party_id === party.id &&
115139 s.moment === moment &&
116 s.due === deadline.due,
140 s.due === deadline.due &&
141 s.move_id === key,
117142 );
118143 const declined = deal.declined.find(
119144 (s) =>
120145 s.deadline_id === deadline.id &&
121146 s.party_id === party.id &&
122147 s.moment === moment &&
123 s.due === deadline.due,
148 s.due === deadline.due &&
149 s.move_id === key,
124150 );
125151 const drafted = words(deal, deadline, party, moment, agent);
126152 return {
@@ -134,7 +160,7 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
134160 party_role: party.role,
135161 contact: party.contact,
136162 moment,
137 on: sendOn(deadline.due, moment),
163 on: moment === "moved" ? today(new Date(lastMove(deadline)!.at)) : sendOn(deadline.due, moment),
138164 // A sent reminder keeps the words it went with, whatever the deal says now.
139165 subject: sent !== undefined && sent.subject !== "" ? sent.subject : drafted.subject,
140166 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
src/routes.ts +5 −5
@@ -191,7 +191,7 @@ export const DEAL: Schema = {
191191 id: { type: "integer" },
192192 deadline_id: { type: "integer" },
193193 party_id: { type: "integer" },
194 moment: { enum: ["before", "day_of", "late"] },
194 moment: { enum: ["before", "day_of", "late", "moved"] },
195195 due: DATE,
196196 reason: { type: "string", description: "Why the agent chose not to send it." },
197197 by_name: { type: "string" },
@@ -212,7 +212,7 @@ export const DEAL: Schema = {
212212 label: { type: "string", description: "The date it was about, as named when sent." },
213213 party_name: { type: "string" },
214214 party_role: { type: "string", description: "The party's role when sent; empty on a reminder sent before roles were kept." },
215 moment: { enum: ["before", "day_of", "late"] },
215 moment: { enum: ["before", "day_of", "late", "moved"] },
216216 due: DATE,
217217 by_name: { type: "string" },
218218 sent_at: { type: "string" },
@@ -253,7 +253,7 @@ export const DRAFT: Schema = {
253253 party_name: { type: "string" },
254254 party_role: ROLE,
255255 contact: { type: "string" },
256 moment: { enum: ["before", "day_of", "late"] },
256 moment: { enum: ["before", "day_of", "late", "moved"] },
257257 on: DATE,
258258 subject: { type: "string" },
259259 body: { type: "string" },
@@ -768,7 +768,7 @@ export const routes: readonly Route[] = [
768768 "Choose not to send a reminder, with a reason (1 to 200 characters). It is kept as a record, no longer counts as to send, and leaves /tick.",
769769 body: {
770770 type: "object",
771 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
771 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
772772 required: ["deadline_id", "party_id", "moment", "reason"],
773773 },
774774 answer: { type: "object", properties: { id: { type: "integer" }, reason: { type: "string" }, by_name: { type: "string" } }, required: ["id", "reason"] },
@@ -790,7 +790,7 @@ export const routes: readonly Route[] = [
790790 summary: "Take back a decline: the reminder is a draft again.",
791791 body: {
792792 type: "object",
793 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late"] } },
793 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
794794 required: ["deadline_id", "party_id", "moment"],
795795 },
796796 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
src/sample.ts +2 −1
@@ -199,6 +199,7 @@ export function refresh(db: Database, on = today()): void {
199199 for (const m of shifted.moves) db.query("UPDATE deadline_move SET from_due = ?1, to_due = ?2 WHERE id = ?3").run(m.fromDue, m.toDue, m.id);
200200 // The sample's sent reminder follows its date, so it stays "yesterday's".
201201 const days = `+${daysBetween(anchor, on)} days`;
202 db.query("UPDATE deadline_move SET at = strftime('%Y-%m-%dT%H:%M:%fZ', at, ?1) WHERE deadline_id IN (SELECT id FROM deadline WHERE deal_id = ?2)").run(days, deal.id);
202203 db.query("UPDATE reminder SET due = date(due, ?1), sent_at = strftime('%Y-%m-%dT%H:%M:%fZ', sent_at, ?1) WHERE deal_id = ?2 AND sample = 1").run(days, deal.id);
203204 }
204205 db.query("UPDATE app_meta SET value = ?1 WHERE key = 'sample_anchor'").run(on);
@@ -236,7 +237,7 @@ function writeSamples(db: Database, on: string): void {
236237 const d = db.query<{ id: number; due: string }, [number, string]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!;
237238 const to = addDays(on, days);
238239 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(to, d.id);
239 db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5)").run(d.id, d.due, to, reason, SAMPLE.name);
240 db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, at, notify) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1)").run(d.id, d.due, to, reason, SAMPLE.name, `${on}T08:00:00.000Z`);
240241 }
241242 }
242243 db.query("INSERT OR REPLACE INTO app_meta (key, value) VALUES ('seeded', ?1)").run(on);
src/server.test.ts +44
@@ -1123,3 +1123,47 @@ test("People lists each person once with the dates they owe, the page and the AP
11231123 const list = JSON.parse((await rpc({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_people", arguments: {} } }, pat)).result.content[0].text);
11241124 expect(list).toEqual(people);
11251125 });
1126
1127 test("a moved date's Date changed notice is sent, declined and undone through the routes and MCP, and the API keeps a plain date", async () => {
1128 const opened = await api("/api/deals", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ address: "77 Notice Rd", buyer: "Bea Buyer", seller: "Sid Seller", contract_date: "2026-11-02", closing_date: "2026-12-20" }) }, editor);
1129 expect(opened.status).toBe(201);
1130 const id = ((await opened.json()) as { id: number }).id;
1131 type View = { deadlines: { id: number; kind: string; due: string }[]; parties: { id: number; role: string }[]; sent: { moment: string; due: string; subject: string }[]; declined: { moment: string; due: string }[] };
1132 const read = async () => (await (await api(`/api/deals/${id}`, {}, editor)).json()) as View;
1133 const deal = await read();
1134 const insp = deal.deadlines.find((d) => d.kind === "inspection")!;
1135 const form = (path: string, fields: Record<string, string>, who = editor) => {
1136 const body = new FormData();
1137 for (const [k, v] of Object.entries(fields)) body.set(k, v);
1138 return api(path, { method: "POST", body, redirect: "manual" }, who);
1139 };
1140 expect((await form(`/deadlines/${insp.id}/move`, { due: "2026-12-01", reason: "Inspector away", to: "/" })).status).toBe(303);
1141 const [buyer, seller] = [deal.parties.find((p) => p.role === "buyer")!, deal.parties.find((p) => p.role === "seller")!];
1142 const ask = (party: { id: number }) => ({ deadline: String(insp.id), party: String(party.id), moment: "moved", to: "/" });
1143 const page = await (await api("/", {}, editor)).text();
1144 expect(page).toContain("Date changed");
1145 // The page's forms: send with edited words, decline, undo.
1146 expect((await form("/reminders", { ...ask(buyer), subject: "New date", body: "Moved to Dec 1." })).status).toBe(303);
1147 expect((await form("/reminders/decline", { ...ask(seller), reason: "Told by phone" })).status).toBe(303);
1148 let now = await read();
1149 expect(now.sent.find((s) => s.moment === "moved")).toMatchObject({ subject: "New date", due: "2026-12-01" });
1150 expect(now.sent.every((s) => /^\d{4}-\d\d-\d\d$/.test(s.due))).toBe(true);
1151 expect(now.declined.find((s) => s.moment === "moved")!.due).toBe("2026-12-01");
1152 expect((await form("/reminders/undo", ask(seller))).status).toBe(303);
1153 expect((await read()).declined.length).toBe(0);
1154 // MCP: decline, undo, then send the seller's notice.
1155 const tool = async (name: string, args: unknown) => (await rpc({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name, arguments: args } }, editor)).result;
1156 const mcp = { deadline_id: insp.id, party_id: seller.id, moment: "moved" };
1157 expect((await tool("decline_reminder", { ...mcp, reason: "Not yet" })).isError).toBeUndefined();
1158 expect((await tool("send_reminder", mcp)).isError).toBe(true);
1159 expect((await tool("undo_decline_reminder", mcp)).isError).toBeUndefined();
1160 const sent = await tool("send_reminder", mcp);
1161 expect(sent.isError).toBeUndefined();
1162 expect(JSON.parse(sent.content[0].text).body).toContain("Dec");
1163 now = await read();
1164 expect(now.sent.filter((s) => s.moment === "moved").length).toBe(2);
1165 expect(now.sent.every((s) => /^\d{4}-\d\d-\d\d$/.test(s.due))).toBe(true);
1166 // No notice exists for a date that never moved.
1167 const other = deal.deadlines.find((d) => d.kind === "financing")!;
1168 expect((await tool("send_reminder", { deadline_id: other.id, party_id: buyer.id, moment: "moved" })).isError).toBe(true);
1169 });
src/terminal.test.ts +43 −1
@@ -7,7 +7,7 @@ import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { addDays, spoken, today } from "./dates.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, markDone, sendReminder, type DealView } from "./deals.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, markDone, moveDeadline, 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";
@@ -478,3 +478,45 @@ test("P lists each person once with the dates they owe across deals; a guest is
478478 guest.press("P");
479479 expect(lines(guest).join("\n")).not.toContain("Lena Lender");
480480 });
481
482 test("a moved date's Date changed notice is on the reminders list; s sends it and the sent list reads its date", () => {
483 const made2 = createDeal(db, alice, { address: "31 Moved Way", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 45) });
484 if (!made2.ok) throw new Error(made2.message);
485 const insp = made2.value.deadlines.find((d) => d.kind === "inspection")!;
486 const to = addDays(insp.due, 5);
487 expect(moveDeadline(db, alice, { id: insp.id, due: to, reason: "Inspector away" }).ok).toBe(true);
488 const t = terminal(db, alice, context);
489 t.press("r");
490 for (let i = 0; i < 300 && !(under(t).includes("31 Moved Way") && under(t).includes("date changed")); i++) t.press("j");
491 expect(under(t)).toContain("date changed");
492 t.press("\r");
493 const read = lines(t).join("\n");
494 expect(read).toContain(spoken(insp.due));
495 expect(read).toContain(spoken(to));
496 expect(read).not.toContain("Inspector away");
497 t.press("s");
498 const row = db.query<{ moment: string; due: string; move_id: number }, [number]>("SELECT moment, due, move_id FROM reminder WHERE deal_id = ?1").get(made2.value.id)!;
499 expect(row.moment).toBe("moved");
500 expect(row.due).toBe(to);
501 expect(row.move_id).toBeGreaterThan(0);
502 const u = terminal(db, alice, context);
503 goTo(u, "Inspection period ends — 31 Moved Way");
504 press(u, "o", "s");
505 expect(lines(u).join("\n")).toContain(`${spoken(to)} · date changed`);
506 });
507
508 test("n declines a Date changed notice with a reason and u undoes it", () => {
509 const made3 = createDeal(db, alice, { address: "32 Moved Way", buyer: "Cy Buyer", seller: "Sol Seller", contractDate: today(), closingDate: addDays(today(), 45) });
510 if (!made3.ok) throw new Error(made3.message);
511 const insp = made3.value.deadlines.find((d) => d.kind === "inspection")!;
512 moveDeadline(db, alice, { id: insp.id, due: addDays(insp.due, 5), reason: "x" });
513 const t = terminal(db, alice, context);
514 t.press("r");
515 for (let i = 0; i < 300 && !(under(t).includes("32 Moved Way") && under(t).includes("date changed")); i++) t.press("j");
516 expect(under(t)).toContain("date changed");
517 press(t, "n", "told by phone\r");
518 const n = () => db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM reminder_declined WHERE deal_id = ?1 AND moment = 'moved'").get(made3.value.id)!.n;
519 expect(n()).toBe(1);
520 t.press("u");
521 expect(n()).toBe(0);
522 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs