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

From a deal's page the agent drafts a status update to the buyers or sellers — what is done, what is next, when it closes — and sends it only after approving the words #88

Merged opened this

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

Merged

mason/deal-clock:mason/85-from-a-deal-s-page-the-agent-drafts-a-st → main 2 commits fork

  • Merged. mason/85-from-a-deal-s-page-the-agent-drafts-a-st was merged into main as 3559004.

Review

Sign in to review this change.
14 files changed +820 −47
README.md +8
@@ -75,6 +75,14 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
7575 Decided against a message? Beside Send, **Don't send** asks why (up to 200
7676 characters). The reminder stops counting as "to send" and reads "Not sent:
7777 <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again.
78 To keep a client informed about the whole deal, a deal's page also has a
79 **Status update** card for each buyer and seller with an email or phone: a
80 draft of what is done, what is next and who owes it, and when it closes,
81 which you edit and send or decline like any reminder; it is offered again
82 only after a date on the deal is done, moved, added or removed. In the
83 terminal, open the deal, move to a buyer or seller and press S: type send to
84 record the draft as written (to change the words, use the page), or no and a
85 reason. Over MCP: `draft_status_update` and `send_status_update`.
7886 Every message you sent is kept: open 1418 Alder Lane's page and find
7987 **Messages**, newest first, each with who it went to, which date and
8088 moment, the day it was sent, and (tap it open) the exact words you approved
contract/openapi.json +153 −7
@@ -692,7 +692,8 @@
692692 "before",
693693 "day_of",
694694 "late",
695 "moved"
695 "moved",
696 "status"
696697 ]
697698 },
698699 "due": {
@@ -743,7 +744,8 @@
743744 "before",
744745 "day_of",
745746 "late",
746 "moved"
747 "moved",
748 "status"
747749 ]
748750 },
749751 "due": {
@@ -1094,6 +1096,145 @@
10941096 }
10951097 }
10961098 },
1099 "/api/deals/{id}/status": {
1100 "get": {
1101 "summary": "The status update each buyer and seller with a contact is owed: what is done, what is next, when it closes, signed with the agent's profile. A sent or declined one is not offered again until a date of the deal is done, moved, added or removed; a closed deal has none. Nothing is sent: send one with POST …/status/send, or decline it with POST …/reminders/decline (moment status, the closing date's deadline_id).",
1102 "operationId": "getApiDealsIdStatus",
1103 "parameters": [
1104 {
1105 "name": "id",
1106 "in": "path",
1107 "required": true,
1108 "schema": {
1109 "type": "integer"
1110 }
1111 }
1112 ],
1113 "responses": {
1114 "200": {
1115 "description": "The status update each buyer and seller with a contact is owed: what is done, what is next, when it closes, signed with the agent's profile. A sent or declined one is not offered again until a date of the deal is done, moved, added or removed; a closed deal has none. Nothing is sent: send one with POST …/status/send, or decline it with POST …/reminders/decline (moment status, the closing date's deadline_id).",
1116 "content": {
1117 "application/json": {
1118 "schema": {
1119 "type": "array",
1120 "items": {
1121 "$ref": "#/components/schemas/Reminder"
1122 }
1123 }
1124 }
1125 }
1126 },
1127 "default": {
1128 "description": "{ error, message }: why not",
1129 "content": {
1130 "application/json": {
1131 "schema": {
1132 "$ref": "#/components/schemas/Error"
1133 }
1134 }
1135 }
1136 }
1137 },
1138 "x-contract": {
1139 "resource": "deal",
1140 "verb": "update",
1141 "least": "user"
1142 }
1143 }
1144 },
1145 "/api/deals/{id}/status/send": {
1146 "post": {
1147 "summary": "Record a status update as sent to one party, with the words the agent approved (subject up to 150 characters, body up to 2000; the draft as it is when left out). The app sends nothing itself: the answer's href opens the agent's own Mail or Messages.",
1148 "operationId": "postApiDealsIdStatusSend",
1149 "parameters": [
1150 {
1151 "name": "id",
1152 "in": "path",
1153 "required": true,
1154 "schema": {
1155 "type": "integer"
1156 }
1157 }
1158 ],
1159 "requestBody": {
1160 "required": true,
1161 "content": {
1162 "application/json": {
1163 "schema": {
1164 "type": "object",
1165 "properties": {
1166 "party_id": {
1167 "type": "integer"
1168 },
1169 "subject": {
1170 "type": "string",
1171 "minLength": 1,
1172 "maxLength": 150
1173 },
1174 "body": {
1175 "type": "string",
1176 "minLength": 1,
1177 "maxLength": 2000
1178 }
1179 },
1180 "required": [
1181 "party_id"
1182 ]
1183 }
1184 }
1185 }
1186 },
1187 "responses": {
1188 "201": {
1189 "description": "Record a status update as sent to one party, with the words the agent approved (subject up to 150 characters, body up to 2000; the draft as it is when left out). The app sends nothing itself: the answer's href opens the agent's own Mail or Messages.",
1190 "content": {
1191 "application/json": {
1192 "schema": {
1193 "type": "object",
1194 "properties": {
1195 "id": {
1196 "type": "integer"
1197 },
1198 "subject": {
1199 "type": "string"
1200 },
1201 "body": {
1202 "type": "string"
1203 },
1204 "href": {
1205 "type": [
1206 "string",
1207 "null"
1208 ]
1209 }
1210 },
1211 "required": [
1212 "id",
1213 "subject",
1214 "body"
1215 ]
1216 }
1217 }
1218 }
1219 },
1220 "default": {
1221 "description": "{ error, message }: why not",
1222 "content": {
1223 "application/json": {
1224 "schema": {
1225 "$ref": "#/components/schemas/Error"
1226 }
1227 }
1228 }
1229 }
1230 },
1231 "x-contract": {
1232 "resource": "deal",
1233 "verb": "update",
1234 "least": "user"
1235 }
1236 }
1237 },
10971238 "/api/deals/{id}/reminders/decline": {
10981239 "post": {
10991240 "summary": "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.",
@@ -1126,7 +1267,8 @@
11261267 "before",
11271268 "day_of",
11281269 "late",
1129 "moved"
1270 "moved",
1271 "status"
11301272 ]
11311273 },
11321274 "reason": {
@@ -1221,7 +1363,8 @@
12211363 "before",
12221364 "day_of",
12231365 "late",
1224 "moved"
1366 "moved",
1367 "status"
12251368 ]
12261369 }
12271370 },
@@ -1852,7 +1995,8 @@
18521995 "before",
18531996 "day_of",
18541997 "late",
1855 "moved"
1998 "moved",
1999 "status"
18562000 ]
18572001 },
18582002 "due": {
@@ -1903,7 +2047,8 @@
19032047 "before",
19042048 "day_of",
19052049 "late",
1906 "moved"
2050 "moved",
2051 "status"
19072052 ]
19082053 },
19092054 "due": {
@@ -1987,7 +2132,8 @@
19872132 "before",
19882133 "day_of",
19892134 "late",
1990 "moved"
2135 "moved",
2136 "status"
19912137 ]
19922138 },
19932139 "on": {
docs/TECHNICAL.md +21
@@ -44,6 +44,27 @@ an earlier notice stays sent and a date moved back and forth is told afresh.
4444 `deadline_move.notify` is 1 only for moves made after the moment existed.
4545 `send_reminder` and the decline and undo doors take `moment: "moved"`.
4646
47 A fifth moment, `status` (*Status update*), is one message about the deal as a
48 whole to each buyer and seller with a contact (`statusDrafts`, `src/reminders.ts`;
49 never part of `drafts`, `/tick` or the review queue). It hangs on the deal's
50 closing date: its sent and declined rows carry that deadline, its due date, and
51 in `move_id` the `standing` of the deal, a hash of every date's id, due date and
52 done state. A change to any date is a new standing, so a sent or declined update
53 stays so until the deal changes and is then drafted afresh; the newest sent row
54 decides, so a deal that returns to an earlier standing is still offered again.
55 Sending it again at a standing it was sent at before adds a row (its `move_id`
56 is the standing plus `SEND_SPAN` for each earlier send; `standingOf` reads it
57 back), so every approved message stays in Messages. A
58 closed deal drafts none. The page card (`#status` on `/deals/:id`) posts to
59 `POST /reminders` and `/reminders/decline` like a sheet. Over the API:
60 `GET /api/deals/:id/status` (`statusUpdates`) and `POST /api/deals/:id/status/send`
61 (`sendStatusUpdate`); declining uses `POST /api/deals/:id/reminders/decline` with
62 `moment: "status"` and the draft's `deadline_id`. MCP: `draft_status_update` and
63 `send_status_update`. Terminal: `S` on a party of an open deal (type `send`, or
64 `no` and a reason). The terminal sends the draft as written: a one-line prompt is
65 no place to edit a paragraph, so to change the words use the page, API or MCP. All are updates of the deal, audited as `reminder.send` /
66 `reminder.decline`; no contract cell changes.
67
4768 *Send* records the agent's approval and the words approved with it; the app
4869 itself sends nothing and has no mail server. `src/outbox.ts` turns a sent
4970 reminder and its party's contact into one link: `mailto:` (subject and body
src/contract.test.ts +20
@@ -15,6 +15,8 @@ import {
1515 deleteDeal,
1616 getDeal,
1717 listDeals,
18 sendStatusUpdate,
19 statusUpdates,
1820 updateDeal,
1921 } from "./deals.ts";
2022 import { actingAs, identities, table, type Verb } from "./can.ts";
@@ -156,3 +158,21 @@ test("People, at the page, GET /api/people and list_people, answers as deal list
156158 expect([said, listed.ok]).toEqual([said, permit(who, "deal", "list") !== "no"]);
157159 }
158160 });
161
162 test("the status update, at GET /api/deals/:id/status, its send and the two MCP tools, answers as deal update says, as every identity", () => {
163 for (const identity of identities(contract)) {
164 const who = whoIs(identity);
165 const { mine, theirs } = actingAs(contract, identity);
166 for (const row of [mine, theirs]) {
167 const id = dealBy(String(row["author_id"]));
168 const said = `status as ${identity} on ${String(row["author_id"])}`;
169 const allowed = permit(who, "deal", "update", row) === "yes";
170 expect([said, statusUpdates(db, who, { dealId: id }).ok]).toEqual([said, allowed]);
171 db.query("INSERT INTO deadline (deal_id, kind, label, due, owes) VALUES (?1, 'closing', 'Closing', '2026-11-01', 'buyer')").run(id);
172 const party = db.query<{ id: number }, [number]>("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, 'buyer', 'B', '[email protected]') RETURNING id").get(id)!.id;
173 expect([said, sendStatusUpdate(db, who, { dealId: id, partyId: party }).ok]).toEqual([said, allowed]);
174 }
175 }
176 expect(statusUpdates(db, { role: "anon" }, { dealId: dealBy("u1") }).ok).toBe(false);
177 expect(sendStatusUpdate(db, { role: "anon" }, { dealId: dealBy("u1"), partyId: 1 }).ok).toBe(false);
178 });
src/db.ts +46
@@ -325,6 +325,52 @@ export const migrations: string[] = [
325325 )`,
326326 // Which change inside a row an audit row was ("reminder.send"), for the Activity page.
327327 `ALTER TABLE audit ADD COLUMN what TEXT`,
328 // A status update on the whole deal is a fifth moment, `status`, hung on the
329 // closing date; its move_id holds a fingerprint of the deal's dates when it
330 // was drafted, so a changed deal is a new draft. Rebuilt as before.
331 `CREATE TABLE reminder_new (
332 id INTEGER PRIMARY KEY,
333 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
334 deadline_id INTEGER NOT NULL,
335 party_id INTEGER NOT NULL,
336 label TEXT NOT NULL,
337 party_name TEXT NOT NULL,
338 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved', 'status')),
339 due TEXT NOT NULL,
340 by_name TEXT NOT NULL,
341 subject TEXT NOT NULL DEFAULT '',
342 body TEXT NOT NULL DEFAULT '',
343 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
344 party_role TEXT NOT NULL DEFAULT '',
345 sample INTEGER NOT NULL DEFAULT 0,
346 move_id INTEGER NOT NULL DEFAULT 0,
347 UNIQUE (deadline_id, party_id, moment, due, move_id)
348 );
349 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)
350 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;
351 DROP TABLE reminder;
352 ALTER TABLE reminder_new RENAME TO reminder;
353 CREATE INDEX reminder_deal ON reminder (deal_id);
354 CREATE TABLE reminder_declined_new (
355 id INTEGER PRIMARY KEY,
356 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
357 deadline_id INTEGER NOT NULL,
358 party_id INTEGER NOT NULL,
359 label TEXT NOT NULL,
360 party_name TEXT NOT NULL,
361 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved', 'status')),
362 due TEXT NOT NULL,
363 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
364 by_name TEXT NOT NULL,
365 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
366 move_id INTEGER NOT NULL DEFAULT 0,
367 UNIQUE (deadline_id, party_id, moment, due, move_id)
368 );
369 INSERT INTO reminder_declined_new (id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at, move_id)
370 SELECT id, deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name, at, move_id FROM reminder_declined;
371 DROP TABLE reminder_declined;
372 ALTER TABLE reminder_declined_new RENAME TO reminder_declined;
373 CREATE INDEX reminder_declined_deal ON reminder_declined (deal_id)`,
328374 ];
329375
330376 export function openDb(dir = dataDir): Database {
src/deals.ts +64 −23
@@ -27,7 +27,7 @@ import { agentOf } from "./profile.ts";
2727 import { emit } from "./live.ts";
2828 import { outbox } from "./outbox.ts";
2929 import { conflictLine, conflicts, type Conflict } from "./order.ts";
30 import { draftsFor, type Agent, type Draft } from "./reminders.ts";
30 import { SEND_SPAN, draftOfMoment, statusDrafts, type Agent, type Draft } from "./reminders.ts";
3131 import { audited, fail, ok, refuse, type Result } from "./result.ts";
3232 import type { Who } from "./who.ts";
3333
@@ -134,9 +134,9 @@ export interface DealView extends Deal {
134134 readonly conflicts: readonly Conflict[];
135135 }
136136
137 export type Moment = "before" | "day_of" | "late" | "moved";
137 export type Moment = "before" | "day_of" | "late" | "moved" | "status";
138138 export const isMoment = (v: unknown): v is Moment =>
139 v === "before" || v === "day_of" || v === "late" || v === "moved";
139 v === "before" || v === "day_of" || v === "late" || v === "moved" || v === "status";
140140
141141 /** Text from a person: trimmed, one line, within bounds — or undefined. */
142142 export function line(value: unknown, min: number, max: number): string | undefined {
@@ -870,7 +870,7 @@ export function sendReminder(
870870 const { dealId, found } = deadlineFor(db, who, input.deadlineId);
871871 if (!found.ok) return within(db, who, "reminder.send", dealId, found);
872872 if (!isMoment(input.moment))
873 return within(db, who, "reminder.send", dealId, fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed."));
873 return within(db, who, "reminder.send", dealId, fail("invalid", "A reminder is for ahead of a date, the day of, the day after (overdue), a date that changed, or a status update."));
874874 const party = Number.isInteger(input.partyId)
875875 ? db
876876 .query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2")
@@ -880,12 +880,8 @@ export function sendReminder(
880880 return within(db, who, "reminder.send", dealId, fail("not_found", "No such party on this deal."));
881881 const { deadline } = found.value;
882882 const seen = view(db, found.value.deal);
883 const draft = draftsFor(
884 seen,
885 seen.deadlines.find((d) => d.id === deadline.id)!,
886 input.agent ?? agentOf(db),
887 ).find((r) => r.party_id === party.id && r.moment === input.moment);
888 if (draft === undefined && input.moment === "moved")
883 const draft = draftOfMoment(seen, seen.deadlines.find((d) => d.id === deadline.id)!, input.agent ?? agentOf(db), party, input.moment);
884 if (draft === undefined && (input.moment === "moved" || input.moment === "status"))
889885 return within(db, who, "reminder.send", dealId, fail("not_found", "No such reminder on this date."));
890886 if (draft?.declined != null)
891887 return within(db, who, "reminder.send", dealId, fail("invalid", "This reminder was declined; undo that first to send it."));
@@ -896,12 +892,33 @@ export function sendReminder(
896892 const body = input.body === undefined ? draft?.body : message(input.body, 1, BODY_MAX);
897893 if (body === undefined)
898894 return within(db, who, "reminder.send", dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`));
899 const sent = db
900 .query<SentRow, [number, number, number, string, string, string, string, string, number, string, string, string]>(
901 `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)
902 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
903 )
904 .get(found.value.deal.id, deadline.id, party.id, draft?.label ?? deadline.label, party.name, party.role, input.moment, draft?.due ?? deadline.due, draft?.move_id ?? 0, authorOf(who).name, subject, body)!;
895 const at = [deadline.id, party.id, input.moment, draft?.due ?? deadline.due] as const;
896 // A status update sent before for these very dates and offered again (the deal went back to
897 // them) is a new send with its own row; any other repeat of a send is the same send.
898 const moveId =
899 input.moment === "status"
900 ? (draft?.move_id ?? 0) +
901 SEND_SPAN *
902 db
903 .query<{ n: number }, [number, number, string, string, number, number]>(
904 "SELECT count(*) AS n FROM reminder WHERE deadline_id = ?1 AND party_id = ?2 AND moment = ?3 AND due = ?4 AND move_id % ?5 = ?6",
905 )
906 .get(...at, SEND_SPAN, draft?.move_id ?? 0)!.n
907 : (draft?.move_id ?? 0);
908 const sent =
909 input.moment === "status" && draft?.sent_at !== null
910 ? // Already sent at this standing: the latest send stands.
911 db
912 .query<SentRow, [number, number, string, string, number, number]>(
913 "SELECT * FROM reminder WHERE deadline_id = ?1 AND party_id = ?2 AND moment = ?3 AND due = ?4 AND move_id % ?5 = ?6 ORDER BY id DESC",
914 )
915 .get(...at, SEND_SPAN, draft!.move_id)!
916 : db
917 .query<SentRow, [number, number, number, string, string, string, string, string, number, string, string, string]>(
918 `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)
919 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
920 )
921 .get(found.value.deal.id, deadline.id, party.id, draft?.label ?? deadline.label, party.name, party.role, input.moment, draft?.due ?? deadline.due, moveId, authorOf(who).name, subject, body)!;
905922 return within(db, who, "reminder.send", dealId, ok(withHref(sent, [party])));
906923 }
907924
@@ -914,18 +931,13 @@ function draftOf(
914931 const { dealId, found } = deadlineFor(db, who, input.deadlineId, input.dealId);
915932 if (!found.ok) return { dealId, found };
916933 if (!isMoment(input.moment))
917 return { dealId, found: fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed.") };
934 return { dealId, found: fail("invalid", "A reminder is for ahead of a date, the day of, the day after (overdue), a date that changed, or a status update.") };
918935 const { deal, deadline } = found.value;
919936 const party = Number.isInteger(input.partyId)
920937 ? db.query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2").get(input.partyId, deal.id)
921938 : null;
922939 const seen = view(db, deal).deadlines.find((d) => d.id === deadline.id)!;
923 const draft =
924 party === null
925 ? undefined
926 : draftsFor(view(db, deal), seen, input.agent ?? agentOf(db)).find(
927 (r) => r.party_id === party.id && r.moment === input.moment,
928 );
940 const draft = party === null ? undefined : draftOfMoment(view(db, deal), seen, input.agent ?? agentOf(db), party, input.moment);
929941 if (party === null || draft === undefined)
930942 return { dealId, found: fail("not_found", "No such reminder on this date.") };
931943 return { dealId, found: ok({ draft, deal, deadline: seen, party }) };
@@ -975,3 +987,32 @@ export function undoDecline(
975987 return within(db, who, "reminder.undo", dealId, fail("invalid", "This reminder was not declined."));
976988 return within(db, who, "reminder.undo", dealId, ok({ id: gone.id }));
977989 }
990
991 // ---- the status update: what is done, what is next, when it closes ----
992
993 /**
994 * The status update each buyer and seller with a contact is owed on this
995 * deal: sent, declined or waiting. Empty for a closed deal.
996 */
997 export function statusUpdates(db: Database, who: Who, input: { dealId: number; agent?: Agent }): Result<readonly Draft[]> {
998 const deal = dealFor(db, who, "update", input.dealId);
999 if (!deal.ok) return deal;
1000 return ok(statusDrafts(view(db, deal.value), input.agent ?? agentOf(db)));
1001 }
1002
1003 /**
1004 * Record a status update as sent to one party, with the words approved (the
1005 * draft's own when none are given). It is a reminder on the deal's closing
1006 * date, so it is sent, declined and kept exactly as one is.
1007 */
1008 export function sendStatusUpdate(
1009 db: Database,
1010 who: Who,
1011 input: { dealId: number; partyId: number; subject?: unknown; body?: unknown; agent?: Agent },
1012 ): Result<Sent> {
1013 const deal = dealFor(db, who, "update", input.dealId);
1014 if (!deal.ok) return deal;
1015 const closing = view(db, deal.value).deadlines.find((d) => d.kind === "closing");
1016 if (closing === undefined) return fail("not_found", "No status update on this deal.");
1017 return sendReminder(db, who, { ...input, deadlineId: closing.id, moment: "status" });
1018 }
src/mcp.ts +29 −3
@@ -27,6 +27,8 @@ import {
2727 removeDeadline,
2828 removeParty,
2929 sendReminder,
30 sendStatusUpdate,
31 statusUpdates,
3032 setReminderLead,
3133 declineReminder,
3234 undoDecline,
@@ -182,7 +184,7 @@ export const tools: readonly Tool[] = [
182184 properties: {
183185 deadline_id: { type: "integer" },
184186 party_id: { type: "integer" },
185 moment: { enum: ["before", "day_of", "late", "moved"] },
187 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
186188 subject: { type: "string", minLength: 1, maxLength: 150 },
187189 body: { type: "string", minLength: 1, maxLength: 2000 },
188190 },
@@ -191,6 +193,30 @@ export const tools: readonly Tool[] = [
191193 run: (db, who, args) =>
192194 sendReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, subject: args.subject, body: args.body }),
193195 },
196 {
197 name: "draft_status_update",
198 description:
199 "The status update each buyer and seller with an email or phone is owed on a deal: what is done, what is next and who owes it, when it closes, signed with the agent's profile. Nothing is sent. Show the words to the agent, then send_status_update with the approved words, or decline_reminder with moment status and the draft's deadline_id. A sent or declined update is offered again only after a date of the deal is done, moved, added or removed; a closed deal has none.",
200 inputSchema: { type: "object", properties: { deal_id: { type: "integer" } }, required: ["deal_id"] },
201 run: (db, who, args) => statusUpdates(db, who, { dealId: Number(args.deal_id) }),
202 },
203 {
204 name: "send_status_update",
205 description:
206 "Record a status update as sent to one party of a deal, after the agent approved its words. The app sends nothing itself: the answer's href is a mailto: or sms: link that opens the agent's own Mail or Messages. Give subject and body to send edited words (subject up to 150 characters, body up to 2000); leave them out to send the draft from draft_status_update as it is.",
207 inputSchema: {
208 type: "object",
209 properties: {
210 deal_id: { type: "integer" },
211 party_id: { type: "integer" },
212 subject: { type: "string", minLength: 1, maxLength: 150 },
213 body: { type: "string", minLength: 1, maxLength: 2000 },
214 },
215 required: ["deal_id", "party_id"],
216 },
217 run: (db, who, args) =>
218 sendStatusUpdate(db, who, { dealId: Number(args.deal_id), partyId: Number(args.party_id), subject: args.subject, body: args.body }),
219 },
194220 {
195221 name: "decline_reminder",
196222 description:
@@ -200,7 +226,7 @@ export const tools: readonly Tool[] = [
200226 properties: {
201227 deadline_id: { type: "integer" },
202228 party_id: { type: "integer" },
203 moment: { enum: ["before", "day_of", "late", "moved"] },
229 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
204230 reason: { type: "string", minLength: 1, maxLength: 200 },
205231 },
206232 required: ["deadline_id", "party_id", "moment", "reason"],
@@ -213,7 +239,7 @@ export const tools: readonly Tool[] = [
213239 description: "Take back a decline: the reminder is a draft again, to send or decline.",
214240 inputSchema: {
215241 type: "object",
216 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
242 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status"] } },
217243 required: ["deadline_id", "party_id", "moment"],
218244 },
219245 run: (db, who, args) =>
src/pages/deal.ts +19 −3
@@ -6,17 +6,17 @@
66
77 import { addDays, relative, short, spoken } from "../dates.ts";
88 import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
9 import { standard } from "../env.ts";
9 import { agent as defaults, standard } from "../env.ts";
1010 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
12 import { sentLabel, type Agent } from "../reminders.ts";
12 import { sentLabel, statusDrafts, type Agent } from "../reminders.ts";
1313 import type { Who } from "../who.ts";
1414 import { amendForm, type AmendState } from "./amend.ts";
1515 import { partyContact } from "./contact.ts";
1616 import { confirmRemove } from "./confirm.ts";
1717 import { layout } from "./layout.ts";
1818 import { progressLine } from "./progress.ts";
19 import { badge, conflictLines, dueLine, outboxLine, owedBy, sheet, sheetId } from "./sheet.ts";
19 import { badge, conflictLines, draftItem, dueLine, outboxLine, owedBy, sheet, sheetId } from "./sheet.ts";
2020
2121 const roleOptions = (selected?: string): string =>
2222 PARTY_ROLES.map(
@@ -46,6 +46,21 @@ const partyControls = (p: Party, to: string): string => `<div class="party-contr
4646 })}
4747 </div>`;
4848
49 /** The status update each buyer and seller is owed: edited, then sent or declined like any reminder. */
50 function statusCard(deal: DealView, agent: Agent, on: string, may: boolean, to: string): string {
51 if (!may) return "";
52 const these = statusDrafts(deal, agent);
53 const body = deal.closed
54 ? `<p class="muted">This deal is closed, so there is nothing to update.</p>`
55 : these.length === 0
56 ? `<p class="muted">Add a buyer or seller with an email or phone to draft a status update.</p>`
57 : `<p class="muted small">What is done, what is next and when it closes. Nothing goes out until you send it.</p><ul class="drafts">${these.map((d) => draftItem(d, on, may, to)).join("")}</ul>`;
58 return `<section class="card" id="status">
59 <h2>Status update</h2>
60 ${body}
61 </section>`;
62 }
63
4964 /** The record of what went out: each sent reminder with the words approved, newest first. */
5065 function messages(deal: DealView, may: boolean): string {
5166 if (deal.sent.length === 0) return `<p class="muted">Nothing sent yet</p>`;
@@ -155,6 +170,7 @@ export function dealPage(input: {
155170 <h2>Parties</h2>
156171 ${parties}
157172 </section>
173 ${statusCard(deal, agent ?? defaults, on, may, path)}
158174 <section class="card" id="messages">
159175 <h2>Messages</h2>
160176 ${messages(deal, may)}
src/pages/sheet.ts +2
@@ -107,6 +107,8 @@ function draftLine(draft: Draft, on: string, withDeal: boolean): string {
107107 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
108108 : draft.declined !== null
109109 ? `<span class="state" data-declined>Not sent: ${escape(draft.declined.reason)} · ${escape(draft.declined.by_name || "someone")}</span>`
110 : draft.moment === "status"
111 ? `<span class="state">Ready to send</span>`
110112 : draft.on < on
111113 ? `<span class="state" data-late>Was due ${escape(short(draft.on))}</span>`
112114 : draft.on === on
src/reminders.ts +93 −3
@@ -8,7 +8,7 @@
88 * sent one, with the words approved; a sent draft reads back those words.
99 */
1010
11 import { addDays, spoken, today } from "./dates.ts";
11 import { addDays, relative, spoken, today } from "./dates.ts";
1212 import { memoizer, print } from "./memo.ts";
1313 import { DEFAULT_LEAD, KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
1414 import type { DealView, DeadlineView, Move, Moment, Party } from "./deals.ts";
@@ -51,6 +51,7 @@ export interface Draft {
5151
5252 export const MOMENTS: readonly Moment[] = ["before", "day_of", "late", "moved"];
5353 const MOMENT_LABEL: Readonly<Record<Exclude<Moment, "before">, string>> = {
54 status: "Status update",
5455 day_of: "Morning of",
5556 late: "Overdue follow-up",
5657 moved: "Date changed",
@@ -67,9 +68,9 @@ export const momentLabel = (moment: Moment, lead: number = DEFAULT_LEAD): string
6768 * then, which the record does not keep, so the "before" one is not numbered.
6869 */
6970 export const sentLabel = (moment: Moment): string => (moment === "before" ? "Ahead of the date" : MOMENT_LABEL[moment]);
70 const OFFSET: Readonly<Record<Exclude<Moment, "before" | "moved">, number>> = { day_of: 0, late: 1 };
71 const OFFSET: Readonly<Record<"day_of" | "late", number>> = { day_of: 0, late: 1 };
7172 /** The morning a reminder goes out; a "date changed" notice goes the day of the move instead. */
72 export const sendOn = (due: string, moment: Exclude<Moment, "moved">, lead: number = DEFAULT_LEAD): string =>
73 export const sendOn = (due: string, moment: "before" | "day_of" | "late", lead: number = DEFAULT_LEAD): string =>
7374 addDays(due, moment === "before" ? -lead : OFFSET[moment]);
7475
7576 /** The move a "date changed" notice is about: the latest, if the agent is to tell people of it. */
@@ -222,6 +223,95 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
222223 );
223224 }
224225
226 // ---- the status update: one message about the deal as a whole ----
227
228 /** At most this many open dates are named as what comes next. */
229 const NEXT_MAX = 4;
230
231 /**
232 * A number that changes whenever a date of the deal is done, reopened, moved,
233 * added or removed, and not otherwise: what makes a status update a new one.
234 */
235 export function standing(deal: DealView): number {
236 let h = 2166136261;
237 const text = deal.deadlines
238 .map((d) => `${d.id}:${d.due}:${d.done_at === null ? 0 : 1}`)
239 .sort()
240 .join("|");
241 for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619) >>> 0;
242 return h % 2147483647 + 1;
243 }
244
245 /**
246 * A status update sent again at a standing it was sent at before is a new row:
247 * its `move_id` is the standing plus one `SEND_SPAN` per earlier send, so no
248 * earlier send is rewritten. `standingOf` reads the standing back.
249 */
250 export const SEND_SPAN = 2 ** 31;
251 export const standingOf = (moveId: number): number => moveId % SEND_SPAN;
252
253 /** The words of a status update to one party. */
254 function statusWords(deal: DealView, party: Party, agent: Agent): { subject: string; body: string } {
255 const closing = deal.deadlines.find((d) => d.kind === "closing")!;
256 const done = deal.deadlines.filter((d) => d.done_at !== null);
257 const open = deal.deadlines.filter((d) => d.done_at === null && d.id !== closing.id).sort((a, b) => a.due.localeCompare(b.due));
258 const owner = (d: DeadlineView): string => deal.parties.find((p) => p.role === d.owes)?.name ?? PARTY_LABEL[d.owes];
259 const next = open.slice(0, NEXT_MAX).map((d) => `• ${d.label}: ${spoken(d.due)} (${owner(d)} · ${PARTY_LABEL[d.owes].toLowerCase()})`);
260 const more = open.length > NEXT_MAX ? `\n• …and ${open.length - NEXT_MAX} more after that` : "";
261 const finished = done.length === 0 ? "Nothing is finished yet." : done.map((d) => `• ${d.label}`).join("\n");
262 return {
263 subject: `${deal.address} — where things stand`,
264 body: `Hi ${first(party.name)}, here is where things stand on ${deal.address}.\n\nDone:\n${finished}\n\nNext:\n${next.length === 0 ? "Nothing else before closing." : next.join("\n")}${more}\n\nClosing is ${spoken(closing.due)} (${relative(closing.due, today())}).\n\nLet me know if you have any questions.\n\n${signOff(agent)}`,
265 };
266 }
267
268 /**
269 * The status update each buyer and seller with a contact is owed, sent or
270 * not. It is keyed by the closing date and `standing`: sent, or declined, it
271 * stays so until a date of the deal changes, and then a new one is offered.
272 * A closed deal drafts none. Never part of the morning's reminders.
273 */
274 export function statusDrafts(deal: DealView, agent: Agent): Draft[] {
275 const closing = deal.deadlines.find((d) => d.kind === "closing");
276 if (deal.closed || closing === undefined) return [];
277 const stand = standing(deal);
278 return deal.parties
279 .filter((p) => (p.role === "buyer" || p.role === "seller") && p.contact !== "")
280 .map((party) => {
281 const last = deal.sent.find((s) => s.party_id === party.id && s.moment === "status");
282 const sent = last !== undefined && standingOf(last.move_id) === stand && last.due === closing.due ? last : undefined;
283 const declined = deal.declined.find(
284 (s) => s.party_id === party.id && s.moment === "status" && s.move_id === stand && s.due === closing.due,
285 );
286 const drafted = statusWords(deal, party, agent);
287 return {
288 deal_id: deal.id,
289 address: deal.address,
290 deadline_id: closing.id,
291 label: closing.label,
292 due: closing.due,
293 party_id: party.id,
294 party_name: party.name,
295 party_role: party.role,
296 contact: party.contact,
297 moment: "status" as const,
298 lead_days: closing.lead_days,
299 move_id: stand,
300 on: today(),
301 subject: sent !== undefined && sent.subject !== "" ? sent.subject : drafted.subject,
302 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
303 sent_at: sent?.sent_at ?? null,
304 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
305 };
306 });
307 }
308
309 /** The draft of `moment` that `party` has on `deadline`, if any: a reminder, or the deal's status update on its closing date. */
310 export function draftOfMoment(deal: DealView, deadline: DeadlineView, agent: Agent, party: Party, moment: Moment): Draft | undefined {
311 const these = moment === "status" ? (deadline.kind === "closing" ? statusDrafts(deal, agent) : []) : draftsFor(deal, deadline, agent);
312 return these.find((r) => r.party_id === party.id && r.moment === moment);
313 }
314
225315 /** Still waiting to be sent: neither sent nor declined. */
226316 export const unsent = (d: Draft): boolean => d.sent_at === null && d.declined === null;
227317
src/routes.ts +39 −5
@@ -60,6 +60,8 @@ import {
6060 removeDeadline,
6161 removeParty,
6262 sendReminder,
63 sendStatusUpdate,
64 statusUpdates,
6365 setReminderLead,
6466 declineReminder,
6567 undoDecline,
@@ -231,7 +233,7 @@ export const DEAL: Schema = {
231233 id: { type: "integer" },
232234 deadline_id: { type: "integer" },
233235 party_id: { type: "integer" },
234 moment: { enum: ["before", "day_of", "late", "moved"] },
236 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
235237 due: DATE,
236238 reason: { type: "string", description: "Why the agent chose not to send it." },
237239 by_name: { type: "string" },
@@ -252,7 +254,7 @@ export const DEAL: Schema = {
252254 label: { type: "string", description: "The date it was about, as named when sent." },
253255 party_name: { type: "string" },
254256 party_role: { type: "string", description: "The party's role when sent; empty on a reminder sent before roles were kept." },
255 moment: { enum: ["before", "day_of", "late", "moved"] },
257 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
256258 due: DATE,
257259 by_name: { type: "string" },
258260 sent_at: { type: "string" },
@@ -302,7 +304,7 @@ export const DRAFT: Schema = {
302304 party_name: { type: "string" },
303305 party_role: ROLE,
304306 contact: { type: "string" },
305 moment: { enum: ["before", "day_of", "late", "moved"] },
307 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
306308 on: DATE,
307309 subject: { type: "string" },
308310 body: { type: "string" },
@@ -1061,6 +1063,38 @@ export const routes: readonly Route[] = [
10611063 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
10621064 },
10631065 },
1066 {
1067 method: "GET",
1068 path: "/api/deals/:id/status",
1069 handle: (c) => answer(statusUpdates(c.db, c.who, { dealId: Number(c.params.id), agent: agentOf(c.db) })),
1070 api: {
1071 summary:
1072 "The status update each buyer and seller with a contact is owed: what is done, what is next, when it closes, signed with the agent's profile. A sent or declined one is not offered again until a date of the deal is done, moved, added or removed; a closed deal has none. Nothing is sent: send one with POST …/status/send, or decline it with POST …/reminders/decline (moment status, the closing date's deadline_id).",
1073 answer: list(DRAFT),
1074 cell: { resource: "deal", verb: "update" },
1075 },
1076 },
1077 {
1078 method: "POST",
1079 path: "/api/deals/:id/status/send",
1080 handle: async (c) => {
1081 const body = await readJson(c.request);
1082 if (body === undefined) return json({ error: "too_large" }, 413);
1083 const f = fields(body);
1084 return answer(sendStatusUpdate(c.db, c.who, { dealId: Number(c.params.id), partyId: Number(f.party_id), subject: f.subject, body: f.body }), 201);
1085 },
1086 api: {
1087 summary:
1088 "Record a status update as sent to one party, with the words the agent approved (subject up to 150 characters, body up to 2000; the draft as it is when left out). The app sends nothing itself: the answer's href opens the agent's own Mail or Messages.",
1089 body: {
1090 type: "object",
1091 properties: { party_id: { type: "integer" }, subject: { type: "string", minLength: 1, maxLength: 150 }, body: { type: "string", minLength: 1, maxLength: 2000 } },
1092 required: ["party_id"],
1093 },
1094 answer: { type: "object", properties: { id: { type: "integer" }, subject: { type: "string" }, body: { type: "string" }, href: { type: ["string", "null"] } }, required: ["id", "subject", "body"] },
1095 status: 201,
1096 },
1097 },
10641098 {
10651099 method: "POST",
10661100 path: "/api/deals/:id/reminders/decline",
@@ -1078,7 +1112,7 @@ export const routes: readonly Route[] = [
10781112 "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.",
10791113 body: {
10801114 type: "object",
1081 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
1115 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
10821116 required: ["deadline_id", "party_id", "moment", "reason"],
10831117 },
10841118 answer: { type: "object", properties: { id: { type: "integer" }, reason: { type: "string" }, by_name: { type: "string" } }, required: ["id", "reason"] },
@@ -1100,7 +1134,7 @@ export const routes: readonly Route[] = [
11001134 summary: "Take back a decline: the reminder is a draft again.",
11011135 body: {
11021136 type: "object",
1103 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
1137 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved", "status"] } },
11041138 required: ["deadline_id", "party_id", "moment"],
11051139 },
11061140 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
src/server.test.ts +2
@@ -181,6 +181,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
181181 "set_reminder_lead",
182182 "amend_deal",
183183 "send_reminder",
184 "draft_status_update",
185 "send_status_update",
184186 "decline_reminder",
185187 "undo_decline_reminder",
186188 "open_deal",
src/status.test.ts added +302
@@ -0,0 +1,302 @@
1 /** The status update: one message about the deal as a whole, approved before it is recorded as sent. */
2 import { afterAll, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { addDays, spoken, today } from "./dates.ts";
7 import {
8 addDeadline, addParty, createDeal, declineReminder, getDeal, markDone, moveDeadline, sendStatusUpdate, statusUpdates, undoDecline, type DealView,
9 } from "./deals.ts";
10 import { openDb } from "./db.ts";
11 import { serve } from "./server.ts";
12 import { dueOn, drafts, standing, statusDrafts } from "./reminders.ts";
13 import { terminal } from "./terminal.ts";
14 import { dealPage } from "./pages/deal.ts";
15 import { sign } from "./who.ts";
16 import type { Who } from "./who.ts";
17
18 const db = openDb(mkdtempSync(join(tmpdir(), "app-status-")));
19 const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "");
20 const alice: Who = { role: "user", id: "u1", name: "alice" };
21 const agent = { name: "Dana", brokerage: "Hearth & Porch", phone: "555-0100", email: "[email protected]" };
22
23 function open(address: string, closed = false): number {
24 const made = createDeal(db, alice, { address, buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(), closingDate: addDays(today(), 40) });
25 if (!made.ok) throw new Error(made.message);
26 const id = made.value.id;
27 for (const p of made.value.parties) db.query("UPDATE party SET contact = ?1 WHERE id = ?2").run(`${p.name.split(" ")[0]!.toLowerCase()}@example.com`, p.id);
28 if (closed) markDone(db, alice, { id: made.value.deadlines.find((d) => d.kind === "closing")!.id, done: true });
29 return id;
30 }
31 const read = (id: number): DealView => {
32 const got = getDeal(db, alice, { id });
33 if (!got.ok) throw new Error(got.message);
34 return got.value;
35 };
36 const updates = (id: number) => {
37 const got = statusUpdates(db, alice, { dealId: id, agent });
38 if (!got.ok) throw new Error(got.message);
39 return got.value;
40 };
41
42 test("the draft lists what is done, what is next and who owes it, and when it closes, signed by the agent", () => {
43 const id = open("1 Status Way");
44 const inspection = read(id).deadlines.find((d) => d.kind === "inspection")!;
45 markDone(db, alice, { id: inspection.id, done: true });
46 const deal = read(id);
47 const drafted = updates(id);
48 expect(drafted.map((d) => d.party_role).sort()).toEqual(["buyer", "seller"]);
49 const buyer = drafted.find((d) => d.party_role === "buyer")!;
50 expect(buyer.moment).toBe("status");
51 expect(buyer.subject).toBe("1 Status Way — where things stand");
52 expect(buyer.body).toContain("Hi Ann,");
53 expect(buyer.body).toContain(`Done:\n• ${inspection.label}`);
54 const next = deal.deadlines.filter((d) => d.done_at === null && d.kind !== "closing").sort((a, b) => a.due.localeCompare(b.due))[0]!;
55 expect(buyer.body).toContain(`• ${next.label}: ${spoken(next.due)}`);
56 expect(buyer.body).toContain("lender");
57 expect(buyer.body).toContain(`Closing is ${spoken(deal.closing)} (in 40 days)`);
58 expect(buyer.body).toContain("Dana, Hearth & Porch\n555-0100 · [email protected]");
59 expect(buyer.deadline_id).toBe(deal.deadlines.find((d) => d.kind === "closing")!.id);
60 });
61
62 test("only a buyer or seller with a contact is drafted for", () => {
63 const id = open("2 Status Way");
64 addParty(db, alice, { dealId: id, role: "lender", name: "Lena Lender", contact: "[email protected]" });
65 addParty(db, alice, { dealId: id, role: "buyer", name: "No Contact", contact: "" });
66 expect(updates(id).map((d) => d.party_name).sort()).toEqual(["Ann Buyer", "Sam Seller"]);
67 });
68
69 test("send keeps the edited words, and the Messages record shows them", () => {
70 const id = open("3 Status Way");
71 const buyer = updates(id).find((d) => d.party_role === "buyer")!;
72 const sent = sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id, subject: "Quick update", body: "My own words, Ann." });
73 expect(sent.ok && sent.value).toMatchObject({ moment: "status", subject: "Quick update", body: "My own words, Ann.", party_name: "Ann Buyer" });
74 const after = updates(id).find((d) => d.party_role === "buyer")!;
75 expect(after).toMatchObject({ sent_at: expect.any(String), subject: "Quick update", body: "My own words, Ann." });
76 expect(read(id).sent.map((m) => m.body)).toEqual(["My own words, Ann."]);
77 const page = dealPage({ who: alice, deal: read(id), on: today() });
78 expect(page).toContain("My own words, Ann.");
79 expect(page).toContain("Status update");
80 // Nothing is recorded without a send; an empty edit is refused.
81 const seller = updates(id).find((d) => d.party_role === "seller")!;
82 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: seller.party_id, body: " " }).ok).toBe(false);
83 expect(read(id).sent.length).toBe(1);
84 });
85
86 test("a sent or declined update is not offered again until a date changes", () => {
87 const id = open("4 Status Way");
88 const [buyer, seller] = [updates(id).find((d) => d.party_role === "buyer")!, updates(id).find((d) => d.party_role === "seller")!];
89 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id }).ok).toBe(true);
90 expect(declineReminder(db, alice, { dealId: id, deadlineId: seller.deadline_id, partyId: seller.party_id, moment: "status", reason: "Told by phone" }).ok).toBe(true);
91 const settled = updates(id);
92 expect(settled.every((d) => d.sent_at !== null || d.declined !== null)).toBe(true);
93 const before = standing(read(id));
94 const date = read(id).deadlines.find((d) => d.kind === "inspection")!;
95 // done, then moved, then added, then removed: each is a change.
96 markDone(db, alice, { id: date.id, done: true });
97 expect(standing(read(id))).not.toBe(before);
98 expect(updates(id).every((d) => d.sent_at === null && d.declined === null)).toBe(true);
99 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id, subject: "Second", body: "Second words" }).ok).toBe(true);
100 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).not.toBeNull();
101 const moved = moveDeadline(db, alice, { id: read(id).deadlines.find((d) => d.kind === "appraisal")!.id, due: addDays(today(), 12), reason: "Lender" });
102 expect(moved.ok).toBe(true);
103 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).toBeNull();
104 const extra = addDeadline(db, alice, { dealId: id, label: "HOA review", due: addDays(today(), 9), owes: "buyer", what: "" });
105 if (!extra.ok) throw new Error(extra.message);
106 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id }).ok).toBe(true);
107 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).not.toBeNull();
108 // Back to the state of an earlier send: the later one is the last word, so it is offered again.
109 markDone(db, alice, { id: date.id, done: false });
110 const again = updates(id).find((d) => d.party_role === "buyer")!;
111 expect(again.sent_at).toBeNull();
112 expect(read(id).sent.filter((m) => m.moment === "status").length).toBe(3);
113 });
114
115 test("a closed deal drafts none", () => {
116 const id = open("5 Status Way", true);
117 expect(updates(id)).toEqual([]);
118 expect(statusDrafts(read(id), agent)).toEqual([]);
119 const refused = sendStatusUpdate(db, alice, { dealId: id, partyId: read(id).parties[0]!.id });
120 expect(refused.ok).toBe(false);
121 expect(read(id).sent).toEqual([]);
122 expect(dealPage({ who: alice, deal: read(id), on: today() })).toContain("nothing to update");
123 });
124
125 test("the old reminders are untouched: the morning's drafts and /tick never include a status update", () => {
126 const id = open("6 Status Way");
127 expect(statusUpdates(db, { role: "anon" }, { dealId: id }).ok).toBe(false);
128 const deal = read(id);
129 expect(updates(id).length).toBe(2);
130 const morning = drafts(deal, agent);
131 expect(morning.length).toBeGreaterThan(0);
132 expect(morning.some((d) => d.moment === "status")).toBe(false);
133 const inspection = deal.deadlines.find((d) => d.kind === "inspection")!;
134 expect(dueOn([deal], inspection.due, agent).some((d) => d.moment === "status")).toBe(false);
135 expect(dueOn([deal], today(), agent).some((d) => d.moment === "status")).toBe(false);
136 expect(deal.sent).toEqual([]);
137 expect(dealPage({ who: alice, deal, on: today() })).toContain('id="status"');
138 });
139
140 test("a status update sent again at the same standing keeps every earlier message", () => {
141 const id = open("6b Status Way");
142 const buyer = updates(id).find((d) => d.party_role === "buyer")!;
143 const date = read(id).deadlines.find((d) => d.kind === "inspection")!;
144 const send = (body: string) => sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id, subject: "Update", body }).ok;
145 expect(send("First words")).toBe(true);
146 // Sent again at the same standing: the same send, nothing new.
147 expect(send("Ignored words")).toBe(true);
148 expect(read(id).sent.map((m) => m.body)).toEqual(["First words"]);
149 markDone(db, alice, { id: date.id, done: true });
150 expect(send("Second words")).toBe(true);
151 markDone(db, alice, { id: date.id, done: false });
152 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).toBeNull();
153 expect(send("Third words")).toBe(true);
154 expect(read(id).sent.map((m) => m.body).sort()).toEqual(["First words", "Second words", "Third words"]);
155 expect(updates(id).find((d) => d.party_role === "buyer")).toMatchObject({ body: "Third words" });
156 const page = dealPage({ who: alice, deal: read(id), on: today() });
157 for (const words of ["First words", "Second words", "Third words"]) expect(page).toContain(words);
158 });
159
160 test("the terminal's S drafts for the party under the cursor and sends on 'send'", () => {
161 const id = open("7 Status Way");
162 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent });
163 t.press("d");
164 for (let i = 0; i < 200 && !t.screen().map(plain).some((l) => l.startsWith("▸") && l.includes("7 Status Way")); i++) t.press("j");
165 t.press("o");
166 for (let i = 0; i < read(id).deadlines.length; i++) t.press("j");
167 t.press("S");
168 for (const c of "send") t.press(c);
169 t.press("\r");
170 expect(read(id).sent.map((m) => m.moment)).toEqual(["status"]);
171 expect(read(id).sent[0]!.party_role).toBe("buyer");
172 });
173
174 test("the terminal's S declines on 'no <reason>' and says why when there is nothing to send", () => {
175 const id = open("8 Status Way");
176 addParty(db, alice, { dealId: id, role: "lender", name: "Lena Lender", contact: "[email protected]" });
177 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent });
178 const screen = (): string => t.screen().map(plain).join("\n");
179 function toParty(index: number): void {
180 t.press("d");
181 for (let i = 0; i < 200 && !t.screen().map(plain).some((l) => l.startsWith("▸") && l.includes("8 Status Way")); i++) t.press("j");
182 t.press("o");
183 for (let i = 0; i < read(id).deadlines.length + index; i++) t.press("j");
184 }
185 const type = (text: string): void => {
186 for (const c of text) t.press(c);
187 t.press("\r");
188 };
189 toParty(0);
190 t.press("S");
191 type("no Told by phone");
192 expect(read(id).declined.map((d) => [d.moment, d.reason])).toEqual([["status", "Told by phone"]]);
193 expect(read(id).sent).toEqual([]);
194 t.press("S");
195 expect(screen()).toContain("Not sent to Ann Buyer: Told by phone");
196 // Take it back, send it, and it is the latest.
197 const buyer = read(id).parties.find((p) => p.role === "buyer")!;
198 expect(undoDecline(db, alice, { dealId: id, deadlineId: updates(id)[0]!.deadline_id, partyId: buyer.id, moment: "status" }).ok).toBe(true);
199 t.press("S");
200 type("send");
201 t.press("S");
202 expect(screen()).toContain("Ann Buyer has the latest status update");
203 expect(read(id).sent.length).toBe(1);
204 // A lender is not a buyer or seller.
205 t.press("j");
206 t.press("j");
207 t.press("S");
208 expect(screen()).toContain("gets no status update");
209 // The deal closes while its page is open: there is nothing to update.
210 markDone(db, alice, { id: read(id).deadlines.find((d) => d.kind === "closing")!.id, done: true });
211 t.press("k");
212 t.press("S");
213 expect(screen()).toContain("A closed deal has no status update.");
214 });
215
216 // ---- the doors ----
217
218 const KEY = "a-key-only-the-forge-holds";
219 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-status-door-")), identityKey: KEY });
220 afterAll(() => server.stop(true));
221 const base = `http://${server.hostname}:${server.port}`;
222 const as = (id: string, name: string): Record<string, string> => {
223 const identity = `${id}|${name}|user|${Date.now() + 60_000}`;
224 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
225 };
226 const editor = as("u1", "alice");
227 const call = (path: string, init: RequestInit = {}, who = editor) =>
228 fetch(base + path, { ...init, headers: { "content-type": "application/json", ...who, ...(init.headers as object) } });
229 const rpc = async (name: string, args: unknown, who = editor) =>
230 (await (await call("/mcp", { method: "POST", body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }, who)).json()) as any;
231
232 test("the API, MCP and the page each reach the same action", async () => {
233 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address: "9 Door Way", buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(), closing_date: addDays(today(), 40) }) });
234 const deal = (await made.json()) as { id: number; parties: { id: number; name: string }[] };
235 for (const p of deal.parties) await call(`/api/deals/${deal.id}/parties/${p.id}`, { method: "PATCH", body: JSON.stringify({ name: p.name, contact: "[email protected]" }) });
236 const drafted = (await (await call(`/api/deals/${deal.id}/status`)).json()) as { moment: string; party_id: number; party_role: string; subject: string }[];
237 expect(drafted.length).toBeGreaterThan(0);
238 expect(drafted.every((d) => d.moment === "status" && (d.party_role === "buyer" || d.party_role === "seller"))).toBe(true);
239 expect((await call(`/api/deals/${deal.id}/status`, {}, {})).status).toBe(401);
240
241 const viaMcp = JSON.parse((await rpc("draft_status_update", { deal_id: deal.id })).result.content[0].text);
242 expect(viaMcp.map((d: { party_id: number }) => d.party_id)).toEqual(drafted.map((d) => d.party_id));
243
244 const sentApi = await call(`/api/deals/${deal.id}/status/send`, { method: "POST", body: JSON.stringify({ party_id: drafted[0]!.party_id, subject: "Edited", body: "Edited over the API" }) });
245 expect(sentApi.status).toBe(201);
246 expect(await sentApi.json()).toMatchObject({ moment: "status", body: "Edited over the API" });
247 const second = drafted.find((d) => d.party_id !== drafted[0]!.party_id)!;
248 expect(second).toBeDefined();
249 const sentMcp = JSON.parse((await rpc("send_status_update", { deal_id: deal.id, party_id: second.party_id, body: "Edited over MCP", subject: "Hi" })).result.content[0].text);
250 expect(sentMcp).toMatchObject({ moment: "status", body: "Edited over MCP" });
251 const again = (await (await call(`/api/deals/${deal.id}/status`)).json()) as { sent_at: string | null }[];
252 expect(again[0]!.sent_at).not.toBeNull();
253 const refused = await call(`/api/deals/${deal.id}/status/send`, { method: "POST", body: JSON.stringify({ party_id: drafted[0]!.party_id }) }, {});
254 expect(refused.status).toBe(401);
255 const page = await (await fetch(`${base}/deals/${deal.id}`, { headers: editor })).text();
256 expect(page).toContain("Edited over the API");
257 });
258
259 test("the page, the API and MCP each send and decline a status update", async () => {
260 const make = async (address: string) => {
261 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address, buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(), closing_date: addDays(today(), 40) }) });
262 const deal = (await made.json()) as { id: number; parties: { id: number; name: string }[] };
263 for (const p of deal.parties) await call(`/api/deals/${deal.id}/parties/${p.id}`, { method: "PATCH", body: JSON.stringify({ name: p.name, contact: "[email protected]" }) });
264 const drafted = (await (await call(`/api/deals/${deal.id}/status`)).json()) as { party_id: number; deadline_id: number }[];
265 return { id: deal.id, drafted };
266 };
267 const view = async (id: number) => (await (await call(`/api/deals/${id}`)).json()) as { sent: { moment: string; body: string }[]; declined: { moment: string; reason: string }[] };
268 const form = (path: string, fields: Record<string, string>) => {
269 const body = new FormData();
270 for (const [k, v] of Object.entries(fields)) body.set(k, v);
271 return fetch(base + path, { method: "POST", body, redirect: "manual", headers: editor });
272 };
273
274 // The page: the card's forms post the closing date, the party and the moment.
275 const viaPage = await make("10 Door Way");
276 const [one, two] = viaPage.drafted as [{ party_id: number; deadline_id: number }, { party_id: number; deadline_id: number }];
277 const ask = (d: { party_id: number; deadline_id: number }) => ({ deadline: String(d.deadline_id), party: String(d.party_id), moment: "status", to: "/" });
278 expect((await form("/reminders", { ...ask(one), subject: "Page subject", body: "Page words" })).status).toBe(303);
279 expect((await form("/reminders/decline", { ...ask(two), reason: "Told by phone" })).status).toBe(303);
280 let seen = await view(viaPage.id);
281 expect(seen.sent.map((m) => [m.moment, m.body])).toEqual([["status", "Page words"]]);
282 expect(seen.declined.map((m) => [m.moment, m.reason])).toEqual([["status", "Told by phone"]]);
283
284 // The API: decline, and a decline of a sent update is refused.
285 const viaApi = await make("11 Door Way");
286 const declined = await call(`/api/deals/${viaApi.id}/reminders/decline`, { method: "POST", body: JSON.stringify({ deadline_id: viaApi.drafted[0]!.deadline_id, party_id: viaApi.drafted[0]!.party_id, moment: "status", reason: "On the phone" }) });
287 expect(declined.status).toBe(201);
288 seen = await view(viaApi.id);
289 expect(seen.declined.map((m) => [m.moment, m.reason])).toEqual([["status", "On the phone"]]);
290 const noReason = await call(`/api/deals/${viaApi.id}/reminders/decline`, { method: "POST", body: JSON.stringify({ deadline_id: viaApi.drafted[1]!.deadline_id, party_id: viaApi.drafted[1]!.party_id, moment: "status", reason: " " }) });
291 expect(noReason.status).toBe(422);
292 expect((await call(`/api/deals/${viaApi.id}/reminders/decline`, { method: "POST", body: "{}" }, {})).status).toBe(401);
293
294 // MCP: decline, then the party is no longer offered.
295 const viaMcp = await make("12 Door Way");
296 const out = await rpc("decline_reminder", { deal_id: viaMcp.id, deadline_id: viaMcp.drafted[0]!.deadline_id, party_id: viaMcp.drafted[0]!.party_id, moment: "status", reason: "Said so in person" });
297 expect(JSON.parse(out.result.content[0].text)).toMatchObject({ reason: "Said so in person" });
298 seen = await view(viaMcp.id);
299 expect(seen.declined.map((m) => m.moment)).toEqual(["status"]);
300 const list = (await (await call(`/api/deals/${viaMcp.id}/status`)).json()) as { party_id: number; declined: { reason: string } | null }[];
301 expect(list.find((d) => d.party_id === viaMcp.drafted[0]!.party_id)!.declined).toMatchObject({ reason: "Said so in person" });
302 });
src/terminal.ts +22 −3
@@ -10,7 +10,7 @@
1010 * timeline a deal's dates as a client would get them (t on a deal)
1111 * activity who approved, declined or changed what, newest first (L, admins); m only messages, o older, y newer
1212 * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults
13 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, D removes it
13 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, S drafts a status update for the party under the cursor, D removes it
1414 *
1515 * On a date (dates or deal view): x marks it done, u reopens it, m moves it
1616 * (a new date, then the reason), l sets how many days before it reminds. o or enter opens its deal; n opens a new
@@ -46,6 +46,8 @@ import {
4646 setReminderLead,
4747 removeParty,
4848 sendReminder,
49 sendStatusUpdate,
50 statusUpdates,
4951 declineReminder,
5052 undoDecline,
5153 REASON_MAX,
@@ -205,9 +207,26 @@ export function terminal(
205207
206208 function onDeal(key: string): boolean {
207209 const deal = openDeal();
208 if (deal === undefined || !["a", "p", "D", "e", "X", "A", "M"].includes(key)) return false;
210 if (deal === undefined || !["a", "p", "D", "e", "X", "A", "M", "S"].includes(key)) return false;
209211 const party = deal.parties[cursor - deal.deadlines.length];
210212 const date = deal.deadlines[cursor];
213 if (key === "S") {
214 const update = statusUpdates(db, me, { dealId: deal.id, agent: agentNow() });
215 const mine = update.ok ? update.value.find((d) => d.party_id === party?.id) : undefined;
216 if (!update.ok) said = update.message;
217 else if (party === undefined) said = "Move to a buyer or seller to draft their status update.";
218 else if (mine === undefined) said = deal.closed ? "A closed deal has no status update." : `${party.name} gets no status update: only a buyer or seller with an email or phone does.`;
219 else if (mine.sent_at !== null) said = `${party.name} has the latest status update; it is offered again when a date changes.`;
220 else if (mine.declined !== null) said = `Not sent to ${party.name}: ${mine.declined.reason}. It is offered again when a date changes.`;
221 else
222 ask(deal, [`Status update to ${party.name}, "${mine.subject}": type send to record it as sent, no and a reason to decline, or enter to cancel`], ([answer]) => {
223 const text = (answer ?? "").trim();
224 if (text === "send") return report(sendStatusUpdate(db, me, { dealId: deal.id, partyId: party.id, subject: mine.subject, body: mine.body }), `Recorded as sent to ${party.name}. ${party.contact === "" ? "" : `Send it from your phone to ${party.contact}.`}`);
225 if (/^no\b/.test(text))
226 return report(declineReminder(db, me, { dealId: deal.id, deadlineId: mine.deadline_id, partyId: party.id, moment: "status", reason: text.slice(2) }), `Not sent to ${party.name}.`);
227 return "Not sent.";
228 }, REASON_MAX);
229 }
211230 if (key === "A")
212231 ask(deal, [`Address (now ${deal.address})`], ([address]) =>
213232 report(updateDeal(db, me, { id: deal.id, address }), `Address is now ${address!.trim()}.`),
@@ -704,7 +723,7 @@ export function terminal(
704723 : view === "timeline"
705724 ? "b back to the deal · d dates · q quit"
706725 : view === "deal"
707 ? "j/k move · t client timeline · s messages · x done · u reopen · m move · l remind lead · a add date · p add party · e edit party · A edit address · M amend the contract · X remove date/party · D remove deal · b back · q quit"
726 ? "j/k move · t client timeline · s messages · x done · u reopen · m move · l remind lead · a add date · p add party · e edit party · A edit address · M amend the contract · S status update to the party · X remove date/party · D remove deal · b back · q quit"
708727 : `j/k move · x done · u reopen · m move · l lead · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · L activity · q quit`;
709728 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
710729 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs