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
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/50-a-lead-who-writes-in-again-with-the-same → main 4 commits fork
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 | ||
| 193 | 193 | were. It is one-way: the app has no button to turn texting back on (new |
| 194 | 194 | written consent comes with a new inquiry), and asking twice changes nothing. |
| 195 | 195 | |
| 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 | ||
| 196 | 208 | **Your signature** goes on every message, and can't be edited off: your |
| 197 | 209 | name, brokerage and license number, as state advertising rules require. |
| 198 | 210 | Texts also say "Reply STOP to opt out." |
src/actions.test.ts +26 −18
| @@ -40,6 +40,14 @@ const maria = { | ||
| 40 | 40 | message: "Is 418 Juniper Ln still available? Could we see it this weekend?", |
| 41 | 41 | consent: true, |
| 42 | 42 | }; |
| 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 | }; | |
| 43 | 51 | const must = <T>(r: { ok: true; value: T } | { ok: false; message: string }): T => { |
| 44 | 52 | if (!r.ok) throw new Error(r.message); |
| 45 | 53 | return r.value; |
| @@ -83,8 +91,8 @@ test("a stranger may not see or add leads; a signed-in person may", () => { | ||
| 83 | 91 | |
| 84 | 92 | test("control characters are refused at the boundary; a textarea's line breaks are kept", () => { |
| 85 | 93 | 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") }, | |
| 88 | 96 | { ...maria, email: "[email protected]\x07" }, |
| 89 | 97 | { ...maria, phone: "555\x9b2J0101" }, |
| 90 | 98 | { ...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 | ||
| 99 | 107 | "line one\nline two\tok", |
| 100 | 108 | ); |
| 101 | 109 | // 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))); | |
| 103 | 111 | const r = sendReply(db, alice, { id: lead.id, body: "Hi\x1b[2J" }, at(0, 1)); |
| 104 | 112 | expect(r.ok).toBe(false); |
| 105 | 113 | 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 | ||
| 124 | 132 | }); |
| 125 | 133 | |
| 126 | 134 | 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))); | |
| 128 | 136 | const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1))); |
| 129 | 137 | expect(sent.state).toBe("contacted"); |
| 130 | 138 | 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 | ||
| 147 | 155 | }); |
| 148 | 156 | |
| 149 | 157 | 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))); | |
| 151 | 159 | const sent = must( |
| 152 | 160 | sendReply(db, alice, { id: lead.id, body: " Hi Ana — free Saturday at 10? " }, at(0, 1)), |
| 153 | 161 | ); |
| 154 | 162 | expect(sent.messages[0]!.body).toBe("Hi Ana — free Saturday at 10?"); |
| 155 | 163 | 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))); | |
| 157 | 165 | for (const body of [" ", "x".repeat(481)]) { |
| 158 | 166 | const r = sendReply(db, alice, { id: lead2.id, body }, at(0, 1)); |
| 159 | 167 | expect(r.ok).toBe(false); |
| @@ -163,14 +171,14 @@ test("an edit is what goes out, with the signature still on it", () => { | ||
| 163 | 171 | |
| 164 | 172 | test("no text is drafted without consent: email only, from first reply to last touch", () => { |
| 165 | 173 | 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)), | |
| 167 | 175 | ); |
| 168 | 176 | expect(lead.messages[0]!.channel).toBe("email"); |
| 169 | 177 | const sent = must(sendReply(db, alice, { id: lead.id }, at(0, 1))); |
| 170 | 178 | expect(sent.messages.every((m) => m.channel === "email")).toBe(true); |
| 171 | 179 | // Consent without a number to text is still email. |
| 172 | 180 | 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)), | |
| 174 | 182 | ); |
| 175 | 183 | expect(noPhone.messages[0]!.channel).toBe("email"); |
| 176 | 184 | // 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 | ||
| 182 | 190 | }); |
| 183 | 191 | |
| 184 | 192 | 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))); | |
| 186 | 194 | must(sendReply(db, alice, { id: lead.id }, at(0))); |
| 187 | 195 | expect(must(tick(db, alice, at(0, 30))).leads).not.toContain(lead.id); |
| 188 | 196 | 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 | ||
| 199 | 207 | }); |
| 200 | 208 | |
| 201 | 209 | 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))); | |
| 203 | 211 | must(sendReply(db, alice, { id: lead.id }, at(0))); |
| 204 | 212 | must(tick(db, alice, at(3, 1))); |
| 205 | 213 | 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 | ||
| 273 | 281 | }); |
| 274 | 282 | |
| 275 | 283 | 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))); | |
| 277 | 285 | must(sendReply(db, alice, { id: lead.id }, at(0))); |
| 278 | 286 | must(tick(db, alice, at(1, 1))); |
| 279 | 287 | 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 | ||
| 294 | 302 | }); |
| 295 | 303 | |
| 296 | 304 | 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))); | |
| 298 | 306 | must(setState(db, alice, { id: lead.id, state: "lost" })); |
| 299 | 307 | expect(must(getLead(db, alice, { id: lead.id })).messages[0]!.status).toBe("skipped"); |
| 300 | 308 | 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 | ||
| 304 | 312 | }); |
| 305 | 313 | |
| 306 | 314 | 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))); | |
| 308 | 316 | const first = must(sendReply(db, alice, { id: lead.id, body: "Hi, edited." }, at(0))); |
| 309 | 317 | const sentBefore = first.messages.find((m) => m.status === "sent")!; |
| 310 | 318 | expect(sentBefore.channel).toBe("text"); |
| @@ -327,7 +335,7 @@ test("opting out turns every unsent text into an email and leaves what was sent | ||
| 327 | 335 | }); |
| 328 | 336 | |
| 329 | 337 | 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))); | |
| 331 | 339 | must(sendReply(db, alice, { id: lead.id }, at(0))); |
| 332 | 340 | must(optOutTexts(db, alice, { id: lead.id }, at(0, 5))); |
| 333 | 341 | 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 | ||
| 336 | 344 | const back = must(setState(db, alice, { id: lead.id, state: "open" }, at(42))); |
| 337 | 345 | expect(back.messages.filter((m) => m.status !== "sent").every((m) => m.channel === "email")).toBe(true); |
| 338 | 346 | // 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))); | |
| 340 | 348 | expect(again.id).not.toBe(lead.id); |
| 341 | 349 | const old = must(getLead(db, alice, { id: lead.id })); |
| 342 | 350 | 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 | ||
| 346 | 354 | }); |
| 347 | 355 | |
| 348 | 356 | 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))); | |
| 350 | 358 | const one = must(optOutTexts(db, alice, { id: lead.id }, at(1))); |
| 351 | 359 | const two = must(optOutTexts(db, alice, { id: lead.id }, at(2))); |
| 352 | 360 | 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))); | |
| 354 | 362 | const refused = optOutTexts(db, alice, { id: never.id }); |
| 355 | 363 | expect(refused.ok).toBe(false); |
| 356 | 364 | 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 | ||
| 359 | 367 | }); |
| 360 | 368 | |
| 361 | 369 | 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))); | |
| 363 | 371 | must(optOutTexts(db, alice, { id: lead.id }, at(1))); |
| 364 | 372 | const row = db |
| 365 | 373 | .query<{ act: string; who_name: string; outcome: string }, [string]>( |
src/actions.ts +26 −6
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | 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"; | |
| 12 | 12 | import { MAX_NOTE, outcomeOf } from "./calls.ts"; |
| 13 | 13 | import { permit } from "./contract.ts"; |
| 14 | 14 | import { |
| @@ -42,7 +42,9 @@ import { | ||
| 42 | 42 | MAX_INBOUND, |
| 43 | 43 | MAX_LEAD_NOTE, |
| 44 | 44 | MAX_QUERY, |
| 45 | findMatch, | |
| 45 | 46 | insertLead, |
| 47 | writeInAgain, | |
| 46 | 48 | lastMessages, |
| 47 | 49 | updateContact, |
| 48 | 50 | writeNote, |
| @@ -284,24 +286,43 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> { | ||
| 284 | 286 | }); |
| 285 | 287 | } |
| 286 | 288 | |
| 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 | */ | |
| 287 | 297 | export const addLead = ( |
| 288 | 298 | db: Database, |
| 289 | 299 | who: Who, |
| 290 | 300 | input: Record<string, unknown>, |
| 291 | 301 | 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 | }; | |
| 294 | 309 | |
| 295 | 310 | function add( |
| 296 | 311 | db: Database, |
| 297 | 312 | who: Who, |
| 298 | 313 | input: Record<string, unknown>, |
| 299 | 314 | at?: Date, |
| 300 | ): Result<LeadDetail> { | |
| 315 | ): Result<Added> { | |
| 301 | 316 | if (permit(who, "lead", "create") !== "yes") |
| 302 | 317 | return refuse(who, "Sign in to add a lead.", "You may not add a lead."); |
| 303 | 318 | const read = readNewLead(input); |
| 304 | 319 | 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 | } | |
| 305 | 326 | const id = insertLead(db, read.value, stamp(at), currentAgent(db)); |
| 306 | 327 | const added = detail(db, id)!; |
| 307 | 328 | emit("lead.added", { id }); |
| @@ -454,8 +475,7 @@ export const addSampleInquiry = ( | ||
| 454 | 475 | db: Database, |
| 455 | 476 | who: Who, |
| 456 | 477 | 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); | |
| 459 | 479 | |
| 460 | 480 | /** |
| 461 | 481 | * 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 }; | ||
| 204 | 204 | |
| 205 | 205 | 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 () => { |
| 206 | 206 | 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) | |
| 208 | 208 | ).json()) as { id: number }; |
| 209 | 209 | await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" }, root); |
| 210 | 210 | 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" }; | ||
| 257 | 257 | test("act is recorded as first_reply, reply, qualified and lost", () => { |
| 258 | 258 | const db = openDb(mkdtempSync(join(tmpdir(), "app-audit-act-"))); |
| 259 | 259 | 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]" }); | |
| 262 | 262 | if (!one.ok || !two.ok || !three.ok) throw new Error("setup"); |
| 263 | 263 | sendReply(db, admin0, { id: one.value.id }); |
| 264 | 264 | // 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 { | ||
| 34 | 34 | readonly detail: string | null; |
| 35 | 35 | } |
| 36 | 36 | |
| 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; | |
| 39 | 39 | export type Act = (typeof ACTS)[number]; |
| 40 | 40 | |
| 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 | ||
| 41 | 59 | export interface Attempt { |
| 42 | 60 | readonly who: Who; |
| 43 | 61 | readonly resource: string; |
src/calls.test.ts +8 −6
| @@ -31,14 +31,16 @@ const MIN = 60_000; | ||
| 31 | 31 | const DAY = 86_400_000; |
| 32 | 32 | |
| 33 | 33 | 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) => { | |
| 35 | 37 | const made = addLead( |
| 36 | 38 | db, |
| 37 | 39 | alice, |
| 38 | 40 | { |
| 39 | 41 | 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")}`, | |
| 42 | 44 | source: "zillow", |
| 43 | 45 | message: "Can I see 12 Oak Street this week?", |
| 44 | 46 | consent: true, |
| @@ -179,11 +181,11 @@ const api = (path: string, init: RequestInit = {}, headers: Record<string, strin | ||
| 179 | 181 | }; |
| 180 | 182 | const json = (path: string, body: unknown) => |
| 181 | 183 | 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> => { | |
| 183 | 185 | const made = await json("/leads", { |
| 184 | 186 | 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")}`, | |
| 187 | 189 | source: "website", |
| 188 | 190 | message: "Do you have time to talk this week?", |
| 189 | 191 | consent: false, |
src/details.test.ts +2 −1
| @@ -25,6 +25,7 @@ const NEW = { | ||
| 25 | 25 | message: "Can I see 12 Oak Street this week?", |
| 26 | 26 | consent: true, |
| 27 | 27 | }; |
| 28 | let arrivals = 0; | |
| 28 | 29 | const T0 = new Date("2026-03-01T10:00:00Z"); |
| 29 | 30 | |
| 30 | 31 | const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-details-"))); |
| @@ -33,7 +34,7 @@ const must = <T>(r: Result<T>): T => { | ||
| 33 | 34 | return r.value; |
| 34 | 35 | }; |
| 35 | 36 | 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; | |
| 37 | 38 | const audits = (db: ReturnType<typeof fresh>) => |
| 38 | 39 | db.query<AuditRow, []>("SELECT * FROM audit WHERE act = 'edited'").all(); |
| 39 | 40 |
src/inbound.test.ts +6 −4
| @@ -32,11 +32,13 @@ const MIN = 60_000; | ||
| 32 | 32 | const DAY = 86_400_000; |
| 33 | 33 | |
| 34 | 34 | const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-inbound-"))); |
| 35 | /** Each arrival is a different person, not one writing in again. */ | |
| 36 | let arrivals = 0; | |
| 35 | 37 | const arrive = (db: ReturnType<typeof fresh>, consent: boolean) => { |
| 36 | 38 | const made = addLead(db, alice, { |
| 37 | 39 | 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")}`, | |
| 40 | 42 | source: "zillow", |
| 41 | 43 | message: "Can I see 12 Oak Street this week?", |
| 42 | 44 | consent, |
| @@ -209,8 +211,8 @@ const json = (path: string, body: unknown) => | ||
| 209 | 211 | const served = async (consent = true): Promise<number> => { |
| 210 | 212 | const made = await json("/leads", { |
| 211 | 213 | 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")}`, | |
| 214 | 216 | source: "website", |
| 215 | 217 | message: "Do you have time to talk this week?", |
| 216 | 218 | consent, |
src/leads.test.ts +101 −1
| @@ -9,7 +9,9 @@ import { tmpdir } from "node:os"; | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { openDb } from "./db.ts"; |
| 11 | 11 | 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"; | |
| 13 | 15 | import { recordLine, sourceLine } from "./clock.ts"; |
| 14 | 16 | |
| 15 | 17 | 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", () => { | ||
| 84 | 86 | expect(responseRecord(db, NOW)).toMatchObject({ leads: 1, median_ms: 1 * M, within_5_min_pct: 100 }); |
| 85 | 87 | }); |
| 86 | 88 | |
| 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 | ||
| 87 | 187 | test("by source: counts, medians, under five, waiting leads by time so far, old ones out", () => { |
| 88 | 188 | const db = fresh(); |
| 89 | 189 | const add = (source: string, ago: number, took?: number) => { |
src/leads.ts +40 −2
| @@ -269,7 +269,7 @@ const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce( | ||
| 269 | 269 | ); |
| 270 | 270 | |
| 271 | 271 | /** |
| 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 | |
| 273 | 273 | * note holds it, or whose phone holds its digits ("555 0101" finds "(206) 555-0101"). |
| 274 | 274 | */ |
| 275 | 275 | export function desk(db: Database, limit: number, q = ""): DeskLead[] { |
| @@ -301,7 +301,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 301 | 301 | WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\' |
| 302 | 302 | OR lead.note LIKE ?2 ESCAPE '\\' |
| 303 | 303 | 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`, | |
| 305 | 305 | ) |
| 306 | 306 | .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`) |
| 307 | 307 | .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( | ||
| 459 | 459 | })(); |
| 460 | 460 | } |
| 461 | 461 | |
| 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 | ||
| 462 | 500 | /** The message ready to approve now: the first reply, or the earliest due touch. */ |
| 463 | 501 | export const readyFor = (db: Database, id: number): Message | null => |
| 464 | 502 | db |
src/next.test.ts +1 −1
| @@ -47,7 +47,7 @@ const arrive = async (name: string): Promise<number> => { | ||
| 47 | 47 | await Bun.sleep(3); |
| 48 | 48 | const made = await post("/leads", { |
| 49 | 49 | name, |
| 50 | email: "x@example.com", | |
| 50 | email: `${name.replace(/\W+/g, "")}@example.com`, | |
| 51 | 51 | source: "zillow", |
| 52 | 52 | message: "Is it still available?", |
| 53 | 53 | }); |
src/openers.test.ts +1 −1
| @@ -32,7 +32,7 @@ const must = <T>(r: Result<T>): T => { | ||
| 32 | 32 | const lead = (source: string, n = 1) => ({ |
| 33 | 33 | name: "Maria Gonzalez", |
| 34 | 34 | email: `maria${n}@example.com`, |
| 35 | phone: "(206) 555-0101", | |
| 35 | phone: `(206) 555-010${n}`, | |
| 36 | 36 | source, |
| 37 | 37 | message: "Could we see 418 Juniper Ln?", |
| 38 | 38 | 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 | ||
| 60 | 60 | const sent = must(sendReply(db, alice, { id: a.id })); |
| 61 | 61 | const oldSignature = sent.messages[0]!.signature; |
| 62 | 62 | 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" })); | |
| 64 | 64 | |
| 65 | 65 | expect(must(saveProfile(db, root, sam))).toMatchObject({ id: 1, ...sam, timeZone: agent.timeZone }); |
| 66 | 66 | expect(currentAgent(db)).toMatchObject({ ...sam, timeZone: agent.timeZone }); |
| 67 | 67 | |
| 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" })); | |
| 69 | 69 | expect(next.messages[0]!.signature).toContain("WA 99887"); |
| 70 | 70 | expect(next.messages[0]!.signature).not.toContain(agent.license); |
| 71 | 71 | // 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[] = [ | ||
| 599 | 599 | posted( |
| 600 | 600 | c, |
| 601 | 601 | (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 | }), | |
| 603 | 606 | 201, |
| 604 | 607 | ), |
| 605 | 608 | 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 | ||
| 42 | 42 | seen.add(added.value.name); |
| 43 | 43 | } |
| 44 | 44 | 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. | |
| 46 | 46 | 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); | |
| 48 | 49 | expect(names(db)).toHaveLength(INQUIRIES.length + 1); |
| 50 | expect(addSampleInquiry(db, alice).ok).toBe(true); | |
| 51 | expect(names(db)).toHaveLength(INQUIRIES.length + 2); | |
| 49 | 52 | }); |
| 50 | 53 | |
| 51 | 54 | test("consent decides the channel of the drafted reply", () => { |
src/sample.ts +12 −2
| @@ -149,7 +149,8 @@ export const INQUIRIES: readonly NewLead[] = [ | ||
| 149 | 149 | |
| 150 | 150 | /** |
| 151 | 151 | * 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. | |
| 153 | 154 | * Restarting the samples clears the desk, so the turn starts over with it. |
| 154 | 155 | */ |
| 155 | 156 | export function nextInquiry(db: Database): NewLead { |
| @@ -163,5 +164,14 @@ export function nextInquiry(db: Database): NewLead { | ||
| 163 | 164 | ); |
| 164 | 165 | const fresh = INQUIRIES.find((i) => !placed.has(i.email)); |
| 165 | 166 | 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 | }; | |
| 167 | 177 | } |
src/sentences.ts +14 −1
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | * `esc` makes the row's own words safe for that door. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import type { AuditRow } from "./audit.ts"; | |
| 8 | import { readMergeDetail, type AuditRow } from "./audit.ts"; | |
| 9 | import { SOURCE_LABEL, type Source } from "./drafts.ts"; | |
| 9 | 10 | |
| 10 | 11 | /** What a correction changed, as ": phone “a” → “b”, …"; "" when the row names nothing readable. */ |
| 11 | 12 | function changeWords(detail: string | null, esc: (text: string) => string): string { |
| @@ -24,6 +25,13 @@ function changeWords(detail: string | null, esc: (text: string) => string): stri | ||
| 24 | 25 | return parts.length === 0 ? "" : `: ${parts.join(", ")}`; |
| 25 | 26 | } |
| 26 | 27 | |
| 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 | ||
| 27 | 35 | export function deed( |
| 28 | 36 | row: AuditRow, |
| 29 | 37 | lead: string, |
| @@ -94,6 +102,11 @@ export function deed( | ||
| 94 | 102 | done: `cancelled the showing with ${lead}`, |
| 95 | 103 | tried: `cancel the showing with ${lead}`, |
| 96 | 104 | }; |
| 105 | if (row.act === "merged") | |
| 106 | return { | |
| 107 | done: `${lead} wrote in again${mergeWords(row.detail, esc)}`, | |
| 108 | tried: `add a lead`, | |
| 109 | }; | |
| 97 | 110 | if (row.act === "reopened") |
| 98 | 111 | return { |
| 99 | 112 | done: `put ${lead} back in follow-ups`, |
src/server.test.ts +31 −4
| @@ -77,8 +77,15 @@ type Lead = { | ||
| 77 | 77 | }; |
| 78 | 78 | const lead = async (id: number): Promise<Lead> => |
| 79 | 79 | (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); | |
| 82 | 89 | expect(response.status).toBe(201); |
| 83 | 90 | return (await response.json()) as Lead; |
| 84 | 91 | }; |
| @@ -146,7 +153,7 @@ test("POST /leads: a lead arrives with its reply drafted; a stranger and a bad f | ||
| 146 | 153 | // From the page's form: back to the lead, its reply ready. |
| 147 | 154 | const posted = await api( |
| 148 | 155 | "/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" }, | |
| 150 | 157 | alice, |
| 151 | 158 | ); |
| 152 | 159 | expect(posted.status).toBe(303); |
| @@ -329,7 +336,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 329 | 336 | expect(mcpDesk.leads.length).toBeGreaterThan(0); |
| 330 | 337 | const refused = await call("add_lead", NEW); |
| 331 | 338 | 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); | |
| 333 | 340 | expect(added.result.isError).toBeUndefined(); |
| 334 | 341 | const made = JSON.parse(added.result.content[0].text); |
| 335 | 342 | 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 | ||
| 716 | 723 | ).then((r) => r.status, () => 500); |
| 717 | 724 | expect(garbled).toBeGreaterThanOrEqual(400); |
| 718 | 725 | }); |
| 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 | ||
| 408 | 408 | const db = fresh(); |
| 409 | 409 | const t = terminal(db, alice); |
| 410 | 410 | 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"); | |
| 412 | 412 | t.key("\x04"); |
| 413 | 413 | let screen = read(t); |
| 414 | 414 | 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 | ||
| 417 | 417 | expect(read(t)).toContain("Priya Raman is on the desk"); |
| 418 | 418 | const listed = listLeads(db, alice); |
| 419 | 419 | 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"); | |
| 421 | 421 | expect(added && added.source).toBe("zillow"); |
| 422 | 422 | expect(added && added.consent).toBe(false); |
| 423 | 423 | // 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 | ||
| 426 | 426 | t.key("\x04"); |
| 427 | 427 | expect(read(t)).toContain("Paste the text of the email"); |
| 428 | 428 | }); |
| 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( | ||
| 544 | 544 | consent: /^y/i.test(fields.consent ?? ""), |
| 545 | 545 | }); |
| 546 | 546 | 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.`; | |
| 548 | 550 | view = { name: "lead", id: added.value.id }; |
| 549 | 551 | } else { |
| 550 | 552 | said = added.message; |
new above
offline