Public: anyone can read this; the crew can change it.
The agent holds a reminder until tomorrow with one tap, so a message they are not ready to approve waits instead of being declined or lost #103
Check · Review · Land · Live done — Landed and live in production.
mason/deal-clock:mason/100-the-agent-holds-a-reminder-until-tomorro → main 2 commits fork 1 thread · 1 unresolved
20 files
changed +478
−26
README.md +1
| @@ -75,6 +75,7 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture | ||
| 75 | 75 | Decided against a message? Beside Send, **Don't send** asks why (up to 200 |
| 76 | 76 | characters). The reminder stops counting as "to send" and reads "Not sent: |
| 77 | 77 | <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again. |
| 78 | Not ready to approve one? **Tomorrow** holds it: it leaves today's list and the count, and returns at the top tomorrow as "Held from <weekday>" with your edited words (hold it again to push it another day). In the terminal, press h on the reminders list. | |
| 78 | 79 | To keep a client informed about the whole deal, a deal's page also has a |
| 79 | 80 | **Status update** card for each buyer and seller with an email or phone: a |
| 80 | 81 | draft of what is done, what is next and who owes it, and when it closes, |
contract/openapi.json +89
| @@ -1441,6 +1441,95 @@ | ||
| 1441 | 1441 | } |
| 1442 | 1442 | } |
| 1443 | 1443 | }, |
| 1444 | "/api/deals/{id}/reminders/hold": { | |
| 1445 | "post": { | |
| 1446 | "summary": "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.", | |
| 1447 | "operationId": "postApiDealsIdRemindersHold", | |
| 1448 | "parameters": [ | |
| 1449 | { | |
| 1450 | "name": "id", | |
| 1451 | "in": "path", | |
| 1452 | "required": true, | |
| 1453 | "schema": { | |
| 1454 | "type": "integer" | |
| 1455 | } | |
| 1456 | } | |
| 1457 | ], | |
| 1458 | "requestBody": { | |
| 1459 | "required": true, | |
| 1460 | "content": { | |
| 1461 | "application/json": { | |
| 1462 | "schema": { | |
| 1463 | "type": "object", | |
| 1464 | "properties": { | |
| 1465 | "deadline_id": { | |
| 1466 | "type": "integer" | |
| 1467 | }, | |
| 1468 | "party_id": { | |
| 1469 | "type": "integer" | |
| 1470 | }, | |
| 1471 | "moment": { | |
| 1472 | "enum": [ | |
| 1473 | "before", | |
| 1474 | "day_of", | |
| 1475 | "late", | |
| 1476 | "moved" | |
| 1477 | ] | |
| 1478 | } | |
| 1479 | }, | |
| 1480 | "required": [ | |
| 1481 | "deadline_id", | |
| 1482 | "party_id", | |
| 1483 | "moment" | |
| 1484 | ] | |
| 1485 | } | |
| 1486 | } | |
| 1487 | } | |
| 1488 | }, | |
| 1489 | "responses": { | |
| 1490 | "201": { | |
| 1491 | "description": "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.", | |
| 1492 | "content": { | |
| 1493 | "application/json": { | |
| 1494 | "schema": { | |
| 1495 | "type": "object", | |
| 1496 | "properties": { | |
| 1497 | "id": { | |
| 1498 | "type": "integer" | |
| 1499 | }, | |
| 1500 | "until": { | |
| 1501 | "type": "string" | |
| 1502 | }, | |
| 1503 | "by_name": { | |
| 1504 | "type": "string" | |
| 1505 | } | |
| 1506 | }, | |
| 1507 | "required": [ | |
| 1508 | "id", | |
| 1509 | "until" | |
| 1510 | ] | |
| 1511 | } | |
| 1512 | } | |
| 1513 | } | |
| 1514 | }, | |
| 1515 | "default": { | |
| 1516 | "description": "{ error, message }: why not", | |
| 1517 | "content": { | |
| 1518 | "application/json": { | |
| 1519 | "schema": { | |
| 1520 | "$ref": "#/components/schemas/Error" | |
| 1521 | } | |
| 1522 | } | |
| 1523 | } | |
| 1524 | } | |
| 1525 | }, | |
| 1526 | "x-contract": { | |
| 1527 | "resource": "deal", | |
| 1528 | "verb": "update", | |
| 1529 | "least": "user" | |
| 1530 | } | |
| 1531 | } | |
| 1532 | }, | |
| 1444 | 1533 | "/api/deals/{id}/reminders/undo": { |
| 1445 | 1534 | "post": { |
| 1446 | 1535 | "summary": "Take back a decline: the reminder is a draft again.", |
docs/TECHNICAL.md +7
| @@ -102,6 +102,13 @@ sent until undone. Over the API: `POST /api/deals/:id/reminders/decline` and | ||
| 102 | 102 | `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the |
| 103 | 103 | reason on the reminders list, and `u` to undo. Each is an update of the deal. |
| 104 | 104 | |
| 105 | A hold (`holdReminder`) is a row of `reminder_hold`, keyed like a sent or declined | |
| 106 | reminder (`deadline_id`, `party_id`, `moment`, `due`, `move_id`) with the morning it | |
| 107 | returns (`until`). It leaves `todaysDrafts`, the waiting count and `/tick` until then, | |
| 108 | returns at the top as "Held from <weekday>", and holding again pushes `until` one more | |
| 109 | day. Posts: `/reminders/hold`, `/reminders/today/hold`, `POST /api/deals/:id/reminders/hold`; | |
| 110 | MCP `hold_reminder`; in the terminal, `h` on the reminders list. A reminder can be held only from its send morning on. Audited as `reminder.hold:<until>`. Same `deal` update cell as Send. | |
| 111 | ||
| 105 | 112 | `GET /deals/:id/sheets` is an HTML fragment: every date's sheet for one deal. The clock carries |
| 106 | 113 | no sheets (they were most of its size); `sheets.js` fetches a deal's the first time one of its dates is tapped, |
| 107 | 114 | and without script the date is a link to `/deals/:id#sheet-N`; the deal page has its sheets inline, |
src/actions.ts +2 −2
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import { MESSAGE_WHATS, type AuditRow } from "./audit.ts"; | |
| 10 | import { HOLD_WHAT, MESSAGE_WHATS, type AuditRow } from "./audit.ts"; | |
| 11 | 11 | import { permit } from "./contract.ts"; |
| 12 | 12 | import { emit } from "./live.ts"; |
| 13 | 13 | import { audited, fail, ok, refuse, type Result } from "./result.ts"; |
| @@ -43,7 +43,7 @@ export function listAudit( | ||
| 43 | 43 | : Number.MAX_SAFE_INTEGER; |
| 44 | 44 | const kept = |
| 45 | 45 | input.only === "messages" |
| 46 | ? ` AND what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")})` | |
| 46 | ? ` AND (what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")}) OR what LIKE '${HOLD_WHAT}:%')` | |
| 47 | 47 | : ""; |
| 48 | 48 | return ok( |
| 49 | 49 | db |
src/activity.ts +10 −1
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | import type { AuditRow } from "./audit.ts"; | |
| 8 | import { HOLD_WHAT, type AuditRow } from "./audit.ts"; | |
| 9 | import { isDate, spoken } from "./dates.ts"; | |
| 9 | 10 | |
| 10 | 11 | /** Rows to a page; a door asks for one more to know whether there is an older page. */ |
| 11 | 12 | export const ACTIVITY_PAGE = 100; |
| @@ -14,6 +15,7 @@ export const ACTIVITY_PAGE = 100; | ||
| 14 | 15 | const WORDS: Readonly<Record<string, string>> = { |
| 15 | 16 | "reminder.send": "sent a reminder", |
| 16 | 17 | "reminder.decline": "declined a reminder", |
| 18 | "reminder.hold": "held a reminder", | |
| 17 | 19 | "reminder.undo": "undid a declined reminder", |
| 18 | 20 | "date.move": "moved a date", |
| 19 | 21 | "date.done": "marked a date done", |
| @@ -50,7 +52,14 @@ const AT = new Intl.DateTimeFormat("en-US", { | ||
| 50 | 52 | timeZoneName: "short", |
| 51 | 53 | }); |
| 52 | 54 | |
| 55 | /** "held a reminder until Wed, Nov 4": a hold's audit name carries the day it comes back. */ | |
| 56 | const heldWords = (what: string | null): string | undefined => { | |
| 57 | const until = what?.startsWith(`${HOLD_WHAT}:`) ? what.slice(HOLD_WHAT.length + 1) : ""; | |
| 58 | return isDate(until) ? `held a reminder until ${spoken(until)}` : undefined; | |
| 59 | }; | |
| 60 | ||
| 53 | 61 | export const wording = (row: Pick<AuditRow, "resource" | "verb" | "what">): string => |
| 62 | heldWords(row.what) || | |
| 54 | 63 | (row.what !== null && WORDS[row.what]) || WORDS[`${row.resource} ${row.verb}`] || `${row.resource} ${row.verb}`; |
| 55 | 64 | |
| 56 | 65 | /** "Fri, Oct 16, 3:04 PM UTC" from the stored ISO time; the text itself if it does not read. */ |
src/audit.ts +3 −1
| @@ -41,8 +41,10 @@ export interface Attempt { | ||
| 41 | 41 | readonly what?: string | undefined; |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | /** The changes that are a message's life: sent, declined, undone. The Activity page's `only=messages`. */ | |
| 44 | /** The changes that are a message's life: sent, declined, held, undone. The Activity page's `only=messages`. */ | |
| 45 | 45 | export const MESSAGE_WHATS = ["reminder.send", "reminder.decline", "reminder.undo"] as const; |
| 46 | /** A hold is audited as `reminder.hold:<the day it comes back>`. */ | |
| 47 | export const HOLD_WHAT = "reminder.hold"; | |
| 46 | 48 | |
| 47 | 49 | /** The newest rows kept; older ones go as new ones come. */ |
| 48 | 50 | export const KEEP = 50_000; |
src/contract.test.ts +18
| @@ -14,6 +14,7 @@ import { | ||
| 14 | 14 | createDeal, |
| 15 | 15 | deleteDeal, |
| 16 | 16 | getDeal, |
| 17 | holdReminder, | |
| 17 | 18 | listDeals, |
| 18 | 19 | sendStatusUpdate, |
| 19 | 20 | statusUpdates, |
| @@ -179,6 +180,23 @@ test("the status update, at GET /api/deals/:id/status, its send and the two MCP | ||
| 179 | 180 | expect(sendStatusUpdate(db, { role: "anon" }, { dealId: dealBy("u1"), partyId: 1 }).ok).toBe(false); |
| 180 | 181 | }); |
| 181 | 182 | |
| 183 | test("holding a reminder answers as deal update says, as every identity", () => { | |
| 184 | for (const identity of identities(contract)) { | |
| 185 | const who = whoIs(identity); | |
| 186 | const { mine, theirs } = actingAs(contract, identity); | |
| 187 | for (const row of [mine, theirs]) { | |
| 188 | const id = dealBy(String(row["author_id"])); | |
| 189 | const said = `hold as ${identity} on ${String(row["author_id"])}`; | |
| 190 | const allowed = permit(who, "deal", "update", row) === "yes"; | |
| 191 | const deadline = db.query<{ id: number }, [number]>("INSERT INTO deadline (deal_id, kind, label, due, owes) VALUES (?1, 'closing', 'Closing', '2026-11-01', 'buyer') RETURNING id").get(id)!.id; | |
| 192 | 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; | |
| 193 | const held = holdReminder(db, who, { dealId: id, deadlineId: deadline, partyId: party, moment: "day_of", on: "2026-11-01" }); | |
| 194 | expect([said, held.ok]).toEqual([said, allowed]); | |
| 195 | } | |
| 196 | } | |
| 197 | expect(holdReminder(db, { role: "anon" }, { dealId: dealBy("u1"), deadlineId: 1, partyId: 1, moment: "day_of" }).ok).toBe(false); | |
| 198 | }); | |
| 199 | ||
| 182 | 200 | test("the spreadsheet, at GET /deals/csv and GET /api/deals.csv, answers as deal list says, as every identity", async () => { |
| 183 | 201 | for (const path of ["/deals/csv", "/api/deals.csv"]) { |
| 184 | 202 | const route = routes.find((r) => r.method === "GET" && r.path === path)!; |
src/dates.ts +5
| @@ -138,6 +138,11 @@ const SHORT = new Intl.DateTimeFormat("en-US", { | ||
| 138 | 138 | /** "Fri, Oct 16" — how a person reads a date in a sentence. */ |
| 139 | 139 | export const spoken = (date: string): string => SPOKEN.format(toMs(date)); |
| 140 | 140 | |
| 141 | const WEEKDAY = new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone: "UTC" }); | |
| 142 | ||
| 143 | /** "Friday" — the day of the week a date falls on. */ | |
| 144 | export const weekday = (date: string): string => WEEKDAY.format(toMs(date)); | |
| 145 | ||
| 141 | 146 | /** "Oct 16" — for tight places. */ |
| 142 | 147 | export const short = (date: string): string => SHORT.format(toMs(date)); |
| 143 | 148 |
src/db.ts +17
| @@ -374,6 +374,23 @@ export const migrations: string[] = [ | ||
| 374 | 374 | // A date the buyer gave up on purpose: neither done nor gone. Who waived it is kept with the day. |
| 375 | 375 | `ALTER TABLE deadline ADD COLUMN waived_at TEXT`, |
| 376 | 376 | `ALTER TABLE deadline ADD COLUMN waived_by TEXT`, |
| 377 | // A reminder the agent holds until a later morning. It is keyed like a | |
| 378 | // sent or declined one, so a moved date's notice is held once, not twice. | |
| 379 | `CREATE TABLE IF NOT EXISTS reminder_hold ( | |
| 380 | id INTEGER PRIMARY KEY, | |
| 381 | deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE, | |
| 382 | deadline_id INTEGER NOT NULL, | |
| 383 | party_id INTEGER NOT NULL, | |
| 384 | moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')), | |
| 385 | due TEXT NOT NULL, | |
| 386 | move_id INTEGER NOT NULL DEFAULT 0, | |
| 387 | until TEXT NOT NULL, | |
| 388 | held_on TEXT NOT NULL, | |
| 389 | by_name TEXT NOT NULL, | |
| 390 | at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), | |
| 391 | UNIQUE (deadline_id, party_id, moment, due, move_id) | |
| 392 | ); | |
| 393 | CREATE INDEX IF NOT EXISTS reminder_hold_deal ON reminder_hold (deal_id)`, | |
| 377 | 394 | ]; |
| 378 | 395 | |
| 379 | 396 | export function openDb(dir = dataDir): Database { |
src/deals.ts +57 −1
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import { permit } from "./contract.ts"; |
| 11 | import { isBusinessDay, isDate, nextBusinessDay, today } from "./dates.ts"; | |
| 11 | import { addDays, isBusinessDay, isDate, nextBusinessDay, spoken, today } from "./dates.ts"; | |
| 12 | 12 | import { |
| 13 | 13 | DEFAULT_LENGTHS, |
| 14 | 14 | isClosed, |
| @@ -78,6 +78,21 @@ export interface Move { | ||
| 78 | 78 | /** The addendum that made this move together with others; 0 for a move made on its own. */ |
| 79 | 79 | readonly amendment: number; |
| 80 | 80 | } |
| 81 | /** A reminder held until a later morning; keyed like a sent or declined one. */ | |
| 82 | export interface Held { | |
| 83 | readonly id: number; | |
| 84 | readonly deal_id: number; | |
| 85 | readonly deadline_id: number; | |
| 86 | readonly party_id: number; | |
| 87 | readonly moment: Moment; | |
| 88 | readonly due: string; | |
| 89 | readonly move_id: number; | |
| 90 | /** The morning it comes back. */ | |
| 91 | readonly until: string; | |
| 92 | /** The day it was held. */ | |
| 93 | readonly held_on: string; | |
| 94 | readonly by_name: string; | |
| 95 | } | |
| 81 | 96 | export interface Sent { |
| 82 | 97 | readonly id: number; |
| 83 | 98 | readonly deal_id: number; |
| @@ -137,6 +152,7 @@ export interface DealView extends Deal { | ||
| 137 | 152 | readonly deadlines: readonly DeadlineView[]; |
| 138 | 153 | readonly sent: readonly Sent[]; |
| 139 | 154 | readonly declined: readonly Declined[]; |
| 155 | readonly held: readonly Held[]; | |
| 140 | 156 | /** Open dates due on or after the open closing date (`order.ts`). */ |
| 141 | 157 | readonly conflicts: readonly Conflict[]; |
| 142 | 158 | } |
| @@ -197,6 +213,7 @@ interface Children { | ||
| 197 | 213 | parties: Party[]; |
| 198 | 214 | sent: SentRow[]; |
| 199 | 215 | declined: Declined[]; |
| 216 | held: Held[]; | |
| 200 | 217 | } |
| 201 | 218 | |
| 202 | 219 | /** A sent reminder with the link for the party's contact as it stands now; none once the party is gone. */ |
| @@ -221,6 +238,7 @@ function assemble(deal: Deal, rows: Children): DealView { | ||
| 221 | 238 | })), |
| 222 | 239 | sent: rows.sent.map((m) => withHref(m, rows.parties)), |
| 223 | 240 | declined: rows.declined, |
| 241 | held: rows.held, | |
| 224 | 242 | conflicts: conflicts(rows.deadlines), |
| 225 | 243 | }; |
| 226 | 244 | } |
| @@ -252,6 +270,7 @@ function view(db: Database, deal: Deal): DealView { | ||
| 252 | 270 | "SELECT * FROM reminder_declined WHERE deal_id = ?1 ORDER BY id", |
| 253 | 271 | ) |
| 254 | 272 | .all(deal.id), |
| 273 | held: db.query<Held, [number]>("SELECT * FROM reminder_hold WHERE deal_id = ?1 ORDER BY id").all(deal.id), | |
| 255 | 274 | }); |
| 256 | 275 | } |
| 257 | 276 | |
| @@ -306,6 +325,10 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] { | ||
| 306 | 325 | db.query<Declined, string[]>(`SELECT * FROM reminder_declined WHERE ${of} ORDER BY id`).all(...params), |
| 307 | 326 | (r) => r.deal_id, |
| 308 | 327 | ); |
| 328 | const held = byDeal( | |
| 329 | db.query<Held, string[]>(`SELECT * FROM reminder_hold WHERE ${of} ORDER BY id`).all(...params), | |
| 330 | (r) => r.deal_id, | |
| 331 | ); | |
| 309 | 332 | return deals.map((deal) => |
| 310 | 333 | assemble(deal, { |
| 311 | 334 | deadlines: deadlines.get(deal.id) ?? [], |
| @@ -313,6 +336,7 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] { | ||
| 313 | 336 | parties: parties.get(deal.id) ?? [], |
| 314 | 337 | sent: sent.get(deal.id) ?? [], |
| 315 | 338 | declined: declined.get(deal.id) ?? [], |
| 339 | held: held.get(deal.id) ?? [], | |
| 316 | 340 | }), |
| 317 | 341 | ); |
| 318 | 342 | } |
| @@ -1047,6 +1071,38 @@ export function declineReminder( | ||
| 1047 | 1071 | return within(db, who, "reminder.decline", dealId, ok(declined)); |
| 1048 | 1072 | } |
| 1049 | 1073 | |
| 1074 | /** | |
| 1075 | * Hold a reminder until tomorrow: it leaves today's list and comes back the | |
| 1076 | * next morning with the words as edited. Held again, it waits one more day. | |
| 1077 | * A status update is not a morning reminder and is not held. | |
| 1078 | */ | |
| 1079 | export function holdReminder( | |
| 1080 | db: Database, | |
| 1081 | who: Who, | |
| 1082 | input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent; on?: string }, | |
| 1083 | ): Result<Held> { | |
| 1084 | const { dealId, found } = draftOf(db, who, input); | |
| 1085 | if (!found.ok) return within(db, who, "reminder.hold", dealId, found); | |
| 1086 | const { draft, deal } = found.value; | |
| 1087 | if (draft.moment === "status") | |
| 1088 | return within(db, who, "reminder.hold", dealId, fail("invalid", "A status update is not held; send it or decline it.")); | |
| 1089 | if (draft.sent_at !== null) | |
| 1090 | return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was already sent.")); | |
| 1091 | if (draft.declined !== null) | |
| 1092 | return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was declined; undo that first to hold it.")); | |
| 1093 | const day = input.on ?? today(); | |
| 1094 | if (draft.on > day) | |
| 1095 | return within(db, who, "reminder.hold", dealId, fail("invalid", `This reminder goes out on ${spoken(draft.on)}; it can be held from that morning.`)); | |
| 1096 | const until = addDays(draft.held !== null && draft.held.until > day ? draft.held.until : day, 1); | |
| 1097 | const held = db | |
| 1098 | .query<Held, [number, number, number, string, string, number, string, string, string]>( | |
| 1099 | `INSERT INTO reminder_hold (deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) | |
| 1100 | ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET until = excluded.until, held_on = excluded.held_on, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`, | |
| 1101 | ) | |
| 1102 | .get(deal.id, draft.deadline_id, draft.party_id, draft.moment, draft.due, draft.move_id, until, day, authorOf(who).name)!; | |
| 1103 | return within(db, who, `reminder.hold:${until}`, dealId, ok(held)); | |
| 1104 | } | |
| 1105 | ||
| 1050 | 1106 | /** Take back a decline: the reminder is a draft again. */ |
| 1051 | 1107 | export function undoDecline( |
| 1052 | 1108 | db: Database, |
src/hold.test.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** Holding a reminder until tomorrow: it leaves today, comes back with its words, and is sent like any other. */ | |
| 2 | import { afterAll, beforeEach, expect, test } from "bun:test"; | |
| 3 | import { mkdtempSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { listAudit, restoreSamples } from "./actions.ts"; | |
| 7 | import { addDays, today } from "./dates.ts"; | |
| 8 | import { openDb } from "./db.ts"; | |
| 9 | import { createDeal, getDeal, holdReminder, sendReminder, declineReminder, type DealView } from "./deals.ts"; | |
| 10 | import { drafts, dueOn, todaysDrafts, waitingCount, type Draft } from "./reminders.ts"; | |
| 11 | import { wording } from "./activity.ts"; | |
| 12 | import { forgetRationing } from "./security.ts"; | |
| 13 | import { serve } from "./server.ts"; | |
| 14 | import type { Who } from "./who.ts"; | |
| 15 | import { sign } from "./who.ts"; | |
| 16 | ||
| 17 | const db = openDb(mkdtempSync(join(tmpdir(), "app-hold-"))); | |
| 18 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 19 | const admin: Who = { role: "admin", id: "a1", name: "root" }; | |
| 20 | const anon: Who = { role: "anon" }; | |
| 21 | const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty", phone: "(555) 010-0142", email: "[email protected]" }; | |
| 22 | ||
| 23 | const now = today(); | |
| 24 | const deal = ((): DealView => { | |
| 25 | const made = createDeal(db, alice, { openAnyway: true, address: "7 Hold Ln", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(now, -5), closingDate: addDays(now, 40), lengths: { inspection: "8" } }); | |
| 26 | if (!made.ok) throw new Error(made.message); | |
| 27 | return made.value; | |
| 28 | })(); | |
| 29 | const fresh = (): DealView => { | |
| 30 | const got = getDeal(db, alice, { id: deal.id }); | |
| 31 | if (!got.ok) throw new Error(got.message); | |
| 32 | return got.value; | |
| 33 | }; | |
| 34 | const inspection = deal.deadlines.find((d) => d.kind === "inspection")!; | |
| 35 | const mine = (list: readonly Draft[]) => list.filter((d) => d.deadline_id === inspection.id); | |
| 36 | // The inspection is due in 3 days: its "before" reminder goes out today. | |
| 37 | const first = mine(todaysDrafts([fresh()], now, agent)).find((d) => d.moment === "before")!; | |
| 38 | const ask = { dealId: deal.id, deadlineId: first.deadline_id, partyId: first.party_id, moment: first.moment }; | |
| 39 | const tomorrow = addDays(now, 1); | |
| 40 | const listed = (day: string) => mine(todaysDrafts([fresh()], day, agent)).filter((d) => d.party_id === first.party_id && d.moment === "before"); | |
| 41 | ||
| 42 | test("a held reminder is missing from today, back tomorrow with its words, sent the day after", () => { | |
| 43 | expect(listed(now).length).toBe(1); | |
| 44 | const before = waitingCount([fresh()], now, agent); | |
| 45 | const held = holdReminder(db, alice, ask); | |
| 46 | expect(held.ok && held.value.until).toBe(tomorrow); | |
| 47 | expect(listed(now)).toEqual([]); | |
| 48 | expect(waitingCount([fresh()], now, agent)).toBe(before - 1); | |
| 49 | expect(mine(dueOn([fresh()], now, agent)).some((d) => d.party_id === first.party_id && d.moment === "before")).toBe(false); | |
| 50 | // Tomorrow: back, at the top, labelled, and on /tick. | |
| 51 | const back = listed(tomorrow); | |
| 52 | expect(back.length).toBe(1); | |
| 53 | expect(back[0]!.held).toEqual({ until: tomorrow, from: now, by_name: "alice" }); | |
| 54 | expect(back[0]!.subject).toBe(first.subject); | |
| 55 | expect(todaysDrafts([fresh()], tomorrow, agent)[0]!.held).not.toBeNull(); | |
| 56 | expect(mine(dueOn([fresh()], tomorrow, agent)).some((d) => d.party_id === first.party_id && d.moment === "before")).toBe(true); | |
| 57 | // Sent the day after: recorded like any other. | |
| 58 | const sent = sendReminder(db, alice, { ...ask, subject: "Edited", body: "Edited words" }); | |
| 59 | expect(sent.ok).toBe(true); | |
| 60 | const after = drafts(fresh(), agent).find((d) => d.deadline_id === first.deadline_id && d.party_id === first.party_id && d.moment === "before")!; | |
| 61 | expect(after.sent_at).not.toBeNull(); | |
| 62 | expect(after.held).toBeNull(); | |
| 63 | expect(fresh().sent.length).toBe(1); | |
| 64 | }); | |
| 65 | ||
| 66 | test("holding a held reminder pushes it one more day, and a sent one cannot be held", () => { | |
| 67 | const second = mine(drafts(fresh(), agent)).find((d) => d.moment === "late")!; | |
| 68 | const k = { dealId: deal.id, deadlineId: second.deadline_id, partyId: second.party_id, moment: second.moment }; | |
| 69 | // Not before its send morning. | |
| 70 | expect(holdReminder(db, alice, k).ok).toBe(false); | |
| 71 | const morning = second.on; | |
| 72 | const hold = holdReminder(db, alice, { ...k, on: morning }); | |
| 73 | expect(hold.ok && hold.value.until).toBe(addDays(morning, 1)); | |
| 74 | const again = holdReminder(db, alice, { ...k, on: addDays(morning, 1) }); | |
| 75 | expect(again.ok && again.value.until).toBe(addDays(morning, 2)); | |
| 76 | const twice = holdReminder(db, alice, { ...k, on: addDays(morning, 1) }); | |
| 77 | expect(twice.ok && twice.value.until).toBe(addDays(morning, 3)); | |
| 78 | expect(holdReminder(db, alice, ask).ok).toBe(false); | |
| 79 | }); | |
| 80 | ||
| 81 | test("a held reminder can be declined, and the hold is audited with its day", () => { | |
| 82 | const late = mine(drafts(fresh(), agent)).find((d) => d.moment === "day_of" && d.party_id === first.party_id)!; | |
| 83 | const k = { dealId: deal.id, deadlineId: late.deadline_id, partyId: late.party_id, moment: late.moment }; | |
| 84 | expect(holdReminder(db, alice, { ...k, on: late.on }).ok).toBe(true); | |
| 85 | expect(declineReminder(db, alice, { ...k, reason: "Spoke by phone" }).ok).toBe(true); | |
| 86 | const row = listAudit(db, admin, { only: "messages" }); | |
| 87 | expect(row.ok && row.value.some((r) => wording(r).startsWith("held a reminder until"))).toBe(true); | |
| 88 | expect(holdReminder(db, alice, k).ok).toBe(false); | |
| 89 | }); | |
| 90 | ||
| 91 | test("a status update is not held, an anonymous visitor is refused, and restore clears holds on samples only", () => { | |
| 92 | expect(holdReminder(db, anon, ask).ok).toBe(false); | |
| 93 | const status = holdReminder(db, alice, { ...ask, moment: "status" }); | |
| 94 | expect(status.ok).toBe(false); | |
| 95 | const sample = db.query<{ id: number }, []>("SELECT id FROM deal WHERE author_id = 'sample' LIMIT 1").get()!; | |
| 96 | const sdeal = getDeal(db, alice, { id: sample.id }); | |
| 97 | if (!sdeal.ok) throw new Error(sdeal.message); | |
| 98 | const todo = drafts(sdeal.value, agent).find((d) => d.sent_at === null)!; | |
| 99 | expect(holdReminder(db, alice, { dealId: sample.id, deadlineId: todo.deadline_id, partyId: todo.party_id, moment: todo.moment, on: todo.on > now ? todo.on : now }).ok).toBe(true); | |
| 100 | const holds = (): number => db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_hold").get()!.n; | |
| 101 | const mineHeld = db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM reminder_hold WHERE deal_id = ?1").get(deal.id)!.n; | |
| 102 | expect(holds()).toBeGreaterThan(mineHeld); | |
| 103 | expect(restoreSamples(db, admin).ok).toBe(true); | |
| 104 | expect(holds()).toBe(mineHeld); | |
| 105 | }); | |
| 106 | ||
| 107 | // ---- through the door ---- | |
| 108 | ||
| 109 | const KEY = "a-key-only-the-forge-holds"; | |
| 110 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-hold-web-")), identityKey: KEY }); | |
| 111 | const base = `http://${server.hostname}:${server.port}`; | |
| 112 | afterAll(() => server.stop(true)); | |
| 113 | beforeEach(forgetRationing); | |
| 114 | const identity = `u1|alice|user|${Date.now() + 600_000}`; | |
| 115 | const signed = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 116 | const post = (path: string, fields: Record<string, string>, headers: Record<string, string> = signed) => | |
| 117 | fetch(base + path, { method: "POST", body: new URLSearchParams(fields), headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" }); | |
| 118 | ||
| 119 | test("Tomorrow is a form on the review page and posts; another origin and an anonymous visitor are refused", async () => { | |
| 120 | const page = await (await fetch(`${base}/reminders/today`, { headers: signed })).text(); | |
| 121 | expect(page).toContain('action="/reminders/today/hold"'); | |
| 122 | expect(page).toContain(">Tomorrow<"); | |
| 123 | const hidden = (name: string) => new RegExp(`name="${name}" value="([^"]*)"`).exec(page)![1]!; | |
| 124 | const keys = { deadline: hidden("deadline"), party: hidden("party"), moment: hidden("moment"), at: "0", done: "0", q: "" }; | |
| 125 | const cross = await post("/reminders/today/hold", keys, { ...signed, origin: "https://evil.example" }); | |
| 126 | expect(cross.status).toBeGreaterThanOrEqual(400); | |
| 127 | expect((await post("/reminders/today/hold", keys, {})).status).toBe(401); | |
| 128 | const total = (p: string): number => Number(/(\d+) of (\d+)/.exec(p)?.[2] ?? 0); | |
| 129 | const res = await post("/reminders/today/hold", keys); | |
| 130 | expect(res.status).toBe(303); | |
| 131 | const after = await (await fetch(`${base}/reminders/today`, { headers: signed })).text(); | |
| 132 | expect(total(after)).toBe(total(page) - 1); | |
| 133 | // The deal's sheet offers it too, and the API documents the route. | |
| 134 | expect(await (await fetch(`${base}/openapi.json`, { headers: signed })).text()).toContain("/api/deals/{id}/reminders/hold"); | |
| 135 | }); |
src/mcp.ts +14 −1
| @@ -32,6 +32,7 @@ import { | ||
| 32 | 32 | statusUpdates, |
| 33 | 33 | setReminderLead, |
| 34 | 34 | declineReminder, |
| 35 | holdReminder, | |
| 35 | 36 | undoDecline, |
| 36 | 37 | } from "./deals.ts"; |
| 37 | 38 | import { LENGTH_MAX, standard, title } from "./env.ts"; |
| @@ -86,7 +87,7 @@ export const tools: readonly Tool[] = [ | ||
| 86 | 87 | }, |
| 87 | 88 | { |
| 88 | 89 | name: "reminders_today", |
| 89 | description: "The reminder drafts that go out today and have not been sent.", | |
| 90 | description: "The reminder drafts that go out today and have not been sent, including ones held from an earlier day that come back today.", | |
| 90 | 91 | inputSchema: { type: "object", properties: {} }, |
| 91 | 92 | run: (db, who) => { |
| 92 | 93 | const deals = listDeals(db, who); |
| @@ -245,6 +246,18 @@ export const tools: readonly Tool[] = [ | ||
| 245 | 246 | run: (db, who, args) => |
| 246 | 247 | declineReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, reason: args.reason }), |
| 247 | 248 | }, |
| 249 | { | |
| 250 | name: "hold_reminder", | |
| 251 | description: | |
| 252 | "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. Held again, it waits one more day. A status update is not held.", | |
| 253 | inputSchema: { | |
| 254 | type: "object", | |
| 255 | properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } }, | |
| 256 | required: ["deadline_id", "party_id", "moment"], | |
| 257 | }, | |
| 258 | run: (db, who, args) => | |
| 259 | holdReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment }), | |
| 260 | }, | |
| 248 | 261 | { |
| 249 | 262 | name: "undo_decline_reminder", |
| 250 | 263 | description: "Take back a decline: the reminder is a draft again, to send or decline.", |
src/pages/deal.ts +11 −5
| @@ -9,7 +9,7 @@ import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, t | ||
| 9 | 9 | import { agent as defaults, standard } from "../env.ts"; |
| 10 | 10 | import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts"; |
| 11 | 11 | import { escape } from "../http.ts"; |
| 12 | import { sentLabel, statusDrafts, type Agent } from "../reminders.ts"; | |
| 12 | import { drafts, sentLabel, statusDrafts, type Agent } from "../reminders.ts"; | |
| 13 | 13 | import type { Who } from "../who.ts"; |
| 14 | 14 | import { amendForm, type AmendState } from "./amend.ts"; |
| 15 | 15 | import { partyContact } from "./contact.ts"; |
| @@ -62,8 +62,14 @@ function statusCard(deal: DealView, agent: Agent, on: string, may: boolean, to: | ||
| 62 | 62 | } |
| 63 | 63 | |
| 64 | 64 | /** The record of what went out: each sent reminder with the words approved, newest first. */ |
| 65 | function messages(deal: DealView, may: boolean): string { | |
| 66 | if (deal.sent.length === 0) return `<p class="muted">Nothing sent yet</p>`; | |
| 65 | function messages(deal: DealView, may: boolean, agent: Agent): string { | |
| 66 | const holding = drafts(deal, agent).flatMap((d) => (d.held === null ? [] : [{ d, held: d.held }])); | |
| 67 | const waiting = holding.length === 0 | |
| 68 | ? "" | |
| 69 | : `<ul class="drafts">${holding | |
| 70 | .map(({ d, held }) => `<li class="draft"><span><b>${escape(d.party_name)}</b> <span class="muted">· ${escape(d.label)}, ${escape(short(d.due))} · ${escape(sentLabel(d.moment))}</span></span><span class="state">Held until ${escape(spoken(held.until))} by ${escape(held.by_name || "someone")}</span></li>`) | |
| 71 | .join("")}</ul>`; | |
| 72 | if (deal.sent.length === 0) return `${waiting}<p class="muted">Nothing sent yet</p>`; | |
| 67 | 73 | const live = new Set(deal.deadlines.map((d) => d.id)); |
| 68 | 74 | const item = (m: Sent): string => { |
| 69 | 75 | const role = m.party_role === "" ? "" : ` · ${escape(PARTY_LABEL[m.party_role])}`; |
| @@ -74,7 +80,7 @@ function messages(deal: DealView, may: boolean): string { | ||
| 74 | 80 | : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.href, may)}`; |
| 75 | 81 | return `<li class="draft"><details><summary><span><b>${escape(m.party_name)}</b> <span class="muted">${role} · ${escape(m.label)}${removed}, ${escape(short(m.due))} · ${escape(sentLabel(m.moment))}</span><br>${escape(m.subject === "" ? "(no subject kept)" : m.subject)}</span><span class="state" data-sent>Sent ${escape(short(m.sent_at.slice(0, 10)))}</span></summary>${words}</details></li>`; |
| 76 | 82 | }; |
| 77 | return `<ul class="drafts">${deal.sent.map(item).join("")}</ul>`; | |
| 83 | return `${waiting}<ul class="drafts">${deal.sent.map(item).join("")}</ul>`; | |
| 78 | 84 | } |
| 79 | 85 | |
| 80 | 86 | export function dealPage(input: { |
| @@ -176,7 +182,7 @@ export function dealPage(input: { | ||
| 176 | 182 | ${statusCard(deal, agent ?? defaults, on, may, path)} |
| 177 | 183 | <section class="card" id="messages"> |
| 178 | 184 | <h2>Messages</h2> |
| 179 | ${messages(deal, may)} | |
| 185 | ${messages(deal, may, agent ?? defaults)} | |
| 180 | 186 | </section> |
| 181 | 187 | ${deal.deadlines.map((d) => sheet(deal, d, who, on, path, agent)).join("")} |
| 182 | 188 | </div> |
src/pages/review.ts +4 −3
| @@ -11,10 +11,10 @@ import { BODY_MAX, REASON_MAX, SUBJECT_MAX } from "../deals.ts"; | ||
| 11 | 11 | import { spoken } from "../dates.ts"; |
| 12 | 12 | import { PARTY_LABEL } from "../deadlines.ts"; |
| 13 | 13 | import { escape } from "../http.ts"; |
| 14 | import { momentLabel, type Draft } from "../reminders.ts"; | |
| 14 | import { heldFrom, momentLabel, type Draft } from "../reminders.ts"; | |
| 15 | 15 | import type { Who } from "../who.ts"; |
| 16 | 16 | import { layout } from "./layout.ts"; |
| 17 | import { hidden } from "./sheet.ts"; | |
| 17 | import { hidden, holdForm } from "./sheet.ts"; | |
| 18 | 18 | |
| 19 | 19 | export const REVIEW_PATH = "/reminders/today"; |
| 20 | 20 | |
| @@ -89,7 +89,7 @@ function form( | ||
| 89 | 89 | <p class="eyebrow">${s.position} of ${s.total}</p> |
| 90 | 90 | <h1>Review today's reminders</h1> |
| 91 | 91 | <p><a href="/deals/${draft.deal_id}">${escape(draft.address)}</a></p> |
| 92 | <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(momentLabel(draft.moment, draft.lead_days))}</span></p> | |
| 92 | <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(momentLabel(draft.moment, draft.lead_days))}${draft.held === null ? "" : ` · ${escape(heldFrom(draft.held))}`}</span></p> | |
| 93 | 93 | <p>To <b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])} · ${escape(draft.contact === "" ? "no contact on file" : draft.contact)}</span></p> |
| 94 | 94 | <form class="move" method="post" action="${REVIEW_PATH}/send">${hidden(keys)} |
| 95 | 95 | ${problem("subject")} |
| @@ -98,6 +98,7 @@ function form( | ||
| 98 | 98 | <label>Message<textarea class="input" name="body" rows="9" maxlength="${BODY_MAX}" required${invalid("body")}>${escape(typed.body)}</textarea></label> |
| 99 | 99 | <button class="button">Send</button> |
| 100 | 100 | </form> |
| 101 | ${holdForm(draft, "", `${REVIEW_PATH}/hold`, keys)} | |
| 101 | 102 | <form class="move" method="post" action="${REVIEW_PATH}/decline">${hidden(keys)} |
| 102 | 103 | ${problem("reason")} |
| 103 | 104 | <label>Why not<input class="input" name="reason" value="${escape(typed.reason)}" maxlength="${REASON_MAX}" required placeholder="e.g. Buyer already confirmed by phone"${invalid("reason")}></label> |
src/pages/sheet.ts +14 −2
| @@ -14,7 +14,7 @@ import { memoizer, print } from "../memo.ts"; | ||
| 14 | 14 | import { labelOf, NO_CONTACT, outbox } from "../outbox.ts"; |
| 15 | 15 | import { conflictLine } from "../order.ts"; |
| 16 | 16 | import { agent as defaults } from "../env.ts"; |
| 17 | import { draftsFor, momentLabel, MOMENTS, remindsLine, type Agent, type Draft } from "../reminders.ts"; | |
| 17 | import { draftsFor, heldFrom, momentLabel, MOMENTS, remindsLine, type Agent, type Draft } from "../reminders.ts"; | |
| 18 | 18 | import type { Who } from "../who.ts"; |
| 19 | 19 | import { owner } from "../week.ts"; |
| 20 | 20 | |
| @@ -110,6 +110,14 @@ const declineForm = (draft: Draft, to: string): string => | ||
| 110 | 110 | <button class="button button-quiet">Don't send</button> |
| 111 | 111 | </form>`; |
| 112 | 112 | |
| 113 | /** Beside *Send* and *Don't send*: hold it until tomorrow. A plain POST, no reason asked. */ | |
| 114 | export const holdForm = (draft: Draft, to: string, action = "/reminders/hold", keys?: Record<string, string | number>): string => | |
| 115 | draft.moment === "status" | |
| 116 | ? "" | |
| 117 | : `<form class="move" method="post" action="${action}">${hidden(keys ?? { deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })} | |
| 118 | <button class="button button-quiet">Tomorrow</button> | |
| 119 | </form>`; | |
| 120 | ||
| 113 | 121 | /** A declined reminder: the reason on record, and — for whoever may change the deal — the way back. */ |
| 114 | 122 | const undoForm = (draft: Draft, to: string): string => |
| 115 | 123 | `<form method="post" action="/reminders/undo">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })} |
| @@ -123,6 +131,10 @@ function draftLine(draft: Draft, on: string, withDeal: boolean): string { | ||
| 123 | 131 | ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>` |
| 124 | 132 | : draft.declined !== null |
| 125 | 133 | ? `<span class="state" data-declined>Not sent: ${escape(draft.declined.reason)} · ${escape(draft.declined.by_name || "someone")}</span>` |
| 134 | : draft.held !== null && draft.held.until > on | |
| 135 | ? `<span class="state">Held until ${escape(short(draft.held.until))}</span>` | |
| 136 | : draft.held !== null | |
| 137 | ? `<span class="state" data-late>${escape(heldFrom(draft.held))}</span>` | |
| 126 | 138 | : draft.moment === "status" |
| 127 | 139 | ? `<span class="state">Ready to send</span>` |
| 128 | 140 | : draft.on < on |
| @@ -144,7 +156,7 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string): s | ||
| 144 | 156 | : draft.declined !== null |
| 145 | 157 | ? `${draftText(draft)}${may ? undoForm(draft, to) : ""}` |
| 146 | 158 | : may |
| 147 | ? `${sendForm(draft, to)}${declineForm(draft, to)}` | |
| 159 | ? `${sendForm(draft, to)}${holdForm(draft, to)}${declineForm(draft, to)}` | |
| 148 | 160 | : draftText(draft); |
| 149 | 161 | return `<li class="draft"><details><summary>${draftLine(draft, on, false)}</summary>${inside}</details></li>`; |
| 150 | 162 | } |
src/reminders.ts +21 −5
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | * sent one, with the words approved; a sent draft reads back those words. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { addDays, relative, spoken, today } from "./dates.ts"; | |
| 11 | import { addDays, relative, spoken, today, weekday } from "./dates.ts"; | |
| 12 | 12 | import { memoizer, print } from "./memo.ts"; |
| 13 | 13 | import { DEFAULT_LEAD, isOpen, KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts"; |
| 14 | 14 | import type { DealView, DeadlineView, Move, Moment, Party } from "./deals.ts"; |
| @@ -47,6 +47,8 @@ export interface Draft { | ||
| 47 | 47 | readonly sent_at: string | null; |
| 48 | 48 | /** Why the agent chose not to send it, and who; null while it stands. */ |
| 49 | 49 | readonly declined: { readonly reason: string; readonly by_name: string } | null; |
| 50 | /** Held by the agent until a later morning, and who held it; null while it is not (and once sent or declined). */ | |
| 51 | readonly held: { readonly until: string; readonly from: string; readonly by_name: string } | null; | |
| 50 | 52 | } |
| 51 | 53 | |
| 52 | 54 | export const MOMENTS: readonly Moment[] = ["before", "day_of", "late", "moved"]; |
| @@ -198,6 +200,7 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent): | ||
| 198 | 200 | (amended || (s.deadline_id === deadline.id && s.due === deadline.due)); |
| 199 | 201 | const sent = deal.sent.find(mine); |
| 200 | 202 | const declined = deal.declined.find(mine); |
| 203 | const held = sent === undefined && declined === undefined ? deal.held.find(mine) : undefined; | |
| 201 | 204 | const drafted = words(deal, deadline, party, moment, agent, notice); |
| 202 | 205 | return [{ |
| 203 | 206 | deal_id: deal.id, |
| @@ -218,6 +221,7 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent): | ||
| 218 | 221 | body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body, |
| 219 | 222 | sent_at: sent?.sent_at ?? null, |
| 220 | 223 | declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name }, |
| 224 | held: held === undefined ? null : { until: held.until, from: held.held_on, by_name: held.by_name }, | |
| 221 | 225 | }]; |
| 222 | 226 | }), |
| 223 | 227 | ); |
| @@ -302,6 +306,7 @@ export function statusDrafts(deal: DealView, agent: Agent): Draft[] { | ||
| 302 | 306 | body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body, |
| 303 | 307 | sent_at: sent?.sent_at ?? null, |
| 304 | 308 | declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name }, |
| 309 | held: null, | |
| 305 | 310 | }; |
| 306 | 311 | }); |
| 307 | 312 | } |
| @@ -318,7 +323,7 @@ export const unsent = (d: Draft): boolean => d.sent_at === null && d.declined == | ||
| 318 | 323 | |
| 319 | 324 | /** What goes out on `day` and has not gone yet: `POST /tick`'s answer. */ |
| 320 | 325 | export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Draft[] => |
| 321 | deals.flatMap((deal) => drafts(deal, agent)).filter((d) => d.on === day && d.sent_at === null && d.declined === null); | |
| 326 | deals.flatMap((deal) => drafts(deal, agent)).filter((d) => unsent(d) && (d.held === null ? d.on === day : d.held.until === day)); | |
| 322 | 327 | |
| 323 | 328 | /** |
| 324 | 329 | * Waiting on `day`: goes out that morning, or was missed and still matters — |
| @@ -326,15 +331,26 @@ export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Dr | ||
| 326 | 331 | * long as the date stays open. |
| 327 | 332 | */ |
| 328 | 333 | export const pending = (d: Draft, day: string): boolean => |
| 329 | d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late")); | |
| 334 | d.held !== null | |
| 335 | ? d.held.until <= day && (d.on === day || d.due >= day || d.moment === "late") | |
| 336 | : d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late")); | |
| 330 | 337 | |
| 331 | 338 | /** |
| 332 | 339 | * The drafts waiting on `day` across these deals, in the order the clock lists |
| 333 | 340 | * them: deal by deal, date by date. The clock's "Reminders for today" and the |
| 334 | 341 | * review page both read it, so they never disagree. |
| 335 | 342 | */ |
| 336 | export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] => | |
| 337 | deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day))); | |
| 343 | export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] => { | |
| 344 | const these = deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day))); | |
| 345 | // A reminder held from an earlier day comes back at the top. | |
| 346 | return [...these.filter(returned), ...these.filter((d) => !returned(d))]; | |
| 347 | }; | |
| 348 | ||
| 349 | /** Held earlier and back: unsent, with its hold run out. */ | |
| 350 | const returned = (d: Draft): boolean => d.held !== null; | |
| 351 | ||
| 352 | /** "Held from Monday": what a reminder that came back says it was. */ | |
| 353 | export const heldFrom = (held: NonNullable<Draft["held"]>): string => `Held from ${weekday(held.from)}`; | |
| 338 | 354 | |
| 339 | 355 | const waitingIn = memoizer<number>(400); |
| 340 | 356 |
src/routes.ts +37
| @@ -67,6 +67,7 @@ import { | ||
| 67 | 67 | statusUpdates, |
| 68 | 68 | setReminderLead, |
| 69 | 69 | declineReminder, |
| 70 | holdReminder, | |
| 70 | 71 | undoDecline, |
| 71 | 72 | updateDeal, |
| 72 | 73 | type NewDeal, |
| @@ -505,6 +506,7 @@ async function reviewed(c: Context, act: (f: Record<string, string>) => Result<{ | ||
| 505 | 506 | } |
| 506 | 507 | |
| 507 | 508 | const SENT = "Reminder sent."; |
| 509 | const HELD = "Held until tomorrow."; | |
| 508 | 510 | |
| 509 | 511 | /** An unticked box is absent from a form: that says no, not "the agent's default". */ |
| 510 | 512 | const fromForm = (f: Record<string, unknown>): Record<string, unknown> => ({ |
| @@ -984,6 +986,15 @@ export const routes: readonly Route[] = [ | ||
| 984 | 986 | ); |
| 985 | 987 | }, |
| 986 | 988 | }, |
| 989 | { | |
| 990 | method: "POST", | |
| 991 | path: "/reminders/hold", | |
| 992 | handle: async (c) => { | |
| 993 | const f = await form(c); | |
| 994 | if (f instanceof Response) return f; | |
| 995 | return done(holdReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }), backTo(f.to), HELD); | |
| 996 | }, | |
| 997 | }, | |
| 987 | 998 | { |
| 988 | 999 | method: "GET", |
| 989 | 1000 | path: "/reminders/today", |
| @@ -1020,6 +1031,11 @@ export const routes: readonly Route[] = [ | ||
| 1020 | 1031 | handle: (c) => |
| 1021 | 1032 | reviewed(c, (f) => declineReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, reason: f.reason }), "Reminder declined; the reason is kept."), |
| 1022 | 1033 | }, |
| 1034 | { | |
| 1035 | method: "POST", | |
| 1036 | path: "/reminders/today/hold", | |
| 1037 | handle: (c) => reviewed(c, (f) => holdReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }), HELD), | |
| 1038 | }, | |
| 1023 | 1039 | { |
| 1024 | 1040 | method: "POST", |
| 1025 | 1041 | path: "/reminders/undo", |
| @@ -1224,6 +1240,27 @@ export const routes: readonly Route[] = [ | ||
| 1224 | 1240 | status: 201, |
| 1225 | 1241 | }, |
| 1226 | 1242 | }, |
| 1243 | { | |
| 1244 | method: "POST", | |
| 1245 | path: "/api/deals/:id/reminders/hold", | |
| 1246 | handle: async (c) => { | |
| 1247 | const body = await readJson(c.request); | |
| 1248 | if (body === undefined) return json({ error: "too_large" }, 413); | |
| 1249 | const f = fields(body); | |
| 1250 | return answer(holdReminder(c.db, c.who, { dealId: Number(c.params.id), deadlineId: Number(f.deadline_id), partyId: Number(f.party_id), moment: f.moment }), 201); | |
| 1251 | }, | |
| 1252 | api: { | |
| 1253 | summary: | |
| 1254 | "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.", | |
| 1255 | body: { | |
| 1256 | type: "object", | |
| 1257 | properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } }, | |
| 1258 | required: ["deadline_id", "party_id", "moment"], | |
| 1259 | }, | |
| 1260 | answer: { type: "object", properties: { id: { type: "integer" }, until: { type: "string" }, by_name: { type: "string" } }, required: ["id", "until"] }, | |
| 1261 | status: 201, | |
| 1262 | }, | |
| 1263 | }, | |
| 1227 | 1264 | { |
| 1228 | 1265 | method: "POST", |
| 1229 | 1266 | path: "/api/deals/:id/reminders/undo", |
src/server.test.ts +1
| @@ -186,6 +186,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 186 | 186 | "draft_status_update", |
| 187 | 187 | "send_status_update", |
| 188 | 188 | "decline_reminder", |
| 189 | "hold_reminder", | |
| 189 | 190 | "undo_decline_reminder", |
| 190 | 191 | "open_deal", |
| 191 | 192 | "add_date", |
src/terminal.test.ts +16
| @@ -269,6 +269,22 @@ test("n declines a reminder with a reason, u undoes it; anon is not asked to typ | ||
| 269 | 269 | expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before); |
| 270 | 270 | }); |
| 271 | 271 | |
| 272 | test("h holds a reminder until tomorrow: it leaves the list, is written, and anon cannot", () => { | |
| 273 | const t = terminal(db, alice, context); | |
| 274 | t.press("r"); | |
| 275 | const row = under(t); | |
| 276 | const holds = () => db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_hold").get()!.n; | |
| 277 | const before = holds(); | |
| 278 | t.press("h"); | |
| 279 | expect(lines(t).join("\n")).toContain("Held until"); | |
| 280 | expect(holds()).toBe(before + 1); | |
| 281 | expect(lines(t).join("\n")).not.toContain(row); | |
| 282 | const guest = terminal(db, { role: "anon" }, context); | |
| 283 | guest.press("r"); | |
| 284 | guest.press("h"); | |
| 285 | expect(holds()).toBe(before + 1); | |
| 286 | }); | |
| 287 | ||
| 272 | 288 | test("a closed deal's dates leave the date list and reminders, it is listed under Closed, and u reopens it", () => { |
| 273 | 289 | // The inspection ends in three days, so its "3 days before" reminder goes out today. |
| 274 | 290 | const other = createDeal(db, alice, { |
src/terminal.ts +16 −5
| @@ -50,6 +50,7 @@ import { | ||
| 50 | 50 | sendStatusUpdate, |
| 51 | 51 | statusUpdates, |
| 52 | 52 | declineReminder, |
| 53 | holdReminder, | |
| 53 | 54 | undoDecline, |
| 54 | 55 | REASON_MAX, |
| 55 | 56 | ROLL_REASON, |
| @@ -62,7 +63,7 @@ import { conflictLine } from "./order.ts"; | ||
| 62 | 63 | import { isOpen, PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts"; |
| 63 | 64 | import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts"; |
| 64 | 65 | import { permit } from "./contract.ts"; |
| 65 | import { drafts, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts"; | |
| 66 | import { drafts, heldFrom, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts"; | |
| 66 | 67 | import type { AuditRow } from "./audit.ts"; |
| 67 | 68 | import type { Result } from "./result.ts"; |
| 68 | 69 | import type { Who } from "./who.ts"; |
| @@ -149,11 +150,13 @@ export function terminal( | ||
| 149 | 150 | /** Today's reminders: what goes out today, and what should have and has not, for dates still ahead. */ |
| 150 | 151 | const reminderRows = (): { deal: DealView; draft: Draft }[] => { |
| 151 | 152 | const day = on(); |
| 152 | return deals().flatMap((deal) => | |
| 153 | const rows = deals().flatMap((deal) => | |
| 153 | 154 | drafts(deal, agentNow()) |
| 154 | 155 | .filter((r) => pending(r, day)) |
| 155 | 156 | .map((draft) => ({ deal, draft })), |
| 156 | 157 | ); |
| 158 | // A reminder held from an earlier day comes back at the top, as on the page. | |
| 159 | return [...rows.filter((r) => r.draft.held !== null), ...rows.filter((r) => r.draft.held === null)]; | |
| 157 | 160 | }; |
| 158 | 161 | const editKey = (d: Draft): string => `${d.deadline_id}:${d.party_id}:${d.moment}`; |
| 159 | 162 | /** The draft with any words typed for it; a sent one is as it went. */ |
| @@ -304,7 +307,7 @@ export function terminal( | ||
| 304 | 307 | } |
| 305 | 308 | |
| 306 | 309 | function onReminder(key: string): boolean { |
| 307 | if (key !== "\r" && key !== "s" && key !== "e" && key !== "n" && key !== "u") return false; | |
| 310 | if (key !== "\r" && key !== "s" && key !== "e" && key !== "n" && key !== "u" && key !== "h") return false; | |
| 308 | 311 | const row = reminderRows()[cursor]; |
| 309 | 312 | if (row === undefined) { |
| 310 | 313 | said = "No reminder here."; |
| @@ -345,6 +348,14 @@ export function terminal( | ||
| 345 | 348 | return report(declined, `Not sent to ${draft.party_name}: ${reason}`); |
| 346 | 349 | }, REASON_MAX); |
| 347 | 350 | } |
| 351 | if (key === "h") { | |
| 352 | if (drafted.sent_at !== null) said = "Already sent; it cannot be held."; | |
| 353 | else if (drafted.declined !== null) said = "Already declined; u undoes it."; | |
| 354 | else { | |
| 355 | const held = holdReminder(db, me, { deadlineId: draft.deadline_id, partyId: draft.party_id, moment: draft.moment }); | |
| 356 | said = report(held, () => `Held until ${held.ok ? spoken(held.value.until) : ""}: ${draft.party_name}'s reminder returns then.`); | |
| 357 | } | |
| 358 | } | |
| 348 | 359 | if (key === "u") { |
| 349 | 360 | if (drafted.declined === null) said = "Not declined, nothing to undo."; |
| 350 | 361 | else |
| @@ -730,7 +741,7 @@ export function terminal( | ||
| 730 | 741 | const rows = reminderRows(); |
| 731 | 742 | if (rows.length === 0) lines.push(dim("Nothing goes out today.")); |
| 732 | 743 | rows.forEach(({ draft }, i) => { |
| 733 | const state = draft.sent_at !== null ? dim("sent") : draft.declined !== null ? dim("not sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send"); | |
| 744 | const state = draft.sent_at !== null ? dim("sent") : draft.declined !== null ? dim("not sent") : draft.held !== null ? tint("overdue", heldFrom(draft.held).toLowerCase()) : draft.on < day ? tint("overdue", "late") : tint("soon", "to send"); | |
| 734 | 745 | const text = `${draft.party_name} (${PARTY_LABEL[draft.party_role].toLowerCase()}) · ${draft.label}, ${draft.address} · ${momentLabel(draft.moment, draft.lead_days).toLowerCase()}`; |
| 735 | 746 | lines.push(`${i === cursor ? "▸" : " "} ${state.padEnd(16)} ${i === cursor ? bold(text) : text}`); |
| 736 | 747 | if (reading === i) { |
| @@ -754,7 +765,7 @@ export function terminal( | ||
| 754 | 765 | : view === "people" |
| 755 | 766 | ? "P people · d dates · w this week · r reminders · q quit" |
| 756 | 767 | : view === "reminders" |
| 757 | ? "j/k move · enter read · e edit · s send · n don't send · u undo · / find · d dates · q quit" | |
| 768 | ? "j/k move · enter read · e edit · s send · n don't send · h tomorrow · u undo · / find · d dates · q quit" | |
| 758 | 769 | : view === "messages" |
| 759 | 770 | ? "j/k move · enter read · b back to the deal · d dates · q quit" |
| 760 | 771 | : view === "timeline" |
new above
offline
Nothing stops holding a reminder whose send day is still in the future. It then returns on
until, before it is due (see dueOn). Refuse that, or return it no earlier than d.on.