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

Right after approving from the desk, the desk's confirmation offers "Undo send" for the minute it lasts #101

Merged opened this

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

Merged

mason/speed-to-lead:mason/93-right-after-approving-from-the-desk-the → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/93-right-after-approving-from-the-desk-the was merged into main as 32f9d3f.

Review

Sign in to review this change.
4 files changed +125 −7
README.md +3 −2
@@ -417,8 +417,9 @@ the clock, not by a person, so it is not audited: Activity shows the text as
417417 `held` (and the cancel), but never the send itself.
418418
419419 **Undo send.** Pressed Send on the wrong lead? For 60 seconds after you
420 approve a message, its lead's page shows **Undo send** beside it. One tap
421 returns the message to a draft with the words it went with, and the lead is as
420 approve a message, its lead's page shows **Undo send** beside it, and so does
421 the Due follow-ups page after "Send the ticked ones", naming each lead sent to.
422 One tap returns the message to a draft with the words it went with, and the lead is as
422423 it was before: a first reply undone leaves the lead new with the clock running
423424 again (and out of your response record), and the follow-ups that send
424425 scheduled are taken back, so sending again makes them once. It works on a text
src/due-undo.test.ts added +83
@@ -0,0 +1,83 @@
1 /**

Add the expired-minute case and the not-permitted case (box 5); neither is covered.

2 * The due page after "Send the ticked ones": the leads just sent to carry
3 * "Undo send" while the minute lasts, only to who may update, and an undo
4 * from there lands back on the page.
5 */
6 import { expect, test } from "bun:test";
7 import { Database } from "bun:sqlite";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { agent } from "./env.ts";
12 import { duePage } from "./pages/due.ts";
13 import { serve } from "./server.ts";
14 import { sign } from "./who.ts";
15
16 const root = { role: "admin", id: "u0", name: "root" } as const;
17
18 test("the page names each lead sent to and offers Undo send, escaped", () => {
19 const page = duePage({ who: root, agent, due: [], undo: [{ lead_id: 7, name: "<b>Ann</b>" }] });
20 expect(page).toContain('action="/leads/7/undo?from=due"');
21 expect(page).toContain("Undo send");
22 expect(page).toContain("For a minute after sending.");
23 expect(page).toContain("&lt;b&gt;Ann&lt;/b&gt;");
24 expect(duePage({ who: root, agent, due: [] })).not.toContain("Undo send");
25 });
26
27 test("within the minute /due?sent= shows the button; after an undo, never; a stranger sees none", async () => {
28 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-dueundo-")), identityKey: "k", sample: false });
29 const url = `http://${server.hostname}:${server.port}`;
30 try {
31 const as = (id: string, role: string) => {
32 const identity = `${id}|${id}|${role}|${Date.now() + 60_000}`;
33 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k") };
34 };
35 const user = { ...as("u1", "user"), "content-type": "application/json", accept: "application/json" };
36 const made = await fetch(`${url}/leads`, { method: "POST", headers: user, body: JSON.stringify({ name: "Sam Lee", email: "[email protected]", source: "zillow", message: "Hello?" }) });
37 const id = ((await made.json()) as { id: number }).id;
38 expect((await fetch(`${url}/leads/${id}/reply`, { method: "POST", headers: user, body: "{}" })).status).toBe(200);
39 const browser = as("u1", "user");
40 const shown = await (await fetch(`${url}/due?sent=${id}`, { headers: browser })).text();
41 expect(shown).toContain("Undo send");
42 expect(shown).toContain("Sam Lee");
43 // Nothing offered for a lead nothing was sent to, or for junk in the query.
44 expect(await (await fetch(`${url}/due?sent=99999,abc,-1`, { headers: browser })).text()).not.toContain("Undo send");
45 // The undo lands back on the page, then the button is gone.
46 const undone = await fetch(`${url}/leads/${id}/undo?from=due`, { method: "POST", headers: browser, redirect: "manual" });
47 expect(undone.status).toBe(303);
48 expect(undone.headers.get("location")).toBe("/due");
49 expect(await (await fetch(`${url}/due?sent=${id}`, { headers: browser })).text()).not.toContain("Undo send");
50 // Anyone else lands on the lead as before.
51 const plain = await fetch(`${url}/leads/${id}/undo`, { method: "POST", headers: browser, redirect: "manual" });
52 expect(plain.headers.get("location")).toBe(`/leads/${id}`);
53 } finally {
54 server.stop(true);
55 }
56 });
57
58 test("after the minute the confirmation has no button, and a role that may not update sees none", async () => {
59 const dir = mkdtempSync(join(tmpdir(), "app-dueundo-late-"));
60 const server = serve({ port: 0, dataDir: dir, identityKey: "k", sample: false });
61 const url = `http://${server.hostname}:${server.port}`;
62 try {
63 const as = (id: string, role: string) => {
64 const identity = `${id}|${id}|${role}|${Date.now() + 60_000}`;
65 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k") };
66 };
67 const user = { ...as("u1", "user"), "content-type": "application/json", accept: "application/json" };
68 const made = await fetch(`${url}/leads`, { method: "POST", headers: user, body: JSON.stringify({ name: "Kim Ode", email: "[email protected]", source: "zillow", message: "Hello?" }) });
69 const id = ((await made.json()) as { id: number }).id;
70 await fetch(`${url}/leads/${id}/reply`, { method: "POST", headers: user, body: "{}" });
71 const browser = as("u1", "user");
72 expect(await (await fetch(`${url}/due?sent=${id}`, { headers: browser })).text()).toContain("Undo send");
73 // The same page, for someone the table does not let update a lead: no button.
74 expect(await (await fetch(`${url}/due?sent=${id}`, { headers: as("anon", "anon") })).text()).not.toContain("Undo send");
75 // Backdate the send past the minute: the confirmation reads as before.
76 const db = new Database(join(dir, "app.db"));
77 db.query("UPDATE undo_send SET taken_at = ?1 WHERE lead_id = ?2").run(new Date(Date.now() - 61_000).toISOString(), id);
78 db.close();
79 expect(await (await fetch(`${url}/due?sent=${id}`, { headers: browser })).text()).not.toContain("Undo send");
80 } finally {
81 server.stop(true);
82 }
83 });
src/pages/due.ts +16 −1
@@ -20,13 +20,28 @@ const item = (m: DueFollowUp): string => `<li class="card stack">
2020 <p class="sig">${escape(m.signature)}</p>
2121 </li>`;
2222
23 /** A lead just sent to from this page: its send can be taken back while the minute lasts. */
24 export interface TakeBack {
25 readonly lead_id: number;
26 readonly name: string;
27 }
28
29 const takeBack = (t: TakeBack): string => `<li class="row">
30 <span>Sent to <strong>${escape(t.name)}</strong>.</span>
31 <form method="post" action="/leads/${t.lead_id}/undo?from=due" data-undo><button class="button button-quiet">Undo send</button> <span class="hint">For a minute after sending.</span></form>
32 </li>`;
33
2334 export function duePage(input: {
2435 who: Who;
2536 agent: Agent;
2637 due: readonly DueFollowUp[];
2738 notice?: string | undefined;
39 /** Leads sent to a moment ago whose send can still be taken back; empty when none. */
40 undo?: readonly TakeBack[];
2841 }): string {
2942 const { who, agent, due, notice } = input;
43 const undo = input.undo ?? [];
44 const taken = undo.length === 0 ? "" : `<ul class="stack">${undo.map(takeBack).join("")}</ul>`;
3045 const body =
3146 due.length === 0
3247 ? `<p class="empty">No follow-up is due. <a href="/">Back to the desk</a></p>`
@@ -35,5 +50,5 @@ export function duePage(input: {
3550 <ul class="stack">${due.map(item).join("")}</ul>
3651 <button class="button">Send the ticked ones</button>
3752 </form>`;
38 return layout({ who, agent, path: "/due", heading: "Due follow-ups", notice, body: `<h1>Due follow-ups</h1>${body}` });
53 return layout({ who, agent, path: "/due", heading: "Due follow-ups", notice, body: `<h1>Due follow-ups</h1>${taken}${body}` });
3954 }
src/routes.ts +23 −4
@@ -85,7 +85,7 @@ import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
8585 import { MAX_EMAIL_TEXT } from "./intake.ts";
8686 import { MAX_SIGNIN_TEXT } from "./signins.ts";
8787 import { LOST_REASONS, lostSaid } from "./lost.ts";
outdated

Duplicate import source: fold findLead into the existing ./leads.ts import below.

88 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type LeadDetail, type NewLead } from "./leads.ts";
88 import { findLead, MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type LeadDetail, type NewLead } from "./leads.ts";
8989 import { dueSaid } from "./sentences.ts";
9090 import { undoable } from "./undo.ts";
9191 import { events } from "./live.ts";
@@ -930,7 +930,20 @@ export const routes: readonly Route[] = [
930930 STATUS[found.error],
931931 );
932932 const { notice, clear } = readNotice(c.request);
933 return html(duePage({ who: c.who, agent, due: found.value.due, notice }), 200, clear);
933 // Leads just sent to travel as ids in the query; each is asked of `undoable` and `permit` again, never trusted.
934 const sent = (c.url.searchParams.get("sent") ?? "")
935 .split(",")
936 .filter((id) => /^\d{1,9}$/.test(id))
937 .map(Number)
938 .slice(0, MAX_DUE_BATCH);
939 const undo =
940 permit(c.who, "lead", "update") === "yes"
941 ? sent.flatMap((id) => {
942 const lead = undoable(c.db, id, Date.now()) === null ? null : findLead(c.db, id);
943 return lead === null ? [] : [{ lead_id: id, name: lead.name }];
944 })
945 : [];
946 return html(duePage({ who: c.who, agent, due: found.value.due, notice, undo }), 200, clear);
934947 },
935948 },
936949 {
@@ -940,7 +953,10 @@ export const routes: readonly Route[] = [
940953 posted(
941954 c,
942955 (input) => sendDue(c.db, c.who, { ids: idsOf(input) }),
943 (value) => ({ to: "/due", said: value === undefined ? "Nothing was sent." : dueSaid(value) }),
956 (value) => ({
957 to: value === undefined || value.sent.length === 0 ? "/due" : `/due?sent=${value.sent.map((s) => s.lead_id).join(",")}`,
958 said: value === undefined ? "Nothing was sent." : dueSaid(value),
959 }),
944960 ),
945961 api: {
946962 summary: `Approve the follow-ups you name, in one call: \`ids\` is a list of message ids (whole numbers, at most ${MAX_DUE_BATCH}), each a follow-up that is due (not a first reply, not an answer to a lead who wrote back; 422 otherwise, and nothing is sent). Each goes the way send on its lead does: a text outside 8:00 a.m. to 9:00 p.m. is held for 8:00 (\`held\`), each can be taken back for a minute, the audit names who approved each. A follow-up that stopped being due meanwhile is skipped and named in \`skipped\`, never sent. An empty list sends nothing.`,
@@ -1482,7 +1498,10 @@ export const routes: readonly Route[] = [
14821498 posted(
14831499 c,
14841500 () => undoSend(c.db, c.who, { id: ID(c) }),
1485 () => ({ to: `/leads/${ID(c)}`, said: "Taken back. It is a draft again, and the lead is as it was before." }),
1501 () => ({
1502 to: c.url.searchParams.get("from") === "due" ? "/due" : `/leads/${ID(c)}`,
1503 said: "Taken back. It is a draft again, and the lead is as it was before.",
1504 }),
14861505 ),
14871506 api: {
14881507 summary:

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs