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

A lead who writes in again with the same email or phone lands on their existing lead, not as a second one #53

Merged opened this

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

Merged

mason/speed-to-lead:mason/50-a-lead-who-writes-in-again-with-the-same → main 4 commits fork

  • Merged. mason/50-a-lead-who-writes-in-again-with-the-same was merged into main as 8a18d73.

Review

Sign in to review this change.
20 files changed +339 −60
README.md +12
@@ -193,6 +193,18 @@ written again as an email, and sent messages stay in the history as they
193193 were. It is one-way: the app has no button to turn texting back on (new
194194 written consent comes with a new inquiry), and asking twice changes nothing.
195195
196 **When someone writes in twice**, they stay one lead. A new arrival (desk
197 form, pasted email, inbound webhook, MCP, terminal) whose email matches an
198 existing lead in any letter case, or whose phone has the same digits, adds no
199 row: their message joins that lead's history, a qualified or lost lead is
200 reopened, a fresh reply is drafted, the lead moves back to the top of the desk,
201 and the page says "Dana P. wrote in again". An open lead is preferred to a
202 closed one. The audit log records one `merged` event naming the arrival's
203 source and the lead. A name alone never merges. Two people who share a phone
204 (a family) do merge unless one gives another number, so give each their own.
205 The "Add a sample inquiry" button always adds a new person, with an address
206 and number of its own, once the set of examples is used up.
207
196208 **Your signature** goes on every message, and can't be edited off: your
197209 name, brokerage and license number, as state advertising rules require.
198210 Texts also say "Reply STOP to opt out."
src/actions.test.ts +26 −18
@@ -40,6 +40,14 @@ const maria = {
4040 message: "Is 418 Juniper Ln still available? Could we see it this weekend?",
4141 consent: true,
4242 };
43 /** A distinct address per name, so leads the test adds are not one person writing in again. */
44 const mail = (name: string): string => `${name.toLowerCase().replace(/\W+/g, ".")}@example.com`;
45 /** A number of its own for each name, so two test leads are never one person on the phone. */
46 const numbers = new Map<string, string>();
47 const phoneOf = (name: string): string => {
48 if (!numbers.has(name)) numbers.set(name, `(206) 555-${String(2000 + numbers.size).padStart(4, "0")}`);
49 return numbers.get(name)!;
50 };
4351 const must = <T>(r: { ok: true; value: T } | { ok: false; message: string }): T => {
4452 if (!r.ok) throw new Error(r.message);
4553 return r.value;
@@ -83,8 +91,8 @@ test("a stranger may not see or add leads; a signed-in person may", () => {
8391
8492 test("control characters are refused at the boundary; a textarea's line breaks are kept", () => {
8593 for (const bad of [
86 { ...maria, name: "Eve\x1b[2J" },
87 { ...maria, name: "Eve\nNewline" },
94 { ...maria, name: "Eve\x1b[2J", email: mail("Eve\x1b[2J"), phone: phoneOf("Eve\x1b[2J") },
95 { ...maria, name: "Eve\nNewline", email: mail("Eve\nNewline"), phone: phoneOf("Eve\nNewline") },
8896 { ...maria, email: "[email protected]\x07" },
8997 { ...maria, phone: "555\x9b2J0101" },
9098 { ...maria, message: "hi\x1b]52;c;aGk=\x07" },
@@ -99,7 +107,7 @@ test("control characters are refused at the boundary; a textarea's line breaks a
99107 "line one\nline two\tok",
100108 );
101109 // An edited reply is held to the same.
102 const lead = must(addLead(db, alice, { ...maria, name: "Plain Text" }, at(0)));
110 const lead = must(addLead(db, alice, { ...maria, name: "Plain Text", email: mail("Plain Text"), phone: phoneOf("Plain Text") }, at(0)));
103111 const r = sendReply(db, alice, { id: lead.id, body: "Hi\x1b[2J" }, at(0, 1));
104112 expect(r.ok).toBe(false);
105113 if (!r.ok) expect(r.error).toBe("invalid");
@@ -124,7 +132,7 @@ test("a new lead arrives with its first reply drafted, signed, by text when they
124132 });
125133
126134 test("approve and send: the reply goes, the clock stops, and the cadence is drafted", () => {
127 const lead = must(addLead(db, alice, { ...maria, name: "Sam Ortiz" }, at(0)));
135 const lead = must(addLead(db, alice, { ...maria, name: "Sam Ortiz", email: mail("Sam Ortiz"), phone: phoneOf("Sam Ortiz") }, at(0)));
128136 const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1)));
129137 expect(sent.state).toBe("contacted");
130138 expect(sent.replied_at).toBe(at(0, 1).toISOString());
@@ -147,13 +155,13 @@ test("approve and send: the reply goes, the clock stops, and the cadence is draf
147155 });
148156
149157 test("an edit is what goes out, with the signature still on it", () => {
150 const lead = must(addLead(db, alice, { ...maria, name: "Ana Diaz" }, at(0)));
158 const lead = must(addLead(db, alice, { ...maria, name: "Ana Diaz", email: mail("Ana Diaz"), phone: phoneOf("Ana Diaz") }, at(0)));
151159 const sent = must(
152160 sendReply(db, alice, { id: lead.id, body: " Hi Ana — free Saturday at 10? " }, at(0, 1)),
153161 );
154162 expect(sent.messages[0]!.body).toBe("Hi Ana — free Saturday at 10?");
155163 expect(sent.messages[0]!.signature).toContain(agent.license);
156 const lead2 = must(addLead(db, alice, { ...maria, name: "Bo Lin" }, at(0)));
164 const lead2 = must(addLead(db, alice, { ...maria, name: "Bo Lin", email: mail("Bo Lin"), phone: phoneOf("Bo Lin") }, at(0)));
157165 for (const body of [" ", "x".repeat(481)]) {
158166 const r = sendReply(db, alice, { id: lead2.id, body }, at(0, 1));
159167 expect(r.ok).toBe(false);
@@ -163,14 +171,14 @@ test("an edit is what goes out, with the signature still on it", () => {
163171
164172 test("no text is drafted without consent: email only, from first reply to last touch", () => {
165173 const lead = must(
166 addLead(db, alice, { ...maria, name: "No Consent", consent: false }, at(0)),
174 addLead(db, alice, { ...maria, name: "No Consent", email: mail("No Consent"), phone: phoneOf("No Consent"), consent: false }, at(0)),
167175 );
168176 expect(lead.messages[0]!.channel).toBe("email");
169177 const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1)));
170178 expect(sent.messages.every((m) => m.channel === "email")).toBe(true);
171179 // Consent without a number to text is still email.
172180 const noPhone = must(
173 addLead(db, alice, { ...maria, name: "No Phone", phone: "" }, at(0)),
181 addLead(db, alice, { ...maria, name: "No Phone", email: mail("No Phone"), phone: "" }, at(0)),
174182 );
175183 expect(noPhone.messages[0]!.channel).toBe("email");
176184 // And the file refuses a text for them, whatever asks.
@@ -182,7 +190,7 @@ test("no text is drafted without consent: email only, from first reply to last t
182190 });
183191
184192 test("the day turns: a touch comes due on its day, once, and is sent when approved", () => {
185 const lead = must(addLead(db, alice, { ...maria, name: "Cadence Test" }, at(0)));
193 const lead = must(addLead(db, alice, { ...maria, name: "Cadence Test", email: mail("Cadence Test"), phone: phoneOf("Cadence Test") }, at(0)));
186194 must(sendReply(db, alice, { id: lead.id }, at(0)));
187195 expect(must(tick(db, alice, at(0, 30))).leads).not.toContain(lead.id);
188196 expect(must(tick(db, alice, at(1, 1))).leads).toContain(lead.id);
@@ -199,7 +207,7 @@ test("the day turns: a touch comes due on its day, once, and is sent when approv
199207 });
200208
201209 test("qualified or lost leaves the cadence", () => {
202 const lead = must(addLead(db, alice, { ...maria, name: "Leaving" }, at(0)));
210 const lead = must(addLead(db, alice, { ...maria, name: "Leaving", email: mail("Leaving"), phone: phoneOf("Leaving") }, at(0)));
203211 must(sendReply(db, alice, { id: lead.id }, at(0)));
204212 must(tick(db, alice, at(3, 1)));
205213 const closed = must(setState(db, alice, { id: lead.id, state: "qualified" }));
@@ -273,7 +281,7 @@ test("the desk's views: each lists exactly its leads, counts add up, a bad value
273281 });
274282
275283 test("reopening a closed lead reschedules the unsent cadence from now, never in a burst", () => {
276 const lead = must(addLead(db, alice, { ...maria, name: "Comes Back" }, at(0)));
284 const lead = must(addLead(db, alice, { ...maria, name: "Comes Back", email: mail("Comes Back"), phone: phoneOf("Comes Back") }, at(0)));
277285 must(sendReply(db, alice, { id: lead.id }, at(0)));
278286 must(tick(db, alice, at(1, 1)));
279287 must(sendReply(db, alice, { id: lead.id }, at(1, 1)));
@@ -294,7 +302,7 @@ test("reopening a closed lead reschedules the unsent cadence from now, never in
294302 });
295303
296304 test("reopening a lead that was never answered makes it new with its first reply drafted", () => {
297 const lead = must(addLead(db, alice, { ...maria, name: "Never Answered" }, at(0)));
305 const lead = must(addLead(db, alice, { ...maria, name: "Never Answered", email: mail("Never Answered"), phone: phoneOf("Never Answered") }, at(0)));
298306 must(setState(db, alice, { id: lead.id, state: "lost" }));
299307 expect(must(getLead(db, alice, { id: lead.id })).messages[0]!.status).toBe("skipped");
300308 const back = must(setState(db, alice, { id: lead.id, state: "open" }));
@@ -304,7 +312,7 @@ test("reopening a lead that was never answered makes it new with its first reply
304312 });
305313
306314 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)));
315 const lead = must(addLead(db, alice, { ...maria, name: "Says Stop", email: mail("Says Stop"), phone: phoneOf("Says Stop") }, at(0)));
308316 const first = must(sendReply(db, alice, { id: lead.id, body: "Hi, edited." }, at(0)));
309317 const sentBefore = first.messages.find((m) => m.status === "sent")!;
310318 expect(sentBefore.channel).toBe("text");
@@ -327,7 +335,7 @@ test("opting out turns every unsent text into an email and leaves what was sent
327335 });
328336
329337 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)));
338 const lead = must(addLead(db, alice, { ...maria, name: "Quiet Now", email: mail("Quiet Now"), phone: phoneOf("Quiet Now") }, at(0)));
331339 must(sendReply(db, alice, { id: lead.id }, at(0)));
332340 must(optOutTexts(db, alice, { id: lead.id }, at(0, 5)));
333341 must(tick(db, alice, at(40)));
@@ -336,7 +344,7 @@ test("an opted-out lead is never texted: not by tick, not by putting a closed le
336344 const back = must(setState(db, alice, { id: lead.id, state: "open" }, at(42)));
337345 expect(back.messages.filter((m) => m.status !== "sent").every((m) => m.channel === "email")).toBe(true);
338346 // 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)));
347 const again = must(addLead(db, alice, { ...maria, name: "Quiet Now", email: "[email protected]" }, at(43)));
340348 expect(again.id).not.toBe(lead.id);
341349 const old = must(getLead(db, alice, { id: lead.id }));
342350 expect(old.consent).toBe(false);
@@ -346,11 +354,11 @@ test("an opted-out lead is never texted: not by tick, not by putting a closed le
346354 });
347355
348356 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)));
357 const lead = must(addLead(db, alice, { ...maria, name: "Twice", email: mail("Twice"), phone: phoneOf("Twice") }, at(0)));
350358 const one = must(optOutTexts(db, alice, { id: lead.id }, at(1)));
351359 const two = must(optOutTexts(db, alice, { id: lead.id }, at(2)));
352360 expect(two).toEqual(one);
353 const never = must(addLead(db, alice, { ...maria, name: "Never", consent: false }, at(0)));
361 const never = must(addLead(db, alice, { ...maria, name: "Never", email: mail("Never"), phone: phoneOf("Never"), consent: false }, at(0)));
354362 const refused = optOutTexts(db, alice, { id: never.id });
355363 expect(refused.ok).toBe(false);
356364 expect(!refused.ok && refused.error).toBe("invalid");
@@ -359,7 +367,7 @@ test("opting out twice is harmless; a lead that never consented has nothing to s
359367 });
360368
361369 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)));
370 const lead = must(addLead(db, alice, { ...maria, name: "Audited Stop", email: mail("Audited Stop"), phone: phoneOf("Audited Stop") }, at(0)));
363371 must(optOutTexts(db, alice, { id: lead.id }, at(1)));
364372 const row = db
365373 .query<{ act: string; who_name: string; outcome: string }, [string]>(
src/actions.ts +26 −6
@@ -8,7 +8,7 @@
88
99 import type { Database } from "bun:sqlite";
1010 import { csvName, leadsCsv } from "./export.ts";
11 import { record, type Act, type AuditRow } from "./audit.ts";
11 import { mergeDetail, record, type Act, type AuditRow } from "./audit.ts";
1212 import { MAX_NOTE, outcomeOf } from "./calls.ts";
1313 import { permit } from "./contract.ts";
1414 import {
@@ -42,7 +42,9 @@ import {
4242 MAX_INBOUND,
4343 MAX_LEAD_NOTE,
4444 MAX_QUERY,
45 findMatch,
4546 insertLead,
47 writeInAgain,
4648 lastMessages,
4749 updateContact,
4850 writeNote,
@@ -284,24 +286,43 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> {
284286 });
285287 }
286288
289 /** A lead added; `again` when it was someone already on the desk who wrote in again. */
290 export type Added = LeadDetail & { readonly again?: true };
291
292 /**
293 * A lead arrives. Someone already on the desk (same email, or the same phone
294 * when no email came) is not made twice: their message joins that lead's
295 * history, a closed lead is reopened, and the trail records one `merged`.
296 */
287297 export const addLead = (
288298 db: Database,
289299 who: Who,
290300 input: Record<string, unknown>,
291301 at?: Date,
292 ): Result<LeadDetail> =>
293 audited(db, who, "lead", "create", undefined, add(db, who, input, at));
302 ): Result<Added> => {
303 const result = add(db, who, input, at);
304 if (!result.ok || result.value.again !== true)
305 return audited(db, who, "lead", "create", undefined, result);
306 const detail = mergeDetail({ source: sourceOf(input.source)!, lead: result.value.id });
307 return audited(db, who, "lead", "create", undefined, result, "merged", detail);
308 };
294309
295310 function add(
296311 db: Database,
297312 who: Who,
298313 input: Record<string, unknown>,
299314 at?: Date,
300 ): Result<LeadDetail> {
315 ): Result<Added> {
301316 if (permit(who, "lead", "create") !== "yes")
302317 return refuse(who, "Sign in to add a lead.", "You may not add a lead.");
303318 const read = readNewLead(input);
304319 if (!read.ok) return read;
320 const known = findMatch(db, read.value);
321 if (known !== null) {
322 writeInAgain(db, known, read.value.message, stamp(at), currentAgent(db));
323 emit("lead.changed", { id: known.id });
324 return ok({ ...detail(db, known.id)!, again: true });
325 }
305326 const id = insertLead(db, read.value, stamp(at), currentAgent(db));
306327 const added = detail(db, id)!;
307328 emit("lead.added", { id });
@@ -454,8 +475,7 @@ export const addSampleInquiry = (
454475 db: Database,
455476 who: Who,
456477 at?: Date,
457 ): Result<LeadDetail> =>
458 audited(db, who, "lead", "create", undefined, add(db, who, nextInquiry(db), at));
478 ): Result<Added> => addLead(db, who, nextInquiry(db), at);
459479
460480 /**
461481 * Approve and send what is ready for this lead — the first reply, or the
src/audit.test.ts +3 −3
@@ -204,7 +204,7 @@ const admin = { id: "u0", name: "Jordan <b>Avery", role: "admin" as const };
204204
205205 test("/activity: an admin reads a sent reply and a refused attempt in sentences; a user is refused; a visitor is asked to sign in", async () => {
206206 const lead = (await (
207 await call("/leads", { method: "POST", body: JSON.stringify({ ...NEW, name: "Maria <script>x</script>" }) }, alice)
207 await call("/leads", { method: "POST", body: JSON.stringify({ ...NEW, name: "Maria <script>x</script>", email: "[email protected]" }) }, alice)
208208 ).json()) as { id: number };
209209 await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" }, root);
210210 await call(`/leads/${lead.id}/state`, { method: "POST", body: JSON.stringify({ state: "lost" }) }, root);
@@ -257,8 +257,8 @@ const admin0: Who = { role: "admin", id: "u0", name: "root" };
257257 test("act is recorded as first_reply, reply, qualified and lost", () => {
258258 const db = openDb(mkdtempSync(join(tmpdir(), "app-audit-act-")));
259259 const one = addLead(db, admin0, NEW);
260 const two = addLead(db, admin0, { ...NEW, name: "Second" });
261 const three = addLead(db, admin0, { ...NEW, name: "Third" });
260 const two = addLead(db, admin0, { ...NEW, name: "Second", email: "[email protected]" });
261 const three = addLead(db, admin0, { ...NEW, name: "Third", email: "[email protected]" });
262262 if (!one.ok || !two.ok || !three.ok) throw new Error("setup");
263263 sendReply(db, admin0, { id: one.value.id });
264264 // Later touches are due days after; send the next one by moving time on.
src/audit.ts +20 −2
@@ -34,10 +34,28 @@ export interface AuditRow {
3434 readonly detail: string | null;
3535 }
3636
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; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `openers` is a change to how first replies open (the profile). */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "noted"] 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; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile). */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "noted", "merged"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
41 /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */
42 export interface MergeDetail {
43 readonly source: string;
44 readonly lead: number;
45 }
46
47 export const mergeDetail = (detail: MergeDetail): string => JSON.stringify(detail);
48
49 /** A `merged` row's detail read back; null when it holds no source. */
50 export function readMergeDetail(detail: string | null): MergeDetail | null {
51 try {
52 const { source, lead } = JSON.parse(detail ?? "") as Partial<MergeDetail>;
53 return typeof source === "string" && typeof lead === "number" ? { source, lead } : null;
54 } catch {
55 return null;
56 }
57 }
58
4159 export interface Attempt {
4260 readonly who: Who;
4361 readonly resource: string;
src/calls.test.ts +8 −6
@@ -31,14 +31,16 @@ const MIN = 60_000;
3131 const DAY = 86_400_000;
3232
3333 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-calls-")));
34 const arrive = (db: ReturnType<typeof fresh>, phone = "(206) 555-0199") => {
34 /** Each arrival is a different person, not one writing in again. */
35 let arrivals = 0;
36 const arrive = (db: ReturnType<typeof fresh>, phone?: string) => {
3537 const made = addLead(
3638 db,
3739 alice,
3840 {
3941 name: "Dana Reyes",
40 email: "[email protected]",
41 phone,
42 email: `dana${++arrivals}@example.com`,
43 phone: phone ?? `(206) 555-${String(1000 + arrivals).padStart(4, "0")}`,
4244 source: "zillow",
4345 message: "Can I see 12 Oak Street this week?",
4446 consent: true,
@@ -179,11 +181,11 @@ const api = (path: string, init: RequestInit = {}, headers: Record<string, strin
179181 };
180182 const json = (path: string, body: unknown) =>
181183 api(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
182 const served = async (phone = "206 555 0111"): Promise<number> => {
184 const served = async (phone?: string): Promise<number> => {
183185 const made = await json("/leads", {
184186 name: "Pat <i>Lee</i>",
185 email: "[email protected]",
186 phone,
187 email: `pat${++arrivals}@example.com`,
188 phone: phone ?? `206 555 ${String(1000 + arrivals).padStart(4, "0")}`,
187189 source: "website",
188190 message: "Do you have time to talk this week?",
189191 consent: false,
src/details.test.ts +2 −1
@@ -25,6 +25,7 @@ const NEW = {
2525 message: "Can I see 12 Oak Street this week?",
2626 consent: true,
2727 };
28 let arrivals = 0;
2829 const T0 = new Date("2026-03-01T10:00:00Z");
2930
3031 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-details-")));
@@ -33,7 +34,7 @@ const must = <T>(r: Result<T>): T => {
3334 return r.value;
3435 };
3536 const arrive = (db: ReturnType<typeof fresh>, over: Record<string, unknown> = {}) =>
36 must(addLead(db, alice, { ...NEW, ...over }, T0)).id;
37 must(addLead(db, alice, { ...NEW, ...(over.email !== undefined && over.phone === undefined ? { phone: `(206) 555-${String(3000 + ++arrivals).padStart(4, "0")}` } : {}), ...over }, T0)).id;
3738 const audits = (db: ReturnType<typeof fresh>) =>
3839 db.query<AuditRow, []>("SELECT * FROM audit WHERE act = 'edited'").all();
3940
src/inbound.test.ts +6 −4
@@ -32,11 +32,13 @@ const MIN = 60_000;
3232 const DAY = 86_400_000;
3333
3434 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-inbound-")));
35 /** Each arrival is a different person, not one writing in again. */
36 let arrivals = 0;
3537 const arrive = (db: ReturnType<typeof fresh>, consent: boolean) => {
3638 const made = addLead(db, alice, {
3739 name: "Dana Reyes",
38 email: "[email protected]",
39 phone: "(206) 555-0199",
40 email: `dana${++arrivals}@example.com`,
41 phone: `(206) 555-${String(1000 + arrivals).padStart(4, "0")}`,
4042 source: "zillow",
4143 message: "Can I see 12 Oak Street this week?",
4244 consent,
@@ -209,8 +211,8 @@ const json = (path: string, body: unknown) =>
209211 const served = async (consent = true): Promise<number> => {
210212 const made = await json("/leads", {
211213 name: "Pat <i>Lee</i>",
212 email: "[email protected]",
213 phone: "206 555 0111",
214 email: `pat${++arrivals}@example.com`,
215 phone: `206 555 ${String(1000 + arrivals).padStart(4, "0")}`,
214216 source: "website",
215217 message: "Do you have time to talk this week?",
216218 consent,
src/leads.test.ts +101 −1
@@ -9,7 +9,9 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { openDb } from "./db.ts";
1111 import { agent } from "./env.ts";
12 import { findLead, insertLead, readyFor, responseRecord, send } from "./leads.ts";
12 import { findLead, findMatch, insertLead, readyFor, responseRecord, send } from "./leads.ts";
13 import { addLead, listAudit, listLeads, setState } from "./actions.ts";
14 import type { Who } from "./who.ts";
1315 import { recordLine, sourceLine } from "./clock.ts";
1416
1517 const NOW = Date.parse("2026-10-30T12:00:00.000Z");
@@ -84,6 +86,104 @@ test("leads older than 30 days are not in the record", () => {
8486 expect(responseRecord(db, NOW)).toMatchObject({ leads: 1, median_ms: 1 * M, within_5_min_pct: 100 });
8587 });
8688
89 const me: Who = { role: "admin", id: "u1", name: "alice" };
90 const ADMIN = me;
91 const arrive = (db: ReturnType<typeof fresh>, over: Record<string, unknown> = {}) =>
92 addLead(db, me, { name: "Dana P.", email: "[email protected]", phone: "", source: "website", message: "Is it still for sale?", ...over });
93 const count = (db: ReturnType<typeof fresh>) =>
94 db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM lead").get()!.n;
95
96 test("the same email in another case is the same lead, with the message added and a fresh draft", () => {
97 const db = fresh();
98 const first = arrive(db);
99 const again = arrive(db, { email: "[email protected]", source: "zillow", message: "Can I see it Sunday?" });
100 expect(first.ok && again.ok).toBe(true);
101 if (!first.ok || !again.ok) return;
102 expect(count(db)).toBe(1);
103 expect(again.value.id).toBe(first.value.id);
104 expect(again.value.again).toBe(true);
105 expect(first.value.again).toBeUndefined();
106 expect(again.value.replies.map((r) => r.body)).toEqual(["Can I see it Sunday?"]);
107 expect(again.value.messages.some((m) => m.status === "draft" && m.day > 0)).toBe(true);
108 });
109
110 test("the same phone typed differently is the same lead, whatever email comes with it", () => {
111 const db = fresh();
112 const first = arrive(db, { phone: "(555) 010-2030" });
113 const again = arrive(db, { email: "[email protected]", phone: "555.010.2030", message: "Writing from work." });
114 if (!first.ok || !again.ok) throw new Error("refused");
115 expect(count(db)).toBe(1);
116 expect(again.value.id).toBe(first.value.id);
117 expect(again.value.again).toBe(true);
118 expect(findMatch(db, { name: "Dana", email: "", phone: "+1 555 010 2030" })).toBeNull();
119 expect(findMatch(db, { name: "Dana", email: "", phone: "555 010 9999" })).toBeNull();
120 expect(findMatch(db, { name: "Dana P.", email: "", phone: "" })).toBeNull();
121 expect(findMatch(db, { name: "Dana", email: "", phone: "555 010 2030" })?.id).toBe(first.value.id);
122 });
123
124 test("a different person with no match is a new lead; a name alone never merges", () => {
125 const db = fresh();
126 arrive(db, { phone: "555 010 2030" });
127 arrive(db, { name: "Sam P.", email: "[email protected]", phone: "555 010 9999" });
128 arrive(db, { email: "[email protected]", phone: "" });
129 expect(count(db)).toBe(3);
130 });
131
132 test("an open lead is preferred to a closed one with the same email", () => {
133 const db = fresh();
134 const old = arrive(db, { email: "[email protected]" });
135 if (!old.ok) throw new Error("not added");
136 setState(db, ADMIN, { id: old.value.id, state: "lost" });
137 const open = insertLead(db, { name: "Kim", email: "[email protected]", phone: "", source: "website", message: "hi", consent: false }, new Date(NOW).toISOString(), agent);
138 expect(findMatch(db, { name: "Kim", email: "[email protected]", phone: "" })?.id).toBe(open);
139 });
140
141 for (const closed of ["lost", "qualified"] as const) {
142 test(`a ${closed} lead is reopened, through reopen, when its person writes in again`, () => {
143 const db = fresh();
144 const first = arrive(db);
145 if (!first.ok) throw new Error("not added");
146 const reply = readyFor(db, first.value.id)!;
147 send(db, findLead(db, first.value.id)!, reply, reply.body, "alice", new Date(NOW).toISOString(), agent);
148 setState(db, ADMIN, { id: first.value.id, state: closed });
149 const again = arrive(db, { message: "I changed my mind" });
150 if (!again.ok) throw new Error("not merged");
151 expect(count(db)).toBe(1);
152 // Sent before it closed, so reopened as contacted, with its cadence scheduled again.
153 expect(again.value.state).toBe("contacted");
154 expect(again.value.messages.some((m) => m.status === "scheduled")).toBe(true);
155 expect(again.value.messages.some((m) => m.status === "skipped")).toBe(false);
156 expect(again.value.replies.map((r) => r.body)).toEqual(["I changed my mind"]);
157 const rows = listAudit(db, ADMIN, {});
158 if (!rows.ok) throw new Error("no trail");
159 expect(rows.value.filter((r) => r.act === "merged")).toHaveLength(1);
160 });
161 }
162
163 test("the lead comes back to the top of needs you", () => {
164 const db = fresh();
165 const at = (min: number) => new Date(NOW + min * M);
166 const input = { name: "Dana P.", email: "[email protected]", phone: "", source: "website", message: "Is it still for sale?" };
167 const first = addLead(db, me, input, at(0));
168 addLead(db, me, { ...input, name: "Other", email: "[email protected]" }, at(1));
169 addLead(db, me, { ...input, message: "Hello again" }, at(2));
170 const needs = listLeads(db, ADMIN, { show: "needs" });
171 if (!needs.ok || !first.ok) throw new Error("no desk");
172 expect(needs.value.leads[0]!.id).toBe(first.value.id);
173 });
174
175 test("the trail records one merge naming the source and the lead", () => {
176 const db = fresh();
177 const first = arrive(db);
178 arrive(db, { source: "zillow" });
179 const rows = listAudit(db, ADMIN, {});
180 if (!rows.ok || !first.ok) throw new Error("no trail");
181 const merged = rows.value.filter((r) => r.act === "merged");
182 expect(merged).toHaveLength(1);
183 expect(merged[0]!.target).toBe(String(first.value.id));
184 expect(JSON.parse(merged[0]!.detail!)).toEqual({ source: "zillow", lead: first.value.id });
185 });
186
87187 test("by source: counts, medians, under five, waiting leads by time so far, old ones out", () => {
88188 const db = fresh();
89189 const add = (source: string, ago: number, took?: number) => {
src/leads.ts +40 −2
@@ -269,7 +269,7 @@ const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce(
269269 );
270270
271271 /**
272 * The desk, newest inquiry first; with `q`, only leads whose name, email or
272 * The desk, newest inquiry first (a lead who wrote in again counts from then); with `q`, only leads whose name, email or
273273 * note holds it, or whose phone holds its digits ("555 0101" finds "(206) 555-0101").
274274 */
275275 export function desk(db: Database, limit: number, q = ""): DeskLead[] {
@@ -301,7 +301,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
301301 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
302302 OR lead.note LIKE ?2 ESCAPE '\\'
303303 OR (?3 <> '' AND ${DIGITS} LIKE ?3)
304 ORDER BY created_at DESC, id DESC LIMIT ?1`,
304 ORDER BY max(created_at, coalesce((SELECT max(at) FROM inbound WHERE lead_id = lead.id), '')) DESC, id DESC LIMIT ?1`,
305305 )
306306 .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`)
307307 .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, ...row }) => ({
@@ -459,6 +459,44 @@ export function insertLead(
459459 })();
460460 }
461461
462 const digitsOf = (phone: string): string => phone.replace(/\D/g, "");
463
464 /**
465 * The lead this arrival is already on the desk as: the same email (any
466 * case) or the same phone digits. An open lead is preferred to a closed
467 * one, then the newest. Never the name.
468 */
469 export function findMatch(db: Database, input: Contact): Lead | null {
470 const email = input.email.toLowerCase();
471 const digits = digitsOf(input.phone);
472 if (email === "" && digits === "") return null;
473 return db
474 .query<Lead, [string, string]>(
475 `SELECT * FROM lead
476 WHERE (?1 != '' AND lower(email) = ?1) OR (?2 != '' AND ${DIGITS} = ?2)
477 ORDER BY (state IN ('qualified', 'lost')), id DESC LIMIT 1`,
478 )
479 .get(email, digits);
480 }
481
482 /**
483 * A known lead wrote in again at `at`: a closed one goes back in follow-ups,
484 * and their new message joins the history as something they wrote, with a
485 * fresh answer drafted (see `recordInbound`). Returns the reply's id.
486 */
487 export function writeInAgain(
488 db: Database,
489 found: Lead,
490 message: string,
491 at: string,
492 agent: Agent,
493 ): number {
494 return db.transaction(() => {
495 if (CLOSED.includes(found.state)) reopen(db, found, at, agent);
496 return recordInbound(db, findLead(db, found.id)!, "email", message, at, agent);
497 })();
498 }
499
462500 /** The message ready to approve now: the first reply, or the earliest due touch. */
463501 export const readyFor = (db: Database, id: number): Message | null =>
464502 db
src/next.test.ts +1 −1
@@ -47,7 +47,7 @@ const arrive = async (name: string): Promise<number> => {
4747 await Bun.sleep(3);
4848 const made = await post("/leads", {
4949 name,
50 email: "x@example.com",
50 email: `${name.replace(/\W+/g, "")}@example.com`,
5151 source: "zillow",
5252 message: "Is it still available?",
5353 });
src/openers.test.ts +1 −1
@@ -32,7 +32,7 @@ const must = <T>(r: Result<T>): T => {
3232 const lead = (source: string, n = 1) => ({
3333 name: "Maria Gonzalez",
3434 email: `maria${n}@example.com`,
35 phone: "(206) 555-0101",
35 phone: `(206) 555-010${n}`,
3636 source,
3737 message: "Could we see 418 Juniper Ln?",
3838 consent: false,
src/profile.test.ts +2 −2
@@ -60,12 +60,12 @@ test("saving changes the next draft's signature and the unsent ones, never a sen
6060 const sent = must(sendReply(db, alice, { id: a.id }));
6161 const oldSignature = sent.messages[0]!.signature;
6262 expect(oldSignature).toContain(agent.license);
63 const b = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
63 const b = must(addLead(db, alice, { ...lead, email: "[email protected]", phone: "(206) 555-0102" }));
6464
6565 expect(must(saveProfile(db, root, sam))).toMatchObject({ id: 1, ...sam, timeZone: agent.timeZone });
6666 expect(currentAgent(db)).toMatchObject({ ...sam, timeZone: agent.timeZone });
6767
68 const next = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
68 const next = must(addLead(db, alice, { ...lead, email: "[email protected]", phone: "(206) 555-0103" }));
6969 expect(next.messages[0]!.signature).toContain("WA 99887");
7070 expect(next.messages[0]!.signature).not.toContain(agent.license);
7171 // A draft written before the save is signed, and worded, as the saved profile.
src/routes.ts +4 −1
@@ -599,7 +599,10 @@ export const routes: readonly Route[] = [
599599 posted(
600600 c,
601601 (input) => addLead(c.db, c.who, input),
602 (lead) => ({ to: lead === undefined ? "/" : `/leads/${lead.id}` }),
602 (lead) => ({
603 to: lead === undefined ? "/" : `/leads/${lead.id}`,
604 ...(lead?.again === true ? { said: `${lead.name} wrote in again` } : {}),
605 }),
603606 201,
604607 ),
605608 api: {
src/sample.test.ts +5 −2
@@ -42,10 +42,13 @@ test("one press adds one lead with a fresh clock and a draft; presses differ unt
4242 seen.add(added.value.name);
4343 }
4444 expect(seen.size).toBe(INQUIRIES.length);
45 // Used up: it comes round again, and still adds exactly one.
45 // Used up: the button still adds a lead, the oldest inquiry over again from a new address and number.
4646 const again = addSampleInquiry(db, alice);
47 expect(again.ok).toBe(true);
47 expect(again.ok && again.value.again).toBeFalsy();
48 expect(again.ok && INQUIRIES.some((i) => i.name === again.value.name)).toBe(true);
4849 expect(names(db)).toHaveLength(INQUIRIES.length + 1);
50 expect(addSampleInquiry(db, alice).ok).toBe(true);
51 expect(names(db)).toHaveLength(INQUIRIES.length + 2);
4952 });
5053
5154 test("consent decides the channel of the drafted reply", () => {
src/sample.ts +12 −2
@@ -149,7 +149,8 @@ export const INQUIRIES: readonly NewLead[] = [
149149
150150 /**
151151 * The next inquiry in turn, read off the desk and not remembered: the first
152 * that is not on it, or, when all are, the one that has been there longest.
152 * that is not on it, or, when all are, the one that has been there longest
153 * again, under an address and number of its own.
153154 * Restarting the samples clears the desk, so the turn starts over with it.
154155 */
155156 export function nextInquiry(db: Database): NewLead {
@@ -163,5 +164,14 @@ export function nextInquiry(db: Database): NewLead {
163164 );
164165 const fresh = INQUIRIES.find((i) => !placed.has(i.email));
165166 if (fresh !== undefined) return fresh;
166 return [...INQUIRIES].sort((a, b) => placed.get(a.email)! - placed.get(b.email)!)[0]!;
167 // All are on the desk: the longest-standing one writes again as a new
168 // person (own address and number), since the same email would merge.
169 const oldest = [...INQUIRIES].sort((a, b) => placed.get(a.email)! - placed.get(b.email)!)[0]!;
170 const n = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM lead").get()!.n;
171 const [local = "", host = ""] = oldest.email.split("@");
172 return {
173 ...oldest,
174 email: `${local}.${n}@${host}`,
175 phone: `(206) 555-${String(3000 + n).padStart(4, "0")}`,
176 };
167177 }
src/sentences.ts +14 −1
@@ -5,7 +5,8 @@
55 * `esc` makes the row's own words safe for that door.
66 */
77
8 import type { AuditRow } from "./audit.ts";
8 import { readMergeDetail, type AuditRow } from "./audit.ts";
9 import { SOURCE_LABEL, type Source } from "./drafts.ts";
910
1011 /** What a correction changed, as ": phone “a” → “b”, …"; "" when the row names nothing readable. */
1112 function changeWords(detail: string | null, esc: (text: string) => string): string {
@@ -24,6 +25,13 @@ function changeWords(detail: string | null, esc: (text: string) => string): stri
2425 return parts.length === 0 ? "" : `: ${parts.join(", ")}`;
2526 }
2627
28 /** A merge's arrival: " (via Zillow)"; "" when the row names no source. */
29 function mergeWords(detail: string | null, esc: (text: string) => string): string {
30 const source = readMergeDetail(detail)?.source;
31 const label = source === undefined ? undefined : SOURCE_LABEL[source as Source];
32 return label === undefined ? "" : ` (via ${esc(label)})`;
33 }
34
2735 export function deed(
2836 row: AuditRow,
2937 lead: string,
@@ -94,6 +102,11 @@ export function deed(
94102 done: `cancelled the showing with ${lead}`,
95103 tried: `cancel the showing with ${lead}`,
96104 };
105 if (row.act === "merged")
106 return {
107 done: `${lead} wrote in again${mergeWords(row.detail, esc)}`,
108 tried: `add a lead`,
109 };
97110 if (row.act === "reopened")
98111 return {
99112 done: `put ${lead} back in follow-ups`,
src/server.test.ts +31 −4
@@ -77,8 +77,15 @@ type Lead = {
7777 };
7878 const lead = async (id: number): Promise<Lead> =>
7979 (await (await api(`/leads/${id}`, { headers: asJson }, alice)).json()) as Lead;
80 const created = async (body: unknown = NEW): Promise<Lead> => {
81 const response = await api("/leads", { method: "POST", ...jsonBody(body) }, alice);
80 let numbered = 0;
81 /** A lead added over the door; each gets its own address and number, so none is one writing in again. */
82 const created = async (body: { name: string; email: string } = NEW): Promise<Lead> => {
83 const own = {
84 ...body,
85 email: `${body.name.toLowerCase().replace(/\W+/g, ".")}@example.com`,
86 phone: `(206) 555-${String(4000 + ++numbered).padStart(4, "0")}`,
87 };
88 const response = await api("/leads", { method: "POST", ...jsonBody(own) }, alice);
8289 expect(response.status).toBe(201);
8390 return (await response.json()) as Lead;
8491 };
@@ -146,7 +153,7 @@ test("POST /leads: a lead arrives with its reply drafted; a stranger and a bad f
146153 // From the page's form: back to the lead, its reply ready.
147154 const posted = await api(
148155 "/leads",
149 { method: "POST", body: form({ ...NEW, name: "Form Person", consent: "yes" }), redirect: "manual" },
156 { method: "POST", body: form({ ...NEW, name: "Form Person", email: "[email protected]", phone: "(206) 555-0188", consent: "yes" }), redirect: "manual" },
150157 alice,
151158 );
152159 expect(posted.status).toBe(303);
@@ -329,7 +336,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
329336 expect(mcpDesk.leads.length).toBeGreaterThan(0);
330337 const refused = await call("add_lead", NEW);
331338 expect(refused.result.isError).toBe(true);
332 const added = await call("add_lead", { ...NEW, name: "Over MCP" }, root);
339 const added = await call("add_lead", { ...NEW, name: "Over MCP", email: "[email protected]", phone: "(206) 555-0189" }, root);
333340 expect(added.result.isError).toBeUndefined();
334341 const made = JSON.parse(added.result.content[0].text);
335342 expect(made.name).toBe("Over MCP");
@@ -716,3 +723,23 @@ test("a bodyless POST has no fields, but a garbled form body still fails", async
716723 ).then((r) => r.status, () => 500);
717724 expect(garbled).toBeGreaterThanOrEqual(400);
718725 });
726
727 test("a lead writing in again lands on their page, and the page says so", async () => {
728 const mine = { ...NEW, name: "Dana P.", email: "[email protected]", phone: "(206) 555-0166", consent: "yes" } as Record<string, string>;
729 const first = await api("/leads", { method: "POST", body: form(mine), redirect: "manual" }, alice);
730 const where = first.headers.get("location")!;
731 // The first time there is nothing to say.
732 expect(first.headers.get("set-cookie") ?? "").not.toContain("wrote");
733 const again = await api(
734 "/leads",
735 { method: "POST", body: form({ ...mine, email: "[email protected]", message: "Still there?" }), redirect: "manual" },
736 alice,
737 );
738 expect(again.status).toBe(303);
739 expect(again.headers.get("location")).toBe(where);
740 const notice = /notice=([^;]*)/.exec(again.headers.get("set-cookie") ?? "")?.[1];
741 expect(decodeURIComponent(notice!)).toBe("Dana P. wrote in again");
742 const page = await (await api(where, { headers: { cookie: `notice=${notice}` } }, alice)).text();
743 expect(page).toContain("Dana P. wrote in again");
744 expect(page).toContain("Still there?");
745 });
src/terminal.test.ts +22 −2
@@ -408,7 +408,7 @@ test("v reads a pasted email into the add screen, says what is missing, and adds
408408 const db = fresh();
409409 const t = terminal(db, alice);
410410 t.key("v");
411 t.key("From: Zillow <[email protected]>\r\nName: Priya Raman\r\nEmail: priya.raman@example.com\r\nMessage: Is 12 Example St still available?\r\n");
411 t.key("From: Zillow <[email protected]>\r\nName: Priya Raman\r\nEmail: priya.new@example.com\r\nMessage: Is 12 Example St still available?\r\n");
412412 t.key("\x04");
413413 let screen = read(t);
414414 expect(screen).toContain("Not found in the email: phone");
@@ -417,7 +417,7 @@ test("v reads a pasted email into the add screen, says what is missing, and adds
417417 expect(read(t)).toContain("Priya Raman is on the desk");
418418 const listed = listLeads(db, alice);
419419 const added = listed.ok && listed.value.leads.find((l) => l.name === "Priya Raman");
420 expect(added && added.email).toBe("priya.raman@example.com");
420 expect(added && added.email).toBe("priya.new@example.com");
421421 expect(added && added.source).toBe("zillow");
422422 expect(added && added.consent).toBe(false);
423423 // Nothing readable says so, and esc writes nothing.
@@ -426,3 +426,23 @@ test("v reads a pasted email into the add screen, says what is missing, and adds
426426 t.key("\x04");
427427 expect(read(t)).toContain("Paste the text of the email");
428428 });
429
430 test("adding someone already on the desk says they wrote in again, and adds no lead", () => {
431 const db = fresh();
432 const t = terminal(db, alice);
433 const add = (message: string): void => {
434 t.key("\x1b");
435 t.key("n");
436 for (const field of ["Zoe Park", "[email protected]", "", "3", message, "n"]) {
437 type(t, field);
438 t.key("\r");
439 }
440 };
441 add("Saw the yard sign on Elm. Can we tour?");
442 expect(read(t)).toContain("Zoe Park is on the desk");
443 const before = listLeads(db, alice);
444 add("Still interested!");
445 expect(read(t)).toContain("Zoe Park wrote in again");
446 const after = listLeads(db, alice);
447 expect(before.ok && after.ok && after.value.leads.length === before.value.leads.length).toBe(true);
448 });
src/terminal.ts +3 −1
@@ -544,7 +544,9 @@ export function terminal(
544544 consent: /^y/i.test(fields.consent ?? ""),
545545 });
546546 if (added.ok) {
547 said = `${added.value.name} is on the desk; the first reply is drafted.`;
547 said = added.value.again
548 ? `${added.value.name} wrote in again; an answer is drafted.`
549 : `${added.value.name} is on the desk; the first reply is drafted.`;
548550 view = { name: "lead", id: added.value.id };
549551 } else {
550552 said = added.message;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs