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

A year after a deal closes, the agent gets a drafted "Happy home anniversary" note to their clients, approved like any reminder, so past clients hear from them when referrals come from #177

Merged opened this

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

Merged

mason/deal-clock:mason/173-a-year-after-a-deal-closes-the-agent-get → main 2 commits fork

  • Merged. mason/173-a-year-after-a-deal-closes-the-agent-get was merged into main as aa80ca6.

Review

Sign in to review this change.
25 files changed +417 −57
README.md +2 −1
@@ -102,7 +102,8 @@ sends each party one notice. Every date also takes a short working note only
102102 you see. A deal that falls through is marked with **Fell through…** and moves to
103103 the Closed list; **Reopen** brings it back. Closing a deal is marking its
104104 Closing date done: it steps off the clock, and a month later a drafted "How is
105 the new home?" check-in waits in Review.
105 the new home?" check-in waits in Review, and a year after, a "Happy home
106 anniversary" note to each past client that gently asks for referrals.
106107
107108 **Status update.** A deal's page offers each buyer and seller a drafted summary
108109 of what is done, what is next and when it closes, which you edit and send or
contract/openapi.json +18 −9
@@ -1179,7 +1179,8 @@
11791179 "late",
11801180 "moved",
11811181 "status",
1182 "checkin"
1182 "checkin",
1183 "anniversary"
11831184 ]
11841185 },
11851186 "due": {
@@ -1232,7 +1233,8 @@
12321233 "late",
12331234 "moved",
12341235 "status",
1235 "checkin"
1236 "checkin",
1237 "anniversary"
12361238 ]
12371239 },
12381240 "due": {
@@ -1835,7 +1837,8 @@
18351837 "late",
18361838 "moved",
18371839 "status",
1838 "checkin"
1840 "checkin",
1841 "anniversary"
18391842 ]
18401843 },
18411844 "reason": {
@@ -1931,7 +1934,8 @@
19311934 "day_of",
19321935 "late",
19331936 "moved",
1934 "checkin"
1937 "checkin",
1938 "anniversary"
19351939 ]
19361940 },
19371941 "subject": {
@@ -2029,7 +2033,8 @@
20292033 "day_of",
20302034 "late",
20312035 "moved",
2032 "checkin"
2036 "checkin",
2037 "anniversary"
20332038 ]
20342039 }
20352040 },
@@ -2113,7 +2118,8 @@
21132118 "late",
21142119 "moved",
21152120 "status",
2116 "checkin"
2121 "checkin",
2122 "anniversary"
21172123 ]
21182124 }
21192125 },
@@ -3310,7 +3316,8 @@
33103316 "late",
33113317 "moved",
33123318 "status",
3313 "checkin"
3319 "checkin",
3320 "anniversary"
33143321 ]
33153322 },
33163323 "due": {
@@ -3363,7 +3370,8 @@
33633370 "late",
33643371 "moved",
33653372 "status",
3366 "checkin"
3373 "checkin",
3374 "anniversary"
33673375 ]
33683376 },
33693377 "due": {
@@ -3464,7 +3472,8 @@
34643472 "late",
34653473 "moved",
34663474 "status",
3467 "checkin"
3475 "checkin",
3476 "anniversary"
34683477 ],
34693478 "description": "Why it goes out. checkin is the \"How is the new home?\" message to a past client 30 days after the deal's closing was marked done (buyers on a buyer-side deal, sellers on a listing, both on a both-sides deal); it hangs on the closing's deadline_id, its due is the day the closing was marked done, and a reopened or fell-through deal has none."
34703479 },
docs/TECHNICAL.md +8
@@ -38,6 +38,14 @@ was marked done. It hangs on the closing's `deadline_id`, is keyed by that day
3838 (so reopening and closing again is a new one), and is sent, held, declined and
3939 listed in `/tick` like any reminder. A reopened or fell-through deal has none.
4040
41 The same clients get a home anniversary note (`moment: "anniversary"`) on the
42 morning one year after that day, for ten years, drafted by `anniversaryDrafts`.
43 It is keyed by the closing, the day it was marked done and the year's number
44 (`move_id` 1 to 10), so a year's note that was sent, held or declined is never
45 made again; a closing marked done on 29 February is remembered on 28 February
46 in years without one. A missed note waits 30 days, then the year has passed.
47 Send, hold and decline name the latest year already come.
48
4149 A deal that falls through has `fell_at`, `fell_reason` and `fell_by` set
4250 (`deal.fell_through` in the JSON of `GET /api/deals`); `closed` keeps meaning
4351 "Closing marked done". It is off the clock like a closed deal: no reminders,
src/anniversary.test.ts added +125
@@ -0,0 +1,125 @@
1 /** A year after a closing is marked done, each past client is owed a home anniversary note, approved like any reminder. */
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 { anniversaryOn } from "./checkin.ts";
7 import { today, DEFAULT_ZONE } from "./dates.ts";
8 import { createDeal, declineReminder, getDeal, holdReminder, listDeals, markDone, sendReminder } from "./deals.ts";
9 import { openDb } from "./db.ts";
10 import { anniversaryDrafts, dueOn, todaysDrafts, unsent, waitingCount } from "./reminders.ts";
11 import { dealPage } from "./pages/deal.ts";
12 import type { Who } from "./who.ts";
13
14 const alice: Who = { role: "user", id: "u1", name: "alice" };
15 const dana = { name: "Dana", brokerage: "HP", phone: "(555) 010-0142", email: "[email protected]" };
16 const db = openDb(mkdtempSync(join(tmpdir(), "app-anniversary-")));
17
18 function closed(address: string, side: string, doneOn = "2026-10-01") {
19 const made = createDeal(db, alice, { openAnyway: true, address, buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-09-01", closingDate: "2026-10-01", side, salePrice: 612000 });
20 if (!made.ok) throw new Error(made.message);
21 db.query("UPDATE party SET email = lower(substr(name, 1, 3)) || '@example.com', contact = lower(substr(name, 1, 3)) || '@example.com' WHERE deal_id = ?1").run(made.value.id);
22 const closing = getDeal(db, alice, { id: made.value.id }).value!.deadlines.find((d) => d.kind === "closing")!;
23 markDone(db, alice, { id: closing.id, done: true });
24 db.query("UPDATE deadline SET done_at = ?1 WHERE id = ?2").run(`${doneOn}T12:00:00.000Z`, closing.id);
25 return { id: made.value.id, closing: closing.id };
26 }
27 const view = (id: number) => getDeal(db, alice, { id }).value!;
28 const all = () => listDeals(db, alice).value!;
29 const mine = (day: string, address: string) => todaysDrafts(all(), day, dana).filter((d) => d.moment === "anniversary" && d.address === address);
30
31 test("drafted on the day a year after the closing was marked done, to the clients the side names", () => {
32 closed("1 Buyer Side", "buyer");
33 closed("2 Listing", "listing");
34 closed("3 Both", "both");
35 const day = (d: string) => todaysDrafts(all(), d, dana).filter((x) => x.moment === "anniversary").map((x) => `${x.address}:${x.party_role}`);
36 expect(day("2027-09-30")).toEqual([]);
37 expect(day("2027-10-01").sort()).toEqual(["1 Buyer Side:buyer", "2 Listing:seller", "3 Both:buyer", "3 Both:seller"]);
38 expect(dueOn(all(), "2027-10-01", dana).filter((x) => x.moment === "anniversary")).toHaveLength(4);
39 expect(waitingCount(all(), "2027-10-01", dana) - waitingCount(all(), "2027-09-30", dana)).toBe(4);
40 // The next year it comes again; the day after it is not a new draft.
41 expect(day("2028-10-01")).toHaveLength(4);
42 expect(day("2027-10-02")).toHaveLength(4); // still waiting, the same four
43 });
44
45 test("the words greet by first name, name the address, ask once and never name the price", () => {
46 const d = anniversaryDrafts(view(closed("4 Words Lane", "buyer").id), dana)[0]!;
47 expect(d.subject).toContain("Happy home anniversary");
48 expect(d.subject).toContain("4 Words Lane");
49 expect(d.body).toStartWith("Hi Ann,");
50 expect(d.body).toContain("4 Words Lane");
51 expect(d.body.match(/buying or selling/g)).toHaveLength(1);
52 expect(d.body).not.toMatch(/612|\$/);
53 expect(d.body.endsWith("\n\nDana, HP\n(555) 010-0142 · [email protected]")).toBe(true);
54 });
55
56 test("a closing marked done on 29 February has its anniversary on 28 February in other years", () => {
57 expect(anniversaryOn("2028-02-29", 1)).toBe("2029-02-28");
58 expect(anniversaryOn("2028-02-29", 3)).toBe("2031-02-28");
59 expect(anniversaryOn("2028-02-29", 4)).toBe("2032-02-29");
60 expect(anniversaryOn("2026-10-01", 2)).toBe("2028-10-01");
61 const c = closed("5 Leap Year", "buyer", "2028-02-29");
62 expect(mine("2029-02-28", "5 Leap Year")).toHaveLength(1);
63 expect(mine("2029-03-01", "5 Leap Year").every((d) => d.on === "2029-02-28")).toBe(true);
64 expect(anniversaryDrafts(view(c.id), dana).map((d) => d.on)).toContain("2032-02-29");
65 });
66
67 test("a reopened deal and a fell-through deal get none", () => {
68 const a = closed("6 Reopened", "buyer");
69 expect(anniversaryDrafts(view(a.id), dana).length).toBeGreaterThan(0);
70 markDone(db, alice, { id: a.closing, done: false });
71 expect(anniversaryDrafts(view(a.id), dana)).toEqual([]);
72 const b = closed("7 Fell", "buyer");
73 db.query("UPDATE deal SET fell_at = '2026-10-05T00:00:00.000Z', fell_reason = 'x' WHERE id = ?1").run(b.id);
74 expect(anniversaryDrafts(view(b.id), dana)).toEqual([]);
75 expect(mine("2027-10-01", "7 Fell")).toEqual([]);
76 });
77
78 test("sent, declined or held, a year's note is never made again; the next year has its own", () => {
79 const s = closed("8 Sent", "buyer");
80 const d = anniversaryDrafts(view(s.id), dana)[0]!;
81 const sent = sendReminder(db, alice, { deadlineId: s.closing, partyId: d.party_id, moment: "anniversary", body: "Hi Ann, happy anniversary!", agent: dana });
82 expect(sent).toMatchObject({ ok: true, value: { moment: "anniversary", body: "Hi Ann, happy anniversary!" } });
83 expect(view(s.id).sent[0]).toMatchObject({ moment: "anniversary", body: "Hi Ann, happy anniversary!" });
84 // Offered again by a repeated tick: the same send, no second record.
85 sendReminder(db, alice, { deadlineId: s.closing, partyId: d.party_id, moment: "anniversary", agent: dana });
86 expect(view(s.id).sent.filter((m) => m.moment === "anniversary")).toHaveLength(1);
87 expect(mine("2027-10-01", "8 Sent").filter(unsent)).toEqual([]);
88 expect(mine("2027-10-02", "8 Sent").filter(unsent)).toEqual([]);
89 expect(mine("2028-10-01", "8 Sent").filter(unsent)).toHaveLength(1);
90
91 const n = closed("9 Declined", "buyer");
92 const nd = anniversaryDrafts(view(n.id), dana)[0]!;
93 expect(declineReminder(db, alice, { deadlineId: n.closing, partyId: nd.party_id, moment: "anniversary", reason: "Moved abroad", agent: dana }).ok).toBe(true);
94 expect(mine("2027-10-01", "9 Declined").filter(unsent)).toEqual([]);
95 expect(mine("2028-10-01", "9 Declined").filter(unsent)).toHaveLength(1);
96
97 const h = closed("10 Held", "buyer");
98 const hd = anniversaryDrafts(view(h.id), dana)[0]!;
99 expect(holdReminder(db, alice, { deadlineId: h.closing, partyId: hd.party_id, moment: "anniversary", on: "2027-10-01", agent: dana }).ok).toBe(true);
100 expect(mine("2027-10-01", "10 Held").filter(unsent)).toEqual([]);
101 expect(mine("2027-10-02", "10 Held").filter(unsent)).toHaveLength(1);
102 });
103
104 test("a missed note waits a month, then the year has passed", () => {
105 closed("11 Missed", "buyer");
106 expect(mine("2027-10-31", "11 Missed").filter(unsent)).toHaveLength(1);
107 expect(mine("2027-11-01", "11 Missed").filter(unsent)).toEqual([]);
108 });
109
110 test("the deal page offers the note on the day, not before", () => {
111 const c = closed("12 Page", "buyer");
112 expect(dealPage({ who: alice, deal: view(c.id), on: "2027-09-30" })).not.toContain("Home anniversary");
113 expect(dealPage({ who: alice, deal: view(c.id), on: "2027-10-01" })).toContain("Home anniversary");
114 });
115
116 test("a new database has one closed sample whose anniversary is today, waiting in Review", () => {
117 const fresh = openDb(mkdtempSync(join(tmpdir(), "app-anniversary-sample-")));
118 const on = today(DEFAULT_ZONE);
119 const deals = listDeals(fresh, alice).value!;
120 const waiting = todaysDrafts(deals, on, dana).filter((d) => d.moment === "anniversary");
121 expect(waiting).toHaveLength(1);
122 expect(waiting[0]!).toMatchObject({ address: "58 Larkspur Way", on, sent_at: null });
123 // Its month-after check-in went out long ago, so only the anniversary waits.
124 expect(todaysDrafts(deals, on, dana).filter((d) => d.address === "58 Larkspur Way" && unsent(d))).toHaveLength(1);
125 });
src/checkin.ts +25
@@ -26,3 +26,28 @@ export function checkinWords(address: string, firstName: string, signOff: string
2626 body: `Hi ${firstName}, it has been about a month since ${address}, and I wanted to ask how the move went. Is the home treating you well?\n\nIf anything has come up since closing, I'm happy to help with it, whether that's a question about the paperwork or a good name for a plumber.\n\nAnd if you know someone thinking of buying or selling, I'd be glad to look after them the way I looked after you. No pressure at all; I'm just glad to have been part of it.\n\n${signOff}`,
2727 };
2828 }
29
30 // ---- the home anniversary: each year after the closing, to the same clients ----
31
32 /** How many anniversaries are drafted after a closing: ten years of keeping in touch. */
33 export const ANNIVERSARY_YEARS = 10;
34
35 /**
36 * The morning of the `year`th anniversary of the day a closing was marked
37 * done. A closing marked done on 29 February has it on 28 February in the
38 * years that have no 29th.
39 */
40 export function anniversaryOn(doneOn: string, year: number): string {
41 const y = Number(doneOn.slice(0, 4)) + year;
42 const md = doneOn.slice(5);
43 const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
44 return `${String(y).padStart(4, "0")}-${md === "02-29" && !leap ? "02-28" : md}`;
45 }
46
47 /** The words of a home anniversary note to one client; never the price. */
48 export function anniversaryWords(address: string, firstName: string, signOff: string): { subject: string; body: string } {
49 return {
50 subject: `Happy home anniversary — ${address}`,
51 body: `Hi ${firstName}, happy home anniversary! It was a year ago that ${address} became yours, and I was thinking of you today. I hope it feels more like home with every season.\n\nIf you know someone thinking of buying or selling, I'd be glad to look after them the way I looked after you. No pressure at all; I'm just glad to have been part of it.\n\n${signOff}`,
52 };
53 }
src/db.test.ts +1 −1
@@ -31,7 +31,7 @@ test("the sample deals are written once, however many processes open a new file"
3131 openDb(dir);
3232 const count = (db: typeof a) =>
3333 db.query<{ n: number }, []>("SELECT count(*) AS n FROM deal WHERE author_id = 'sample'").get()!.n;
34 expect([count(a), count(b)]).toEqual([7, 7]);
34 expect([count(a), count(b)]).toEqual([8, 8]);
3535 });
3636
3737 test("sample deals boot looking like today, and a changed one is left alone", () => {
src/db.ts +66
@@ -503,6 +503,72 @@ export const migrations: string[] = [
503503 `ALTER TABLE profile ADD COLUMN zone TEXT NOT NULL DEFAULT 'America/New_York' CHECK (length(zone) BETWEEN 1 AND 64)`,
504504 // A cash purchase has no loan: its deal plans no appraisal or financing date and tells no lender.
505505 `ALTER TABLE deal ADD COLUMN cash INTEGER NOT NULL DEFAULT 0 CHECK (cash IN (0, 1))`,
506 // A home anniversary a year after a closing is a seventh moment, `anniversary`. SQLite cannot alter a
507 // CHECK, so the three tables that hold a moment are rebuilt as before.
508 `CREATE TABLE reminder_new (
509 id INTEGER PRIMARY KEY,
510 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
511 deadline_id INTEGER NOT NULL,
512 party_id INTEGER NOT NULL,
513 label TEXT NOT NULL,
514 party_name TEXT NOT NULL,
515 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved', 'status', 'checkin', 'anniversary')),
516 due TEXT NOT NULL,
517 by_name TEXT NOT NULL,
518 subject TEXT NOT NULL DEFAULT '',
519 body TEXT NOT NULL DEFAULT '',
520 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
521 party_role TEXT NOT NULL DEFAULT '',
522 sample INTEGER NOT NULL DEFAULT 0,
523 move_id INTEGER NOT NULL DEFAULT 0,
524 UNIQUE (deadline_id, party_id, moment, due, move_id)
525 );
526 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)
527 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body, sent_at, party_role, sample, move_id FROM reminder;
528 DROP TABLE reminder;
529 ALTER TABLE reminder_new RENAME TO reminder;
530 CREATE INDEX reminder_deal ON reminder (deal_id);
531 CREATE TABLE reminder_declined_new (
532 id INTEGER PRIMARY KEY,
533 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
534 deadline_id INTEGER NOT NULL,
535 party_id INTEGER NOT NULL,
536 label TEXT NOT NULL,
537 party_name TEXT NOT NULL,
538 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved', 'status', 'checkin', 'anniversary')),
539 due TEXT NOT NULL,
540 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
541 by_name TEXT NOT NULL,
542 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
543 move_id INTEGER NOT NULL DEFAULT 0,
544 UNIQUE (deadline_id, party_id, moment, due, move_id)
545 );
546 INSERT INTO reminder_declined_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at, move_id)
547 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at, move_id FROM reminder_declined;
548 DROP TABLE reminder_declined;
549 ALTER TABLE reminder_declined_new RENAME TO reminder_declined;
550 CREATE INDEX reminder_declined_deal ON reminder_declined (deal_id);
551 CREATE TABLE reminder_hold_new (
552 id INTEGER PRIMARY KEY,
553 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
554 deadline_id INTEGER NOT NULL,
555 party_id INTEGER NOT NULL,
556 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved', 'checkin', 'anniversary')),
557 due TEXT NOT NULL,
558 move_id INTEGER NOT NULL DEFAULT 0,
559 until TEXT NOT NULL,
560 held_on TEXT NOT NULL,
561 by_name TEXT NOT NULL,
562 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
563 subject TEXT NOT NULL DEFAULT '',
564 body TEXT NOT NULL DEFAULT '',
565 UNIQUE (deadline_id, party_id, moment, due, move_id)
566 );
567 INSERT INTO reminder_hold_new (id, deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name, at, subject, body)
568 SELECT id, deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name, at, subject, body FROM reminder_hold;
569 DROP TABLE reminder_hold;
570 ALTER TABLE reminder_hold_new RENAME TO reminder_hold;
571 CREATE INDEX reminder_hold_deal ON reminder_hold (deal_id)`,
506572 ];
507573
508574 export function openDb(dir = dataDir): Database {
src/deals.test.ts +2 −2
@@ -64,7 +64,7 @@ test("a new database carries four sample deals: one overdue, one closing this we
6464 const all = listDeals(db, bob);
6565 if (!all.ok) throw new Error(all.message);
6666 const samples = all.value.filter((d) => d.author_id === "sample");
67 expect(samples.length).toBe(7);
67 expect(samples.length).toBe(8);
6868 const on = today(DEFAULT_ZONE);
6969 expect(
7070 samples.some((d) => d.deadlines.some((x) => x.done_at === null && x.due < on)),
@@ -289,7 +289,7 @@ test("the book: every open date of every open deal, no done dates, no closed dea
289289 const all = listDeals(db, bob);
290290 if (!all.ok) throw new Error(all.message);
291291 const deals = all.value.filter((d) => d.author_id === "sample");
292 expect(deals.length).toBe(7);
292 expect(deals.length).toBe(8);
293293 const stamp = new Date("2026-10-12T08:00:00Z");
294294 const count = (ics: string) => ics.split("BEGIN:VEVENT").length - 1;
295295 const openDates = (list: readonly DealView[]) =>
src/deals.ts +2 −2
@@ -206,9 +206,9 @@ export interface DealView extends Deal {
206206 readonly conflicts: readonly Conflict[];
207207 }
208208
209 export type Moment = "before" | "day_of" | "late" | "moved" | "status" | "checkin";
209 export type Moment = "before" | "day_of" | "late" | "moved" | "status" | "checkin" | "anniversary";
210210 export const isMoment = (v: unknown): v is Moment =>
211 v === "before" || v === "day_of" || v === "late" || v === "moved" || v === "status" || v === "checkin";
211 v === "before" || v === "day_of" || v === "late" || v === "moved" || v === "status" || v === "checkin" || v === "anniversary";
212212
213213 /** Text from a person: trimmed, one line, within bounds — or undefined. */
214214 export function line(value: unknown, min: number, max: number): string | undefined {
src/earnest.test.ts +1 −1
@@ -66,7 +66,7 @@ test("the restored samples carry the deposit: done on three, ahead on Juniper Co
6666 "SELECT d.address, k.due, k.done_at FROM deadline k JOIN deal d ON d.id = k.deal_id WHERE k.kind = 'earnest' ORDER BY d.id",
6767 )
6868 .all();
69 expect(rows.length).toBe(7);
69 expect(rows.length).toBe(8);
7070 const by = (a: string) => rows.find((r) => r.address.includes(a))!;
7171 expect(by("Alder Lane").done_at).not.toBeNull();
7272 expect(by("Juniper").done_at).toBeNull();
src/figures.test.ts +1 −1
@@ -160,7 +160,7 @@ test("the sample deals carry plausible figures, and restoring them brings them b
160160 const rows = db.query<{ address: string; sale_price: number | null; earnest_amount: number | null }, [string]>("SELECT address, sale_price, earnest_amount FROM deal WHERE author_id = ?1 ORDER BY id").all("sample");
161161 return rows;
162162 };
163 expect(figures().length).toBe(7);
163 expect(figures().length).toBe(8);
164164 for (const r of figures()) {
165165 expect(r.sale_price).toBeGreaterThan(100_000);
166166 expect(r.earnest_amount).toBeGreaterThan(0);
src/mcp.ts +5 −5
@@ -248,7 +248,7 @@ export const tools: readonly Tool[] = [
248248 properties: {
249249 deadline_id: { type: "integer" },
250250 party_id: { type: "integer" },
251 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] },
251 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] },
252252 subject: { type: "string", minLength: 1, maxLength: 150 },
253253 body: { type: "string", minLength: 1, maxLength: 2000 },
254254 },
@@ -290,7 +290,7 @@ export const tools: readonly Tool[] = [
290290 properties: {
291291 deadline_id: { type: "integer" },
292292 party_id: { type: "integer" },
293 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] },
293 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] },
294294 reason: { type: "string", minLength: 1, maxLength: 200 },
295295 },
296296 required: ["deadline_id", "party_id", "moment", "reason"],
@@ -304,7 +304,7 @@ export const tools: readonly Tool[] = [
304304 "Hold a reminder until tomorrow, for a message the agent is not ready to approve: it leaves reminders_today and comes back the next morning with its words, labelled held. Give subject (up to 150 characters) and body (up to 2000) to hold the agent's edited words; leave them out to keep any already held. Held again, it waits one more day. A status update is not held.",
305305 inputSchema: {
306306 type: "object",
307 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin"] }, subject: { type: "string" }, body: { type: "string" } },
307 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin", "anniversary"] }, subject: { type: "string" }, body: { type: "string" } },
308308 required: ["deadline_id", "party_id", "moment"],
309309 },
310310 run: (db, who, args) =>
@@ -315,7 +315,7 @@ export const tools: readonly Tool[] = [
315315 description: "Bring a held reminder back to today, for when the agent is ready to send it after all: the hold is deleted and it returns to reminders_today. Refused when it is not held, or was already sent or declined.",
316316 inputSchema: {
317317 type: "object",
318 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin"] } },
318 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin", "anniversary"] } },
319319 required: ["deadline_id", "party_id", "moment"],
320320 },
321321 run: (db, who, args) =>
@@ -326,7 +326,7 @@ export const tools: readonly Tool[] = [
326326 description: "Take back a decline: the reminder is a draft again, to send or decline.",
327327 inputSchema: {
328328 type: "object",
329 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] } },
329 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] } },
330330 required: ["deadline_id", "party_id", "moment"],
331331 },
332332 run: (db, who, args) =>
src/migrations.pin.json +2 −1
@@ -54,5 +54,6 @@
5454 "72f67a8e8f06f9b9fcac58ff22eb3f4222c77a0968da5981d4e7dce8d4b8ce7d",
5555 "166c5e5ec18272d556b87786396c5c3a17da8b56185643e8efeeb83742cc2b5b",
5656 "3fbd9e1851d9bc86a3a4c5adfc9f2300712c450b66a87d253cfcb91586cbbe25",
57 "7e011fb3dab2123101aa981ef9050d8f8d2c34fb3ba137ecc832f86d464b98a2"
57 "7e011fb3dab2123101aa981ef9050d8f8d2c34fb3ba137ecc832f86d464b98a2",
58 "429a2adfb36ff61def2d1979556a9db87f4758663fa9c56b97e599b3bc13b773"
5859 ]
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/.test(m));
16 const before = migrations.filter((m) => !/profile ADD COLUMN line|commission_rate|profile ADD COLUMN zone|ADD COLUMN cash|'anniversary'/.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/deal.ts +15 −1
@@ -13,7 +13,7 @@ import { escape } from "../http.ts";
1313 import { coming, comingLine, type Coming } from "../coming.ts";
1414 import { closingLine } from "../closing.ts";
1515 import { commission, dollars, percent } from "../money.ts";
16 import { checkinDrafts, drafts, sentLabel, statusDrafts, type Agent } from "../reminders.ts";
16 import { anniversaryDrafts, checkinDrafts, drafts, pending, sentLabel, statusDrafts, type Agent } from "../reminders.ts";
1717 import type { Who } from "../who.ts";
1818 import { amendForm, type AmendState } from "./amend.ts";
1919 import { partyContact } from "./contact.ts";
@@ -109,6 +109,19 @@ function checkinCard(deal: DealView, agent: Agent, on: string, may: boolean, to:
109109 </section>`;
110110 }
111111
112 /** A closed deal's home anniversary notes: offered on the day, or once they have a record; never before. */
113 function anniversaryCard(deal: DealView, agent: Agent, on: string, may: boolean, to: string): string {
114 const these = anniversaryDrafts(deal, agent).filter(
115 (d) => pending(d, on) || d.sent_at !== null || d.declined !== null || d.held !== null,
116 );
117 if (these.length === 0) return "";
118 return `<section class="card" id="anniversary">
119 <h2>Home anniversary</h2>
120 <p class="muted small">A year after closing: a warm note to each past client, with one gentle ask for a referral. Nothing goes out until you send it.</p>
121 <ul class="drafts">${these.map((d) => draftItem(d, on, may, to)).join("")}</ul>
122 </section>`;
123 }
124
112125 /** The record of what went out: each sent reminder with the words approved, newest first. */
113126 function messages(deal: DealView, may: boolean, agent: Agent, to: string): string {
114127 const holding = drafts(deal, agent).flatMap((d) => (d.held === null ? [] : [{ d, held: d.held }]));
@@ -375,6 +388,7 @@ export function dealPage(input: {
375388 </section>
376389 ${statusCard(deal, agent ?? defaults, on, may, path)}
377390 ${checkinCard(deal, agent ?? defaults, on, may, path)}
391 ${anniversaryCard(deal, agent ?? defaults, on, may, path)}
378392 <section class="card" id="messages">
379393 <h2>Messages</h2>
380394 ${messages(deal, may, agent ?? defaults, path)}
src/pages/sheet.ts +2 −2
@@ -182,8 +182,8 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string): s
182182 * for, where the draft is edited and sent. The clock carries no forms.
183183 */
184184 export const draftLink = (draft: Draft, on: string): string =>
185 draft.moment === "checkin"
186 ? `<li class="draft"><a class="draft-open" href="/deals/${draft.deal_id}#checkin">${draftLine(draft, on, true)}</a></li>`
185 draft.moment === "checkin" || draft.moment === "anniversary"
186 ? `<li class="draft"><a class="draft-open" href="/deals/${draft.deal_id}#${draft.moment}">${draftLine(draft, on, true)}</a></li>`
187187 : `<li class="draft"><a class="draft-open" href="/deals/${draft.deal_id}#sheet-${draft.deadline_id}" data-sheet="sheet-${draft.deadline_id}" data-sheets="/deals/${draft.deal_id}/sheets">${draftLine(draft, on, true)}</a></li>`;
188188
189189 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string, agent: Agent = defaults, typed?: { id: number; note: string }): string {
src/reminders.ts +76 −5
@@ -8,9 +8,9 @@
88 * sent one, with the words approved; a sent draft reads back those words.
99 */
1010
11 import { addDays, dayOf, dayOfStamp, relative, short, spoken, today, weekday } from "./dates.ts";
11 import { addDays, daysBetween, dayOf, dayOfStamp, relative, short, spoken, today, weekday } from "./dates.ts";
1212 import { closingAfterDate } from "./closing.ts";
13 import { checkinOn, checkinRoles, checkinWords } from "./checkin.ts";
13 import { ANNIVERSARY_YEARS, anniversaryOn, anniversaryWords, checkinOn, checkinRoles, checkinWords } from "./checkin.ts";
1414 import { dollars } from "./money.ts";
1515 import { memoizer, print } from "./memo.ts";
1616 import { DEFAULT_LEAD, isOpen, KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
@@ -65,6 +65,7 @@ export interface Draft {
6565 export const MOMENTS: readonly Moment[] = ["before", "day_of", "late", "moved"];
6666 const MOMENT_LABEL: Readonly<Record<Exclude<Moment, "before">, string>> = {
6767 checkin: "Check-in",
68 anniversary: "Home anniversary",
6869 status: "Status update",
6970 day_of: "Morning of",
7071 late: "Overdue follow-up",
@@ -199,7 +200,7 @@ function words(
199200 * reminds no one of a date, but has its check-ins a month after the closing.
200201 */
201202 export function drafts(deal: DealView, agent: Agent): readonly Draft[] {
202 if (deal.closed && !deal.fell_through) return checkinDrafts(deal, agent);
203 if (deal.closed && !deal.fell_through) return [...checkinDrafts(deal, agent), ...anniversaryDrafts(deal, agent)];
203204 if (deal.closed || deal.fell_through) return [];
204205 return remembered(`${JSON.stringify(agent)}|${print(deal)}`, () =>
205206 deal.deadlines
@@ -305,6 +306,59 @@ export function checkinDrafts(deal: DealView, agent: Agent): Draft[] {
305306 });
306307 }
307308
309 // ---- the home anniversary: each year after the closing, to the clients ----
310
311 /**
312 * The anniversary note each client with a contact is owed every year after the
313 * closing was marked done, for `ANNIVERSARY_YEARS` years. Keyed by the closing,
314 * the day it was marked done and the year's number (`move_id`), so a draft
315 * made, held, declined or sent for one year is never made again for it.
316 */
317 export function anniversaryDrafts(deal: DealView, agent: Agent): Draft[] {
318 const closing = deal.deadlines.find((d) => d.kind === "closing");
319 if (!deal.closed || deal.fell_through || closing === undefined || closing.done_on === null) return [];
320 const doneOn = closing.done_on;
321 const roles = checkinRoles(deal.side);
322 return deal.parties
323 .filter((p) => roles.includes(p.role) && p.contact !== "")
324 .flatMap((party) =>
325 Array.from({ length: ANNIVERSARY_YEARS }, (_, i) => i + 1).map((year) => {
326 const mine = (s: { deadline_id: number; party_id: number; moment: Moment; due: string; move_id: number }): boolean =>
327 s.deadline_id === closing.id && s.party_id === party.id && s.moment === "anniversary" && s.due === doneOn && s.move_id === year;
328 const sent = deal.sent.find(mine);
329 const declined = deal.declined.find(mine);
330 const held = sent === undefined && declined === undefined ? deal.held.find(mine) : undefined;
331 const drafted = anniversaryWords(deal.address, first(party.name), signOff(agent));
332 return {
333 deal_id: deal.id,
334 address: deal.address,
335 deadline_id: closing.id,
336 label: closing.label,
337 due: doneOn,
338 party_id: party.id,
339 party_name: party.name,
340 party_role: party.role,
341 contact: party.contact,
342 email: party.email,
343 phone: party.phone,
344 moment: "anniversary" as const,
345 lead_days: closing.lead_days,
346 move_id: year,
347 on: anniversaryOn(doneOn, year),
348 subject: sent !== undefined && sent.subject !== "" ? sent.subject : held !== undefined && held.subject !== "" ? held.subject : drafted.subject,
349 body: sent !== undefined && sent.subject !== "" ? sent.body : held !== undefined && held.body !== "" ? held.body : drafted.body,
350 sent_at: sent?.sent_at ?? null,
351 sent_on: sent === undefined ? null : dayOfStamp(deal.zone, sent.sent_at),
352 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
353 held: held === undefined ? null : { until: held.until, from: held.held_on, by_name: held.by_name },
354 };
355 }),
356 );
357 }
358
359 /** A missed anniversary note still waits this many days; after that the year has passed. */
360 const ANNIVERSARY_GRACE = 30;
361
308362 // ---- the status update: one message about the deal as a whole ----
309363
310364 /** At most this many open dates are named as what comes next. */
@@ -392,8 +446,15 @@ export function statusDrafts(deal: DealView, agent: Agent): Draft[] {
392446 });
393447 }
394448
449 /** The one anniversary note a send, hold or decline means: the latest year already come, sent or not, else the first. */
450 function anniversaryOf(years: readonly Draft[], zone: string): Draft | undefined {
451 const day = today(zone);
452 return years.filter((d) => d.on <= day).at(-1) ?? years[0];
453 }
454
395455 /** The draft of `moment` that `party` has on `deadline`, if any: a reminder, or the deal's status update on its closing date. */
396456 export function draftOfMoment(deal: DealView, deadline: DeadlineView, agent: Agent, party: Party, moment: Moment): Draft | undefined {
457 if (moment === "anniversary") return deadline.kind === "closing" ? anniversaryOf(anniversaryDrafts(deal, agent).filter((r) => r.party_id === party.id), deal.zone) : undefined;
397458 if (moment === "checkin") return deadline.kind === "closing" ? checkinDrafts(deal, agent).find((r) => r.party_id === party.id) : undefined;
398459 if (moment !== "status" && !isOpen(deadline)) return undefined;
399460 const these = moment === "status" ? (deadline.kind === "closing" ? statusDrafts(deal, agent) : []) : draftsFor(deal, deadline, agent);
@@ -413,17 +474,27 @@ export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Dr
413474 * long as the date stays open.
414475 */
415476 export const pending = (d: Draft, day: string): boolean =>
416 d.held !== null
477 d.moment === "anniversary"
478 ? d.held !== null
479 ? d.held.until <= day && d.on <= day && daysBetween(d.on, day) < 365
480 : d.on === day || (d.on < day && unsent(d) && daysBetween(d.on, day) <= ANNIVERSARY_GRACE)
481 : d.held !== null
417482 ? d.held.until <= day && (d.on === day || d.due >= day || d.moment === "late" || d.moment === "checkin")
418483 : d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late" || d.moment === "checkin"));
419484
485 /** Open deals first, then the closed ones newest first: the clock's own order, so the review page's first draft is the clock's first row. */
486 export const inClockOrder = (deals: readonly DealView[]): DealView[] => {
487 const closed = (deal: DealView): boolean => deal.closed && !deal.fell_through;
488 return [...deals.filter((deal) => !closed(deal)), ...deals.filter(closed).sort((a, b) => b.closing.localeCompare(a.closing) || b.id - a.id)];
489 };
490
420491 /**
421492 * The drafts waiting on `day` across these deals, in the order the clock lists
422493 * them: deal by deal, date by date. The clock's "Reminders for today" and the
423494 * review page both read it, so they never disagree.
424495 */
425496 export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] => {
426 const these = deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day)));
497 const these = inClockOrder(deals).flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day)));
427498 // A reminder held from an earlier day comes back at the top.
428499 return [...these.filter(returned), ...these.filter((d) => !returned(d))];
429500 };
src/restore.test.ts +3 −3
@@ -40,7 +40,7 @@ test("restoring brings the README walk-through back and leaves a person's deal b
4040 expect(date(sample("Harbor View"), "inspection").done_at).not.toBeNull();
4141 const restored = restoreSamples(db, root);
4242 expect(restored.ok).toBe(true);
43 expect(samples().length).toBe(7);
43 expect(samples().length).toBe(8);
4444 expect(JSON.stringify(all().find((d) => d.id === mine.value.id))).toBe(before);
4545
4646 const harbor = date(sample("Harbor View"), "inspection");
@@ -60,7 +60,7 @@ test("restoring twice leaves what once did, and the seeded guard is not tripped"
6060 const once = JSON.stringify(shape());
6161 restoreSamples(db, root);
6262 expect(JSON.stringify(shape())).toBe(once);
63 expect(samples().length).toBe(7);
63 expect(samples().length).toBe(8);
6464 expect(db.query("SELECT count(*) AS n FROM app_meta WHERE key = 'seeded'").get()).toEqual({ n: 1 });
6565 });
6666
@@ -91,6 +91,6 @@ test("a sample whose address was corrected is still that sample: it moves with t
9191 expect(moved.address).toBe("9 Orchard Row, Unit 2");
9292 expect(moved.closing).toBe(addDays(closing, 5));
9393 restoreSamples(db, root);
94 expect(samples().length).toBe(7);
94 expect(samples().length).toBe(8);
9595 expect(samples().filter((d) => d.address.includes("Orchard Row")).map((d) => d.address)).toEqual(["9 Orchard Row"]);
9696 });
src/review.test.ts +7 −3
@@ -21,7 +21,7 @@ const get = async (path: string): Promise<string> => (await fetch(base + path, {
2121 const clockRows = async (): Promise<string[]> => {
2222 const page = await get("/");
2323 const today = page.slice(page.indexOf('id="today"'));
24 return [...today.matchAll(/<li class="draft"><a class="draft-open" href="\/deals\/(\d+)#sheet-(\d+)"[^>]*><span><b>([^<]*)<\/b>/g)].map((m) => `${m[2]}:${m[3]}`);
24 return [...today.matchAll(/<li class="draft"><a class="draft-open" href="\/deals\/(\d+)#(?:sheet-(\d+)|anniversary)"[^>]*><span><b>([^<]*)<\/b>/g)].map((m) => `${m[2] ?? ""}:${m[3]}`);
2525 };
2626
2727 /** The draft a review page shows: its date's id, the party, and the hidden fields to post back. */
@@ -40,8 +40,12 @@ const keys = (s: ReturnType<typeof shown>) => ({ deadline: s.deadline, party: s.
4040 test("the clock offers Review all, and the page's first draft is the clock's first row", async () => {
4141 expect(await get("/")).toContain('href="/reminders/today">Review all</a>');
4242 const rows = await clockRows();
43 const first = shown(await get("/reminders/today"));
44 expect(first.deadline).toBe(rows[0]!.split(":")[0]!);
43 const page = await get("/reminders/today");
44 const first = shown(page);
45 const [deadline, name] = rows[0]!.split(":") as [string, string];
46 // A home anniversary note hangs on the deal's page, not on a date's sheet: the clock names no date for it.
47 if (deadline === "") expect(page).toContain(`<b>${name}</b>`);
48 else expect(first.deadline).toBe(deadline);
4549 expect(first.counter).toBe(`1/${rows.length}`);
4650 });
4751
src/routes.ts +7 −7
@@ -347,7 +347,7 @@ export const DEAL: Schema = {
347347 id: { type: "integer" },
348348 deadline_id: { type: "integer" },
349349 party_id: { type: "integer" },
350 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] },
350 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] },
351351 due: DATE,
352352 reason: { type: "string", description: "Why the agent chose not to send it." },
353353 by_name: { type: "string" },
@@ -368,7 +368,7 @@ export const DEAL: Schema = {
368368 label: { type: "string", description: "The date it was about, as named when sent." },
369369 party_name: { type: "string" },
370370 party_role: { type: "string", description: "The party's role when sent; empty on a reminder sent before roles were kept." },
371 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] },
371 moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] },
372372 due: DATE,
373373 by_name: { type: "string" },
374374 sent_at: { type: "string" },
@@ -433,7 +433,7 @@ export const DRAFT: Schema = {
433433 phone: { type: "string" },
434434 contact: CONTACT,
435435 moment: {
436 enum: ["before", "day_of", "late", "moved", "status", "checkin"],
436 enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"],
437437 description:
438438 "Why it goes out. checkin is the \"How is the new home?\" message to a past client 30 days after the deal's closing was marked done (buyers on a buyer-side deal, sellers on a listing, both on a both-sides deal); it hangs on the closing's deadline_id, its due is the day the closing was marked done, and a reopened or fell-through deal has none.",
439439 },
@@ -1605,7 +1605,7 @@ export const routes: readonly Route[] = [
16051605 "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.",
16061606 body: {
16071607 type: "object",
1608 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
1608 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
16091609 required: ["deadline_id", "party_id", "moment", "reason"],
16101610 },
16111611 answer: { type: "object", properties: { id: { type: "integer" }, reason: { type: "string" }, by_name: { type: "string" } }, required: ["id", "reason"] },
@@ -1626,7 +1626,7 @@ export const routes: readonly Route[] = [
16261626 "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Give subject (up to 150 characters) and body (up to 2000) to hold the agent's edited words; leave them out to keep any words already held. Held again, it waits one more day. A status update is not held.",
16271627 body: {
16281628 type: "object",
1629 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin"] }, subject: { type: "string", minLength: 1, maxLength: 150 }, body: { type: "string", minLength: 1, maxLength: 2000 } },
1629 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin", "anniversary"] }, subject: { type: "string", minLength: 1, maxLength: 150 }, body: { type: "string", minLength: 1, maxLength: 2000 } },
16301630 required: ["deadline_id", "party_id", "moment"],
16311631 },
16321632 answer: { type: "object", properties: { id: { type: "integer" }, until: { type: "string" }, by_name: { type: "string" } }, required: ["id", "until"] },
@@ -1646,7 +1646,7 @@ export const routes: readonly Route[] = [
16461646 summary: "Bring a held reminder back to today: the hold is deleted and the reminder returns to today's list and /tick. Refused as a conflict when it is not held, or was already sent or declined.",
16471647 body: {
16481648 type: "object",
1649 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin"] } },
1649 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "checkin", "anniversary"] } },
16501650 required: ["deadline_id", "party_id", "moment"],
16511651 },
16521652 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
@@ -1667,7 +1667,7 @@ export const routes: readonly Route[] = [
16671667 summary: "Take back a decline: the reminder is a draft again.",
16681668 body: {
16691669 type: "object",
1670 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin"] } },
1670 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status", "checkin", "anniversary"] } },
16711671 required: ["deadline_id", "party_id", "moment"],
16721672 },
16731673 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
src/sample.test.ts +4 −3
@@ -72,7 +72,8 @@ const agent = { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" };
7272 const closedSamples = (db: ReturnType<typeof openDb>) => {
7373 const listed = listDeals(db, { role: "user", id: "u1", name: "alice" });
7474 if (!listed.ok) throw new Error(listed.message);
75 return listed.value.filter((d) => d.author_id === "sample" && d.closed);
75 // The sample closed a year ago (for its home anniversary) is not one of the three closed this year.
76 return listed.value.filter((d) => d.author_id === "sample" && d.closed && d.address !== "58 Larkspur Way");
7677 };
7778
7879 test("the samples include three deals closed earlier this year: priced, rated and in the book", () => {
@@ -163,7 +164,7 @@ test("the closed samples are off the clock, This week, People and the calendar,
163164 const alice: Who = { role: "user", id: "u1", name: "alice" };
164165 const listed = listDeals(db, alice);
165166 if (!listed.ok) throw new Error(listed.message);
166 const closed = listed.value.filter((d) => d.author_id === "sample" && d.closed);
167 const closed = listed.value.filter((d) => d.author_id === "sample" && d.closed && d.address !== "58 Larkspur Way");
167168 expect(closed.length).toBe(3);
168169 const html = clock({ who: alice, deals: listed.value, on: today(DEFAULT_ZONE) });
169170 const cut = html.indexOf('id="closed"');
@@ -190,7 +191,7 @@ test("refresh keeps the closed samples in the past and in this year, across a Ne
190191 const closings = (on: string) => {
191192 const listed = listDeals(db, alice);
192193 if (!listed.ok) throw new Error(listed.message);
193 const c = listed.value.filter((d) => d.author_id === "sample" && d.closed);
194 const c = listed.value.filter((d) => d.author_id === "sample" && d.closed && d.address !== "58 Larkspur Way");
194195 expect(c.length).toBe(3);
195196 expect(tally(listed.value, on).closedThisYear).toBe(3);
196197 return c.map((d) => d.closing);
src/sample.ts +38 −3
@@ -1,8 +1,9 @@
11 /**
2 * Seven sample deals, written once into a new database so the first screen
2 * Eight sample deals, written once into a new database so the first screen
33 * shows the job: one with a date gone overdue, one closing this week, one
44 * with a moved date, and one just signed; then three closed earlier this
5 * year, so the book line and the Closed list show a year of sales. Dates are
5 * year, so the book line and the Closed list show a year of sales, and one
6 * closed a year ago today, so its home anniversary note waits in Review. Dates are
67 * set relative to the day the database is created, so a fresh preview always
78 * looks like today.
89 */
@@ -31,6 +32,8 @@ interface Sample {
3132 readonly earnest: number;
3233 /** Which side the agent is on; buyer unless said. */
3334 readonly side?: Side;
35 /** Closed a year ago to the day, so its home anniversary note waits today; the buyer's email. */
36 readonly anniversary?: string;
3437 readonly lengths?: Partial<typeof BRIEF_LENGTHS>;
3538 /** When and where it closes, for the sample that closes this week. */
3639 readonly closingAt?: readonly [string, string];
@@ -176,10 +179,33 @@ const SAMPLES: readonly Sample[] = [
176179 ],
177180 done: ["earnest", "inspection", "appraisal", "financing", "title", "walkthrough", "closing"],
178181 },
182 // Closed a year ago today: its home anniversary note waits in Review.
183 {
184 address: "58 Larkspur Way",
185 buyer: "Nadia & Sam Desai",
186 seller: "Walter Ames",
187 contract: -400,
188 closing: -366,
189 anniversary: "[email protected]",
190 price: 351_000,
191 rate: 250,
192 earnest: 7_000,
193 parties: [
194 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
195 ["title", "Bayside Title", "[email protected]"],
196 ],
197 done: ["earnest", "inspection", "appraisal", "financing", "title", "walkthrough", "closing"],
198 },
179199 ];
180200
181201 /** The sample's dates in days from `on`; a closing in the past is held inside the year `on` is in, so it still counts as closed this year in January. */
182202 function placed(s: Sample, on: string): { contract: number; closing: number } {
203 if (s.anniversary !== undefined) {
204 // Marked done the day before it was due: its first anniversary is `on`.
205 const done = `${Number(on.slice(0, 4)) - 1}-${on.slice(5) === "02-29" ? "02-28" : on.slice(5)}`;
206 const closing = daysBetween(on, done) + 1;
207 return { contract: closing - (s.closing - s.contract), closing };
208 }
183209 if (s.closing >= 0) return s;
184210 const closing = -Math.min(-s.closing, daysBetween(`${on.slice(0, 4)}-01-01`, on));
185211 return { contract: closing - (s.closing - s.contract), closing };
@@ -304,7 +330,7 @@ export function refresh(db: Database, on = today(zoneOf(db))): void {
304330 );
305331 // A sample closed earlier this year stays in the year: crossing New Year, it is held at 1 January.
306332 const closingRow = deadlines.find((d) => d.kind === "closing");
307 if (closingRow?.done_at != null) {
333 if (closingRow?.done_at != null && SAMPLES.find((x) => x.address === deal.sample)?.anniversary === undefined) {
308334 const closingNow = shifted.deadlines.find((d) => d.id === closingRow.id)!.due;
309335 const newYear = `${on.slice(0, 4)}-01-01`;
310336 if (closingNow < newYear) shifted = shiftSample(shifted, closingNow, newYear);
@@ -344,6 +370,8 @@ function writeSamples(db: Database, on: string): void {
344370 if (s.closingAt !== undefined)
345371 db.query("UPDATE deal SET closing_time = ?1, closing_place = ?2 WHERE id = ?3").run(s.closingAt[0], s.closingAt[1], deal.id);
346372 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);
373 if (s.anniversary !== undefined)
374 db.query("UPDATE party SET email = ?1, contact = ?1 WHERE deal_id = ?2 AND role = 'buyer'").run(s.anniversary, deal.id);
347375 for (const [role, name, first, second] of s.parties) {
348376 const email = validEmail(first) ? first : "";
349377 const phone = second ?? (email === "" ? first : "");
@@ -364,6 +392,13 @@ function writeSamples(db: Database, on: string): void {
364392 const at = `${moment === "before" ? addDays(d.due, -3) : d.due}T08:30:00.000Z`;
365393 db.query("INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, by_name, subject, body, sent_at, sample) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, 1)").run(deal.id, d.id, p.id, d.label, p.name, role, moment, d.due, SAMPLE.name, subject, body, at);
366394 }
395 if (s.anniversary !== undefined) {
396 // Last month's check-in went out long ago; only the anniversary waits.
397 const d = db.query<{ id: number; label: string; done_at: string }, [number]>("SELECT id, label, done_at FROM deadline WHERE deal_id = ?1 AND kind = 'closing'").get(deal.id)!;
398 const p = db.query<{ id: number; name: string }, [number]>("SELECT id, name FROM party WHERE deal_id = ?1 AND role = 'buyer'").get(deal.id)!;
399 const doneOn = d.done_at.slice(0, 10);
400 db.query("INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, by_name, subject, body, sent_at, sample) VALUES (?1, ?2, ?3, ?4, ?5, 'buyer', 'checkin', ?6, ?7, '', '', ?8, 1)").run(deal.id, d.id, p.id, d.label, p.name, doneOn, SAMPLE.name, `${addDays(doneOn, 30)}T08:30:00.000Z`);
401 }
367402 if (s.moved !== undefined) {
368403 const [kind, days, reason] = s.moved;
369404 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)!;
src/server.test.ts +2 −2
@@ -403,14 +403,14 @@ test("restore_samples over MCP: an admin restores, anyone else is refused and no
403403 const sampleIds = async () =>
404404 ((await (await api("/api/deals", {}, root)).json()) as { id: number; author_id: string }[]).filter((d) => d.author_id === "sample").map((d) => d.id);
405405 const before = await sampleIds();
406 expect(before.length).toBe(7);
406 expect(before.length).toBe(8);
407407 expect((await call()).result.isError).toBe(true);
408408 expect((await call(rita)).result.isError).toBe(true);
409409 expect(await sampleIds()).toEqual(before);
410410 const restored = await call(root);
411411 expect(restored.result.isError).toBeUndefined();
412412 const after = await sampleIds();
413 expect(after.length).toBe(7);
413 expect(after.length).toBe(8);
414414 const trail = (await (await api("/api/audit", {}, root)).json()) as { verb: string; outcome: string }[];
415415 expect(trail.some((r) => r.verb === "delete" && r.outcome === "ok")).toBe(true);
416416 });
src/terminal.test.ts +2 −2
@@ -326,13 +326,13 @@ test("a closed deal's dates leave the date list and reminders, it is listed unde
326326 expect(lines(t).join("\n")).toContain("88 Shut Ave");
327327 t.press("d");
328328 expect(lines(t).join("\n")).toContain("88 Shut Ave");
329 expect(lines(t).join("\n")).toContain("Closed (3)");
329 expect(lines(t).join("\n")).toContain("Closed (4)");
330330 expect(lines(t).join("\n")).not.toContain("88 Shut Ave — closed");
331331 markDone(db, alice, { id: closing.id, done: true });
332332 t.press("d");
333333 const dates = lines(t).join("\n");
334334 expect(dates).not.toContain("Inspection period ends — 88 Shut Ave");
335 expect(dates).toContain("Closed (4)");
335 expect(dates).toContain("Closed (5)");
336336 expect(dates).toContain(`88 Shut Ave — closed ${spoken(today(DEFAULT_ZONE))}`);
337337 t.press("r");
338338 expect(lines(t).join("\n")).not.toContain("88 Shut Ave");
src/terminal.ts +2 −2
@@ -76,7 +76,7 @@ import { exportDeals, exportName } from "./export.ts";
7676 import { mkdirSync, writeFileSync } from "node:fs";
7777 import { join } from "node:path";
7878 import { coming, comingLine } from "./coming.ts";
79 import { drafts, heldFrom, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
79 import { drafts, heldFrom, inClockOrder, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
8080 import type { AuditRow } from "./audit.ts";
8181 import type { Result } from "./result.ts";
8282 import type { Who } from "./who.ts";
@@ -174,7 +174,7 @@ export function terminal(
174174 .filter((r) => unsent(r) && r.held !== null && r.held.until > day)
175175 .map((draft) => ({ deal, draft })),
176176 );
177 const rows = deals().flatMap((deal) =>
177 const rows = inClockOrder(deals()).flatMap((deal) =>
178178 drafts(deal, agentNow())
179179 .filter((r) => pending(r, day))
180180 .map((draft) => ({ deal, draft })),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs