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

Fix a lead's name, email or phone from the lead's page, and unsent drafts follow the new details #38

Merged opened this

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

Merged

mason/speed-to-lead:mason/35-fix-a-lead-s-name-email-or-phone-from-th → main 3 commits fork 2 threads · 2 unresolved

  • Merged. mason/35-fix-a-lead-s-name-email-or-phone-from-th was merged into main as d335462.

Review

Sign in to review this change.
15 files changed +729 −41
README.md +12
@@ -78,6 +78,18 @@ samples (step 1).
7878 terminal desk. They go through the same path as `POST /leads`, for anyone who
7979 may add a lead. The turn is read off the desk, so it needs no extra state.
8080
81 **Fixing a lead's details.** A website form brings in a misspelled name or a
82 mistyped phone, so an open lead's page has **Edit details** (name, email,
83 phone; checked as when a lead is added, and one of email or phone must
84 remain). The same edit is `PATCH /leads/{id}` or `POST /leads/{id}/edit`
85 with JSON, the MCP `edit_lead` tool, and `d` on the terminal's lead screen.
86 Drafts not yet sent follow the new details: they are written again for the
87 new name, and with no phone (or after STOP) unsent texts become emails; with no
88 email, unsent emails become texts only for a lead who agreed to be texted,
89 otherwise they wait and the page says so (nothing can be sent to no address).
90 Sent messages stay as they were. The Activity page tells which fields changed,
91 with old and new values.
92
8193 **The desk** (the first screen) lists your leads, newest first. Links above
8294 the list narrow it: **Needs you** (a first reply or follow-up waiting),
8395 **In follow-up** (open, nothing waiting), **Closed** and **All**, each with
contract/openapi.json +88 −6
@@ -195,7 +195,7 @@
195195 }
196196 },
197197 "patch": {
198 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state).",
198 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
199199 "operationId": "patchLeadsId",
200200 "parameters": [
201201 {
@@ -220,18 +220,29 @@
220220 "lost",
221221 "open"
222222 ]
223 },
224 "name": {
225 "type": "string",
226 "minLength": 1,
227 "maxLength": 120
228 },
229 "email": {
230 "type": "string",
231 "maxLength": 254,
232 "description": "Empty takes it away, if a phone remains."
233 },
234 "phone": {
235 "type": "string",
236 "description": "7 to 20 digits; empty takes it away, if an email remains."
223237 }
224 },
225 "required": [
226 "state"
227 ]
238 }
228239 }
229240 }
230241 }
231242 },
232243 "responses": {
233244 "200": {
234 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state).",
245 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
235246 "content": {
236247 "application/json": {
237248 "schema": {
@@ -873,6 +884,70 @@
873884 }
874885 }
875886 },
887 "/leads/{id}/edit": {
888 "post": {
889 "summary": "Correct a lead's name, email or phone (a field left out stays as it is; an empty email or phone takes it away, but one of them must remain). Unsent drafts follow the new details: with no phone, or after STOP, unsent texts become emails; with no email, unsent emails become texts only where the lead agreed to be texted, otherwise they wait. The audit trail names the fields changed.",
890 "operationId": "postLeadsIdEdit",
891 "parameters": [
892 {
893 "name": "id",
894 "in": "path",
895 "required": true,
896 "schema": {
897 "type": "integer"
898 }
899 }
900 ],
901 "requestBody": {
902 "required": true,
903 "content": {
904 "application/json": {
905 "schema": {
906 "type": "object",
907 "properties": {
908 "name": {
909 "type": "string",
910 "minLength": 1,
911 "maxLength": 120
912 },
913 "email": {
914 "type": "string",
915 "maxLength": 254,
916 "description": "Empty takes it away, if a phone remains."
917 },
918 "phone": {
919 "type": "string",
920 "description": "7 to 20 digits; empty takes it away, if an email remains."
921 }
922 }
923 }
924 }
925 }
926 },
927 "responses": {
928 "200": {
929 "description": "Correct a lead's name, email or phone (a field left out stays as it is; an empty email or phone takes it away, but one of them must remain). Unsent drafts follow the new details: with no phone, or after STOP, unsent texts become emails; with no email, unsent emails become texts only where the lead agreed to be texted, otherwise they wait. The audit trail names the fields changed.",
930 "content": {
931 "application/json": {
932 "schema": {
933 "$ref": "#/components/schemas/Lead"
934 }
935 }
936 }
937 },
938 "default": {
939 "description": "{ error, message }: why not",
940 "content": {
941 "application/json": {
942 "schema": {
943 "$ref": "#/components/schemas/Error"
944 }
945 }
946 }
947 }
948 }
949 }
950 },
876951 "/leads/{id}/opt-out": {
877952 "post": {
878953 "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.",
@@ -1904,6 +1979,13 @@
19041979 "string",
19051980 "null"
19061981 ]
1982 },
1983 "detail": {
1984 "type": [
1985 "string",
1986 "null"
1987 ],
1988 "description": "For a correction of a lead's details: the fields changed, as JSON, each with its old and new value."
19071989 }
19081990 },
19091991 "required": [
src/actions.ts +97 −6
@@ -27,6 +27,7 @@ import {
2727 MAX_INBOUND,
2828 MAX_QUERY,
2929 insertLead,
30 updateContact,
3031 optOut,
3132 nextNeeding,
3233 readyFor,
@@ -39,6 +40,7 @@ import {
3940 responseRecord,
4041 send,
4142 viewOf,
43 type Contact,
4244 type Desk,
4345 type LeadDetail,
4446 type NewLead,
@@ -78,9 +80,11 @@ const audited = <T extends { readonly id: number }>(
7880 target: number | undefined,
7981 result: Result<T>,
8082 act?: Act,
83 detail?: string,
8184 ): Result<T> => {
8285 record(db, {
8386 ...(act === undefined ? {} : { act }),
87 ...(detail === undefined ? {} : { detail }),
8488 who,
8589 resource,
8690 verb,
@@ -185,6 +189,23 @@ const lines = (s: string): string => s.replace(/\r\n?/g, "\n");
185189 export const hasControl = (s: string, multiline: boolean): boolean =>
186190 CONTROL.test(s) || (!multiline && LINE_BREAK.test(s));
187191
192 /**
193 * What is wrong with a lead's name, email and phone, if anything: the one
194 * check `addLead` and `editLead` share. An email may be missing only when
195 * `contactable` says a phone number is how to reach them.
196 */
197 function contactProblem(c: Contact, contactable: boolean): string | undefined {
198 if (c.name.length === 0 || c.name.length > 120)
199 return "A name is 1 to 120 characters.";
200 if (c.email.length > 254 || !(c.email === "" && contactable ? true : EMAIL.test(c.email)))
201 return "An email address looks like [email protected].";
202 if (c.phone !== "" && !PHONE.test(c.phone))
203 return "A phone number is 7 to 20 digits.";
204 if (contactable && c.email === "" && c.phone === "")
205 return "A lead needs an email or a phone number to be reached by.";
206 return undefined;
207 }
208
188209 /** What arrived, checked field by field: a lead to keep, or what is wrong with it. */
189210 export function readNewLead(input: Record<string, unknown>): Result<NewLead> {
190211 const text = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
@@ -201,12 +222,8 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> {
201222 "invalid",
202223 "A lead's details are plain text: no control characters, and line breaks only in what they asked.",
203224 );
204 if (name.length === 0 || name.length > 120)
205 return fail("invalid", "A name is 1 to 120 characters.");
206 if (email.length > 254 || !EMAIL.test(email))
207 return fail("invalid", "An email address looks like [email protected].");
208 if (phone !== "" && !PHONE.test(phone))
209 return fail("invalid", "A phone number is 7 to 20 digits.");
225 const wrong = contactProblem({ name, email, phone }, false);
226 if (wrong !== undefined) return fail("invalid", wrong);
210227 if (source === undefined)
211228 return fail(
212229 "invalid",
@@ -248,6 +265,78 @@ function add(
248265 return ok(added);
249266 }
250267
268 /** The fields of a lead's details, in the order they are told. */
269 const CONTACT_FIELDS = ["name", "email", "phone"] as const;
270 export type ContactField = (typeof CONTACT_FIELDS)[number];
271 /** What an edit changed: each field's old and new value. */
272 export type Changes = Partial<Record<ContactField, { from: string; to: string }>>;
273
274 /**
275 * The agent corrects a lead's name, email or phone (a field not given stays
276 * as it is; an empty email or phone takes it away, so long as one of them
277 * is left). The details are checked as `addLead` checks them. Unsent
278 * messages follow the new details; the audit row names the fields changed.
279 */
280 export const editLead = (
281 db: Database,
282 who: Who,
283 input: { id: number } & Partial<Record<ContactField, unknown>>,
284 at?: Date,
285 ): Result<LeadDetail> => {
286 const edited = correct(db, who, input, at);
287 const changed = edited.ok && Object.keys(edited.value.changes).length > 0;
288 const result: Result<LeadDetail> = edited.ok ? ok(edited.value.lead) : edited;
289 return audited(
290 db,
291 who,
292 "lead",
293 "update",
294 input.id,
295 result,
296 changed ? "edited" : undefined,
297 changed ? JSON.stringify(edited.value.changes) : undefined,
298 );
299 };
300
301 function correct(
302 db: Database,
303 who: Who,
304 input: { id: number } & Partial<Record<ContactField, unknown>>,
305 at?: Date,
306 ): Result<{ lead: LeadDetail; changes: Changes }> {
307 const found = leadFor(db, who, "update", input.id, {
308 signIn: "Sign in to edit this lead.",
309 no: "You may not edit this lead.",
310 });
311 if (!found.ok) return found;
312 const lead = found.value;
313 if (CLOSED.includes(lead.state))
314 return fail("invalid", "This lead is marked qualified or lost: put it back in follow-ups first.");
315 const to: Record<ContactField, string> = {
316 name: lead.name,
317 email: lead.email,
318 phone: lead.phone,
319 };
320 for (const field of CONTACT_FIELDS) {
321 const given = input[field];
322 if (given === undefined) continue;
323 if (typeof given !== "string")
324 return fail("invalid", `A lead's ${field} is text.`);
325 to[field] = field === "email" ? given.trim().toLowerCase() : given.trim();
326 }
327 if (CONTACT_FIELDS.some((field) => hasControl(to[field], false)))
328 return fail("invalid", "A lead's details are plain text: no control characters.");
329 const wrong = contactProblem(to, true);
330 if (wrong !== undefined) return fail("invalid", wrong);
331 const changes: Changes = {};
332 for (const field of CONTACT_FIELDS)
333 if (to[field] !== lead[field]) changes[field] = { from: lead[field], to: to[field] };
334 if (Object.keys(changes).length === 0) return ok({ lead, changes });
335 updateContact(db, lead, to, stamp(at), currentAgent(db));
336 emit("lead.changed", { id: lead.id });
337 return ok({ lead: detail(db, lead.id)!, changes });
338 }
339
251340 /** The next sample inquiry arrives now, by the same path as any lead. */
252341 export const addSampleInquiry = (
253342 db: Database,
@@ -336,6 +425,8 @@ function reply(
336425 "invalid",
337426 `A${ready.channel === "text" ? " text" : "n email"} is 1 to ${max} characters.`,
338427 );
428 if (ready.channel === "email" && found.value.email === "")
429 return fail("invalid", "This lead has no email address and has not agreed to be texted: add one, or call them.");
339430 const by = who.role === "anon" ? "" : who.name;
340431 send(db, found.value, ready, body, by, stamp(at), currentAgent(db));
341432 emit("lead.changed", { id: found.value.id });
src/audit.ts +10 −4
@@ -30,10 +30,12 @@ export interface AuditRow {
3030 readonly outcome: string;
3131 /** What a lead change was, when it is known: see `Act`. */
3232 readonly act: string | null;
33 /** For `edited`: the fields changed, as JSON — `{ "phone": { "from": "…", "to": "…" } }`. */
34 readonly detail: string | null;
3335 }
3436
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; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off"] as const;
37 /** 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; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited"] as const;
3739 export type Act = (typeof ACTS)[number];
3840
3941 export interface Attempt {
@@ -43,6 +45,8 @@ export interface Attempt {
4345 readonly target?: string | number | undefined;
4446 readonly outcome: string;
4547 readonly act?: Act | undefined;
48 /** What changed, when the act has more to say: JSON text. */
49 readonly detail?: string | undefined;
4650 }
4751
4852 /** The newest rows kept; older ones go as new ones come. */
@@ -55,7 +59,7 @@ export const allowed = (outcome: string): boolean =>
5559 outcome !== "cross_site";
5660
5761 export function record(db: Database, attempt: Attempt): void {
58 const { who, resource, verb, target, outcome, act } = attempt;
62 const { who, resource, verb, target, outcome, act, detail } = attempt;
5963 const row = {
6064 who_id: who.role === "anon" ? null : who.id,
6165 who_name: who.role === "anon" ? null : who.name,
@@ -66,11 +70,12 @@ export function record(db: Database, attempt: Attempt): void {
6670 allowed: allowed(outcome) ? 1 : 0,
6771 outcome,
6872 act: act !== undefined && ACTS.includes(act) ? act : null,
73 detail: detail ?? null,
6974 };
7075 try {
7176 const { lastInsertRowid } = db
7277 .query(
73 "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome, act) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
78 "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome, act, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
7479 )
7580 .run(
7681 row.who_id,
@@ -82,6 +87,7 @@ export function record(db: Database, attempt: Attempt): void {
8287 row.allowed,
8388 row.outcome,
8489 row.act,
90 row.detail,
8591 );
8692 db.query("DELETE FROM audit WHERE id <= ?1").run(
8793 Number(lastInsertRowid) - KEEP,
src/contract.test.ts +5
@@ -12,6 +12,7 @@ import {
1212 addLead,
1313 addSampleInquiry,
1414 deleteLead,
15 editLead,
1516 getAudit,
1617 getLead,
1718 getProfile,
@@ -120,9 +121,13 @@ const doors: Record<
120121 const week = new Date(Date.now() + 7 * 86_400_000).toISOString();
121122 const showing = bookShowing(db, who, { id: replied, when: week }).ok;
122123 const off = cancelShowing(db, who, { id: replied }).ok;
124 // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id
125 // with a name, email or phone, and the MCP tool edit_lead).
126 const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok;
123127 const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok;
124128 expect(showing).toBe(changed);
125129 expect(off).toBe(changed);
130 expect(edited).toBe(changed);
126131 expect(logged).toBe(changed);
127132 expect(called).toBe(changed);
128133 return changed;
src/db.test.ts +1
@@ -26,5 +26,6 @@ test("the inbound migrations tolerate a file that already has them (a preview th
2626 const db = openDb(mkdtempSync(join(tmpdir(), "app-db-")));
2727 const at = migrations.findIndex((m) => m.includes("TABLE IF NOT EXISTS inbound"));
2828 db.exec("DELETE FROM schema_version WHERE version > " + at);
29 db.exec("ALTER TABLE audit DROP COLUMN detail"); // the one migration after them that is not safe to run twice
2930 expect(() => migrate(db)).not.toThrow();
3031 });
src/db.ts +38 −1
@@ -135,6 +135,36 @@ export const migrations: string[] = [
135135 hold_until TEXT NOT NULL,
136136 booked_at TEXT NOT NULL
137137 )`,
138 // What a change was, in the fields it touched (old and new), as JSON.
139 `ALTER TABLE audit ADD COLUMN detail TEXT`,
140 // A lead's email can be taken away once the agent corrects the details (a
141 // phone is then the way to reach them), so the floor on its length goes.
142 // SQLite cannot drop a CHECK in place: the table is rebuilt (`migrate`
143 // turns foreign keys off around the list, or the drop would cascade away
144 // every message). Safe to run again.
145 `DROP TABLE IF EXISTS lead_new`,
146 `CREATE TABLE lead_new (
147 id INTEGER PRIMARY KEY,
148 name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120),
149 email TEXT NOT NULL CHECK (length(email) <= 254),
150 phone TEXT NOT NULL DEFAULT '',
151 source TEXT NOT NULL CHECK (source IN ('zillow', 'website', 'open_house', 'referral')),
152 message TEXT NOT NULL CHECK (length(message) BETWEEN 1 AND 2000),
153 consent INTEGER NOT NULL CHECK (consent IN (0, 1)),
154 state TEXT NOT NULL DEFAULT 'new' CHECK (state IN ('new', 'contacted', 'qualified', 'lost')),
155 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
156 replied_at TEXT,
157 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
158 opted_out_at TEXT
159 )`,
160 `INSERT INTO lead_new (id, name, email, phone, source, message, consent, state, created_at, replied_at, updated_at, opted_out_at)
161 SELECT id, name, email, phone, source, message, consent, state, created_at, replied_at, updated_at, opted_out_at FROM lead`,
162 `DROP TABLE lead`,
163 // (legacy mode: the triggers that read `lead` are not re-checked mid-rename)
164 `PRAGMA legacy_alter_table = ON;
165 ALTER TABLE lead_new RENAME TO lead;
166 PRAGMA legacy_alter_table = OFF`,
167 `CREATE INDEX IF NOT EXISTS lead_created ON lead (created_at)`,
138168 ];
139169
140170 export function openDb(dir = dataDir): Database {
@@ -149,10 +179,13 @@ export function openDb(dir = dataDir): Database {
149179
150180 /** Apply the migrations past the recorded version, all or none. Returns the version. */
151181 export function migrate(db: Database): number {
182 // Foreign keys are off while the list runs (a table rebuild must not
183 // cascade) and checked, then back on, after it.
184 db.exec("PRAGMA foreign_keys = OFF");
152185 db.exec(
153186 "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))",
154187 );
155 return db.transaction(() => {
188 const version = db.transaction(() => {
156189 const current = db
157190 .query<
158191 { version: number },
@@ -165,8 +198,12 @@ export function migrate(db: Database): number {
165198 current + i + 1,
166199 );
167200 });
201 if (db.query("PRAGMA foreign_key_check").all().length > 0)
202 throw new Error("a migration left a row pointing at nothing");
168203 return migrations.length;
169204 })();
205 db.exec("PRAGMA foreign_keys = ON");
206 return version;
170207 }
171208
172209 export function check(db: Database): { version: number; integrity: string } {
src/details.test.ts added +263
@@ -0,0 +1,263 @@
1 /**
2 * Fixing a lead's name, email or phone: the same checks as adding one, one
3 * audit row naming what changed, and the drafts not yet sent follow. At
4 * the action, the page, the JSON API, the MCP and the terminal.
5 */
6 import { afterAll, expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addLead, editLead, getLead, sendReply, setState, type Result } from "./actions.ts";
11 import type { AuditRow } from "./audit.ts";
12 import { migrations, openDb } from "./db.ts";
13 import { serve } from "./server.ts";
14 import { plain, terminal } from "./terminal.ts";
15 import type { Who } from "./who.ts";
16 import { sign } from "./who.ts";
17
18 const alice: Who = { role: "user", id: "u1", name: "alice" };
19 const anon: Who = { role: "anon" };
20 const NEW = {
21 name: "Dana Reys",
22 email: "[email protected]",
23 phone: "(206) 555-0199",
24 source: "website",
25 message: "Can I see 12 Oak Street this week?",
26 consent: true,
27 };
28 const T0 = new Date("2026-03-01T10:00:00Z");
29
30 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-details-")));
31 const must = <T>(r: Result<T>): T => {
32 if (!r.ok) throw new Error(r.message);
33 return r.value;
34 };
35 const arrive = (db: ReturnType<typeof fresh>, over: Record<string, unknown> = {}) =>
36 must(addLead(db, alice, { ...NEW, ...over }, T0)).id;
37 const audits = (db: ReturnType<typeof fresh>) =>
38 db.query<AuditRow, []>("SELECT * FROM audit WHERE act = 'edited'").all();
39
40 test("a valid edit changes the lead and writes one audit row with old and new values", () => {
41 const db = fresh();
42 const id = arrive(db);
43 const edited = must(editLead(db, alice, { id, name: " Dana Reyes ", email: "[email protected]" }));
44 expect(edited.name).toBe("Dana Reyes");
45 expect(edited.email).toBe("[email protected]");
46 expect(edited.phone).toBe(NEW.phone);
47 const rows = audits(db);
48 expect(rows).toHaveLength(1);
49 expect(rows[0]!.who_name).toBe("alice");
50 expect(rows[0]!.target).toBe(String(id));
51 expect(JSON.parse(rows[0]!.detail!)).toEqual({
52 name: { from: "Dana Reys", to: "Dana Reyes" },
53 email: { from: "[email protected]", to: "[email protected]" },
54 });
55 // The first reply, still unsent, greets them by the corrected name.
56 expect(edited.messages[0]!.body).toContain("Hi Dana,");
57 // Saving what is already there changes nothing and says nothing.
58 must(editLead(db, alice, { id, name: "Dana Reyes" }));
59 expect(audits(db)).toHaveLength(1);
60 });
61
62 test("an invalid email or phone is refused and changes nothing", () => {
63 const db = fresh();
64 const id = arrive(db);
65 for (const bad of [
66 { email: "not-an-email" },
67 { phone: "12" },
68 { name: "" },
69 { name: "x".repeat(121) },
70 { name: "Dana\u001b[2J" },
71 { email: "", phone: "" },
72 { phone: 5206555 },
73 ]) {
74 const r = editLead(db, alice, { id, ...bad });
75 expect(r.ok).toBe(false);
76 if (!r.ok) expect(r.error).toBe("invalid");
77 }
78 const after = must(getLead(db, alice, { id }));
79 expect(after.name).toBe(NEW.name);
80 expect(after.email).toBe(NEW.email);
81 expect(after.phone).toBe(NEW.phone);
82 expect(audits(db)).toHaveLength(0);
83 });
84
85 test("removing the phone turns unsent texts into emails; the sent ones stay as they were", () => {
86 const db = fresh();
87 const id = arrive(db);
88 expect(must(getLead(db, alice, { id })).messages[0]!.channel).toBe("text");
89 must(sendReply(db, alice, { id }, T0));
90 const edited = must(editLead(db, alice, { id, phone: "" }));
91 const [first, ...later] = edited.messages;
92 expect(first!.status).toBe("sent");
93 expect(first!.channel).toBe("text");
94 expect(later.length).toBeGreaterThan(0);
95 for (const m of later) {
96 expect(m.channel).toBe("email");
97 expect(m.signature).toContain("License");
98 }
99 });
100
101 test("a new phone on a lead who never agreed to texts keeps drafts as emails; removing the email texts only the consenting", () => {
102 const db = fresh();
103 const none = arrive(db, { consent: false });
104 const kept = must(editLead(db, alice, { id: none, email: "" }));
105 expect(kept.email).toBe("");
106 expect(kept.messages[0]!.channel).toBe("email");
107 // Nothing can be sent to nobody: it waits, and says why.
108 const waits = sendReply(db, alice, { id: none }, T0);
109 expect(waits.ok).toBe(false);
110 expect(!waits.ok && waits.message).toContain("no email address");
111
112 const yes = arrive(db, { email: "[email protected]" });
113 const first = must(editLead(db, alice, { id: yes, email: "" }));
114 expect(first.messages[0]!.channel).toBe("text");
115
116 const opted = arrive(db, { email: "[email protected]" });
117 const done = must(editLead(db, alice, { id: opted, email: "[email protected]", phone: "2065550100" }));
118 expect(done.messages[0]!.channel).toBe("text");
119 });
120
121 test("a closed lead is not edited; an identity that may not update is refused and recorded", () => {
122 const db = fresh();
123 const id = arrive(db);
124 const denied = editLead(db, anon, { id, name: "Mallory" });
125 expect(!denied.ok && denied.error).toBe("signin_required");
126 expect(must(getLead(db, alice, { id })).name).toBe(NEW.name);
127 const refusal = db
128 .query<AuditRow, []>("SELECT * FROM audit WHERE verb = 'update' AND allowed = 0")
129 .all();
130 expect(refusal).toHaveLength(1);
131 must(setState(db, alice, { id, state: "lost" }));
132 expect(editLead(db, alice, { id, name: "Late" }).ok).toBe(false);
133 expect(editLead(db, alice, { id: 9999, name: "Nobody" }).ok).toBe(false);
134 });
135
136 test("the lead table rebuild keeps every message, inbound reply and call", () => {
137 const dir = mkdtempSync(join(tmpdir(), "app-details-"));
138 const before = openDb(dir);
139 const id = arrive(before);
140 const edit = migrations.findIndex((m) => m.includes("DROP TABLE IF EXISTS lead_new"));
141 before.exec(`DELETE FROM schema_version WHERE version > ${edit}`);
142 before.close();
143 const after = openDb(dir);
144 expect(after.query("SELECT count(*) AS n FROM message WHERE lead_id = ?1").get(id)).toEqual({ n: 1 });
145 expect(after.query("PRAGMA foreign_keys").get()).toEqual({ foreign_keys: 1 });
146 });
147
148 // --- the doors ---
149
150 const KEY = "a-key-only-the-forge-holds";
151 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY });
152 const base = `http://${server.hostname}:${server.port}`;
153 afterAll(() => server.stop(true));
154 let grants = 0;
155 const as = (id: string, name: string, role = "user") => {
156 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
157 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
158 };
159 const call = (path: string, init: RequestInit = {}, who: Record<string, string> = as(`u-${++grants}`, "alice")) =>
160 fetch(base + path, { ...init, headers: { ...(init.headers as object), ...who } });
161 const JSON_HEADERS = { "content-type": "application/json", accept: "application/json" };
162 const made = async () =>
163 (await (await call("/leads", { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(NEW) })).json()) as { id: number };
164
165 test("PATCH /leads/:id and POST /leads/:id/edit correct the details; bad input is 422; strangers are refused; cross-site is refused", async () => {
166 const { id } = await made();
167 const patch = (body: unknown, who?: Record<string, string>, headers: object = {}) =>
168 call(`/leads/${id}`, { method: "PATCH", headers: { ...JSON_HEADERS, ...headers }, body: JSON.stringify(body) }, who);
169
170 const ok = await patch({ name: "Dana Reyes", phone: "" });
171 expect(ok.status).toBe(200);
172 const body = (await ok.json()) as { name: string; phone: string; messages: { channel: string }[] };
173 expect(body.name).toBe("Dana Reyes");
174 expect(body.phone).toBe("");
175 expect(body.messages[0]!.channel).toBe("email");
176
177 expect((await patch({ email: "nope" })).status).toBe(422);
178 expect((await patch({ state: "lost", name: "Both" })).status).toBe(422);
179 expect((await patch({ name: "No Phone", email: "" }, undefined)).status).toBe(422);
180 expect((await patch({ name: "X" }, {})).status).toBe(401);
181 expect((await patch({ name: "X" }, undefined, { "sec-fetch-site": "cross-site" })).status).toBe(403);
182 // The state field still works as before.
183 expect((await patch({ state: "lost" })).status).toBe(200);
184
185 const other = await made();
186 const posted = await call(`/leads/${other.id}/edit`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ phone: "206 555 0111" }) });
187 expect(posted.status).toBe(200);
188 const f = new FormData();
189 f.set("name", "Form Name");
190 f.set("email", "[email protected]");
191 f.set("phone", "206 555 0111");
192 const form = await call(`/leads/${other.id}/edit`, { method: "POST", body: f, redirect: "manual" });
193 expect(form.status).toBe(303);
194 const cross = await call(`/leads/${other.id}/edit`, { method: "POST", body: f, headers: { "sec-fetch-site": "cross-site" } });
195 expect(cross.status).toBe(403);
196 const shown = (await (await call(`/leads/${other.id}`, { headers: { accept: "application/json" } })).json()) as { name: string };
197 expect(shown.name).toBe("Form Name");
198
199 const spec = (await (await call("/openapi.json")).json()) as { paths: Record<string, unknown> };
200 expect(Object.keys(spec.paths)).toContain("/leads/{id}/edit");
201 });
202
203 test("the page shows Edit details to whoever may use it, and the Activity page tells what changed", async () => {
204 const { id } = await made();
205 const alice = as("u-page", "alice");
206 const page = await (await call(`/leads/${id}`, {}, alice)).text();
207 expect(page).toContain("Edit details");
208 expect(page).toContain(`action="/leads/${id}/edit"`);
209 expect(page).toContain('value="[email protected]"');
210 expect(await (await call(`/leads/${id}`, {}, {})).text()).not.toContain("Edit details");
211
212 const f = new FormData();
213 f.set("name", "Dana <b>Reyes");
214 f.set("email", "[email protected]");
215 f.set("phone", "");
216 await call(`/leads/${id}/edit`, { method: "POST", body: f, redirect: "manual" }, alice);
217 const closed = await call(`/leads/${id}/state`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ state: "lost" }) }, alice);
218 expect(closed.status).toBe(200);
219 expect(await (await call(`/leads/${id}`, {}, alice)).text()).not.toContain("Edit details");
220
221 const activity = await (await call("/activity", {}, as("u0", "root", "admin"))).text();
222 expect(activity).toContain("alice corrected");
223 expect(activity).toContain("phone “(206) 555-0199” → nothing");
224 expect(activity).toContain("name “Dana Reys” → “Dana &lt;b&gt;Reyes”");
225 });
226
227 test("the MCP edits a lead, and refuses a stranger", async () => {
228 const { id } = await made();
229 const rpc = (who: Record<string, string>, args: unknown) =>
230 call("/mcp", {
231 method: "POST",
232 headers: JSON_HEADERS,
233 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "edit_lead", arguments: args } }),
234 }, who).then((r) => r.json() as Promise<any>);
235 const done = await rpc(as("u-mcp", "alice"), { id, name: "Via Mcp" });
236 expect(done.result.isError).toBeUndefined();
237 expect(JSON.stringify(done.result)).toContain("Via Mcp");
238 const refused = await rpc({}, { id, name: "Nope" });
239 expect(refused.result?.isError ?? true).toBe(true);
240 const bad = await rpc(as("u-mcp", "alice"), { id, email: "bad" });
241 expect(bad.result.isError).toBe(true);
242 });
243
244 test("the terminal fixes details with d, a step at a time, and the screen says what failed", () => {
245 const db = fresh();
246 const id = arrive(db);
247 const t = terminal(db, alice);
248 const read = () => t.screen(100).map(plain).join("\n");
249 t.key("\r");
250 expect(read()).toContain("d fix details");
251 t.key("d");
252 expect(read()).toContain("Name: Dana Reys█");
253 for (let i = 0; i < 2; i++) t.key("\x7f");
254 for (const ch of "yes") t.key(ch);
255 t.key("\r"); // email, kept
256 expect(read()).toContain("Email (empty takes it away): [email protected]█");
257 t.key("\r");
258 t.key("\r"); // the phone, kept: saves
259 expect(read()).toContain("Details saved");
260 expect(must(getLead(db, alice, { id })).name).toBe("Dana Reyes");
261 const closed = terminal(db, anon);
262 expect(closed.screen(100).map(plain).join("\n")).not.toContain("fix details");
263 });
src/leads.ts +48 −16
@@ -597,25 +597,57 @@ export function optOut(db: Database, found: Lead, at: string, agent: Agent): voi
597597 db.query(
598598 "UPDATE lead SET consent = 0, opted_out_at = coalesce(opted_out_at, ?1), updated_at = ?1 WHERE id = ?2",
599599 ).run(at, found.id);
600 const now = findLead(db, found.id)!;
601 const channel = channelFor(now);
602 const unsent = db
603 .query<{ id: number; day: number }, [number]>(
604 "SELECT id, day FROM message WHERE lead_id = ?1 AND status <> 'sent'",
605 )
606 .all(found.id);
607 for (const m of unsent)
608 db.query(
609 "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4",
610 ).run(
611 channel,
612 isAnswer(m.day) ? answerAgain(db, now, m.day) : draft(now, m.day, agent),
613 signature(channel, agent),
614 m.id,
615 );
600 redraftFor(db, findLead(db, found.id)!, agent, true);
616601 })();
617602 }
618603
604 /** What the agent can correct about a lead, as it is kept. */
605 export interface Contact {
606 readonly name: string;
607 readonly email: string;
608 readonly phone: string;
609 }
610
611 /**
612 * The lead's name, email and phone are corrected, and what is not yet sent
613 * follows: each unsent message goes by the channel the lead allows now (a
614 * text only with consent and a number) and is drafted again for the new
615 * details. An email for a lead left with no email stays an email, waiting
616 * for an address (the page says so). Sent messages stay as they were.
617 */
618 export function updateContact(db: Database, found: Lead, to: Contact, at: string, agent: Agent): void {
619 db.transaction(() => {
620 db.query(
621 "UPDATE lead SET name = ?1, email = ?2, phone = ?3, updated_at = ?4 WHERE id = ?5",
622 ).run(to.name, to.email, to.phone, at, found.id);
623 redraftFor(db, findLead(db, found.id)!, agent, false);
624 })();
625 }
626
627 /**
628 * Every message of `lead` not yet sent, drafted again by the channel it now
629 * allows. A message set aside (`skipped`) is included only when `aside` says so.
outdated

Avoid building SQL from a joined list; use bound parameters or fixed queries. Also confirm the opt-out status list equals the old <> sent.

630 */
631 function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): void {
632 const channel = channelFor(lead);
633 const unsent = db
634 .query<{ id: number; day: number }, [number]>(
635 aside
636 ? "SELECT id, day FROM message WHERE lead_id = ?1 AND status <> 'sent'"
637 : "SELECT id, day FROM message WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')",
638 )
639 .all(lead.id);
640 for (const m of unsent)
641 db.query(
642 "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4",
643 ).run(
644 channel,
645 isAnswer(m.day) ? answerAgain(db, lead, m.day) : draft(lead, m.day, agent),
646 signature(channel, agent),
647 m.id,
648 );
649 }
650
619651 /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */
620652 export function close(
621653 db: Database,
src/mcp.ts +18
@@ -14,6 +14,7 @@ import {
1414 getProfile,
1515 listLeads,
1616 saveProfile,
17 editLead,
1718 optOutTexts,
1819 approveReply,
1920 setState,
@@ -190,6 +191,23 @@ export const tools: readonly Tool[] = [
190191 run: (db, who, args) =>
191192 setState(db, who, { id: Number(args.id), state: args.state }),
192193 },
194 {
195 name: "edit_lead",
196 description:
197 "Correct a lead's name, email or phone (fields left out stay as they are; an empty email or phone takes it away, but one of them must remain). Unsent drafts follow the new details: with no phone, or after STOP, unsent texts become emails; with no email, unsent emails become texts only for a lead who agreed to be texted, otherwise they wait. Nothing is sent. The audit trail records the old and new values.",
198 inputSchema: {
199 type: "object",
200 properties: {
201 id: { type: "integer" },
202 name: { type: "string", minLength: 1, maxLength: 120 },
203 email: { type: "string", maxLength: 254 },
204 phone: { type: "string" },
205 },
206 required: ["id"],
207 },
208 run: (db, who, args) =>
209 editLead(db, who, { id: Number(args.id), name: args.name, email: args.email, phone: args.phone }),
210 },
193211 {
194212 name: "opt_out_texts",
195213 description:
src/pages/lead.ts +24 −2
@@ -55,7 +55,9 @@ export function leadPage(input: {
5555 const closed = lead.state === "qualified" || lead.state === "lost";
5656 const path = `/leads/${lead.id}`;
5757 const contact = [
58 `<a href="mailto:${escape(lead.email)}">${escape(lead.email)}</a>`,
58 ...(lead.email === ""
59 ? []
60 : [`<a href="mailto:${escape(lead.email)}">${escape(lead.email)}</a>`]),
5961 ...(lead.phone === ""
6062 ? []
6163 : [`<a href="tel:${escape(lead.phone.replace(/[^\d+]/g, ""))}">${escape(lead.phone)}</a>`]),
@@ -90,7 +92,9 @@ export function leadPage(input: {
9092 : ""
9193 }
9294 ${
93 channelFor(lead) === "email"
95 ready.channel === "email" && lead.email === ""
96 ? `<p class="hint">No email address on file, and they have not agreed to be texted: this waits until you add an address or call them.</p>`
97 : channelFor(lead) === "email"
9498 ? `<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>`
9599 : ""
96100 }
@@ -194,6 +198,8 @@ export function leadPage(input: {
194198 </details>`
195199 : "";
196200
201 const details = editDetails(lead, path, mayUpdate && !closed);
202
197203 const min = new Date(now).toISOString().slice(0, 16);
198204 const max = new Date(now + MAX_AHEAD_DAYS * 86_400_000).toISOString().slice(0, 16);
199205 const showing =
@@ -264,6 +270,7 @@ export function leadPage(input: {
264270 ${call}
265271 ${showing}
266272 ${record}
273 ${details}
267274 ${plan}
268275 ${states}
269276 ${stop}
@@ -271,6 +278,21 @@ export function leadPage(input: {
271278 });
272279 }
273280
281 /** "Edit details": the lead's name, email and phone, for whoever may update it. */
282 function editDetails(lead: LeadDetail, path: string, may: boolean): string {
283 if (!may) return "";
284 return `<details class="card add record" id="edit-details">
285 <summary>Edit details</summary>
286 <form class="stack" method="post" action="${path}/edit">
287 <label>Name <input class="input" name="name" value="${escape(lead.name)}" required maxlength="120"></label>
288 <label>Email <input class="input" type="email" name="email" value="${escape(lead.email)}" maxlength="254"></label>
289 <label>Phone <input class="input" type="tel" name="phone" value="${escape(lead.phone)}" maxlength="20"></label>
290 <p class="hint">Clear email or phone to take it away; one of them must stay. Unsent drafts follow the new details: with no phone, texts become emails.</p>
291 <button class="button">Save details</button>
292 </form>
293 </details>`;
294 }
295
274296 const PLAN: Readonly<Record<Message["status"], string>> = {
275297 draft: "Drafted",
276298 scheduled: "Upcoming",
src/routes.ts +45 −6
@@ -18,6 +18,7 @@ import {
1818 addSampleInquiry,
1919 deleteLead,
2020 activity,
21 editLead,
2122 getAudit,
2223 getLead,
2324 getProfile,
@@ -305,6 +306,10 @@ export const AUDIT_ROW: Schema = {
305306 allowed: { enum: [0, 1] },
306307 outcome: { type: "string" },
307308 act: { type: ["string", "null"] },
309 detail: {
310 type: ["string", "null"],
311 description: "For a correction of a lead's details: the fields changed, as JSON, each with its old and new value.",
312 },
308313 },
309314 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
310315 };
@@ -391,6 +396,16 @@ async function readFields(
391396 );
392397 }
393398
399 /** The details an edit may carry, and the fields of them that a body names. */
outdated

This doc comment belongs to posted below; it is now orphaned above the CONTACT block. Move it back.

400 const CONTACT = ["name", "email", "phone"] as const;
401 const contactOf = (input: Record<string, unknown>): Record<string, unknown> =>
402 Object.fromEntries(CONTACT.filter((f) => input[f] !== undefined).map((f) => [f, input[f]]));
403 const EDIT_FIELDS = {
404 name: { type: "string", minLength: 1, maxLength: 120 },
405 email: { type: "string", maxLength: 254, description: "Empty takes it away, if a phone remains." },
406 phone: { type: "string", description: "7 to 20 digits; empty takes it away, if an email remains." },
407 } as const;
408
394409 /** One POST, answered for whoever sent it: JSON to a script, back to the page for a form. */
395410 const posted = async <T>(
396411 c: Context,
@@ -533,16 +548,24 @@ export const routes: readonly Route[] = [
533548 handle: async (c) => {
534549 const body = await readJson(c.request);
535550 if (body === undefined) return json({ error: "too_large" }, 413);
536 return answer(
537 setState(c.db, c.who, { id: ID(c), state: fields(body).state }),
538 );
551 const input = fields(body);
552 // One change at a time: a mark, or a correction of the details.
553 const details = CONTACT.some((field) => input[field] !== undefined);
554 if (details && input.state !== undefined)
555 return json(
556 { error: "invalid", message: "Send a state, or details to correct, not both." },
557 422,
558 );
559 if (details)
560 return answer(editLead(c.db, c.who, { id: ID(c), ...contactOf(input) }));
561 return answer(setState(c.db, c.who, { id: ID(c), state: input.state }));
539562 },
540563 api: {
541 summary: "Mark a lead qualified or lost (the same as POST /leads/{id}/state).",
564 summary:
565 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
542566 body: {
543567 type: "object",
544 properties: { state: { enum: ["qualified", "lost", "open"] } },
545 required: ["state"],
568 properties: { state: { enum: ["qualified", "lost", "open"] }, ...EDIT_FIELDS },
546569 },
547570 answer: LEAD,
548571 },
@@ -728,6 +751,22 @@ export const routes: readonly Route[] = [
728751 answer: LEAD,
729752 },
730753 },
754 {
755 method: "POST",
756 path: "/leads/:id/edit",
757 handle: (c) =>
758 posted(
759 c,
760 (input) => editLead(c.db, c.who, { id: ID(c), ...contactOf(input) }),
761 () => ({ to: `/leads/${ID(c)}`, said: "Details saved. Unsent drafts follow them." }),
762 ),
763 api: {
764 summary:
765 "Correct a lead's name, email or phone (a field left out stays as it is; an empty email or phone takes it away, but one of them must remain). Unsent drafts follow the new details: with no phone, or after STOP, unsent texts become emails; with no email, unsent emails become texts only where the lead agreed to be texted, otherwise they wait. The audit trail names the fields changed.",
766 body: { type: "object", properties: EDIT_FIELDS },
767 answer: LEAD,
768 },
769 },
731770 {
732771 method: "POST",
733772 path: "/leads/:id/opt-out",
src/sentences.ts +24
@@ -7,6 +7,23 @@
77
88 import type { AuditRow } from "./audit.ts";
99
10 /** What a correction changed, as ": phone “a” → “b”, …"; "" when the row names nothing readable. */
11 function changeWords(detail: string | null, esc: (text: string) => string): string {
12 let changes: unknown;
13 try {
14 changes = JSON.parse(detail ?? "");
15 } catch {
16 return "";
17 }
18 if (typeof changes !== "object" || changes === null) return "";
19 const shown = (v: unknown): string => (v === "" || typeof v !== "string" ? "nothing" : `“${esc(v)}”`);
20 const parts = Object.entries(changes).map(([field, change]) => {
21 const { from, to } = (change ?? {}) as { from?: unknown; to?: unknown };
22 return `${esc(field)} ${shown(from)} → ${shown(to)}`;
23 });
24 return parts.length === 0 ? "" : `: ${parts.join(", ")}`;
25 }
26
1027 export function deed(
1128 row: AuditRow,
1229 lead: string,
@@ -40,6 +57,13 @@ export function deed(
4057 done: `logged a call with ${lead}`,
4158 tried: `log a call with ${lead}`,
4259 };
60 if (row.act === "edited") {
61 const said = changeWords(row.detail, esc);
62 return {
63 done: `corrected ${lead}'s details${said}`,
64 tried: `correct ${lead}'s details`,
65 };
66 }
4367 if (row.act === "showing")
4468 return {
4569 done: `booked a showing with ${lead}`,
src/server.test.ts +1
@@ -292,6 +292,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
292292 "book_showing",
293293 "cancel_showing",
294294 "mark_lead",
295 "edit_lead",
295296 "opt_out_texts",
296297 "get_profile",
297298 "set_profile",
src/terminal.ts +55
@@ -27,6 +27,7 @@ import {
2727 addLead,
2828 addSampleInquiry,
2929 deleteLead,
30 editLead,
3031 getLead,
3132 getProfile,
3233 listLeads,
@@ -122,9 +123,17 @@ type View =
122123 | { name: "call"; id: number; outcome: Outcome; text: string }
123124 | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string }
124125 | { name: "wrote"; id: number; text: string; channel: Channel }
126 | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> }
125127 | { name: "add"; step: number; typed: string; fields: Record<string, string> }
126128 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
127129
130 /** The details the agent can correct, in the order asked. */
131 const DETAIL_FIELDS = [
132 { key: "name", label: "Name" },
133 { key: "email", label: "Email (empty takes it away)" },
134 { key: "phone", label: "Phone (empty takes it away)" },
135 ] as const;
136
128137 const titleOf = (m: Message): string =>
129138 m.day === 0
130139 ? "First reply"
@@ -249,6 +258,10 @@ export function terminal(
249258 return lines;
250259 }
251260
261 /** Whether details can be corrected here: the table says yes and the lead is still open. */
262 const mayEdit = (l: LeadDetail): boolean =>
263 permit(me, "lead", "update", { ...l }) === "yes" && !CLOSED.includes(l.state);
264
252265 function leadScreen(id: number, width: number, editing?: string): string[] {
253266 const l = lead(id);
254267 if (l === undefined) {
@@ -334,6 +347,7 @@ export function terminal(
334347 ...(l.state === "qualified" || l.state === "lost"
335348 ? ["o put back in follow-ups"]
336349 : ["q qualified", "x lost"]),
350 ...(mayEdit(l) ? ["d fix details"] : []),
337351 ...(l.consent ? ["t they asked to stop texts"] : []),
338352 ...(nextLead(db, me, { except: l.id }) === null ? [] : ["] next that needs you"]),
339353 ...(admin() ? ["D remove"] : []),
@@ -404,6 +418,16 @@ export function terminal(
404418 return lines;
405419 }
406420
421 function detailsScreen(v: Extract<View, { name: "details" }>): string[] {
422 const lines = [bold(`Fix ${clean(lead(v.id)?.name ?? "the lead")}'s details`), ""];
423 DETAIL_FIELDS.forEach((field, i) => {
424 if (i < v.step) lines.push(`${field.label}: ${clean(v.fields[field.key] ?? "")}`);
425 if (i === v.step) lines.push(`${field.label}: ${clean(v.typed)}█`);
426 });
427 lines.push("", dim("enter next, the last one saves · esc cancel"));
428 return lines;
429 }
430
407431 function addScreen(v: Extract<View, { name: "add" }>): string[] {
408432 const lines = [bold("Log a lead by hand"), ""];
409433 ADD_FIELDS.forEach((field, i) => {
@@ -494,6 +518,8 @@ export function terminal(
494518 "",
495519 dim("type a note · enter new line · ctrl-o outcome · ctrl-d log the call · esc cancel"),
496520 ]
521 : view.name === "details"
522 ? detailsScreen(view)
497523 : view.name === "add"
498524 ? addScreen(view)
499525 : [
@@ -632,6 +658,8 @@ export function terminal(
632658 said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message;
633659 } else if (input === "w")
634660 view = { name: "wrote", id, text: "", channel: "email" };
661 else if (input === "d" && mayEdit(l))
662 view = { name: "details", id, step: 0, typed: l.name, fields: {} };
635663 else if (input === "o" && CLOSED.includes(l.state)) {
636664 const back = setState(db, me, { id, state: "open" });
637665 said = back.ok ? `${l.name}: back in follow-ups.` : back.message;
@@ -732,6 +760,33 @@ export function terminal(
732760 }
733761 return;
734762 }
763 case "details": {
764 if (input === "\x1b") {
765 said = "Nothing changed.";
766 view = { name: "lead", id: view.id };
767 } else if (input === "\r") {
768 const field = DETAIL_FIELDS[view.step]!;
769 const fields = { ...view.fields, [field.key]: view.typed.trim() };
770 const following = DETAIL_FIELDS[view.step + 1];
771 if (following !== undefined) {
772 const l = lead(view.id);
773 view = {
774 ...view,
775 step: view.step + 1,
776 typed: l === undefined ? "" : l[following.key],
777 fields,
778 };
779 } else {
780 const saved = editLead(db, me, { id: view.id, ...fields });
781 said = saved.ok ? "Details saved. Unsent drafts follow them." : saved.message;
782 view = saved.ok ? { name: "lead", id: view.id } : { ...view, step: 0, typed: fields.name ?? "", fields: {} };
783 }
784 } else {
785 const next = typing(view.typed, input);
786 if (next !== undefined) view = { ...view, typed: next };
787 }
788 return;
789 }
735790 case "add": {
736791 if (input === "\x1b") {
737792 said = "Nothing logged.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs