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

The agent can decline a reminder with a reason, so a message they chose not to send stops asking and the record says why #24

Merged opened this

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

Merged

mason/deal-clock:mason/21-the-agent-can-decline-a-reminder-with-a → main 1 commit fork

  • Merged. mason/21-the-agent-can-decline-a-reminder-with-a was merged into main as ec4452c.

Review

Sign in to review this change.
15 files changed +651 −18
README.md +4 −1
@@ -35,6 +35,9 @@ since they were last set, so the screen always looks like today.
3535 today's date and your edited words, not the original draft. Under the
3636 clock, the heading "Reminders for today" counts what is left ("14 to send"
3737 becomes "13 to send"; when nothing is left it reads "all sent").
38 Decided against a message? Beside Send, **Don't send** asks why (up to 200
39 characters). The reminder stops counting as "to send" and reads "Not sent:
40 <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again.
3841 5. **Move a date, with a reason.** Open the same marker again and use Move
3942 this date: pick a new date and say why ("Inspector delayed"). The marker
4043 jumps to the new date, and the sheet lists the move, the reason and who
@@ -74,7 +77,7 @@ since they were last set, so the screen always looks like today.
7477
7578 - **Real:** the dates and their math, mark done, moves with their reasons,
7679 who owes what, the reminder drafts and editing them, the record of what was
77 sent, the calendar file, and adding parties, dates and deals.
80 sent, the reasons for messages you chose not to send, the calendar file, and adding parties, dates and deals.
7881 - **Simulated:** sending. Send records that a reminder went out and keeps the
7982 words that were approved; no email or text message leaves the app.
8083 - **Not in this prototype (phase two):** real email or text messages,
contract/openapi.json +225
@@ -498,6 +498,179 @@
498498 }
499499 }
500500 },
501 "/api/deals/{id}/reminders/decline": {
502 "post": {
503 "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.",
504 "operationId": "postApiDealsIdRemindersDecline",
505 "parameters": [
506 {
507 "name": "id",
508 "in": "path",
509 "required": true,
510 "schema": {
511 "type": "integer"
512 }
513 }
514 ],
515 "requestBody": {
516 "required": true,
517 "content": {
518 "application/json": {
519 "schema": {
520 "type": "object",
521 "properties": {
522 "deadline_id": {
523 "type": "integer"
524 },
525 "party_id": {
526 "type": "integer"
527 },
528 "moment": {
529 "enum": [
530 "before",
531 "day_of"
532 ]
533 },
534 "reason": {
535 "type": "string",
536 "minLength": 1,
537 "maxLength": 200
538 }
539 },
540 "required": [
541 "deadline_id",
542 "party_id",
543 "moment",
544 "reason"
545 ]
546 }
547 }
548 }
549 },
550 "responses": {
551 "201": {
552 "description": "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.",
553 "content": {
554 "application/json": {
555 "schema": {
556 "type": "object",
557 "properties": {
558 "id": {
559 "type": "integer"
560 },
561 "reason": {
562 "type": "string"
563 },
564 "by_name": {
565 "type": "string"
566 }
567 },
568 "required": [
569 "id",
570 "reason"
571 ]
572 }
573 }
574 }
575 },
576 "default": {
577 "description": "{ error, message }: why not",
578 "content": {
579 "application/json": {
580 "schema": {
581 "$ref": "#/components/schemas/Error"
582 }
583 }
584 }
585 }
586 },
587 "x-contract": {
588 "resource": "deal",
589 "verb": "update",
590 "least": "user"
591 }
592 }
593 },
594 "/api/deals/{id}/reminders/undo": {
595 "post": {
596 "summary": "Take back a decline: the reminder is a draft again.",
597 "operationId": "postApiDealsIdRemindersUndo",
598 "parameters": [
599 {
600 "name": "id",
601 "in": "path",
602 "required": true,
603 "schema": {
604 "type": "integer"
605 }
606 }
607 ],
608 "requestBody": {
609 "required": true,
610 "content": {
611 "application/json": {
612 "schema": {
613 "type": "object",
614 "properties": {
615 "deadline_id": {
616 "type": "integer"
617 },
618 "party_id": {
619 "type": "integer"
620 },
621 "moment": {
622 "enum": [
623 "before",
624 "day_of"
625 ]
626 }
627 },
628 "required": [
629 "deadline_id",
630 "party_id",
631 "moment"
632 ]
633 }
634 }
635 }
636 },
637 "responses": {
638 "200": {
639 "description": "Take back a decline: the reminder is a draft again.",
640 "content": {
641 "application/json": {
642 "schema": {
643 "type": "object",
644 "properties": {
645 "id": {
646 "type": "integer"
647 }
648 },
649 "required": [
650 "id"
651 ]
652 }
653 }
654 }
655 },
656 "default": {
657 "description": "{ error, message }: why not",
658 "content": {
659 "application/json": {
660 "schema": {
661 "$ref": "#/components/schemas/Error"
662 }
663 }
664 }
665 }
666 },
667 "x-contract": {
668 "resource": "deal",
669 "verb": "update",
670 "least": "user"
671 }
672 }
673 },
501674 "/api/deals/{id}/deadlines/{deadline}": {
502675 "delete": {
503676 "summary": "Remove a custom date the contract dropped, and its unsent reminders. A standard contract date is refused (422): move it or mark it done.",
@@ -874,6 +1047,43 @@
8741047 }
8751048 }
8761049 },
1050 "declined": {
1051 "type": "array",
1052 "items": {
1053 "type": "object",
1054 "properties": {
1055 "id": {
1056 "type": "integer"
1057 },
1058 "deadline_id": {
1059 "type": "integer"
1060 },
1061 "party_id": {
1062 "type": "integer"
1063 },
1064 "moment": {
1065 "enum": [
1066 "before",
1067 "day_of"
1068 ]
1069 },
1070 "due": {
1071 "type": "string",
1072 "format": "date"
1073 },
1074 "reason": {
1075 "type": "string",
1076 "description": "Why the agent chose not to send it."
1077 },
1078 "by_name": {
1079 "type": "string"
1080 },
1081 "at": {
1082 "type": "string"
1083 }
1084 }
1085 }
1086 },
8771087 "sent": {
8781088 "type": "array",
8791089 "items": {
@@ -983,6 +1193,21 @@
9831193 "string",
9841194 "null"
9851195 ]
1196 },
1197 "declined": {
1198 "type": [
1199 "object",
1200 "null"
1201 ],
1202 "description": "Why the agent chose not to send it, and who; null while it stands.",
1203 "properties": {
1204 "reason": {
1205 "type": "string"
1206 },
1207 "by_name": {
1208 "type": "string"
1209 }
1210 }
9861211 }
9871212 },
9881213 "required": [
docs/TECHNICAL.md +8
@@ -24,6 +24,14 @@ Sending is simulated: *Send* records that a reminder went out and the
2424 words approved with it; nothing leaves the app. The record is shown on the
2525 page, in `/api/deals/:id`, in MCP and in the terminal.
2626
27 *Don't send* declines a reminder with a reason (1 to 200 characters), kept in
28 `reminder_declined` and shown as "Not sent: reason · who". A declined reminder
29 is not "to send" and is left out of `/tick` and `reminders_today`; it cannot be
30 sent until undone. Over the API: `POST /api/deals/:id/reminders/decline` and
31 `.../undo` (body `deadline_id`, `party_id`, `moment`, and `reason`); over MCP,
32 `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the
33 reason on the reminders list, and `u` to undo. Each is an update of the deal.
34
2735 `POST /tick` answers the reminders that go out today and are not yet
2836 marked sent, as JSON — call it each morning as a signed-in account (a
2937 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. The JSON API is
src/db.ts +18
@@ -125,6 +125,24 @@ export const migrations: string[] = [
125125 DROP TABLE reminder;
126126 ALTER TABLE reminder_kept RENAME TO reminder;
127127 CREATE INDEX reminder_deal ON reminder (deal_id)`,
128 // A reminder the agent chose not to send, with the reason: a record like a
129 // sent one (it names the date and party in words and outlives them), undone
130 // by deleting the row.
131 `CREATE TABLE IF NOT EXISTS reminder_declined (
132 id INTEGER PRIMARY KEY,
133 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
134 deadline_id INTEGER NOT NULL,
135 party_id INTEGER NOT NULL,
136 label TEXT NOT NULL,
137 party_name TEXT NOT NULL,
138 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of')),
139 due TEXT NOT NULL,
140 reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200),
141 by_name TEXT NOT NULL,
142 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
143 UNIQUE (deadline_id, party_id, moment, due)
144 );
145 CREATE INDEX IF NOT EXISTS reminder_declined_deal ON reminder_declined (deal_id)`,
128146 ];
129147
130148 export function openDb(dir = dataDir): Database {
src/deals.test.ts +48
@@ -12,6 +12,7 @@ import {
1212 addDeadline,
1313 addParty,
1414 createDeal,
15 declineReminder,
1516 deleteDeal,
1617 editParty,
1718 getDeal,
@@ -21,6 +22,7 @@ import {
2122 removeDeadline,
2223 removeParty,
2324 sendReminder,
25 undoDecline,
2426 type DealView,
2527 } from "./deals.ts";
2628 import { openDb } from "./db.ts";
@@ -354,3 +356,49 @@ test("correcting and removing are updates of the deal: audited, and refused to a
354356 expect(rows[0]).toMatchObject({ verb: "update", allowed: 1, outcome: "ok" });
355357 expect(rows.slice(1).map((r) => [r.verb, r.outcome])).toEqual([["update", "signin_required"], ["update", "signin_required"], ["update", "signin_required"]]);
356358 });
359
360 test("a declined reminder leaves the unsent count and /tick, keeps its reason, and undo brings it back", () => {
361 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
362 const inspection = due(deal, "inspection");
363 const tick = () => dueOn([fresh(deal.id)], today(), agent).filter((r) => r.deadline_id === inspection.id);
364 const buyer = tick().find((r) => r.moment === "before")!;
365 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
366 const before = tick().length;
367 const declined = declineReminder(db, alice, { ...ask, reason: " Buyer confirmed <b>by phone</b> " });
368 expect(declined.ok && declined.value.reason).toBe("Buyer confirmed <b>by phone</b>");
369 expect(tick().length).toBe(before - 1);
370 const draft = drafts(fresh(deal.id), agent).find((r) => r.party_id === buyer.party_id && r.moment === "before" && r.deadline_id === inspection.id)!;
371 expect(draft.declined).toEqual({ reason: "Buyer confirmed <b>by phone</b>", by_name: "alice" });
372 expect(draft.sent_at).toBeNull();
373 // Declined is not sent, and a declined reminder cannot be sent until undone.
374 const sent = sendReminder(db, alice, ask);
375 expect(sent.ok).toBe(false);
376 expect(fresh(deal.id).sent.length).toBe(0);
377 // Undo returns it to the draft list.
378 expect(undoDecline(db, alice, ask).ok).toBe(true);
379 expect(tick().length).toBe(before);
380 expect(fresh(deal.id).declined.length).toBe(0);
381 expect(undoDecline(db, alice, ask).ok).toBe(false);
382 });
383
384 test("a decline needs a reason of 1 to 200 characters, a real unsent reminder, and someone signed in", () => {
385 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30) });
386 const inspection = due(deal, "inspection");
387 const buyer = drafts(deal, agent).find((r) => r.deadline_id === inspection.id && r.moment === "before")!;
388 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
389 for (const reason of ["", " ", undefined, 7, "x".repeat(201)]) {
390 const refused = declineReminder(db, alice, { ...ask, reason });
391 expect(refused.ok).toBe(false);
392 if (!refused.ok) expect(refused.error).toBe("invalid");
393 }
394 expect(declineReminder(db, alice, { ...ask, moment: "later", reason: "x" }).ok).toBe(false);
395 expect(declineReminder(db, alice, { ...ask, partyId: open().parties[0]!.id, reason: "x" }).ok).toBe(false);
396 const guest = declineReminder(db, anon, { ...ask, reason: "No thanks" });
397 expect(guest.ok).toBe(false);
398 if (!guest.ok) expect(guest.error).toBe("signin_required");
399 expect(undoDecline(db, anon, ask).ok).toBe(false);
400 expect(fresh(deal.id).declined.length).toBe(0);
401 // A sent reminder is not declined afterwards.
402 sendReminder(db, alice, ask);
403 expect(declineReminder(db, alice, { ...ask, reason: "Too late" }).ok).toBe(false);
404 });
src/deals.ts +94 −1
@@ -21,7 +21,7 @@ import {
2121 } from "./deadlines.ts";
2222 import { agent as defaultAgent } from "./env.ts";
2323 import { emit } from "./live.ts";
24 import { draftsFor, type Agent } from "./reminders.ts";
24 import { draftsFor, type Agent, type Draft } from "./reminders.ts";
2525 import { audited, fail, ok, refuse, type Result } from "./result.ts";
2626 import type { Who } from "./who.ts";
2727
@@ -41,6 +41,20 @@ export interface Party {
4141 readonly name: string;
4242 readonly contact: string;
4343 }
44 export interface Declined {
45 readonly id: number;
46 readonly deal_id: number;
47 readonly deadline_id: number;
48 readonly party_id: number;
49 readonly label: string;
50 readonly party_name: string;
51 readonly moment: Moment;
52 readonly due: string;
53 /** Why the agent chose not to send it. */
54 readonly reason: string;
55 readonly by_name: string;
56 readonly at: string;
57 }
4458 export interface Move {
4559 readonly id: number;
4660 readonly deadline_id: number;
@@ -86,6 +100,7 @@ export interface DealView extends Deal {
86100 readonly parties: readonly Party[];
87101 readonly deadlines: readonly DeadlineView[];
88102 readonly sent: readonly Sent[];
103 readonly declined: readonly Declined[];
89104 }
90105
91106 export type Moment = "before" | "day_of";
@@ -114,6 +129,7 @@ export function message(value: unknown, min: number, max: number): string | unde
114129 }
115130
116131 export const SUBJECT_MAX = 150;
132 export const REASON_MAX = 200;
117133 export const BODY_MAX = 2000;
118134
119135 /** The name a row is written under: the person, as the forge signed them. */
@@ -163,6 +179,11 @@ function view(db: Database, deal: Deal): DealView {
163179 "SELECT * FROM reminder WHERE deal_id = ?1 ORDER BY id",
164180 )
165181 .all(deal.id),
182 declined: db
183 .query<Declined, [number]>(
184 "SELECT * FROM reminder_declined WHERE deal_id = ?1 ORDER BY id",
185 )
186 .all(deal.id),
166187 };
167188 }
168189
@@ -633,6 +654,8 @@ export function sendReminder(
633654 { ...deadline, moves: [] },
634655 input.agent ?? defaultAgent,
635656 ).find((r) => r.party_id === party.id && r.moment === input.moment);
657 if (draft?.declined != null)
658 return within(db, who, dealId, fail("invalid", "This reminder was declined; undo that first to send it."));
636659 const subject =
637660 input.subject === undefined ? draft?.subject : line(input.subject, 1, SUBJECT_MAX);
638661 if (subject === undefined)
@@ -648,3 +671,73 @@ export function sendReminder(
648671 .get(found.value.deal.id, deadline.id, party.id, deadline.label, party.name, input.moment, deadline.due, authorOf(who).name, subject, body)!;
649672 return within(db, who, dealId, ok(sent));
650673 }
674
675 /** The draft one decline or undo names, on a date `who` may change. */
676 function draftOf(
677 db: Database,
678 who: Who,
679 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent },
680 ): { dealId?: number; found: Result<{ draft: Draft; deal: Deal; deadline: Deadline; party: Party }> } {
681 const { dealId, found } = deadlineFor(db, who, input.deadlineId, input.dealId);
682 if (!found.ok) return { dealId, found };
683 if (!isMoment(input.moment))
684 return { dealId, found: fail("invalid", "A reminder is for three days before, or the day of.") };
685 const { deal, deadline } = found.value;
686 const party = Number.isInteger(input.partyId)
687 ? db.query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2").get(input.partyId, deal.id)
688 : null;
689 const draft =
690 party === null
691 ? undefined
692 : draftsFor(view(db, deal), { ...deadline, moves: [] }, input.agent ?? defaultAgent).find(
693 (r) => r.party_id === party.id && r.moment === input.moment,
694 );
695 if (party === null || draft === undefined)
696 return { dealId, found: fail("not_found", "No such reminder on this date.") };
697 return { dealId, found: ok({ draft, deal, deadline, party }) };
698 }
699
700 /**
701 * Choose not to send a reminder, and say why. The decision is kept as a
702 * record: the reminder stops asking to be sent, and `undoDecline` brings it back.
703 */
704 export function declineReminder(
705 db: Database,
706 who: Who,
707 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; reason: unknown; agent?: Agent },
708 ): Result<Declined> {
709 const { dealId, found } = draftOf(db, who, input);
710 if (!found.ok) return within(db, who, dealId, found);
711 const reason = line(input.reason, 1, REASON_MAX);
712 if (reason === undefined)
713 return within(db, who, dealId, fail("invalid", `Say why in 1 to ${REASON_MAX} characters.`));
714 const { draft, deal } = found.value;
715 if (draft.sent_at !== null)
716 return within(db, who, dealId, fail("invalid", "This reminder was already sent."));
717 const declined = db
718 .query<Declined, [number, number, number, string, string, string, string, string, string]>(
719 `INSERT INTO reminder_declined (deal_id, deadline_id, party_id, label, party_name, moment, due, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
720 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET reason = excluded.reason, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`,
721 )
722 .get(deal.id, draft.deadline_id, draft.party_id, draft.label, draft.party_name, draft.moment, draft.due, reason, authorOf(who).name)!;
723 return within(db, who, dealId, ok(declined));
724 }
725
726 /** Take back a decline: the reminder is a draft again. */
727 export function undoDecline(
728 db: Database,
729 who: Who,
730 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent },
731 ): Result<{ id: number }> {
732 const { dealId, found } = draftOf(db, who, input);
733 if (!found.ok) return within(db, who, dealId, found);
734 const { draft } = found.value;
735 const gone = db
736 .query<{ id: number }, [number, number, string, string]>(
737 "DELETE FROM reminder_declined WHERE deadline_id = ?1 AND party_id = ?2 AND moment = ?3 AND due = ?4 RETURNING id",
738 )
739 .get(draft.deadline_id, draft.party_id, draft.moment, draft.due);
740 if (gone === null)
741 return within(db, who, dealId, fail("invalid", "This reminder was not declined."));
742 return within(db, who, dealId, ok({ id: gone.id }));
743 }
src/mcp.ts +30
@@ -23,6 +23,8 @@ import {
2323 removeDeadline,
2424 removeParty,
2525 sendReminder,
26 declineReminder,
27 undoDecline,
2628 } from "./deals.ts";
2729 import { agent, title } from "./env.ts";
2830 import { dueOn } from "./reminders.ts";
@@ -104,6 +106,34 @@ export const tools: readonly Tool[] = [
104106 run: (db, who, args) =>
105107 sendReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, subject: args.subject, body: args.body }),
106108 },
109 {
110 name: "decline_reminder",
111 description:
112 "Choose not to send a reminder, and say why (1 to 200 characters; e.g. the buyer already confirmed by phone). It is kept as a record, stops counting as to send and leaves reminders_today. Undo it with undo_decline_reminder.",
113 inputSchema: {
114 type: "object",
115 properties: {
116 deadline_id: { type: "integer" },
117 party_id: { type: "integer" },
118 moment: { enum: ["before", "day_of"] },
119 reason: { type: "string", minLength: 1, maxLength: 200 },
120 },
121 required: ["deadline_id", "party_id", "moment", "reason"],
122 },
123 run: (db, who, args) =>
124 declineReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, reason: args.reason }),
125 },
126 {
127 name: "undo_decline_reminder",
128 description: "Take back a decline: the reminder is a draft again, to send or decline.",
129 inputSchema: {
130 type: "object",
131 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of"] } },
132 required: ["deadline_id", "party_id", "moment"],
133 },
134 run: (db, who, args) =>
135 undoDecline(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment }),
136 },
107137 {
108138 name: "open_deal",
109139 description: "Open a deal with its buyer and seller; the standard dates are scheduled from the contract and closing dates.",
src/pages/clock.ts +4 −4
@@ -10,7 +10,7 @@ import type { DealView } from "../deals.ts";
1010 import { KIND } from "../deadlines.ts";
1111 import { agent } from "../env.ts";
1212 import { escape } from "../http.ts";
13 import { drafts } from "../reminders.ts";
13 import { drafts, unsent } from "../reminders.ts";
1414 import type { Who } from "../who.ts";
1515 import { layout } from "./layout.ts";
1616 import { draftItem, sheet, sheetId, URGENCY_LABEL } from "./sheet.ts";
@@ -89,10 +89,10 @@ export function clock(input: {
8989 const { start, days } = span(deals, on);
9090 const today = deals.flatMap((deal) =>
9191 drafts(deal, agent)
92 .filter((r) => r.on === on || (r.on < on && r.sent_at === null && r.due >= on))
92 .filter((r) => r.on === on || (r.on < on && unsent(r) && r.due >= on))
9393 .map((r) => ({ r, may: canChange(who, deal) })),
9494 );
95 const unsent = today.filter(({ r }) => r.sent_at === null).length;
95 const toSend = today.filter(({ r }) => unsent(r)).length;
9696 const timeline =
9797 deals.length === 0
9898 ? `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`
@@ -120,7 +120,7 @@ export function clock(input: {
120120 </ul>
121121 </section>
122122 <section id="today" class="card" data-live="deal.changed">
123 <h2>Reminders for today <span class="muted">· ${unsent === 0 ? "all sent" : `${unsent} to send`}</span></h2>
123 <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2>
124124 ${
125125 today.length === 0
126126 ? `<p class="muted">Nothing goes out today.</p>`
src/pages/sheet.ts +24 −2
@@ -5,7 +5,7 @@
55 * script; the forms post and come back.
66 */
77
8 import { BODY_MAX, canChange, SUBJECT_MAX, type DealView, type DeadlineView } from "../deals.ts";
8 import { BODY_MAX, canChange, REASON_MAX, SUBJECT_MAX, type DealView, type DeadlineView } from "../deals.ts";
99 import { relative, short, spoken, urgency, type Urgency } from "../dates.ts";
1010 import { PARTY_LABEL } from "../deadlines.ts";
1111 import { agent } from "../env.ts";
@@ -63,6 +63,19 @@ const sendForm = (draft: Draft, to: string): string =>
6363 <button class="button">Send</button>
6464 </form>`;
6565
66 /** Beside *Send*: the agent's no, with the reason it is kept under. */
67 const declineForm = (draft: Draft, to: string): string =>
68 `<form class="move" method="post" action="/reminders/decline">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}
69 <label>Why not<input class="input" name="reason" maxlength="${REASON_MAX}" required placeholder="e.g. Buyer already confirmed by phone"></label>
70 <button class="button button-quiet">Don't send</button>
71 </form>`;
72
73 /** A declined reminder: the reason on record, and — for whoever may change the deal — the way back. */
74 const undoForm = (draft: Draft, to: string): string =>
75 `<form method="post" action="/reminders/undo">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}
76 <button class="button button-quiet">Undo: make it a draft again</button>
77 </form>`;
78
6679 /**
6780 * One reminder: who, when, and its words. Opened, an unsent draft is a form
6881 * the agent may edit before *Send*; a sent one shows the words that went out.
@@ -71,13 +84,22 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string, wi
7184 const state =
7285 draft.sent_at !== null
7386 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
87 : draft.declined !== null
88 ? `<span class="state" data-declined>Not sent: ${escape(draft.declined.reason)} · ${escape(draft.declined.by_name || "someone")}</span>`
7489 : draft.on < on
7590 ? `<span class="state" data-late>Was due ${escape(short(draft.on))}</span>`
7691 : draft.on === on
7792 ? `<span class="state" data-today>Goes out today</span>`
7893 : `<span class="state">Goes out ${escape(short(draft.on))}</span>`;
7994 const who = `<span><b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${withDeal ? ` · ${escape(draft.label)}, ${escape(draft.address)}` : ""}</span></span>${state}`;
80 const inside = may && draft.sent_at === null ? sendForm(draft, to) : draftText(draft);
95 const inside =
96 draft.sent_at !== null
97 ? draftText(draft)
98 : draft.declined !== null
99 ? `${draftText(draft)}${may ? undoForm(draft, to) : ""}`
100 : may
101 ? `${sendForm(draft, to)}${declineForm(draft, to)}`
102 : draftText(draft);
81103 return `<li class="draft"><details><summary>${who}</summary>${inside}</details></li>`;
82104 }
83105
src/reminders.ts +14 −1
@@ -32,6 +32,8 @@ export interface Draft {
3232 readonly body: string;
3333 /** When the agent marked it sent, for this date; null while unsent. */
3434 readonly sent_at: string | null;
35 /** Why the agent chose not to send it, and who; null while it stands. */
36 readonly declined: { readonly reason: string; readonly by_name: string } | null;
3537 }
3638
3739 export const MOMENTS: readonly Moment[] = ["before", "day_of"];
@@ -88,6 +90,13 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
8890 s.moment === moment &&
8991 s.due === deadline.due,
9092 );
93 const declined = deal.declined.find(
94 (s) =>
95 s.deadline_id === deadline.id &&
96 s.party_id === party.id &&
97 s.moment === moment &&
98 s.due === deadline.due,
99 );
91100 const drafted = words(deal, deadline, party, moment, agent);
92101 return {
93102 deal_id: deal.id,
@@ -105,11 +114,15 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
105114 subject: sent !== undefined && sent.subject !== "" ? sent.subject : drafted.subject,
106115 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
107116 sent_at: sent?.sent_at ?? null,
117 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
108118 };
109119 }),
110120 );
111121 }
112122
123 /** Still waiting to be sent: neither sent nor declined. */
124 export const unsent = (d: Draft): boolean => d.sent_at === null && d.declined === null;
125
113126 /** What goes out on `day` and has not gone yet: `POST /tick`'s answer. */
114127 export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Draft[] =>
115 deals.flatMap((deal) => drafts(deal, agent)).filter((d) => d.on === day && d.sent_at === null);
128 deals.flatMap((deal) => drafts(deal, agent)).filter((d) => d.on === day && d.sent_at === null && d.declined === null);
src/routes.ts +94
@@ -51,6 +51,8 @@ import {
5151 removeDeadline,
5252 removeParty,
5353 sendReminder,
54 declineReminder,
55 undoDecline,
5456 updateDeal,
5557 type NewDeal,
5658 } from "./deals.ts";
@@ -147,6 +149,22 @@ export const DEAL: Schema = {
147149 },
148150 },
149151 },
152 declined: {
153 type: "array",
154 items: {
155 type: "object",
156 properties: {
157 id: { type: "integer" },
158 deadline_id: { type: "integer" },
159 party_id: { type: "integer" },
160 moment: { enum: ["before", "day_of"] },
161 due: DATE,
162 reason: { type: "string", description: "Why the agent chose not to send it." },
163 by_name: { type: "string" },
164 at: { type: "string" },
165 },
166 },
167 },
150168 sent: {
151169 type: "array",
152170 items: {
@@ -201,6 +219,11 @@ export const DRAFT: Schema = {
201219 subject: { type: "string" },
202220 body: { type: "string" },
203221 sent_at: { type: ["string", "null"] },
222 declined: {
223 type: ["object", "null"],
224 description: "Why the agent chose not to send it, and who; null while it stands.",
225 properties: { reason: { type: "string" }, by_name: { type: "string" } },
226 },
204227 },
205228 required: ["deal_id", "deadline_id", "party_id", "moment", "on", "subject", "body"],
206229 };
@@ -459,6 +482,32 @@ export const routes: readonly Route[] = [
459482 );
460483 },
461484 },
485 {
486 method: "POST",
487 path: "/reminders/decline",
488 handle: async (c) => {
489 const f = await form(c);
490 if (f instanceof Response) return f;
491 return done(
492 declineReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, reason: f.reason }),
493 backTo(f.to),
494 "Reminder declined; the reason is kept.",
495 );
496 },
497 },
498 {
499 method: "POST",
500 path: "/reminders/undo",
501 handle: async (c) => {
502 const f = await form(c);
503 if (f instanceof Response) return f;
504 return done(
505 undoDecline(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }),
506 backTo(f.to),
507 "Reminder is a draft again.",
508 );
509 },
510 },
462511 {
463512 method: "POST",
464513 path: "/tick",
@@ -552,6 +601,51 @@ export const routes: readonly Route[] = [
552601 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
553602 },
554603 },
604 {
605 method: "POST",
606 path: "/api/deals/:id/reminders/decline",
607 handle: async (c) => {
608 const body = await readJson(c.request);
609 if (body === undefined) return json({ error: "too_large" }, 413);
610 const f = fields(body);
611 return answer(
612 declineReminder(c.db, c.who, { dealId: Number(c.params.id), deadlineId: Number(f.deadline_id), partyId: Number(f.party_id), moment: f.moment, reason: f.reason }),
613 201,
614 );
615 },
616 api: {
617 summary:
618 "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.",
619 body: {
620 type: "object",
621 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of"] }, reason: { type: "string", minLength: 1, maxLength: 200 } },
622 required: ["deadline_id", "party_id", "moment", "reason"],
623 },
624 answer: { type: "object", properties: { id: { type: "integer" }, reason: { type: "string" }, by_name: { type: "string" } }, required: ["id", "reason"] },
625 status: 201,
626 },
627 },
628 {
629 method: "POST",
630 path: "/api/deals/:id/reminders/undo",
631 handle: async (c) => {
632 const body = await readJson(c.request);
633 if (body === undefined) return json({ error: "too_large" }, 413);
634 const f = fields(body);
635 return answer(
636 undoDecline(c.db, c.who, { dealId: Number(c.params.id), deadlineId: Number(f.deadline_id), partyId: Number(f.party_id), moment: f.moment }),
637 );
638 },
639 api: {
640 summary: "Take back a decline: the reminder is a draft again.",
641 body: {
642 type: "object",
643 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of"] } },
644 required: ["deadline_id", "party_id", "moment"],
645 },
646 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
647 },
648 },
555649 {
556650 method: "DELETE",
557651 path: "/api/deals/:id/deadlines/:deadline",
src/security.ts +2 −2
@@ -96,9 +96,9 @@ export function doorOf(
9696 const verb = ROW_VERB[method];
9797 return verb === undefined ? undefined : { resource, verb };
9898 }
99 // `<api>/:id/<children>/:child`: a change inside the row is an update of it.
99 // `<api>/:id/<children>/:child` (or `/:action`, posted): a change inside the row is an update of it.
100100 if (rest !== undefined && /^[^/]+\/[^/]+\/[^/]+$/.test(rest))
101 return method === "PATCH" || method === "DELETE" ? { resource, verb: "update" } : undefined;
101 return method === "PATCH" || method === "DELETE" || method === "POST" ? { resource, verb: "update" } : undefined;
102102 }
103103 return undefined;
104104 }
src/server.test.ts +29
@@ -159,6 +159,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
159159 "mark_done",
160160 "move_date",
161161 "send_reminder",
162 "decline_reminder",
163 "undo_decline_reminder",
162164 "open_deal",
163165 "add_date",
164166 "add_party",
@@ -553,6 +555,33 @@ test("MCP send_reminder takes edited words, refuses bad ones, and answers with w
553555 expect(JSON.parse(read.result.content[0].text).sent.map((s: { subject: string }) => s.subject)).toContain("Edited via MCP");
554556 });
555557
558 test("the API and MCP decline a reminder with a reason, the page shows it escaped, and undo restores it", async () => {
559 const deals = (await (await api("/api/deals", {}, editor)).json()) as {
560 id: number;
561 deadlines: { id: number; owes: string; done_at: string | null }[];
562 parties: { id: number; role: string }[];
563 }[];
564 const deal = deals.find((d) => d.deadlines.some((x) => x.done_at === null))!;
565 const deadline = deal.deadlines.find((x) => x.done_at === null)!;
566 const party = deal.parties.find((p) => p.role === deadline.owes)!;
567 const ask = { deadline_id: deadline.id, party_id: party.id, moment: "before" };
568 const post = (path: string, body: unknown, who = editor) =>
569 api(`/api/deals/${deal.id}/reminders/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }, who);
570 expect((await post("decline", { ...ask, reason: "" })).status).toBe(422);
571 expect((await post("decline", { ...ask, reason: "x".repeat(201) })).status).toBe(422);
572 expect((await post("decline", { ...ask, reason: "No" }, {})).status).toBe(401);
573 expect((await post("decline", { ...ask, reason: "Lender asked <i>not</i> to be chased" })).status).toBe(201);
574 const page = await (await api(`/deals/${deal.id}`, {}, editor)).text();
575 expect(page).toContain("Not sent: Lender asked &lt;i&gt;not&lt;/i&gt; to be chased");
576 expect(page).not.toContain("<i>not</i>");
577 const call = await rpc(
578 { jsonrpc: "2.0", id: 11, method: "tools/call", params: { name: "undo_decline_reminder", arguments: ask } },
579 editor,
580 );
581 expect(call.result.isError).toBeUndefined();
582 expect((await post("undo", ask)).status).toBe(422);
583 });
584
556585 test("the page offers an unsent draft as an edit form, and shows a sent one as it was sent, escaped", async () => {
557586 const deals = (await (await api("/api/deals", {}, editor)).json()) as {
558587 id: number;
src/terminal.test.ts +25
@@ -239,3 +239,28 @@ test("e edits the party under the cursor; X removes a party or a custom date aft
239239 press(t, "X", "yes\r");
240240 expect(read().deadlines.some((d) => d.id === hoa.value.id)).toBe(false);
241241 });
242
243 test("n declines a reminder with a reason, u undoes it; anon is not asked to type", () => {
244 const t = terminal(db, alice, context);
245 t.press("r");
246 const row = under(t);
247 const before = db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n;
248 press(t, "n", "Buyer confirmed by phone", "\r");
249 expect(lines(t).join("\n")).toContain("Not sent to");
250 expect(db.query<{ reason: string }, []>("SELECT reason FROM reminder_declined ORDER BY id DESC").get()!.reason).toBe("Buyer confirmed by phone");
251 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before + 1);
252 expect(under(t)).not.toBe(row);
253 // An empty reason is refused with the action's words.
254 press(t, "j", "n", "\r");
255 expect(lines(t).join("\n")).toContain("Say why");
256 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before + 1);
257 t.press("k");
258 expect(under(t)).toContain("not sent");
259 t.press("u");
260 expect(lines(t).join("\n")).toContain("is a draft again");
261 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before);
262 const guest = terminal(db, { role: "anon" }, context);
263 guest.press("r");
264 press(guest, "n", "x", "\r");
265 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before);
266 });
src/terminal.ts +32 −7
@@ -34,11 +34,14 @@ import {
3434 removeDeadline,
3535 removeParty,
3636 sendReminder,
37 declineReminder,
38 undoDecline,
39 REASON_MAX,
3740 type DealView,
3841 type DeadlineView,
3942 } from "./deals.ts";
4043 import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
41 import { drafts, MOMENT_LABEL, type Agent, type Draft } from "./reminders.ts";
44 import { drafts, MOMENT_LABEL, unsent, type Agent, type Draft } from "./reminders.ts";
4245 import type { Result } from "./result.ts";
4346 import type { Who } from "./who.ts";
4447
@@ -112,13 +115,13 @@ export function terminal(
112115 const day = on();
113116 return deals().flatMap((deal) =>
114117 drafts(deal, context.agent)
115 .filter((r) => r.on === day || (r.on < day && r.sent_at === null && r.due >= day))
118 .filter((r) => r.on === day || (r.on < day && unsent(r) && r.due >= day))
116119 .map((draft) => ({ deal, draft })),
117120 );
118121 };
119122 const editKey = (d: Draft): string => `${d.deadline_id}:${d.party_id}:${d.moment}`;
120123 /** The draft with any words typed for it; a sent one is as it went. */
121 const edited = (d: Draft): Draft => (d.sent_at === null ? { ...d, ...edits.get(editKey(d)) } : d);
124 const edited = (d: Draft): Draft => (unsent(d) ? { ...d, ...edits.get(editKey(d)) } : d);
122125 // On a deal the cursor walks its dates, then its parties.
123126 const rowCount = (): number =>
124127 view === "reminders"
@@ -211,7 +214,7 @@ export function terminal(
211214 }
212215
213216 function onReminder(key: string): boolean {
214 if (key !== "\r" && key !== "s" && key !== "e") return false;
217 if (key !== "\r" && key !== "s" && key !== "e" && key !== "n" && key !== "u") return false;
215218 const row = reminderRows()[cursor];
216219 if (row === undefined) {
217220 said = "No reminder here.";
@@ -238,6 +241,28 @@ export function terminal(
238241 BODY_MAX,
239242 );
240243 }
244 if (key === "n") {
245 if (drafted.sent_at !== null) said = "Already sent; it cannot be declined.";
246 else if (drafted.declined !== null) said = "Already declined; u undoes it.";
247 else
248 ask(deal, ["Why not send it (a short reason)"], ([reason]) => {
249 const declined = declineReminder(db, me, {
250 deadlineId: draft.deadline_id,
251 partyId: draft.party_id,
252 moment: draft.moment,
253 reason,
254 });
255 return report(declined, `Not sent to ${draft.party_name}: ${reason}`);
256 }, REASON_MAX);
257 }
258 if (key === "u") {
259 if (drafted.declined === null) said = "Not declined, nothing to undo.";
260 else
261 said = report(
262 undoDecline(db, me, { deadlineId: draft.deadline_id, partyId: draft.party_id, moment: draft.moment }),
263 `${draft.party_name}'s reminder is a draft again.`,
264 );
265 }
241266 if (key === "s") {
242267 const sent = sendReminder(db, me, {
243268 deadlineId: draft.deadline_id,
@@ -313,7 +338,7 @@ export function terminal(
313338 view = "reminders";
314339 cursor = 0;
315340 reading = undefined;
316 } else if (key === "n" || key === "c") {
341 } else if ((key === "n" && view !== "reminders") || key === "c") {
317342 const may = mayOpen(me);
318343 if (!may.ok) said = may.message;
319344 else
@@ -380,7 +405,7 @@ export function terminal(
380405 const rows = reminderRows();
381406 if (rows.length === 0) lines.push(dim("Nothing goes out today."));
382407 rows.forEach(({ draft }, i) => {
383 const state = draft.sent_at !== null ? dim("sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
408 const state = draft.sent_at !== null ? dim("sent") : draft.declined !== null ? dim("not sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
384409 const text = `${draft.party_name} (${PARTY_LABEL[draft.party_role].toLowerCase()}) · ${draft.label}, ${draft.address} · ${MOMENT_LABEL[draft.moment].toLowerCase()}`;
385410 lines.push(`${i === cursor ? "▸" : " "} ${state.padEnd(16)} ${i === cursor ? bold(text) : text}`);
386411 if (reading === i) {
@@ -396,7 +421,7 @@ export function terminal(
396421 if (said !== "") lines.push(...said.split("\n"));
397422 const keys =
398423 view === "reminders"
399 ? "j/k move · enter read · e edit · s send · d dates · q quit"
424 ? "j/k move · enter read · e edit · s send · n don't send · u undo · d dates · q quit"
400425 : view === "deal"
401426 ? "j/k move · x done · u reopen · m move · a add date · p add party · e edit party · X remove date/party · D remove deal · b back · q quit"
402427 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs