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

The agent reviews today's reminders one after another from a single page, approving or declining each and landing on the next, so the morning round takes a minute #75

Merged opened this

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

Merged

mason/deal-clock:mason/73-the-agent-reviews-today-s-reminders-one → main 2 commits fork

  • Merged. mason/73-the-agent-reviews-today-s-reminders-one was merged into main as 3ba91ed.

Review

Sign in to review this change.
9 files changed +323 −5
README.md +3 −1
@@ -67,7 +67,9 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
6767 clock, the heading "Reminders for today" counts what is left ("14 to send"
6868 becomes "13 to send"; when nothing is left it reads "all sent"). Each row
6969 there opens the sheet of the date it is for, where the reminder is edited,
70 sent or declined.
70 sent or declined. Many to get through? **Review all**, beside that heading,
71 walks you through them one page at a time: Send or Don't send, and the next
72 one appears; Skip leaves one for later.
7173 Decided against a message? Beside Send, **Don't send** asks why (up to 200
7274 characters). The reminder stops counting as "to send" and reads "Not sent:
7375 <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again.
docs/TECHNICAL.md +2
@@ -59,6 +59,8 @@ no sheets (they were most of its size); `sheets.js` fetches a deal's the first t
5959 and without script the date is a link to `/deals/:id#sheet-N`; the deal page has its sheets inline,
6060 and `.sheet:target` shows the one the link names.
6161
62 `GET /reminders/today` is the review page: today's unsent reminders (`todaysDrafts`, `src/reminders.ts`, the same list the clock shows; `?q=` narrows it like Find) one at a time, rendered by `src/pages/review.ts`. Its forms post to `POST /reminders/today/send` and `/reminders/today/decline`, which call `sendReminder` and `declineReminder` (an update of the deal, audited as on a sheet) and redirect to the next draft; `at` counts the drafts skipped and `done` those settled in the round. A refused form answers 422 with the same draft and what was typed. No new contract cell.
63
6264 `GET /deals/:id/timeline` is a deal's printable client timeline: its dates in
6365 order, who owes each, and Done, Upcoming or Overdue in words, with no forms,
6466 contacts or script (`src/pages/timeline.ts`, rows from `src/timeline.ts`). It
src/pages/clock.ts +3 −2
@@ -10,7 +10,7 @@ import type { DealView } from "../deals.ts";
1010 import { KIND } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
1212 import { agent as defaults } from "../env.ts";
13 import { drafts, pending, unsent, type Agent } from "../reminders.ts";
13 import { todaysDrafts, unsent, type Agent } from "../reminders.ts";
1414 import type { Who } from "../who.ts";
1515 import { thisWeek } from "../week.ts";
1616 import { layout } from "./layout.ts";
@@ -126,7 +126,7 @@ const remembered = memoizer<{ count: number; toSend: number; html: string }>(400
126126 /** One deal's reminders that go out today, as list items: counted, and rendered once while the deal stands. */
127127 function reminderRows(deal: DealView, on: string, agent: Agent): { count: number; toSend: number; html: string } {
128128 return remembered(`${on}|${JSON.stringify(agent)}|${print(deal)}`, () => {
129 const these = drafts(deal, agent).filter((r) => pending(r, on));
129 const these = todaysDrafts([deal], on, agent);
130130 return {
131131 count: these.length,
132132 toSend: these.filter(unsent).length,
@@ -241,6 +241,7 @@ function render(input: {
241241 ${deals.length === 0 ? "" : weekCard(deals, on)}
242242 ${none ? "" : `<section id="today" class="card" data-live="deal.changed">
243243 <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2>
244 ${toSend === 0 ? "" : `<p><a class="button" href="/reminders/today${q === "" ? "" : `?q=${encodeURIComponent(q)}`}">Review all</a></p>`}
244245 ${
245246 todayCount === 0
246247 ? `<p class="muted">Nothing goes out today.</p>`
src/pages/review.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The morning round on one page: today's unsent reminders, one at a time, in
3 * the clock's order. Each is a Send form (words editable) and a Don't send
4 * form (with its reason); after either the next unsent draft is shown, and
5 * Skip moves on without changing anything. Nothing here decides: the forms
6 * post to the same actions the date's sheet uses.
7 */
8
9 import type { Agent } from "../reminders.ts";
10 import { BODY_MAX, REASON_MAX, SUBJECT_MAX } from "../deals.ts";
11 import { spoken } from "../dates.ts";
12 import { PARTY_LABEL } from "../deadlines.ts";
13 import { escape } from "../http.ts";
14 import { MOMENT_LABEL, type Draft } from "../reminders.ts";
15 import type { Who } from "../who.ts";
16 import { layout } from "./layout.ts";
17 import { hidden } from "./sheet.ts";
18
19 export const REVIEW_PATH = "/reminders/today";
20
21 /** The review page's address: the Find query, how many were skipped and how many settled in this round. */
22 export function reviewHref(q: string, at: number, done: number): string {
23 const params = new URLSearchParams();
24 if (q !== "") params.set("q", q);
25 if (at > 0) params.set("at", String(at));
26 if (done > 0) params.set("done", String(done));
27 const s = params.toString();
28 return s === "" ? REVIEW_PATH : `${REVIEW_PATH}?${s}`;
29 }
30
31 /** Which field of the form a refusal is about. */
32 export type ReviewField = "subject" | "body" | "reason";
33
34 export interface ReviewError {
35 readonly field: ReviewField;
36 readonly message: string;
37 }
38
39 /** What was typed, kept when the form was refused. */
40 export interface Typed {
41 readonly subject: string;
42 readonly body: string;
43 readonly reason: string;
44 }
45
46 const FIELD_LABEL: Readonly<Record<ReviewField, string>> = { subject: "Subject", body: "Message", reason: "Why not" };
47
48 export function reviewPage(input: {
49 who: Who;
50 agent?: Agent | undefined;
51 /** The drafts still to send, in the clock's order. */
52 queue: readonly Draft[];
53 q: string;
54 /** How many of the queue this round has skipped past. */
55 at: number;
56 /** How many this round has sent or declined. */
57 done: number;
58 notice?: string | undefined;
59 open?: string | null | undefined;
60 error?: ReviewError | undefined;
61 typed?: Typed | undefined;
62 }): string {
63 const { who, agent, queue, q, done, error, typed } = input;
64 const at = queue.length === 0 ? 0 : input.at % queue.length;
65 const draft = queue[at];
66 const back = `<a href="/${q === "" ? "" : `?q=${encodeURIComponent(q)}`}">Back to the clock</a>`;
67 const body =
68 draft === undefined
69 ? `<section class="card narrow"><h1>Review today's reminders</h1><p>All of today's reminders are sent or declined.</p><p>${back}</p></section>`
70 : form(draft, { q, at, done, position: done + at + 1, total: done + queue.length, error, typed }, back);
71 return layout({ body, who, agent, path: REVIEW_PATH, heading: "Review today's reminders", notice: input.notice, open: input.open, live: false });
72 }
73
74 function form(
75 draft: Draft,
76 s: { q: string; at: number; done: number; position: number; total: number; error: ReviewError | undefined; typed: Typed | undefined },
77 back: string,
78 ): string {
79 const { error } = s;
80 const typed = s.typed ?? { subject: draft.subject, body: draft.body, reason: "" };
81 const keys = { deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, at: s.at, done: s.done, q: s.q };
82 const problem = (field: ReviewField): string =>
83 error?.field === field ? `<p class="conflict" role="alert"><b>${FIELD_LABEL[field]}:</b> ${escape(error.message)}</p>` : "";
84 const invalid = (field: ReviewField): string => (error?.field === field ? ' aria-invalid="true"' : "");
85 const skip = s.total - s.done > 1 ? reviewHref(s.q, s.at + 1, s.done) : "";
86 return `<section class="card narrow">
87 <p class="eyebrow">${s.position} of ${s.total}</p>
88 <h1>Review today's reminders</h1>
89 <p><a href="/deals/${draft.deal_id}">${escape(draft.address)}</a></p>
90 <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(MOMENT_LABEL[draft.moment])}</span></p>
91 <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>
92 <form class="move" method="post" action="${REVIEW_PATH}/send">${hidden(keys)}
93 ${problem("subject")}
94 <label>Subject<input class="input" name="subject" value="${escape(typed.subject)}" maxlength="${SUBJECT_MAX}" required${invalid("subject")}></label>
95 ${problem("body")}
96 <label>Message<textarea class="input" name="body" rows="9" maxlength="${BODY_MAX}" required${invalid("body")}>${escape(typed.body)}</textarea></label>
97 <button class="button">Send</button>
98 </form>
99 <form class="move" method="post" action="${REVIEW_PATH}/decline">${hidden(keys)}
100 ${problem("reason")}
101 <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>
102 <button class="button button-quiet">Don't send</button>
103 </form>
104 <p>${skip === "" ? "" : `<a class="button button-quiet" href="${escape(skip)}">Skip</a> `}${back}</p>
105 </section>`;
106 }
src/pages/sheet.ts +1 −1
@@ -62,7 +62,7 @@ export const conflictLines = (deal: DealView, d?: DeadlineView): string =>
6262 .map((c) => `<p class="conflict" role="note"><b>Out of order:</b> ${escape(conflictLine(c))}</p>`)
6363 .join("");
6464
65 const hidden = (fields: Record<string, string | number>): string =>
65 export const hidden = (fields: Record<string, string | number>): string =>
6666 Object.entries(fields)
6767 .map(([k, v]) => `<input type="hidden" name="${k}" value="${escape(String(v))}">`)
6868 .join("");
src/reminders.ts +8
@@ -220,3 +220,11 @@ export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Dr
220220 */
221221 export const pending = (d: Draft, day: string): boolean =>
222222 d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late"));
223
224 /**
225 * The drafts waiting on `day` across these deals, in the order the clock lists
226 * them: deal by deal, date by date. The clock's "Reminders for today" and the
227 * review page both read it, so they never disagree.
228 */
229 export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] =>
230 deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day)));
src/review.test.ts added +119
@@ -0,0 +1,119 @@
1 /** The review page walks today's reminders one at a time, through the sheet's own actions. */
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 { forgetRationing } from "./security.ts";
7 import { serve } from "./server.ts";
8 import { sign } from "./who.ts";
9
10 const KEY = "a-key-only-the-forge-holds";
11 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-review-")), identityKey: KEY });
12 const base = `http://${server.hostname}:${server.port}`;
13 afterAll(() => server.stop(true));
14 beforeEach(forgetRationing);
15
16 const identity = `u1|alice|user|${Date.now() + 600_000}`;
17 const alice = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
18 const get = async (path: string): Promise<string> => (await fetch(base + path, { headers: alice })).text();
19
20 /** The clock's list: who each row is for, in order. */
21 const clockRows = async (): Promise<string[]> => {
22 const page = await get("/");
23 const today = page.slice(page.indexOf('id="today"'));
24 return [...today.matchAll(/<li class="draft"><a class="draft-open" href="\/deals\/(\d+)#sheet-(\d+)"[^>]*><span><b>([^<]*)<\/b>/g)].map((m) => `${m[2]}:${m[3]}`);
25 };
26
27 /** The draft a review page shows: its date's id, the party, and the hidden fields to post back. */
28 const shown = (page: string) => {
29 const hidden = (name: string) => new RegExp(`name="${name}" value="([^"]*)"`).exec(page)?.[1];
30 return { deadline: hidden("deadline")!, party: hidden("party")!, moment: hidden("moment")!, at: hidden("at") ?? "0", done: hidden("done") ?? "0", counter: /(\d+) of (\d+)/.exec(page)?.slice(1, 3).join("/") };
31 };
32 const unescaped = (s: string) => s.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
33
34 const post = (path: string, fields: Record<string, string>, headers: Record<string, string> = alice) => {
35 const body = new URLSearchParams(fields);
36 return fetch(base + path, { method: "POST", body, headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" });
37 };
38 const keys = (s: ReturnType<typeof shown>) => ({ deadline: s.deadline, party: s.party, moment: s.moment, at: s.at, done: s.done, q: "" });
39
40 test("the clock offers Review all, and the page's first draft is the clock's first row", async () => {
41 expect(await get("/")).toContain('href="/reminders/today">Review all</a>');
42 const rows = await clockRows();
43 const first = shown(await get("/reminders/today"));
44 expect(first.deadline).toBe(rows[0]!.split(":")[0]!);
45 expect(first.counter).toBe(`1/${rows.length}`);
46 });
47
48 test("walking the queue visits the unsent drafts in the clock's order; Skip changes nothing", async () => {
49 const before = await get("/");
50 const page = await get("/reminders/today");
51 const skipHref = /href="([^"]*)">Skip</.exec(page)![1]!;
52 const second = shown(await get(unescaped(skipHref)));
53 expect(second.counter).toMatch(/^2\//);
54 expect(second.party === shown(page).party && second.deadline === shown(page).deadline).toBe(false);
55 expect(await get("/")).toBe(before);
56 });
57
58 test("Send on draft 1 records the edited words and shows draft 2 with the Open link", async () => {
59 const one = shown(await get("/reminders/today"));
60 const rows = await clockRows();
61 const res = await post("/reminders/today/send", { ...keys(one), subject: "Edited subject", body: "Edited words for you." });
62 expect(res.status).toBe(303);
63 const next = res.headers.get("location")!;
64 expect(next).toContain("done=1");
65 const cookie = res.headers.get("set-cookie")!.split(";")[0]!;
66 const page = await (await fetch(base + next, { headers: { ...alice, cookie } })).text();
67 expect(page).toContain("Reminder sent.");
68 expect(page).toMatch(/Open in (Mail|Messages)|No email or phone on file/);
69 const two = shown(page);
70 expect(two.counter).toBe(`2/${rows.length}`);
71 expect(`${two.deadline}:${two.party}:${two.moment}`).not.toBe(`${one.deadline}:${one.party}:${one.moment}`);
72 // The sheet-side record carries the edited words.
73 const deals = (await (await fetch(base + "/api/deals", { headers: alice })).json()) as { sent: { subject: string; body: string }[] }[];
74 expect(deals.flatMap((d) => d.sent).some((m) => m.subject === "Edited subject" && m.body === "Edited words for you.")).toBe(true);
75 expect((await clockRows()).length).toBeLessThan(rows.length);
76 });
77
78 test("Don't send records the reason and moves on", async () => {
79 const one = shown(await get("/reminders/today"));
80 const res = await post("/reminders/today/decline", { ...keys(one), reason: "Buyer confirmed by phone" });
81 expect(res.status).toBe(303);
82 const deals = (await (await fetch(base + "/api/deals", { headers: alice })).json()) as { declined?: { reason: string }[] }[];
83 expect(JSON.stringify(deals)).toContain("Buyer confirmed by phone");
84 expect(shown(await get(res.headers.get("location")!)).party === one.party && shown(await get(res.headers.get("location")!)).deadline === one.deadline).toBe(false);
85 });
86
87 test("a refused form shows the same draft again, what was typed, and the field named", async () => {
88 const one = shown(await get("/reminders/today"));
89 const long = "x".repeat(2001);
90 const res = await post("/reminders/today/send", { ...keys(one), subject: "Kept subject", body: long });
91 expect(res.status).toBe(422);
92 const page = await res.text();
93 expect(page).toContain("<b>Message:</b>");
94 expect(page).toContain("Kept subject");
95 expect(page).toContain(long);
96 expect(shown(page).deadline).toBe(one.deadline);
97 const empty = await post("/reminders/today/decline", { ...keys(one), reason: "" });
98 expect(empty.status).toBe(422);
99 expect(await empty.text()).toContain("<b>Why not:</b>");
100 });
101
102 test("a query narrows the queue as it narrows the clock", async () => {
103 const page = await get("/reminders/today?q=zzzz-no-such-deal");
104 expect(page).toContain("All of today's reminders are sent or declined");
105 expect(page).toContain('href="/?q=zzzz-no-such-deal"');
106 });
107
108 test("anon is asked to sign in, and a cross-origin or anon POST is refused", async () => {
109 const page = await fetch(base + "/reminders/today");
110 expect(page.status).toBe(401);
111 expect(await page.text()).toContain("/__forge/signin");
112 const one = shown(await get("/reminders/today"));
113 const body = new URLSearchParams({ ...keys(one), subject: "s", body: "b" });
114 const cross = await fetch(base + "/reminders/today/send", { method: "POST", body, headers: { ...alice, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" });
115 expect(cross.status).toBe(403);
116 const anon = await post("/reminders/today/send", { ...keys(one), subject: "s", body: "b" }, {});
117 expect([401, 403]).toContain(anon.status);
118 expect(shown(await get("/reminders/today")).deadline).toBe(one.deadline);
119 });
src/routes.ts +80 −1
@@ -76,10 +76,11 @@ import { dealPage, newDealPage } from "./pages/deal.ts";
7676 import { missingPage } from "./pages/missing.ts";
7777 import { refusedPage } from "./pages/refused.ts";
7878 import { people } from "./people.ts";
79 import { reviewHref, reviewPage, type ReviewField } from "./pages/review.ts";
7980 import { peoplePage } from "./pages/people.ts";
8081 import { timelinePage } from "./pages/timeline.ts";
8182 import { welcomePage } from "./pages/welcome.ts";
82 import { dueOn } from "./reminders.ts";
83 import { dueOn, todaysDrafts, unsent, type Draft } from "./reminders.ts";
8384 import { token, tokensCss } from "./tokens.ts";
8485 import type { Who } from "./who.ts";
8586
@@ -380,6 +381,48 @@ const unconfirmed = (c: Context, path: string): Response =>
380381 STATUS.invalid,
381382 );
382383
384 /** The drafts still to send today, in the clock's order, narrowed by the Find query; or the refusal. */
385 function reviewQueue(c: Context, q: string): Result<Draft[]> {
386 const deals = listDeals(c.db, c.who);
387 if (!deals.ok) return deals;
388 return { ok: true, value: todaysDrafts(find(deals.value, q), today(), agentOf(c.db)).filter(unsent) };
389 }
390
391 /** A small count from the query or a form, or 0. */
392 const count = (value: unknown): number => (typeof value === "string" && /^\d{1,4}$/.test(value) ? Number(value) : 0);
393
394 /** Which field of the review form a refusal names. */
395 const fieldOf = (message: string): ReviewField => (/^The subject/.test(message) ? "subject" : /^Say why/.test(message) ? "reason" : "body");
396
397 /**
398 * A review form posted: `act` sends or declines through the same actions the
399 * sheet uses. Done, the page shows the next unsent draft; refused for what was
400 * typed, it shows the same draft again with the words kept.
401 */
402 async function reviewed(c: Context, act: (f: Record<string, string>) => Result<{ id: number }>, said: string): Promise<Response> {
403 const f = await form(c);
404 if (f instanceof Response) return f;
405 const q = query(f.q ?? "") ?? "";
406 const at = count(f.at);
407 const settled = count(f.done);
408 const result = act(f);
409 if (result.ok) return back(said, reviewHref(q, at, settled + 1), said === SENT ? result.value.id : undefined);
410 if (result.error === "signin_required" || result.error === "forbidden")
411 return html(refusedPage({ who: c.who, agent: agentOf(c.db), path: reviewHref(q, at, settled), heading: "Review today's reminders", error: result.error, message: result.message }), STATUS[result.error]);
412 const queue = reviewQueue(c, q);
413 const same = queue.ok
414 ? queue.value.findIndex((d) => d.deadline_id === Number(f.deadline) && d.party_id === Number(f.party) && d.moment === f.moment)
415 : -1;
416 if (result.error !== "invalid" || !queue.ok || same === -1) return back(result.message, reviewHref(q, at, settled));
417 const typed = { subject: f.subject ?? "", body: f.body ?? "", reason: f.reason ?? "" };
418 return html(
419 reviewPage({ who: c.who, agent: agentOf(c.db), queue: queue.value, q, at: same, done: settled, error: { field: fieldOf(result.message), message: result.message }, typed }),
420 STATUS.invalid,
421 );
422 }
423
424 const SENT = "Reminder sent.";
425
383426 /** An unticked box is absent from a form: that says no, not "the agent's default". */
384427 const fromForm = (f: Record<string, unknown>): Record<string, unknown> => ({
385428 ...f,
@@ -800,6 +843,42 @@ export const routes: readonly Route[] = [
800843 );
801844 },
802845 },
846 {
847 method: "GET",
848 path: "/reminders/today",
849 handle: (c) => {
850 const { notice, open, clear } = readNotice(c.request);
851 const q = query(c.url.searchParams.get("q"));
852 if (q === undefined)
853 return html(refusedPage({ who: c.who, agent: agentOf(c.db), path: "/reminders/today", heading: "Review today's reminders", error: "invalid", message: FIND_REFUSAL }), 400, clear);
854 const queue = reviewQueue(c, q);
855 if (!queue.ok)
856 return html(
857 refusedPage({ who: c.who, agent: agentOf(c.db), path: "/reminders/today", heading: "Review today's reminders", error: queue.error, message: queue.message }),
858 STATUS[queue.error],
859 clear,
860 );
861 const sent = open === undefined ? undefined : listDeals(c.db, c.who);
862 const link = open === undefined || !sent?.ok ? undefined : sent.value.flatMap((d) => d.sent).find((m) => m.id === open)?.href ?? null;
863 return html(
864 reviewPage({ who: c.who, agent: agentOf(c.db), queue: queue.value, q, at: count(c.url.searchParams.get("at")), done: count(c.url.searchParams.get("done")), notice, open: link }),
865 200,
866 clear,
867 );
868 },
869 },
870 {
871 method: "POST",
872 path: "/reminders/today/send",
873 handle: (c) =>
874 reviewed(c, (f) => sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, subject: f.subject, body: f.body }), SENT),
875 },
876 {
877 method: "POST",
878 path: "/reminders/today/decline",
879 handle: (c) =>
880 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."),
881 },
803882 {
804883 method: "POST",
805884 path: "/reminders/undo",
src/speed.test.ts +1
@@ -110,6 +110,7 @@ const routes: [string, () => string][] = [
110110 ["the deal list", () => "/api/deals"],
111111 ["a deal page", () => `/deals/${firstId}`],
112112 ["the client timeline", () => `/deals/${firstId}/timeline`],
113 ["the reminder review", () => "/reminders/today"],
113114 ];
114115
115116 test.each(routes)("%s answers in under 50 ms with 200 deals", async (_name, path) => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs