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

When a lead replies STOP, one tap stops all texts to them and every unsent draft becomes an email #30

Merged opened this

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

Merged

mason/speed-to-lead:mason/28-when-a-lead-replies-stop-one-tap-stops-a → main 3 commits fork 3 threads · 3 unresolved

  • Merged. mason/28-when-a-lead-replies-stop-one-tap-stops-a was merged into main as 801c08a.

Review

Sign in to review this change.
15 files changed +348 −9
README.md +9
@@ -112,6 +112,15 @@ relocating, a first purchase, price. Then:
112112 written consent to be texted, **Email only** if they didn't. The app never
113113 drafts a text to someone without that consent — it writes an email instead.
114114
115 **When someone replies STOP**, open their lead and use **They asked to stop
116 texts** (tick the confirm box first), press `t` on their screen in the
117 terminal, `POST /leads/{id}/opt-out`, or the `opt_out_texts` MCP tool. Their
118 badge reads **Email only (opted out)** with the date, every draft not yet
119 sent — the first reply and the remaining follow-ups, edited or not — is
120 written again as an email, and sent messages stay in the history as they
121 were. It is one-way: the app has no button to turn texting back on (new
122 written consent comes with a new inquiry), and asking twice changes nothing.
123
115124 **Your signature** goes on every message, and can't be edited off: your
116125 name, brokerage and license number, as state advertising rules require.
117126 Texts also say "Reply STOP to opt out."
contract/openapi.json +65
@@ -379,6 +379,14 @@
379379 "type": "boolean",
380380 "description": "Prior written consent to be texted. Without it, only email."
381381 },
382 "opted_out_at": {
383 "type": [
384 "string",
385 "null"
386 ],
387 "format": "date-time",
388 "description": "When they asked to stop texts; consent is false from then on."
389 },
382390 "state": {
383391 "enum": [
384392 "new",
@@ -436,6 +444,7 @@
436444 "source",
437445 "message",
438446 "consent",
447 "opted_out_at",
439448 "state",
440449 "created_at",
441450 "replied_at",
@@ -520,6 +529,44 @@
520529 }
521530 }
522531 },
532 "/leads/{id}/opt-out": {
533 "post": {
534 "summary": "They replied STOP: no more texts to this lead, for good. Every unsent draft becomes an email; sent messages stay as they were. No body needed; asking twice changes nothing.",
535 "operationId": "postLeadsIdOptOut",
536 "parameters": [
537 {
538 "name": "id",
539 "in": "path",
540 "required": true,
541 "schema": {
542 "type": "integer"
543 }
544 }
545 ],
546 "responses": {
547 "200": {
548 "description": "They replied STOP: no more texts to this lead, for good. Every unsent draft becomes an email; sent messages stay as they were. No body needed; asking twice changes nothing.",
549 "content": {
550 "application/json": {
551 "schema": {
552 "$ref": "#/components/schemas/Lead"
553 }
554 }
555 }
556 },
557 "default": {
558 "description": "{ error, message }: why not",
559 "content": {
560 "application/json": {
561 "schema": {
562 "$ref": "#/components/schemas/Error"
563 }
564 }
565 }
566 }
567 }
568 }
569 },
523570 "/tick": {
524571 "post": {
525572 "summary": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.",
@@ -998,6 +1045,14 @@
9981045 "type": "boolean",
9991046 "description": "Prior written consent to be texted. Without it, only email."
10001047 },
1048 "opted_out_at": {
1049 "type": [
1050 "string",
1051 "null"
1052 ],
1053 "format": "date-time",
1054 "description": "When they asked to stop texts; consent is false from then on."
1055 },
10011056 "state": {
10021057 "enum": [
10031058 "new",
@@ -1036,6 +1091,7 @@
10361091 "source",
10371092 "message",
10381093 "consent",
1094 "opted_out_at",
10391095 "state",
10401096 "created_at",
10411097 "replied_at",
@@ -1171,6 +1227,14 @@
11711227 "type": "boolean",
11721228 "description": "Prior written consent to be texted. Without it, only email."
11731229 },
1230 "opted_out_at": {
1231 "type": [
1232 "string",
1233 "null"
1234 ],
1235 "format": "date-time",
1236 "description": "When they asked to stop texts; consent is false from then on."
1237 },
11741238 "state": {
11751239 "enum": [
11761240 "new",
@@ -1225,6 +1289,7 @@
12251289 "source",
12261290 "message",
12271291 "consent",
1292 "opted_out_at",
12281293 "state",
12291294 "created_at",
12301295 "replied_at",
src/actions.test.ts +69
@@ -11,6 +11,7 @@ import {
1111 addLead,
1212 getLead,
1313 listLeads,
14 optOutTexts,
1415 readNewLead,
1516 resetSample,
1617 sendReply,
@@ -301,3 +302,71 @@ test("reopening a lead that was never answered makes it new with its first reply
301302 expect(back.messages[0]!.status).toBe("draft");
302303 expect(setState(db, anon, { id: lead.id, state: "open" }).ok).toBe(false);
303304 });
305
306 test("opting out turns every unsent text into an email and leaves what was sent alone", () => {
307 const lead = must(addLead(db, alice, { ...maria, name: "Says Stop" }, at(0)));
308 const first = must(sendReply(db, alice, { id: lead.id, body: "Hi, edited." }, at(0)));
309 const sentBefore = first.messages.find((m) => m.status === "sent")!;
310 expect(sentBefore.channel).toBe("text");
311 expect(first.messages.filter((m) => m.day > 0).every((m) => m.channel === "text")).toBe(true);
312 must(tick(db, alice, at(1, 1)));
313 const out = must(optOutTexts(db, alice, { id: lead.id }, at(2)));
314 expect(out.consent).toBe(false);
315 expect(out.opted_out_at).toBe(at(2).toISOString());
316 expect(out.state).toBe("contacted");
317 const unsent = out.messages.filter((m) => m.status !== "sent");
318 expect(unsent.length).toBe(5);
319 for (const m of unsent) {
320 expect(m.channel).toBe("email");
321 expect(m.signature).not.toContain("STOP");
322 expect(m.body).toContain("Best,");
323 }
324 expect(out.messages.find((m) => m.id === sentBefore.id)).toEqual(sentBefore);
325 // Statuses are untouched: the due one is still due, the rest still scheduled.
326 expect(unsent.map((m) => m.status)).toEqual(["due", "scheduled", "scheduled", "scheduled", "scheduled"]);
327 });
328
329 test("an opted-out lead is never texted: not by tick, not by putting a closed lead back", () => {
330 const lead = must(addLead(db, alice, { ...maria, name: "Quiet Now" }, at(0)));
331 must(sendReply(db, alice, { id: lead.id }, at(0)));
332 must(optOutTexts(db, alice, { id: lead.id }, at(0, 5)));
333 must(tick(db, alice, at(40)));
334 expect(must(getLead(db, alice, { id: lead.id })).messages.every((m) => m.channel === (m.status === "sent" ? "text" : "email"))).toBe(true);
335 must(setState(db, alice, { id: lead.id, state: "lost" }, at(41)));
336 const back = must(setState(db, alice, { id: lead.id, state: "open" }, at(42)));
337 expect(back.messages.filter((m) => m.status !== "sent").every((m) => m.channel === "email")).toBe(true);
338 // A new inquiry with the same phone and consent is a new lead; the old one stays opted out.
339 const again = must(addLead(db, alice, { ...maria, name: "Quiet Now" }, at(43)));
340 expect(again.id).not.toBe(lead.id);
341 const old = must(getLead(db, alice, { id: lead.id }));
342 expect(old.consent).toBe(false);
343 expect(old.opted_out_at).not.toBeNull();
344 // The file itself refuses a text for them.
345 expect(() => db.query("UPDATE message SET channel = 'text' WHERE lead_id = ?1 AND day = 30").run(lead.id)).toThrow();
346 });
347
348 test("opting out twice is harmless; a lead that never consented has nothing to stop", () => {
349 const lead = must(addLead(db, alice, { ...maria, name: "Twice" }, at(0)));
350 const one = must(optOutTexts(db, alice, { id: lead.id }, at(1)));
351 const two = must(optOutTexts(db, alice, { id: lead.id }, at(2)));
352 expect(two).toEqual(one);
353 const never = must(addLead(db, alice, { ...maria, name: "Never", consent: false }, at(0)));
354 const refused = optOutTexts(db, alice, { id: never.id });
355 expect(refused.ok).toBe(false);
356 expect(!refused.ok && refused.error).toBe("invalid");
357 expect(optOutTexts(db, anon, { id: lead.id }).ok).toBe(false);
358 expect(optOutTexts(db, alice, { id: 999_999 }).ok).toBe(false);
359 });
360
361 test("an opt-out is written to the audit trail, and the sample reset clears it with the rest", () => {
362 const lead = must(addLead(db, alice, { ...maria, name: "Audited Stop" }, at(0)));
363 must(optOutTexts(db, alice, { id: lead.id }, at(1)));
364 const row = db
365 .query<{ act: string; who_name: string; outcome: string }, [string]>(
366 "SELECT act, who_name, outcome FROM audit WHERE target = ?1 AND act = 'opted_out'",
367 )
368 .get(String(lead.id));
369 expect(row).toEqual({ act: "opted_out", who_name: "alice", outcome: "ok" });
370 must(resetSample(db, root));
371 expect(db.query("SELECT count(*) AS n FROM lead WHERE opted_out_at IS NOT NULL").get()).toEqual({ n: 0 });
372 });
src/actions.ts +33
@@ -25,6 +25,7 @@ import {
2525 reopen,
2626 MAX_QUERY,
2727 insertLead,
28 optOut,
2829 nextNeeding,
2930 readyFor,
3031 redraftUnsent,
@@ -380,6 +381,38 @@ function mark(
380381 return ok(detail(db, found.value.id)!);
381382 }
382383
384 /**
385 * They replied STOP. Texting ends for this lead for good (nothing in the app
386 * turns it back on) and every unsent message becomes an email. Asking again
387 * is harmless; a lead who never agreed to texts has nothing to stop.
388 */
389 export const optOutTexts = (
390 db: Database,
391 who: Who,
392 input: { id: number },
393 at?: Date,
394 ): Result<LeadDetail> =>
395 audited(db, who, "lead", "update", input.id, stopTexts(db, who, input, at), "opted_out");
396
397 function stopTexts(
398 db: Database,
399 who: Who,
400 input: { id: number },
401 at?: Date,
402 ): Result<LeadDetail> {
403 const found = leadFor(db, who, "update", input.id, {
404 signIn: "Sign in to update this lead.",
405 no: "You may not update this lead.",
406 });
407 if (!found.ok) return found;
408 if (found.value.opted_out_at !== null) return found;
409 if (!found.value.consent)
410 return fail("invalid", "This lead never agreed to be texted, so there is nothing to stop.");
411 optOut(db, found.value, stamp(at), currentAgent(db));
412 emit("lead.changed", { id: found.value.id });
413 return ok(detail(db, found.value.id)!);
414 }
415
383416 /** Remove one lead and everything said to it — a test entry, a spammer. */
384417 export const deleteLead = (
385418 db: Database,
src/audit.ts +2 −2
@@ -32,8 +32,8 @@ export interface AuditRow {
3232 readonly act: string | null;
3333 }
3434
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened"] as const;
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out"] as const;
3737 export type Act = (typeof ACTS)[number];
3838
3939 export interface Attempt {
src/db.ts +4
@@ -98,6 +98,10 @@ export const migrations: string[] = [
9898 // the Activity page can say it and filter to messages sent. Older rows have none.
9999 `ALTER TABLE audit ADD COLUMN act TEXT`,
100100 `CREATE INDEX audit_act ON audit (act, id)`,
101 // When a lead asked us to stop texting (replied STOP). Opting out clears
102 // `consent` too, so the consent rule and its triggers hold with no change;
103 // nothing in the app sets it back.
104 `ALTER TABLE lead ADD COLUMN opted_out_at TEXT`,
101105 ];
102106
103107 export function openDb(dir = dataDir): Database {
src/leads.ts +27
@@ -35,6 +35,8 @@ export interface Lead {
3535 readonly message: string;
3636 /** Prior written consent to be texted. */
3737 readonly consent: boolean;
38 /** When they asked to stop texts (consent ended); null if they never did. */
39 readonly opted_out_at: string | null;
3840 readonly state: State;
3941 readonly created_at: string;
4042 /** When the first reply went out; null while they wait. */
@@ -402,6 +404,31 @@ export function redraftUnsent(db: Database, agent: Agent): void {
402404 })();
403405 }
404406
407 /**
408 * They replied STOP: consent ends, and every message not yet sent is
409 * drafted again as an email (the edit of an unsent text is replaced).
410 * Sent messages are history and stay as they were. Doing it twice
411 * changes nothing the second time.
412 */
413 export function optOut(db: Database, found: Lead, at: string, agent: Agent): void {
414 db.transaction(() => {
415 db.query(
416 "UPDATE lead SET consent = 0, opted_out_at = coalesce(opted_out_at, ?1), updated_at = ?1 WHERE id = ?2",
417 ).run(at, found.id);
418 const now = findLead(db, found.id)!;
419 const channel = channelFor(now);
420 const unsent = db
421 .query<{ id: number; day: number }, [number]>(
422 "SELECT id, day FROM message WHERE lead_id = ?1 AND status <> 'sent'",
423 )
424 .all(found.id);
425 for (const m of unsent)
426 db.query(
427 "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4",
428 ).run(channel, draft(now, m.day, agent), signature(channel, agent), m.id);
429 })();
430 }
431
405432 /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */
406433 export function close(
407434 db: Database,
src/mcp.ts +8
@@ -14,6 +14,7 @@ import {
1414 getProfile,
1515 listLeads,
1616 saveProfile,
17 optOutTexts,
1718 approveReply,
1819 setState,
1920 type Result,
@@ -124,6 +125,13 @@ export const tools: readonly Tool[] = [
124125 run: (db, who, args) =>
125126 setState(db, who, { id: Number(args.id), state: args.state }),
126127 },
128 {
129 name: "opt_out_texts",
130 description:
131 "A lead replied STOP: no more texts to them, for good (there is no way to turn texting back on). Every unsent draft becomes an email; sent messages stay as they were.",
132 inputSchema: ONE,
133 run: (db, who, args) => optOutTexts(db, who, { id: Number(args.id) }),
134 },
127135 {
128136 name: "get_profile",
129137 description:
src/pages/lead.ts +12 −1
@@ -77,7 +77,7 @@ export function leadPage(input: {
7777 }
7878 ${
7979 channelFor(lead) === "email"
80 ? `<p class="hint">Email only: ${lead.consent ? "no phone number to text." : "they have not given written consent to be texted."}</p>`
80 ? `<p class="hint">Email only: ${lead.consent ? "no phone number to text." : lead.opted_out_at !== null ? "they asked to stop texts." : "they have not given written consent to be texted."}</p>`
8181 : ""
8282 }
8383 </div>`;
@@ -120,6 +120,16 @@ export function leadPage(input: {
120120 </section>`
121121 : "";
122122
123 const stop =
124 mayUpdate && lead.consent
125 ? `<section class="states">
126 <form method="post" action="${path}/opt-out">
127 <p class="hint">Only after they replied STOP. Texting to them ends for good, and every unsent draft, edited or not, is replaced by an email.</p>
128 <label class="check"><input type="checkbox" required> Yes, they asked to stop texts</label>
129 <button class="button button-quiet">They asked to stop texts</button>
130 </form>
131 </section>`
132 : "";
123133 // A page that needs nothing from the agent never leaves them stuck.
124134 const onward =
125135 ready !== undefined
@@ -155,6 +165,7 @@ export function leadPage(input: {
155165 ${thread}
156166 ${plan}
157167 ${states}
168 ${stop}
158169 </div>`,
159170 });
160171 }
src/pages/parts.ts +3 −1
@@ -25,7 +25,9 @@ export const source = (lead: Lead): string =>
2525 export const consent = (lead: Lead): string =>
2626 channelFor(lead) === "text"
2727 ? `<span class="badge" data-consent="text" title="They gave written consent to be texted">Text OK</span>`
28 : `<span class="badge" data-consent="email" title="No written consent to text: email only">Email only</span>`;
28 : lead.opted_out_at !== null
29 ? `<span class="badge" data-consent="email" title="They asked to stop texts">Email only (opted out ${escape(day(lead.opted_out_at))})</span>`
30 : `<span class="badge" data-consent="email" title="No written consent to text: email only">Email only</span>`;
2931
3032 export const STATE_LABEL: Readonly<Record<Lead["state"], string>> = {
3133 new: "New",
src/routes.ts +27
@@ -25,6 +25,7 @@ import {
2525 listLeads,
2626 resetSample,
2727 saveProfile,
28 optOutTexts,
2829 approveReply,
2930 nextLead,
3031 setState,
@@ -120,6 +121,11 @@ const LEAD_FIELDS = {
120121 type: "boolean",
121122 description: "Prior written consent to be texted. Without it, only email.",
122123 },
124 opted_out_at: {
125 type: ["string", "null"],
126 format: "date-time",
127 description: "When they asked to stop texts; consent is false from then on.",
128 },
123129 state: { enum: ["new", "contacted", "qualified", "lost"] },
124130 created_at: STAMP,
125131 replied_at: { type: ["string", "null"], format: "date-time" },
@@ -300,6 +306,12 @@ async function readFields(
300306 const body = await readJson(request);
301307 return body === undefined ? undefined : fields(body);
302308 }
309 // A POST with no body at all (a bare `curl -X POST`) has no fields; a garbled one is still a fault.
310 if (
outdated

MEDIUM: readForm(request).catch(() => new FormData()) changes every form-posting route (add lead, profile, send, mark), not just opt-out. A malformed or garbage body used to fail loudly. Now it silently becomes empty fields, which hides client bugs and invalid input at the boundary. Fix: leave readFields as it was. The opt-out handler never reads fields (posted calls it for you), so handle the empty-body case only for this route, or have readFields treat an absent body (no content-type or content-length 0) as empty rather than catching all errors. Add a test that a malformed form body on another route still fails.

311 !request.headers.has("content-type") &&
312 (request.headers.get("content-length") ?? "0") === "0"
313 )
314 return {};
303315 const form = await readForm(request);
304316 return form === undefined
305317 ? undefined
@@ -529,6 +541,21 @@ export const routes: readonly Route[] = [
529541 answer: LEAD,
530542 },
531543 },
544 {
545 method: "POST",
546 path: "/leads/:id/opt-out",
547 handle: (c) =>
548 posted(
549 c,
550 () => optOutTexts(c.db, c.who, { id: ID(c) }),
551 () => ({ to: `/leads/${ID(c)}`, said: "Texts stopped. Unsent drafts are now emails." }),
552 ),
553 api: {
554 summary:
555 "They replied STOP: no more texts to this lead, for good. Every unsent draft becomes an email; sent messages stay as they were. No body needed; asking twice changes nothing.",
556 answer: LEAD,
557 },
558 },
532559 {
533560 method: "POST",
534561 path: "/tick",
src/sentences.ts +5
@@ -35,6 +35,11 @@ export function deed(
3535 done: `put ${lead} back in follow-ups`,
3636 tried: `put ${lead} back in follow-ups`,
3737 };
38 if (row.act === "opted_out")
39 return {
40 done: `recorded that ${lead} asked to stop texts`,
41 tried: `record that ${lead} asked to stop texts`,
42 };
3843 if (row.verb === "create")
3944 return { done: "added a lead", tried: "add a lead" };
4045 if (row.verb === "delete")
src/server.test.ts +45
@@ -288,6 +288,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
288288 "new_sample_inquiry",
289289 "send_reply",
290290 "mark_lead",
291 "opt_out_texts",
291292 "get_profile",
292293 "set_profile",
293294 ]);
@@ -657,3 +658,47 @@ test("POST /sample/inquiry: the button and the JSON route make the same lead; an
657658 const refused = await api("/sample/inquiry", { method: "POST", ...jsonBody({}) }, {});
658659 expect([401, 403]).toContain(refused.status);
659660 });
661
662 test("a lead is opted out from its page, the API and MCP; same-origin only; no way back", async () => {
663 const one = await created({ ...NEW, name: "Page Stop" });
664 const page = await (await api(`/leads/${one.id}`, {}, alice)).text();
665 expect(page).toContain(`action="/leads/${one.id}/opt-out"`);
666 expect(page).toContain("They asked to stop texts");
667 const cross = await api(`/leads/${one.id}/opt-out`, { method: "POST", headers: { "sec-fetch-site": "cross-site" }, body: form({}) }, alice);
668 expect(cross.status).toBe(403);
669 expect((await lead(one.id)).messages[0]!.channel).toBe("text");
670 const done = await api(`/leads/${one.id}/opt-out`, { method: "POST", body: form({}), redirect: "manual" }, alice);
671 expect(done.status).toBe(303);
672 const after = await (await api(`/leads/${one.id}`, {}, alice)).text();
673 expect(after).toContain("Email only (opted out");
674 expect(after).not.toContain("opt-out");
675 expect((await lead(one.id)).messages[0]!.channel).toBe("email");
676
677 const two = await created({ ...NEW, name: "Api Stop" });
678 expect((await api(`/leads/${two.id}/opt-out`, { method: "POST" }, {})).status).toBeOneOf([401, 403]);
679 const res = await api(`/leads/${two.id}/opt-out`, { method: "POST", ...jsonBody({}) }, alice);
680 expect(res.status).toBe(200);
681 expect(((await res.json()) as { consent: boolean }).consent).toBe(false);
682 expect((await api(`/leads/${two.id}/opt-out`, { method: "POST", ...jsonBody({}) }, alice)).status).toBe(200);
683
684 const three = await created({ ...NEW, name: "Mcp Stop" });
685 const viaMcp = await rpc({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "opt_out_texts", arguments: { id: three.id } } }, alice);
686 expect(viaMcp.result.isError).toBeUndefined();
687 expect((await lead(three.id)).messages[0]!.channel).toBe("email");
688
689 const never = await created({ ...NEW, name: "No Consent", consent: false });
690 expect(await (await api(`/leads/${never.id}`, {}, alice)).text()).not.toContain("opt-out");
691 expect((await api(`/leads/${never.id}/opt-out`, { method: "POST", ...jsonBody({}) }, alice)).status).toBe(422);
692 expect(await (await api("/openapi.json", {}, alice)).text()).toContain("/leads/{id}/opt-out");
693 });
694
695 test("a bodyless POST has no fields, but a garbled form body still fails", async () => {
696 const one = await created({ ...NEW, name: "Garbled" });
697 expect((await api(`/leads/${one.id}/opt-out`, { method: "POST" }, alice)).status).toBeLessThan(400);
698 const garbled = await api(
699 "/leads",
700 { method: "POST", headers: { "content-type": "multipart/form-data" }, body: "garbage" },
701 alice,
702 ).then((r) => r.status, () => 500);
703 expect(garbled).toBeGreaterThanOrEqual(400);
704 });
src/terminal.test.ts +22
@@ -328,3 +328,25 @@ test("o puts a closed lead back in follow-ups", () => {
328328 expect(read(t)).toContain("Maria Gonzalez: back in follow-ups.");
329329 expect(read(t)).toContain("q qualified");
330330 });
331
332 test("t asks, then y records that they asked to stop texts; any other key does not", () => {
333 const db = fresh();
334 const t = terminal(db, alice);
335 t.key("\r");
336 expect(read(t)).toContain("t they asked to stop texts");
337 const id = (listLeads(db, alice) as { ok: true; value: { leads: { id: number }[] } }).value.leads[0]!.id;
338 t.key("t");
339 expect(read(t)).toContain("texting cannot be turned back on");
340 t.key("n");
341 expect((getLead(db, alice, { id }) as { ok: true; value: { consent: boolean } }).value.consent).toBe(true);
342 t.key("t");
343 t.key("y");
344 expect(read(t)).toContain("Texts stopped");
345 const after = (getLead(db, alice, { id }) as { ok: true; value: { consent: boolean; messages: { channel: string }[] } }).value;
346 expect(after.consent).toBe(false);
347 expect(after.messages[0]!.channel).toBe("email");
348 expect(read(t)).toContain("they asked to stop texts.");
349 expect(read(t)).not.toContain("t they asked to stop texts");
outdated

LOW: not.toContain("they asked to stop texts\n") depends on how the screen is wrapped and would pass for the wrong reasons. Assert on the key hint directly, e.g. that the hint line no longer contains "t they asked to stop texts".

350 t.key("t"); // no longer offered
351 expect(read(t)).not.toContain("texting cannot");
352 });
src/terminal.ts +17 −5
@@ -7,7 +7,7 @@
77 * Screens:
88 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email or phone · n log a lead · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · ] next lead that needs you ·
10 * q qualified · x lost · D remove (admin) · esc back
10 * q qualified · x lost · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
1212 * add one field at a time; enter next · esc cancel
1313 * profile the name, brokerage and license every message carries ·
@@ -29,6 +29,7 @@ import {
2929 getLead,
3030 getProfile,
3131 listLeads,
32 optOutTexts,
3233 resetSample,
3334 saveProfile,
3435 approveReply,
@@ -112,7 +113,7 @@ type View =
112113 | { name: "lead"; id: number }
113114 | { name: "edit"; id: number; text: string }
114115 | { name: "add"; step: number; typed: string; fields: Record<string, string> }
115 | { name: "confirm"; what: "remove" | "reset"; id?: number; back: View };
116 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
116117
117118 const titleOf = (m: Message): string =>
118119 m.day === 0 ? "First reply" : `Day ${m.day} follow-up`;
@@ -257,7 +258,9 @@ export function terminal(
257258 dim(
258259 l.consent
259260 ? " Email only: no phone number to text."
260 : " Email only: no written consent to text.",
261 : l.opted_out_at !== null
262 ? " Email only: they asked to stop texts."
263 : " Email only: no written consent to text.",
outdated

LOW: the added ternary branch is indented inconsistently with its sibling : " Email only: no written consent to text." line. Format it as a nested ternary like the rest of the file.

261264 ),
262265 );
263266 const body = editing === undefined ? r.body : `${editing}█`;
@@ -284,6 +287,7 @@ export function terminal(
284287 ...(l.state === "qualified" || l.state === "lost"
285288 ? ["o put back in follow-ups"]
286289 : ["q qualified", "x lost"]),
290 ...(l.consent ? ["t they asked to stop texts"] : []),
287291 ...(nextLead(db, me, { except: l.id }) === null ? [] : ["] next that needs you"]),
288292 ...(admin() ? ["D remove"] : []),
289293 "esc back",
@@ -420,7 +424,9 @@ export function terminal(
420424 : [
421425 view.what === "reset"
422426 ? "Restart the sample leads from now? Every lead on the desk is replaced."
423 : `Remove ${clean(lead(view.id ?? 0)?.name ?? "this lead")} and everything said to them?`,
427 : view.what === "opt-out"
428 ? `${clean(lead(view.id ?? 0)?.name ?? "This lead")} asked to stop texts? Every unsent draft becomes an email, and texting cannot be turned back on.`
429 : `Remove ${clean(lead(view.id ?? 0)?.name ?? "this lead")} and everything said to them?`,
424430 "",
425431 dim("y yes · any other key no"),
426432 ];
@@ -545,7 +551,9 @@ export function terminal(
545551 } else if (input === "o" && CLOSED.includes(l.state)) {
546552 const back = setState(db, me, { id, state: "open" });
547553 said = back.ok ? `${l.name}: back in follow-ups.` : back.message;
548 } else if (input === "D")
554 } else if (input === "t" && l.consent)
555 view = { name: "confirm", what: "opt-out", id, back: view };
556 else if (input === "D")
549557 view = { name: "confirm", what: "remove", id, back: view };
550558 return;
551559 }
@@ -604,6 +612,10 @@ export function terminal(
604612 said = reset.ok ? "The sample leads start again from now." : reset.message;
605613 cursor = 0;
606614 view = { name: "desk" };
615 } else if (what === "opt-out") {
616 const stopped = optOutTexts(db, me, { id: id ?? 0 });
617 said = stopped.ok ? "Texts stopped. Unsent drafts are now emails." : stopped.message;
618 view = back;
607619 } else {
608620 const removed = deleteLead(db, me, { id: id ?? 0 });
609621 said = removed.ok ? "Removed." : removed.message;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs