Public: anyone can read this; the crew can change it.
Mark a lead lost with a reason (bought with another agent, not ready, never answered) and the desk counts why leads are lost #61
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/51-mark-a-lead-lost-with-a-reason-bought-wi → main 5 commits fork 1 thread · 1 unresolved
32 files
changed +598
−79
README.md +15 −4
| @@ -23,7 +23,7 @@ The clocks keep running while the app sits idle, so the colours below are only | ||
| 23 | 23 | what you see right after a restart. Do step 1 first. |
| 24 | 24 | |
| 25 | 25 | 1. Restart the samples. At the bottom of the desk, press "Restart the |
| 26 | sample leads from now" (admin). The twelve sample leads are laid out | |
| 26 | sample leads from now" (admin). The fifteen sample leads are laid out | |
| 27 | 27 | again with fresh clocks. |
| 28 | 28 | 2. Read the desk. The newest leads are at the top. **Maria Gonzalez** and |
| 29 | 29 | **David Chen** have just asked, so their clocks are green, under five |
| @@ -220,6 +220,17 @@ was ever sent), and the follow-ups not yet sent are drafted again and | ||
| 220 | 220 | scheduled from that moment at day 1, 3, 7, 14 and 30, skipping those already |
| 221 | 221 | sent. |
| 222 | 222 | |
| 223 | **Why a lead was lost.** Marking a lead lost asks for one reason: *bought with | |
| 224 | another agent* (`bought_elsewhere`), *not ready yet* (`not_ready`), *never | |
| 225 | answered* (`never_answered`), *not a real lead* (`not_a_lead`) or *other*. On | |
| 226 | the lead's page it is a menu beside **Mark lost**; in the terminal `x` lists | |
| 227 | the five and `1`–`5` picks; the API and MCP take `{"state":"lost","reason":"not_ready"}` | |
| 228 | and answer 422 for a missing or unknown reason. The page then reads "Lost — not | |
| 229 | ready yet" with the date, and putting the lead back clears both. Leads lost | |
| 230 | before reasons were asked for read "no reason given". Admins see a count of | |
| 231 | lost leads per reason over the last 30 days at the top of **Activity**, and the | |
| 232 | CSV export ends with a `lost_reason` column. | |
| 233 | ||
| 223 | 234 | **When a lead answers.** The app sends nothing, so it never sees their |
| 224 | 235 | reply: you paste it in. On the lead's page open **They wrote back**, paste |
| 225 | 236 | what they wrote (up to 2000 characters) and choose email or text (text only |
| @@ -298,9 +309,9 @@ follow-up you skipped skipped. Scripts use | ||
| 298 | 309 | skips the next follow-up in the plan (it says which day) and `K` brings back the |
| 299 | 310 | first one you skipped. Activity shows both. |
| 300 | 311 | |
| 301 | **Sample leads.** The app starts with twelve sample leads so you can see it | |
| 312 | **Sample leads.** The app starts with fifteen sample leads so you can see it | |
| 302 | 313 | work: two just in, two waiting a while, three gone red, and five already |
| 303 | answered and partway through their follow-ups. An admin can restart them | |
| 314 | answered and partway through their follow-ups, plus three lost, each with a different reason. An admin can restart them | |
| 304 | 315 | from the bottom of the desk, so the clocks read fresh for a demonstration. |
| 305 | 316 | |
| 306 | 317 | ## What is real and what is not, in this prototype |
| @@ -448,7 +459,7 @@ says who may do what. | ||
| 448 | 459 | | `src/leads.ts` | leads and messages: arrive, send, follow up, close | |
| 449 | 460 | | `src/drafts.ts` | the drafted words, the signature, the consent rule | |
| 450 | 461 | | `src/clock.ts`, `static/clock.js` | the response clock: its colours, and its tick | |
| 451 | | `src/sample.ts` | the twelve sample leads | | |
| 462 | | `src/sample.ts` | the fifteen sample leads | | |
| 452 | 463 | | `src/pages/` | the desk and the lead page, server-rendered | |
| 453 | 464 | | `src/routes.ts` | every path, each API route described beside it | |
| 454 | 465 | | `src/security.ts`, `src/http.ts` | the door and the floor: rationing, same origin, headers | |
contract/openapi.json +103 −2
| @@ -351,6 +351,16 @@ | ||
| 351 | 351 | "open" |
| 352 | 352 | ] |
| 353 | 353 | }, |
| 354 | "reason": { | |
| 355 | "enum": [ | |
| 356 | "bought_elsewhere", | |
| 357 | "not_ready", | |
| 358 | "never_answered", | |
| 359 | "not_a_lead", | |
| 360 | "other" | |
| 361 | ], | |
| 362 | "description": "Why the lead is lost; required when state is lost." | |
| 363 | }, | |
| 354 | 364 | "name": { |
| 355 | 365 | "type": "string", |
| 356 | 366 | "minLength": 1, |
| @@ -555,6 +565,31 @@ | ||
| 555 | 565 | "lost" |
| 556 | 566 | ] |
| 557 | 567 | }, |
| 568 | "lostReason": { | |
| 569 | "anyOf": [ | |
| 570 | { | |
| 571 | "enum": [ | |
| 572 | "bought_elsewhere", | |
| 573 | "not_ready", | |
| 574 | "never_answered", | |
| 575 | "not_a_lead", | |
| 576 | "other" | |
| 577 | ] | |
| 578 | }, | |
| 579 | { | |
| 580 | "type": "null" | |
| 581 | } | |
| 582 | ], | |
| 583 | "description": "Why the lead was lost; null unless it is lost, and for a lead lost before reasons were asked for." | |
| 584 | }, | |
| 585 | "lostAt": { | |
| 586 | "type": [ | |
| 587 | "string", | |
| 588 | "null" | |
| 589 | ], | |
| 590 | "format": "date-time", | |
| 591 | "description": "When the lead was marked lost; null unless it is lost." | |
| 592 | }, | |
| 558 | 593 | "created_at": { |
| 559 | 594 | "type": "string", |
| 560 | 595 | "format": "date-time" |
| @@ -723,6 +758,8 @@ | ||
| 723 | 758 | "noteUpdatedAt", |
| 724 | 759 | "opted_out_at", |
| 725 | 760 | "state", |
| 761 | "lostReason", | |
| 762 | "lostAt", | |
| 726 | 763 | "created_at", |
| 727 | 764 | "replied_at", |
| 728 | 765 | "updated_at", |
| @@ -982,7 +1019,7 @@ | ||
| 982 | 1019 | }, |
| 983 | 1020 | "/leads/{id}/state": { |
| 984 | 1021 | "post": { |
| 985 | "summary": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 1022 | "summary": "Mark a lead qualified or lost (with a reason): it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 986 | 1023 | "operationId": "postLeadsIdState", |
| 987 | 1024 | "parameters": [ |
| 988 | 1025 | { |
| @@ -1007,6 +1044,16 @@ | ||
| 1007 | 1044 | "lost", |
| 1008 | 1045 | "open" |
| 1009 | 1046 | ] |
| 1047 | }, | |
| 1048 | "reason": { | |
| 1049 | "enum": [ | |
| 1050 | "bought_elsewhere", | |
| 1051 | "not_ready", | |
| 1052 | "never_answered", | |
| 1053 | "not_a_lead", | |
| 1054 | "other" | |
| 1055 | ], | |
| 1056 | "description": "Why the lead is lost; required when state is lost." | |
| 1010 | 1057 | } |
| 1011 | 1058 | }, |
| 1012 | 1059 | "required": [ |
| @@ -1018,7 +1065,7 @@ | ||
| 1018 | 1065 | }, |
| 1019 | 1066 | "responses": { |
| 1020 | 1067 | "200": { |
| 1021 | "description": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 1068 | "description": "Mark a lead qualified or lost (with a reason): it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 1022 | 1069 | "content": { |
| 1023 | 1070 | "application/json": { |
| 1024 | 1071 | "schema": { |
| @@ -1938,6 +1985,31 @@ | ||
| 1938 | 1985 | "lost" |
| 1939 | 1986 | ] |
| 1940 | 1987 | }, |
| 1988 | "lostReason": { | |
| 1989 | "anyOf": [ | |
| 1990 | { | |
| 1991 | "enum": [ | |
| 1992 | "bought_elsewhere", | |
| 1993 | "not_ready", | |
| 1994 | "never_answered", | |
| 1995 | "not_a_lead", | |
| 1996 | "other" | |
| 1997 | ] | |
| 1998 | }, | |
| 1999 | { | |
| 2000 | "type": "null" | |
| 2001 | } | |
| 2002 | ], | |
| 2003 | "description": "Why the lead was lost; null unless it is lost, and for a lead lost before reasons were asked for." | |
| 2004 | }, | |
| 2005 | "lostAt": { | |
| 2006 | "type": [ | |
| 2007 | "string", | |
| 2008 | "null" | |
| 2009 | ], | |
| 2010 | "format": "date-time", | |
| 2011 | "description": "When the lead was marked lost; null unless it is lost." | |
| 2012 | }, | |
| 1941 | 2013 | "created_at": { |
| 1942 | 2014 | "type": "string", |
| 1943 | 2015 | "format": "date-time" |
| @@ -2082,6 +2154,8 @@ | ||
| 2082 | 2154 | "noteUpdatedAt", |
| 2083 | 2155 | "opted_out_at", |
| 2084 | 2156 | "state", |
| 2157 | "lostReason", | |
| 2158 | "lostAt", | |
| 2085 | 2159 | "created_at", |
| 2086 | 2160 | "replied_at", |
| 2087 | 2161 | "updated_at", |
| @@ -2281,6 +2355,31 @@ | ||
| 2281 | 2355 | "lost" |
| 2282 | 2356 | ] |
| 2283 | 2357 | }, |
| 2358 | "lostReason": { | |
| 2359 | "anyOf": [ | |
| 2360 | { | |
| 2361 | "enum": [ | |
| 2362 | "bought_elsewhere", | |
| 2363 | "not_ready", | |
| 2364 | "never_answered", | |
| 2365 | "not_a_lead", | |
| 2366 | "other" | |
| 2367 | ] | |
| 2368 | }, | |
| 2369 | { | |
| 2370 | "type": "null" | |
| 2371 | } | |
| 2372 | ], | |
| 2373 | "description": "Why the lead was lost; null unless it is lost, and for a lead lost before reasons were asked for." | |
| 2374 | }, | |
| 2375 | "lostAt": { | |
| 2376 | "type": [ | |
| 2377 | "string", | |
| 2378 | "null" | |
| 2379 | ], | |
| 2380 | "format": "date-time", | |
| 2381 | "description": "When the lead was marked lost; null unless it is lost." | |
| 2382 | }, | |
| 2284 | 2383 | "created_at": { |
| 2285 | 2384 | "type": "string", |
| 2286 | 2385 | "format": "date-time" |
| @@ -2366,6 +2465,8 @@ | ||
| 2366 | 2465 | "noteUpdatedAt", |
| 2367 | 2466 | "opted_out_at", |
| 2368 | 2467 | "state", |
| 2468 | "lostReason", | |
| 2469 | "lostAt", | |
| 2369 | 2470 | "created_at", |
| 2370 | 2471 | "replied_at", |
| 2371 | 2472 | "updated_at", |
src/actions.test.ts +9 −9
| @@ -221,19 +221,19 @@ test("qualified or lost leaves the cadence", () => { | ||
| 221 | 221 | const odd = setState(db, alice, { id: lead.id, state: "contacted" }); |
| 222 | 222 | expect(odd.ok).toBe(false); |
| 223 | 223 | if (!odd.ok) expect(odd.error).toBe("invalid"); |
| 224 | const gone = setState(db, alice, { id: 999_999, state: "lost" }); | |
| 224 | const gone = setState(db, alice, { id: 999_999, state: "lost", reason: "other" }); | |
| 225 | 225 | expect(gone.ok).toBe(false); |
| 226 | 226 | if (!gone.ok) expect(gone.error).toBe("not_found"); |
| 227 | 227 | }); |
| 228 | 228 | |
| 229 | test("the sample desk: twelve leads, some red, some mid-cadence; only an admin restarts it", () => { | |
| 229 | test("the sample desk: fifteen leads, some red, some mid-cadence; only an admin restarts it", () => { | |
| 230 | 230 | const sampleDb = openDb(mkdtempSync(join(tmpdir(), "app-sample-"))); |
| 231 | 231 | expect(resetSample(sampleDb, alice).ok).toBe(false); |
| 232 | expect(must(resetSample(sampleDb, root, T0)).leads).toBe(12); | |
| 232 | expect(must(resetSample(sampleDb, root, T0)).leads).toBe(15); | |
| 233 | 233 | const listed = must(listLeads(sampleDb, alice, { now: T0.getTime() })); |
| 234 | // A believable first record: 11 leads in 30 days, 6 answered or waiting under 5 minutes. | |
| 235 | expect(listed.record).toMatchObject({ leads: 11, replied: 4, within_5_min_pct: 55 }); | |
| 236 | expect(listed.record.median_ms).toBe(200_000); | |
| 234 | // A believable first record: 14 leads in 30 days, 57% answered or waiting under 5 minutes. | |
| 235 | expect(listed.record).toMatchObject({ leads: 14, replied: 7, within_5_min_pct: 57 }); | |
| 236 | expect(listed.record.median_ms).toBe(195_000); | |
| 237 | 237 | const desk = listed.leads; |
| 238 | 238 | expect(desk).toHaveLength(SAMPLES.length); |
| 239 | 239 | expect(desk[0]!.name).toBe("Maria Gonzalez"); |
| @@ -285,7 +285,7 @@ test("reopening a closed lead reschedules the unsent cadence from now, never in | ||
| 285 | 285 | must(sendReply(db, alice, { id: lead.id }, at(0))); |
| 286 | 286 | must(tick(db, alice, at(1, 1))); |
| 287 | 287 | must(sendReply(db, alice, { id: lead.id }, at(1, 1))); |
| 288 | must(setState(db, alice, { id: lead.id, state: "lost" }, at(2))); | |
| 288 | must(setState(db, alice, { id: lead.id, state: "lost", reason: "other" }, at(2))); | |
| 289 | 289 | expect(setState(db, alice, { id: lead.id, state: "open" }, at(2)).ok).toBe(true); |
| 290 | 290 | const back = must(getLead(db, alice, { id: lead.id })); |
| 291 | 291 | expect(back.state).toBe("contacted"); |
| @@ -303,7 +303,7 @@ test("reopening a closed lead reschedules the unsent cadence from now, never in | ||
| 303 | 303 | |
| 304 | 304 | test("reopening a lead that was never answered makes it new with its first reply drafted", () => { |
| 305 | 305 | const lead = must(addLead(db, alice, { ...maria, name: "Never Answered", email: mail("Never Answered"), phone: phoneOf("Never Answered") }, at(0))); |
| 306 | must(setState(db, alice, { id: lead.id, state: "lost" })); | |
| 306 | must(setState(db, alice, { id: lead.id, state: "lost", reason: "other" })); | |
| 307 | 307 | expect(must(getLead(db, alice, { id: lead.id })).messages[0]!.status).toBe("skipped"); |
| 308 | 308 | const back = must(setState(db, alice, { id: lead.id, state: "open" })); |
| 309 | 309 | expect(back.state).toBe("new"); |
| @@ -340,7 +340,7 @@ test("an opted-out lead is never texted: not by tick, not by putting a closed le | ||
| 340 | 340 | must(optOutTexts(db, alice, { id: lead.id }, at(0, 5))); |
| 341 | 341 | must(tick(db, alice, at(40))); |
| 342 | 342 | expect(must(getLead(db, alice, { id: lead.id })).messages.every((m) => m.channel === (m.status === "sent" ? "text" : "email"))).toBe(true); |
| 343 | must(setState(db, alice, { id: lead.id, state: "lost" }, at(41))); | |
| 343 | must(setState(db, alice, { id: lead.id, state: "lost", reason: "other" }, at(41))); | |
| 344 | 344 | const back = must(setState(db, alice, { id: lead.id, state: "open" }, at(42))); |
| 345 | 345 | expect(back.messages.filter((m) => m.status !== "sent").every((m) => m.channel === "email")).toBe(true); |
| 346 | 346 | // A new inquiry with the same phone and consent is a new lead; the old one stays opted out. |
src/actions.ts +15 −4
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import { REASON_HELP, lostCounts, reasonOf, type LostCount } from "./lost.ts"; | |
| 10 | 11 | import { csvName, leadsCsv } from "./export.ts"; |
| 11 | 12 | import { mergeDetail, record, type Act, type AuditRow } from "./audit.ts"; |
| 12 | 13 | import { MAX_NOTE, outcomeOf } from "./calls.ts"; |
| @@ -826,11 +827,11 @@ function restoring( | ||
| 826 | 827 | return ok(detail(db, found.value.id)!); |
| 827 | 828 | } |
| 828 | 829 | |
| 829 | /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */ | |
| 830 | /** Qualified or lost (with one reason from the list): the lead leaves the cadence; open: it returns to it. */ | |
| 830 | 831 | export const setState = ( |
| 831 | 832 | db: Database, |
| 832 | 833 | who: Who, |
| 833 | input: { id: number; state: unknown }, | |
| 834 | input: { id: number; state: unknown; reason?: unknown }, | |
| 834 | 835 | at?: Date, |
| 835 | 836 | ): Result<LeadDetail> => |
| 836 | 837 | audited( |
| @@ -850,7 +851,7 @@ export const setState = ( | ||
| 850 | 851 | function mark( |
| 851 | 852 | db: Database, |
| 852 | 853 | who: Who, |
| 853 | input: { id: number; state: unknown }, | |
| 854 | input: { id: number; state: unknown; reason?: unknown }, | |
| 854 | 855 | at?: Date, |
| 855 | 856 | ): Result<LeadDetail> { |
| 856 | 857 | const found = leadFor(db, who, "update", input.id, { |
| @@ -867,7 +868,14 @@ function mark( | ||
| 867 | 868 | } |
| 868 | 869 | if (input.state !== "qualified" && input.state !== "lost") |
| 869 | 870 | return fail("invalid", "A lead is marked qualified or lost, or put back as open."); |
| 870 | close(db, found.value.id, input.state, stamp(at)); | |
| 871 | const reason = reasonOf(input.reason); | |
| 872 | if (input.state === "lost" && reason === undefined) return fail("invalid", REASON_HELP); | |
| 873 | close( | |
| 874 | db, | |
| 875 | found.value.id, | |
| 876 | input.state === "lost" ? { state: "lost", reason: reason! } : { state: "qualified" }, | |
| 877 | stamp(at), | |
| 878 | ); | |
| 871 | 879 | emit("lead.changed", { id: found.value.id }); |
| 872 | 880 | return ok(detail(db, found.value.id)!); |
| 873 | 881 | } |
| @@ -1195,6 +1203,8 @@ export interface Activity { | ||
| 1195 | 1203 | readonly names: ReadonlyMap<number, string>; |
| 1196 | 1204 | /** The id to page back from, when older rows exist. */ |
| 1197 | 1205 | readonly older: number | undefined; |
| 1206 | /** Leads lost in the last 30 days, by reason. */ | |
| 1207 | readonly lost: readonly LostCount[]; | |
| 1198 | 1208 | } |
| 1199 | 1209 | |
| 1200 | 1210 | /** One page of the audit trail with the leads' names looked up, for the Activity page. */ |
| @@ -1227,6 +1237,7 @@ export function activity( | ||
| 1227 | 1237 | names, |
| 1228 | 1238 | older: |
| 1229 | 1239 | found.value.length > ACTIVITY_PAGE ? rows[rows.length - 1]!.id : undefined, |
| 1240 | lost: lostCounts(db, Date.now()), | |
| 1230 | 1241 | }); |
| 1231 | 1242 | } |
| 1232 | 1243 |
src/audit.test.ts +3 −3
| @@ -207,7 +207,7 @@ test("/activity: an admin reads a sent reply and a refused attempt in sentences; | ||
| 207 | 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 | await call(`/leads/${lead.id}/state`, { method: "POST", body: JSON.stringify({ state: "lost" }) }, root); | |
| 210 | await call(`/leads/${lead.id}/state`, { method: "POST", body: JSON.stringify({ state: "lost", reason: "other" }) }, root); | |
| 211 | 211 | const refused = await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" }); |
| 212 | 212 | expect(refused.status).toBe(401); |
| 213 | 213 | |
| @@ -266,7 +266,7 @@ test("act is recorded as first_reply, reply, qualified and lost", () => { | ||
| 266 | 266 | db.query("UPDATE message SET status = 'due' WHERE lead_id = ?1 AND status = 'scheduled'").run(one.value.id); |
| 267 | 267 | sendReply(db, admin0, { id: one.value.id }, later); |
| 268 | 268 | setState(db, admin0, { id: two.value.id, state: "qualified" }); |
| 269 | setState(db, admin0, { id: three.value.id, state: "lost" }); | |
| 269 | setState(db, admin0, { id: three.value.id, state: "lost", reason: "other" }); | |
| 270 | 270 | const acts = db |
| 271 | 271 | .query<{ act: string | null }, []>("SELECT act FROM audit WHERE verb = 'update' ORDER BY id") |
| 272 | 272 | .all() |
| @@ -279,7 +279,7 @@ test("listAudit sentOnly keeps only sent replies; without it every row comes", ( | ||
| 279 | 279 | const one = addLead(db, admin0, NEW); |
| 280 | 280 | if (!one.ok) throw new Error("setup"); |
| 281 | 281 | sendReply(db, admin0, { id: one.value.id }); |
| 282 | setState(db, admin0, { id: one.value.id, state: "lost" }); | |
| 282 | setState(db, admin0, { id: one.value.id, state: "lost", reason: "other" }); | |
| 283 | 283 | const sent = listAudit(db, admin0, { sentOnly: true }); |
| 284 | 284 | expect(sent.ok && sent.value.map((r) => r.act)).toEqual(["first_reply"]); |
| 285 | 285 | const all = listAudit(db, admin0, {}); |
src/calls.test.ts +1 −1
| @@ -123,7 +123,7 @@ test("a closed lead that was called can be put back without its first reply retu | ||
| 123 | 123 | const db = fresh(); |
| 124 | 124 | const id = arrive(db); |
| 125 | 125 | value(logCall(db, alice, { id, outcome: "talked" }, at(MIN))); |
| 126 | value(setState(db, alice, { id, state: "lost" }, at(2 * MIN))); | |
| 126 | value(setState(db, alice, { id, state: "lost", reason: "other" }, at(2 * MIN))); | |
| 127 | 127 | const back = value(setState(db, alice, { id, state: "open" }, at(DAY))); |
| 128 | 128 | expect(back.state).toBe("contacted"); |
| 129 | 129 | expect(back.messages.find((m) => m.day === 0)!.status).toBe("skipped"); |
src/contract.test.ts +1 −1
| @@ -166,7 +166,7 @@ const doors: Record< | ||
| 166 | 166 | .get(skipId)!.id; |
| 167 | 167 | const skipped = skipFollowUp(db, who, { id: skipId, messageId: upcoming }).ok; |
| 168 | 168 | const restored = skipped && restoreFollowUp(db, who, { id: skipId, messageId: upcoming }).ok; |
| 169 | const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok; | |
| 169 | const changed = setState(db, who, { id: aLead(authorId), state: "lost", reason: "other" }).ok; | |
| 170 | 170 | expect(skipped).toBe(changed); |
| 171 | 171 | expect(restored).toBe(changed); |
| 172 | 172 | expect(untold).toBe(changed); |
src/db.test.ts +25
| @@ -74,3 +74,28 @@ test("a database made before Realtor.com was a source keeps its leads, their mes | ||
| 74 | 74 | expect(() => db.exec("INSERT INTO lead (name, email, source, message, consent) VALUES ('Y', '[email protected]', 'trulia', 'hi', 1)")).toThrow(); |
| 75 | 75 | expect(check(db).integrity).toBe("ok"); |
| 76 | 76 | }); |
| 77 | ||
| 78 | test("a database that stopped between the lost-reason columns and the Realtor.com rebuild is rewound and finishes", () => { | |
| 79 | const db = new Database(":memory:"); | |
| 80 | const start = migrations.findLastIndex((m) => m === "DROP TABLE IF EXISTS lead_new"); | |
| 81 | db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))"); | |
| 82 | migrations.slice(0, start).forEach((sql, i) => { | |
| 83 | try { | |
| 84 | db.exec(sql); | |
| 85 | } catch (e) { | |
| 86 | if (!/duplicate column/.test(String(e))) throw e; | |
| 87 | } | |
| 88 | db.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1); | |
| 89 | }); | |
| 90 | // As the earlier order left it: lost columns added, three versions recorded past the start. | |
| 91 | db.exec("ALTER TABLE lead ADD COLUMN lost_reason TEXT; ALTER TABLE lead ADD COLUMN lost_at TEXT"); | |
| 92 | for (const v of [start + 1, start + 2, start + 3]) db.query("INSERT INTO schema_version (version) VALUES (?1)").run(v); | |
| 93 | db.exec("INSERT INTO lead (id, name, email, source, message, consent, state) VALUES (3, 'A', '[email protected]', 'zillow', 'hi', 1, 'lost')"); | |
| 94 | ||
| 95 | expect(() => migrate(db)).not.toThrow(); | |
| 96 | ||
| 97 | expect(db.query("SELECT id FROM lead").all()).toEqual([{ id: 3 }]); | |
| 98 | expect(db.query("SELECT lost_at IS NOT NULL AS has FROM lead").get()).toEqual({ has: 1 }); | |
| 99 | db.exec("INSERT INTO lead (name, email, source, message, consent) VALUES ('B', '[email protected]', 'realtor_com', 'hi', 1)"); | |
| 100 | expect(check(db).integrity).toBe("ok"); | |
| 101 | }); |
src/db.ts +25 −1
| @@ -254,8 +254,31 @@ export const migrations: string[] = [ | ||
| 254 | 254 | ALTER TABLE lead_new RENAME TO lead; |
| 255 | 255 | PRAGMA legacy_alter_table = OFF`, |
| 256 | 256 | `CREATE INDEX IF NOT EXISTS lead_created ON lead (created_at)`, |
| 257 | // Why a lead was lost (one of a short fixed list, checked by the app) and | |
| 258 | // when. Null on a lead that is not lost, and on one lost before reasons | |
| 259 | // were asked for: those show "no reason given". | |
| 260 | `ALTER TABLE lead ADD COLUMN lost_reason TEXT`, | |
| 261 | `ALTER TABLE lead ADD COLUMN lost_at TEXT`, | |
| 262 | `UPDATE lead SET lost_at = updated_at WHERE state = 'lost'`, | |
| 257 | 263 | ]; |
| 258 | 264 | |
| 265 | /** | |
| 266 | * A database that ran this list before the Realtor.com rebuild was ahead of | |
| 267 | * the lost-reason columns stands part-way into the rebuild without the table | |
| 268 | * it copies into. Rewind it to the rebuild's first step (the rebuild leaves | |
| 269 | * `lost_*` behind; the later migrations add and backfill them again). | |
| 270 | */ | |
| 271 | function rebuildStart(db: Database, current: number): number { | |
| 272 | const start = migrations.findLastIndex((m) => m === "DROP TABLE IF EXISTS lead_new"); | |
| 273 | const midway = current > start && current <= start + 3; | |
| 274 | const copying = db | |
| 275 | .query<{ n: number }, []>("SELECT count(*) AS n FROM sqlite_master WHERE name = 'lead_new'") | |
| 276 | .get()!.n; | |
| 277 | if (start < 0 || !midway || copying > 0) return current; | |
| 278 | db.query("DELETE FROM schema_version WHERE version > ?1").run(start); | |
| 279 | return start; | |
| 280 | } | |
| 281 | ||
| 259 | 282 | /** An `ALTER TABLE … ADD COLUMN` whose column the table already has: nothing to do. */ |
| 260 | 283 | function alreadyAdded(db: Database, sql: string): boolean { |
| 261 | 284 | const added = /^ALTER TABLE (\w+) ADD COLUMN (\w+)/.exec(sql); |
| @@ -287,12 +310,13 @@ export function migrate(db: Database): number { | ||
| 287 | 310 | "CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))", |
| 288 | 311 | ); |
| 289 | 312 | const version = db.transaction(() => { |
| 290 | const current = db | |
| 313 | const recorded = db | |
| 291 | 314 | .query< |
| 292 | 315 | { version: number }, |
| 293 | 316 | [] |
| 294 | 317 | >("SELECT coalesce(max(version), 0) AS version FROM schema_version") |
| 295 | 318 | .get()!.version; |
| 319 | const current = rebuildStart(db, recorded); | |
| 296 | 320 | migrations.slice(current).forEach((sql, i) => { |
| 297 | 321 | if (!alreadyAdded(db, sql)) db.exec(sql); |
| 298 | 322 | db.query("INSERT INTO schema_version (version) VALUES (?1)").run( |
src/details.test.ts +3 −3
| @@ -129,7 +129,7 @@ test("a closed lead is not edited; an identity that may not update is refused an | ||
| 129 | 129 | .query<AuditRow, []>("SELECT * FROM audit WHERE verb = 'update' AND allowed = 0") |
| 130 | 130 | .all(); |
| 131 | 131 | expect(refusal).toHaveLength(1); |
| 132 | must(setState(db, alice, { id, state: "lost" })); | |
| 132 | must(setState(db, alice, { id, state: "lost", reason: "other" })); | |
| 133 | 133 | expect(editLead(db, alice, { id, name: "Late" }).ok).toBe(false); |
| 134 | 134 | expect(editLead(db, alice, { id: 9999, name: "Nobody" }).ok).toBe(false); |
| 135 | 135 | }); |
| @@ -182,7 +182,7 @@ test("PATCH /leads/:id and POST /leads/:id/edit correct the details; bad input i | ||
| 182 | 182 | expect((await patch({ name: "X" }, {})).status).toBe(401); |
| 183 | 183 | expect((await patch({ name: "X" }, undefined, { "sec-fetch-site": "cross-site" })).status).toBe(403); |
| 184 | 184 | // The state field still works as before. |
| 185 | expect((await patch({ state: "lost" })).status).toBe(200); | |
| 185 | expect((await patch({ state: "lost", reason: "other" })).status).toBe(200); | |
| 186 | 186 | |
| 187 | 187 | const other = await made(); |
| 188 | 188 | const posted = await call(`/leads/${other.id}/edit`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ phone: "206 555 0111" }) }); |
| @@ -216,7 +216,7 @@ test("the page shows Edit details to whoever may use it, and the Activity page t | ||
| 216 | 216 | f.set("email", "[email protected]"); |
| 217 | 217 | f.set("phone", ""); |
| 218 | 218 | await call(`/leads/${id}/edit`, { method: "POST", body: f, redirect: "manual" }, alice); |
| 219 | const closed = await call(`/leads/${id}/state`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ state: "lost" }) }, alice); | |
| 219 | const closed = await call(`/leads/${id}/state`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify({ state: "lost", reason: "other" }) }, alice); | |
| 220 | 220 | expect(closed.status).toBe(200); |
| 221 | 221 | expect(await (await call(`/leads/${id}`, {}, alice)).text()).not.toContain("Edit details"); |
| 222 | 222 |
src/export.test.ts +3 −2
| @@ -56,7 +56,7 @@ test("the download has the header, one row per lead, and the file headers", asyn | ||
| 56 | 56 | expect(rows[0]).toEqual([...COLUMNS]); |
| 57 | 57 | const all = await (await get("/leads")).json(); |
| 58 | 58 | expect(rows.length).toBe(1 + all.leads.length); |
| 59 | expect(all.leads.length).toBe(12); | |
| 59 | expect(all.leads.length).toBe(15); | |
| 60 | 60 | expect(rows[1]!.length).toBe(COLUMNS.length); |
| 61 | 61 | expect(["yes", "no"]).toContain(rows[1]![9]!); |
| 62 | 62 | expect(["open", "qualified", "lost"]).toContain(rows[1]![4]!); |
| @@ -169,9 +169,10 @@ test("minutes to first reply, texts allowed, and last message", () => { | ||
| 169 | 169 | "3", |
| 170 | 170 | "2026-11-02T11:00:00.000Z", |
| 171 | 171 | "yes", |
| 172 | "", | |
| 172 | 173 | ]); |
| 173 | 174 | const waiting = parse(leadsCsv([{ ...lead, replied_at: null, consent: false }], new Map()))[1]!; |
| 174 | expect(waiting.slice(6)).toEqual(["", "", "", "no"]); | |
| 175 | expect(waiting.slice(6)).toEqual(["", "", "", "no", ""]); | |
| 175 | 176 | expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv"); |
| 176 | 177 | }); |
| 177 | 178 |
src/export.ts +2
| @@ -17,6 +17,7 @@ export const COLUMNS = [ | ||
| 17 | 17 | "minutes to first reply", |
| 18 | 18 | "last message at", |
| 19 | 19 | "texts allowed", |
| 20 | "lost_reason", | |
| 20 | 21 | ] as const; |
| 21 | 22 | |
| 22 | 23 | /** An international number, "+1 206-555-0101": a plus and then only digits and the marks people type. */ |
| @@ -57,6 +58,7 @@ export function leadsCsv( | ||
| 57 | 58 | : String(Math.max(0, Math.round(between(lead.created_at, lead.replied_at) / 60_000))), |
| 58 | 59 | lastMessageAt.get(lead.id) ?? "", |
| 59 | 60 | lead.consent ? "yes" : "no", |
| 61 | lead.state === "lost" ? (lead.lostReason ?? "no reason given") : "", | |
| 60 | 62 | ]); |
| 61 | 63 | return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone")).join(",")).join("\r\n") + "\r\n"; |
| 62 | 64 | } |
src/inbound.test.ts +2 −2
| @@ -153,7 +153,7 @@ test("who may update a lead may log; nobody else; closed and unanswered leads ar | ||
| 153 | 153 | const fresher = arrive(db, true); |
| 154 | 154 | const early = logLeadReply(db, alice, { id: fresher, body: "hi", channel: "email" }); |
| 155 | 155 | expect(!early.ok && early.message).toContain("first reply"); |
| 156 | setState(db, alice, { id, state: "lost" }); | |
| 156 | setState(db, alice, { id, state: "lost", reason: "other" }); | |
| 157 | 157 | const closed = logLeadReply(db, alice, { id, body: "hi", channel: "email" }); |
| 158 | 158 | expect(!closed.ok && closed.message).toContain("put it back"); |
| 159 | 159 | // Every attempt is in the audit trail. |
| @@ -175,7 +175,7 @@ test("a second reply before the answer keeps one draft and the first clock", () | ||
| 175 | 175 | test("marking lost skips the answer; putting it back does not revive it", () => { |
| 176 | 176 | const { db, id } = answered(); |
| 177 | 177 | logLeadReply(db, alice, { id, body: "one", channel: "email" }, at(DAY)); |
| 178 | setState(db, alice, { id, state: "lost" }); | |
| 178 | setState(db, alice, { id, state: "lost", reason: "other" }); | |
| 179 | 179 | setState(db, alice, { id, state: "open" }, at(2 * DAY)); |
| 180 | 180 | const lead = value(getLead(db, alice, { id })); |
| 181 | 181 | expect(lead.messages.find((m) => m.day >= ANSWER_DAY)!.status).toBe("skipped"); |
src/leads.test.ts +1 −1
| @@ -133,7 +133,7 @@ test("an open lead is preferred to a closed one with the same email", () => { | ||
| 133 | 133 | const db = fresh(); |
| 134 | 134 | const old = arrive(db, { email: "[email protected]" }); |
| 135 | 135 | if (!old.ok) throw new Error("not added"); |
| 136 | setState(db, ADMIN, { id: old.value.id, state: "lost" }); | |
| 136 | setState(db, ADMIN, { id: old.value.id, state: "lost", reason: "other" }); | |
| 137 | 137 | const open = insertLead(db, { name: "Kim", email: "[email protected]", phone: "", source: "website", message: "hi", consent: false }, new Date(NOW).toISOString(), agent); |
| 138 | 138 | expect(findMatch(db, { name: "Kim", email: "[email protected]", phone: "" })?.id).toBe(open); |
| 139 | 139 | }); |
src/leads.ts +25 −12
| @@ -27,6 +27,7 @@ import { answers, type Call, type Outcome } from "./calls.ts"; | ||
| 27 | 27 | import { GREEN_MS } from "./clock.ts"; |
| 28 | 28 | import type { Agent } from "./env.ts"; |
| 29 | 29 | import { isQuiet, nextOpening } from "./quiet.ts"; |
| 30 | import { type LostReason } from "./lost.ts"; | |
| 30 | 31 | import { holdUntil, type Showing } from "./showings.ts"; |
| 31 | 32 | |
| 32 | 33 | export type State = "new" | "contacted" | "qualified" | "lost"; |
| @@ -52,6 +53,10 @@ export interface Lead { | ||
| 52 | 53 | readonly note: string; |
| 53 | 54 | /** When the note was last written; null while there is none. */ |
| 54 | 55 | readonly noteUpdatedAt: string | null; |
| 56 | /** Why the lead was lost; null unless it is lost, and for a lead lost before reasons were asked for. */ | |
| 57 | readonly lostReason: LostReason | null; | |
| 58 | /** When the lead was marked lost; null unless it is lost. */ | |
| 59 | readonly lostAt: string | null; | |
| 55 | 60 | } |
| 56 | 61 | |
| 57 | 62 | export interface Message { |
| @@ -169,14 +174,18 @@ export type NewLead = { | ||
| 169 | 174 | readonly consent: boolean; |
| 170 | 175 | }; |
| 171 | 176 | |
| 172 | type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt"> & { | |
| 177 | type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt"> & { | |
| 173 | 178 | consent: number; |
| 174 | 179 | note_updated_at: string | null; |
| 180 | lost_reason: LostReason | null; | |
| 181 | lost_at: string | null; | |
| 175 | 182 | }; |
| 176 | const lead = ({ note_updated_at, ...row }: LeadRecord): Lead => ({ | |
| 183 | const lead = ({ note_updated_at, lost_reason, lost_at, ...row }: LeadRecord): Lead => ({ | |
| 177 | 184 | ...row, |
| 178 | 185 | consent: row.consent === 1, |
| 179 | 186 | noteUpdatedAt: note_updated_at, |
| 187 | lostReason: lost_reason, | |
| 188 | lostAt: lost_at, | |
| 180 | 189 | }); |
| 181 | 190 | |
| 182 | 191 | const DAY_MS = 86_400_000; |
| @@ -852,18 +861,20 @@ function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): voi | ||
| 852 | 861 | } |
| 853 | 862 | } |
| 854 | 863 | |
| 855 | /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */ | |
| 856 | export function close( | |
| 857 | db: Database, | |
| 858 | id: number, | |
| 859 | state: "qualified" | "lost", | |
| 860 | at: string, | |
| 861 | ): void { | |
| 864 | /** How a lead closes: qualified, or lost, which always comes with its reason. */ | |
| 865 | export type Closing = { readonly state: "qualified" } | { readonly state: "lost"; readonly reason: LostReason }; | |
| 866 | ||
| 867 | /** Qualified or lost (with the reason): the lead leaves the cadence, and nothing more is drafted to go. */ | |
| 868 | export function close(db: Database, id: number, closing: Closing, at: string): void { | |
| 862 | 869 | db.transaction(() => { |
| 863 | db.query("UPDATE lead SET state = ?1, updated_at = ?2 WHERE id = ?3").run( | |
| 864 | state, | |
| 870 | db.query( | |
| 871 | "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5 WHERE id = ?3", | |
| 872 | ).run( | |
| 873 | closing.state, | |
| 865 | 874 | at, |
| 866 | 875 | id, |
| 876 | closing.state === "lost" ? closing.reason : null, | |
| 877 | closing.state === "lost" ? at : null, | |
| 867 | 878 | ); |
| 868 | 879 | db.query( |
| 869 | 880 | "UPDATE message SET status = 'skipped', goes_at = NULL WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due', 'held')", |
| @@ -880,7 +891,9 @@ export function close( | ||
| 880 | 891 | export function reopen(db: Database, found: Lead, at: string, agent: Agent): void { |
| 881 | 892 | db.transaction(() => { |
| 882 | 893 | const replied = found.replied_at !== null; |
| 883 | db.query("UPDATE lead SET state = ?1, updated_at = ?2 WHERE id = ?3").run( | |
| 894 | db.query( | |
| 895 | "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = NULL, lost_at = NULL WHERE id = ?3", | |
| 896 | ).run( | |
| 884 | 897 | replied ? "contacted" : "new", |
| 885 | 898 | at, |
| 886 | 899 | found.id, |
src/lost.test.ts added +199
| @@ -0,0 +1,199 @@ | ||
| 1 | /** | |
| 2 | * Marking a lead lost asks for one reason from a fixed list: checked at the | |
| 3 | * boundary (a 422 otherwise), shown on the lead's page with the date, cleared | |
| 4 | * by reopening, counted on the Activity page over 30 days, and in the CSV. | |
| 5 | */ | |
| 6 | import { afterAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { activity, addLead, exportLeads, getLead, setState, type Result } from "./actions.ts"; | |
| 11 | import { openDb } from "./db.ts"; | |
| 12 | import { LOST_REASONS, lostCounts } from "./lost.ts"; | |
| 13 | import { activityPage } from "./pages/activity.ts"; | |
| 14 | import { leadPage } from "./pages/lead.ts"; | |
| 15 | import { currentAgent } from "./profile.ts"; | |
| 16 | import { serve } from "./server.ts"; | |
| 17 | import { plain, terminal } from "./terminal.ts"; | |
| 18 | import type { Who } from "./who.ts"; | |
| 19 | import { sign } from "./who.ts"; | |
| 20 | ||
| 21 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 22 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 23 | const NEW = { | |
| 24 | name: "Dana Reys", | |
| 25 | email: "[email protected]", | |
| 26 | phone: "(206) 555-0199", | |
| 27 | source: "website", | |
| 28 | message: "Can I see 12 Oak Street this week?", | |
| 29 | consent: true, | |
| 30 | }; | |
| 31 | const T0 = new Date("2026-03-01T10:00:00Z"); | |
| 32 | ||
| 33 | const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-lost-"))); | |
| 34 | const must = <T>(r: Result<T>): T => { | |
| 35 | if (!r.ok) throw new Error(r.message); | |
| 36 | return r.value; | |
| 37 | }; | |
| 38 | let n = 0; | |
| 39 | const arrive = (db: ReturnType<typeof fresh>) => | |
| 40 | must(addLead(db, alice, { ...NEW, name: `Dana ${++n}`, email: `d${n}@example.com`, phone: `(206) 555-${String(3000 + n)}` }, T0)).id; | |
| 41 | ||
| 42 | test("lost needs one reason from the list; anything else is invalid and changes nothing", () => { | |
| 43 | const db = fresh(); | |
| 44 | const id = arrive(db); | |
| 45 | for (const reason of [undefined, "", "tired", 3, "Other", null]) { | |
| 46 | const r = setState(db, alice, { id, state: "lost", reason }); | |
| 47 | expect(r.ok).toBe(false); | |
| 48 | if (!r.ok) expect(r.error).toBe("invalid"); | |
| 49 | } | |
| 50 | expect(must(getLead(db, alice, { id })).state).not.toBe("lost"); | |
| 51 | for (const reason of LOST_REASONS) { | |
| 52 | const lost = must(setState(db, alice, { id, state: "lost", reason }, T0)); | |
| 53 | expect(lost).toMatchObject({ state: "lost", lostReason: reason, lostAt: T0.toISOString() }); | |
| 54 | must(setState(db, alice, { id, state: "open" })); | |
| 55 | } | |
| 56 | }); | |
| 57 | ||
| 58 | test("qualified takes no reason, and reopening clears the reason and the date", () => { | |
| 59 | const db = fresh(); | |
| 60 | const id = arrive(db); | |
| 61 | expect(must(setState(db, alice, { id, state: "qualified" }))).toMatchObject({ lostReason: null, lostAt: null }); | |
| 62 | must(setState(db, alice, { id, state: "open" })); | |
| 63 | must(setState(db, alice, { id, state: "lost", reason: "not_ready" })); | |
| 64 | const back = must(setState(db, alice, { id, state: "open" })); | |
| 65 | expect(back).toMatchObject({ lostReason: null, lostAt: null }); | |
| 66 | }); | |
| 67 | ||
| 68 | test("the lead page says why and when; a lead lost before reasons says no reason given", () => { | |
| 69 | const db = fresh(); | |
| 70 | const id = arrive(db); | |
| 71 | const page = () => | |
| 72 | leadPage({ who: alice, agent: currentAgent(db), lead: must(getLead(db, alice, { id })), mayUpdate: true, next: null, now: T0.getTime() }); | |
| 73 | expect(page()).toContain('<select name="reason"'); | |
| 74 | must(setState(db, alice, { id, state: "lost", reason: "not_ready" }, T0)); | |
| 75 | expect(page()).toContain("Lost — not ready yet, Sun, Mar 1"); | |
| 76 | must(setState(db, alice, { id, state: "open" })); | |
| 77 | expect(page()).not.toContain("Lost —"); | |
| 78 | must(setState(db, alice, { id, state: "lost", reason: "other" }, T0)); | |
| 79 | db.query("UPDATE lead SET lost_reason = NULL WHERE id = ?1").run(id); | |
| 80 | expect(page()).toContain("Lost — no reason given"); | |
| 81 | }); | |
| 82 | ||
| 83 | test("lostCounts counts each reason over the last 30 days, and old losses not at all", () => { | |
| 84 | const db = fresh(); | |
| 85 | const [a, b, c, d] = [arrive(db), arrive(db), arrive(db), arrive(db)]; | |
| 86 | must(setState(db, alice, { id: a!, state: "lost", reason: "not_ready" }, new Date("2026-03-20T10:00:00Z"))); | |
| 87 | must(setState(db, alice, { id: b!, state: "lost", reason: "not_ready" }, new Date("2026-03-21T10:00:00Z"))); | |
| 88 | must(setState(db, alice, { id: c!, state: "lost", reason: "bought_elsewhere" }, new Date("2026-01-01T10:00:00Z"))); | |
| 89 | db.query("UPDATE lead SET state = 'lost', lost_at = ?2, updated_at = ?2 WHERE id = ?1").run(d!, "2026-03-22T10:00:00.000Z"); | |
| 90 | const now = Date.parse("2026-03-25T10:00:00Z"); | |
| 91 | expect(lostCounts(db, now)).toEqual([ | |
| 92 | { reason: "not_ready", count: 2 }, | |
| 93 | { reason: null, count: 1 }, | |
| 94 | ]); | |
| 95 | const html = activityPage({ who: root, agent: currentAgent(db), rows: [], names: new Map(), older: undefined, lost: lostCounts(db, now), sentOnly: false }); | |
| 96 | expect(html).toContain("<strong>2</strong> not ready yet"); | |
| 97 | expect(html).toContain("<strong>1</strong> no reason given"); | |
| 98 | expect(must(activity(db, root, {})).lost).toEqual(lostCounts(db, Date.now())); | |
| 99 | }); | |
| 100 | ||
| 101 | test("the CSV has a lost_reason column: the reason, 'no reason given', or empty", () => { | |
| 102 | const db = fresh(); | |
| 103 | const [a, b, c] = [arrive(db), arrive(db), arrive(db)]; | |
| 104 | must(setState(db, alice, { id: a!, state: "lost", reason: "never_answered" })); | |
| 105 | db.query("UPDATE lead SET state = 'lost' WHERE id = ?1").run(b!); | |
| 106 | const csv = must(exportLeads(db, alice)).csv.trimEnd().split("\r\n"); | |
| 107 | const head = csv[0]!.split(","); | |
| 108 | expect(head[head.length - 1]).toBe("lost_reason"); | |
| 109 | const last = (id: number) => { | |
| 110 | const name = must(getLead(db, alice, { id })).name; | |
| 111 | return csv.find((l) => l.startsWith(`${name},`))!.split(",").pop(); | |
| 112 | }; | |
| 113 | expect(last(a!)).toBe("never_answered"); | |
| 114 | expect(last(b!)).toBe("no reason given"); | |
| 115 | expect(last(c!)).toBe(""); | |
| 116 | }); | |
| 117 | ||
| 118 | test("the terminal asks why on x, marks on 1-5, and esc changes nothing", () => { | |
| 119 | const db = fresh(); | |
| 120 | const id = arrive(db); | |
| 121 | const t = terminal(db, alice); | |
| 122 | const read = () => t.screen(100).map(plain).join("\n"); | |
| 123 | t.key("\r"); | |
| 124 | t.key("x"); | |
| 125 | expect(read()).toContain("1 bought with another agent"); | |
| 126 | t.key("\x1b"); | |
| 127 | expect(must(getLead(db, alice, { id })).state).not.toBe("lost"); | |
| 128 | t.key("x"); | |
| 129 | t.key("0"); // not on the list | |
| 130 | expect(must(getLead(db, alice, { id })).state).not.toBe("lost"); | |
| 131 | t.key("3"); | |
| 132 | expect(must(getLead(db, alice, { id }))).toMatchObject({ state: "lost", lostReason: "never_answered" }); | |
| 133 | expect(read()).toContain("never answered"); | |
| 134 | }); | |
| 135 | ||
| 136 | // --- the doors --- | |
| 137 | ||
| 138 | const KEY = "a-key-only-the-forge-holds"; | |
| 139 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY }); | |
| 140 | const base = `http://${server.hostname}:${server.port}`; | |
| 141 | afterAll(() => server.stop(true)); | |
| 142 | const as = (id: string, name: string, role = "user") => { | |
| 143 | const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`; | |
| 144 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 145 | }; | |
| 146 | const JSON_HEADERS = { "content-type": "application/json", accept: "application/json" }; | |
| 147 | const call = (path: string, init: RequestInit = {}, who = as("u-1", "alice")) => | |
| 148 | fetch(base + path, { ...init, headers: { ...(init.headers as object), ...who } }); | |
| 149 | const made = async () => { | |
| 150 | const body = { ...NEW, email: `w${++n}@example.com`, phone: `(206) 555-${4000 + n}` }; | |
| 151 | return (await (await call("/leads", { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) })).json()) as { id: number }; | |
| 152 | }; | |
| 153 | ||
| 154 | test("POST and PATCH reject a missing or unknown reason with 422, and keep a good one", async () => { | |
| 155 | const { id } = await made(); | |
| 156 | const post = (body: unknown) => | |
| 157 | call(`/leads/${id}/state`, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) }); | |
| 158 | expect((await post({ state: "lost" })).status).toBe(422); | |
| 159 | expect((await post({ state: "lost", reason: "tired" })).status).toBe(422); | |
| 160 | const ok = await post({ state: "lost", reason: "bought_elsewhere" }); | |
| 161 | expect(ok.status).toBe(200); | |
| 162 | expect(await ok.json()).toMatchObject({ state: "lost", lostReason: "bought_elsewhere" }); | |
| 163 | expect((await post({ state: "open" })).status).toBe(200); | |
| 164 | const patch = (body: unknown) => | |
| 165 | call(`/leads/${id}`, { method: "PATCH", headers: JSON_HEADERS, body: JSON.stringify(body) }); | |
| 166 | expect((await patch({ state: "lost" })).status).toBe(422); | |
| 167 | expect(((await (await patch({ state: "lost", reason: "not_a_lead" })).json()) as { lostReason: string }).lostReason).toBe("not_a_lead"); | |
| 168 | }); | |
| 169 | ||
| 170 | test("the page's form posts the reason, and the Activity page counts it for an admin", async () => { | |
| 171 | const { id } = await made(); | |
| 172 | const form = new FormData(); | |
| 173 | form.set("state", "lost"); | |
| 174 | form.set("reason", "not_ready"); | |
| 175 | expect((await call(`/leads/${id}/state`, { method: "POST", body: form, redirect: "manual" })).status).toBe(303); | |
| 176 | const bare = new FormData(); | |
| 177 | bare.set("state", "lost"); | |
| 178 | const { id: other } = await made(); | |
| 179 | await call(`/leads/${other}/state`, { method: "POST", body: bare, redirect: "manual" }); | |
| 180 | const after = await call(`/leads/${other}`, { headers: { accept: "application/json" } }); | |
| 181 | expect(((await after.json()) as { state: string }).state).not.toBe("lost"); | |
| 182 | const seen = await (await call("/activity", {}, as("u0", "root", "admin"))).text(); | |
| 183 | expect(seen).toContain("not ready yet"); | |
| 184 | expect(seen).toContain("Lost in the last 30 days"); | |
| 185 | }); | |
| 186 | ||
| 187 | test("the MCP mark_lead needs the reason too", async () => { | |
| 188 | const { id } = await made(); | |
| 189 | const rpc = (args: unknown) => | |
| 190 | call("/mcp", { | |
| 191 | method: "POST", | |
| 192 | headers: JSON_HEADERS, | |
| 193 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "mark_lead", arguments: args } }), | |
| 194 | }).then((r) => r.json() as Promise<any>); | |
| 195 | expect((await rpc({ id, state: "lost" })).result.isError).toBe(true); | |
| 196 | const done = await rpc({ id, state: "lost", reason: "other" }); | |
| 197 | expect(done.result.isError).toBeUndefined(); | |
| 198 | expect(JSON.parse(done.result.content[0].text)).toMatchObject({ state: "lost", lostReason: "other" }); | |
| 199 | }); |
src/lost.ts added +53
| @@ -0,0 +1,53 @@ | ||
| 1 | /** | |
| 2 | * Why a lead was lost: the short fixed list the agent picks from, and the | |
| 3 | * count of each over the last 30 days. Plain data in, plain data out. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { Database } from "bun:sqlite"; | |
| 7 | ||
| 8 | export const LOST_REASONS = ["bought_elsewhere", "not_ready", "never_answered", "not_a_lead", "other"] as const; | |
| 9 | export type LostReason = (typeof LOST_REASONS)[number]; | |
| 10 | ||
| 11 | /** What each reason says on a page, in the terminal and in the CSV's reading. */ | |
| 12 | export const REASON_LABEL: Readonly<Record<LostReason, string>> = { | |
| 13 | bought_elsewhere: "bought with another agent", | |
| 14 | not_ready: "not ready yet", | |
| 15 | never_answered: "never answered", | |
| 16 | not_a_lead: "not a real lead", | |
| 17 | other: "other", | |
| 18 | }; | |
| 19 | ||
| 20 | /** What a door tells whoever sent a reason that is not on the list. */ | |
| 21 | export const REASON_HELP = `A lead is lost for one reason: ${LOST_REASONS.join(", ")}.`; | |
| 22 | ||
| 23 | /** The reason from user text, or undefined when it is not on the list. */ | |
| 24 | export const reasonOf = (value: unknown): LostReason | undefined => | |
| 25 | LOST_REASONS.find((r) => r === value); | |
| 26 | ||
| 27 | export interface LostCount { | |
| 28 | /** Null for a lead marked lost before reasons were asked for. */ | |
| 29 | readonly reason: LostReason | null; | |
| 30 | readonly count: number; | |
| 31 | } | |
| 32 | ||
| 33 | const DAY_MS = 86_400_000; | |
| 34 | ||
| 35 | /** Leads lost in the 30 days up to `now`, counted by reason, the listed reasons first (zeros left out). */ | |
| 36 | export function lostCounts(db: Database, now: number): LostCount[] { | |
| 37 | const since = new Date(now - 30 * DAY_MS).toISOString(); | |
| 38 | const found = new Map<string | null, number>( | |
| 39 | db | |
| 40 | .query<{ reason: string | null; count: number }, [string]>( | |
| 41 | "SELECT lost_reason AS reason, count(*) AS count FROM lead WHERE state = 'lost' AND coalesce(lost_at, updated_at) >= ?1 GROUP BY lost_reason", | |
| 42 | ) | |
| 43 | .all(since) | |
| 44 | .map((r) => [r.reason, r.count]), | |
| 45 | ); | |
| 46 | return [...LOST_REASONS, null] | |
| 47 | .map((reason) => ({ reason, count: found.get(reason) ?? 0 })) | |
| 48 | .filter((r) => r.count > 0); | |
| 49 | } | |
| 50 | ||
| 51 | /** What a lost lead was lost for, in words; "no reason given" for one lost before reasons were asked for. */ | |
| 52 | export const lostSaid = (lead: { readonly lostReason: LostReason | null }): string => | |
| 53 | lead.lostReason === null ? "no reason given" : REASON_LABEL[lead.lostReason]; |
src/mcp.ts +4 −2
| @@ -36,6 +36,7 @@ import { MAX_ADDRESS } from "./showings.ts"; | ||
| 36 | 36 | import { OPENER_MAX, SOURCES } from "./drafts.ts"; |
| 37 | 37 | import { title } from "./env.ts"; |
| 38 | 38 | import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts"; |
| 39 | import { LOST_REASONS } from "./lost.ts"; | |
| 39 | 40 | import { fields } from "./http.ts"; |
| 40 | 41 | import type { Who } from "./who.ts"; |
| 41 | 42 | |
| @@ -210,17 +211,18 @@ export const tools: readonly Tool[] = [ | ||
| 210 | 211 | }, |
| 211 | 212 | { |
| 212 | 213 | name: "mark_lead", |
| 213 | description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it.", | |
| 214 | description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it. Lost needs a reason: bought_elsewhere, not_ready, never_answered, not_a_lead or other.", | |
| 214 | 215 | inputSchema: { |
| 215 | 216 | type: "object", |
| 216 | 217 | properties: { |
| 217 | 218 | id: { type: "integer" }, |
| 218 | 219 | state: { enum: ["qualified", "lost", "open"] }, |
| 220 | reason: { enum: [...LOST_REASONS], description: "Why the lead is lost; required when state is lost." }, | |
| 219 | 221 | }, |
| 220 | 222 | required: ["id", "state"], |
| 221 | 223 | }, |
| 222 | 224 | run: (db, who, args) => |
| 223 | setState(db, who, { id: Number(args.id), state: args.state }), | |
| 225 | setState(db, who, { id: Number(args.id), state: args.state, reason: args.reason }), | |
| 224 | 226 | }, |
| 225 | 227 | { |
| 226 | 228 | name: "edit_lead", |
src/next.test.ts +2 −2
| @@ -85,13 +85,13 @@ test("the next lead is the longest-waiting one left; the last gives null, and th | ||
| 85 | 85 | test("a closed lead's page shows the link; a lead that needs you does not", async () => { |
| 86 | 86 | const a = await arrive("Dee <i>Closed</i>"); |
| 87 | 87 | const b = await arrive("Eve Waiting"); |
| 88 | await post(`/leads/${a}/state`, { state: "lost" }); | |
| 88 | await post(`/leads/${a}/state`, { state: "lost", reason: "other" }); | |
| 89 | 89 | const closed = await (await api(`/leads/${a}`)).text(); |
| 90 | 90 | expect(closed).toContain(`Next: <a href="/leads/${b}">Eve Waiting, waiting`); |
| 91 | 91 | const waiting = await (await api(`/leads/${b}`)).text(); |
| 92 | 92 | expect(waiting).not.toContain("Next: <a"); |
| 93 | 93 | // The next lead's name is escaped. |
| 94 | await post(`/leads/${b}/state`, { state: "lost" }); | |
| 94 | await post(`/leads/${b}/state`, { state: "lost", reason: "other" }); | |
| 95 | 95 | const c = await arrive("<script>alert(1)</script>"); |
| 96 | 96 | const page = await (await api(`/leads/${a}`)).text(); |
| 97 | 97 | expect(page).toContain(`<script>alert(1)</script>, waiting`); |
src/notes.test.ts +2 −2
| @@ -76,7 +76,7 @@ test("a note works on a qualified or lost lead", () => { | ||
| 76 | 76 | const db = fresh(); |
| 77 | 77 | for (const state of ["qualified", "lost"] as const) { |
| 78 | 78 | const id = arrive(db); |
| 79 | must(setState(db, alice, { id, state })); | |
| 79 | must(setState(db, alice, { id, state, reason: "other" })); | |
| 80 | 80 | expect(must(setNote(db, alice, { id, note: "Call in spring." })).note).toBe("Call in spring."); |
| 81 | 81 | } |
| 82 | 82 | }); |
| @@ -202,7 +202,7 @@ test("PATCH /leads/:id keeps, clears and refuses a note; POST /leads/:id/note wo | ||
| 202 | 202 | |
| 203 | 203 | const tooLong = await patch({ note: "x".repeat(MAX_LEAD_NOTE + 1) }); |
| 204 | 204 | expect(tooLong.status).toBe(422); |
| 205 | expect(await patch({ note: "ok", state: "lost" })).toHaveProperty("status", 422); | |
| 205 | expect(await patch({ note: "ok", state: "lost", reason: "other" })).toHaveProperty("status", 422); | |
| 206 | 206 | expect(await patch({ note: 5 })).toHaveProperty("status", 422); |
| 207 | 207 | expect(await patch({ note: "x" }, {})).toHaveProperty("status", 401); |
| 208 | 208 | expect(await patch({ note: "x" }, undefined, { "sec-fetch-site": "cross-site" })).toHaveProperty("status", 403); |
src/pages/activity.ts +16 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * Every name is escaped; a lead that has since been removed is "a removed lead". |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import type { LostCount } from "../lost.ts"; | |
| 6 | 7 | import type { Activity } from "../actions.ts"; |
| 7 | 8 | import type { AuditRow } from "../audit.ts"; |
| 8 | 9 | import type { Agent } from "../env.ts"; |
| @@ -10,6 +11,7 @@ import { escape } from "../http.ts"; | ||
| 10 | 11 | import { said } from "../sentences.ts"; |
| 11 | 12 | import type { Who } from "../who.ts"; |
| 12 | 13 | import { layout } from "./layout.ts"; |
| 14 | import { REASON_LABEL } from "../lost.ts"; | |
| 13 | 15 | import { when } from "./parts.ts"; |
| 14 | 16 | |
| 15 | 17 | /** The lead a row is about, as a link, or as what it has become. */ |
| @@ -29,15 +31,27 @@ function sentence(row: AuditRow, names: ReadonlyMap<number, string>): string { | ||
| 29 | 31 | return `<li class="activity-row">${text}${refused} <span class="muted">· ${escape(when(row.at))}</span></li>`; |
| 30 | 32 | } |
| 31 | 33 | |
| 34 | /** Leads lost in the last 30 days, counted by the reason the agent gave. */ | |
| 35 | function lostBlock(lost: readonly LostCount[]): string { | |
| 36 | const items = lost | |
| 37 | .map((l) => `<li><strong>${l.count}</strong> ${escape(l.reason === null ? "no reason given" : REASON_LABEL[l.reason])}</li>`) | |
| 38 | .join(""); | |
| 39 | return `<section class="card stack" data-lost-reasons aria-label="Why leads were lost"> | |
| 40 | <h2>Lost in the last 30 days</h2> | |
| 41 | ${items === "" ? `<p class="muted">No lead was lost.</p>` : `<ul>${items}</ul>`} | |
| 42 | </section>`; | |
| 43 | } | |
| 44 | ||
| 32 | 45 | export function activityPage(input: { |
| 33 | 46 | who: Who; |
| 34 | 47 | agent: Agent; |
| 35 | 48 | rows: readonly AuditRow[]; |
| 36 | 49 | names: ReadonlyMap<number, string>; |
| 37 | 50 | older: number | undefined; |
| 51 | lost: readonly LostCount[]; | |
| 38 | 52 | sentOnly: boolean; |
| 39 | 53 | }): string { |
| 40 | const { who, agent, rows, names, older, sentOnly } = input; | |
| 54 | const { who, agent, rows, names, older, lost, sentOnly } = input; | |
| 41 | 55 | const filter = sentOnly ? "&show=sent" : ""; |
| 42 | 56 | const links = `<nav class="row" aria-label="Filter"> |
| 43 | 57 | <a class="button button-quiet" href="/activity"${sentOnly ? "" : ' aria-current="page"'}>Everything</a> |
| @@ -55,6 +69,7 @@ export function activityPage(input: { | ||
| 55 | 69 | body: `<p><a class="backlink" href="/">← All leads</a></p> |
| 56 | 70 | <h1>Activity</h1> |
| 57 | 71 | <p class="muted">Every change, newest first, and who made it. Refused attempts are shown too.</p> |
| 72 | ${lostBlock(lost)} | |
| 58 | 73 | ${links} |
| 59 | 74 | ${list} |
| 60 | 75 | ${older === undefined ? "" : `<p><a class="button button-quiet" href="/activity?before=${older}${filter}">Older</a></p>`}`, |
src/pages/lead.ts +7 −2
| @@ -15,6 +15,7 @@ import { answerSince, MAX_INBOUND, MAX_LEAD_NOTE, type LeadDetail, type Message, | ||
| 15 | 15 | import type { Agent } from "../env.ts"; |
| 16 | 16 | import type { Who } from "../who.ts"; |
| 17 | 17 | import { layout } from "./layout.ts"; |
| 18 | import { LOST_REASONS, REASON_LABEL, lostSaid } from "../lost.ts"; | |
| 18 | 19 | import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts"; |
| 19 | 20 | |
| 20 | 21 | /** One line of the thread: something we sent, or something they wrote back. */ |
| @@ -85,7 +86,9 @@ export function leadPage(input: { | ||
| 85 | 86 | : ready === undefined |
| 86 | 87 | ? `<div class="pane ours"><h2>Nothing to send right now</h2><p class="muted">${ |
| 87 | 88 | closed |
| 88 | ? `Marked ${STATE_LABEL[lead.state].toLowerCase()}: out of the follow-up plan.` | |
| 89 | ? lead.state === "lost" | |
| 90 | ? `Lost — ${escape(lostSaid(lead))}${lead.lostAt === null ? "" : `, ${escape(day(lead.lostAt))}`}: out of the follow-up plan.` | |
| 91 | : `Marked ${STATE_LABEL[lead.state].toLowerCase()}: out of the follow-up plan.` | |
| 89 | 92 | : lead.messages.some((m) => m.status === "scheduled") |
| 90 | 93 | ? "The next follow-up is drafted below and comes due on its day." |
| 91 | 94 | : "Every follow-up has gone out." |
| @@ -191,7 +194,9 @@ export function leadPage(input: { | ||
| 191 | 194 | mayUpdate && !closed |
| 192 | 195 | ? `<section class="states"> |
| 193 | 196 | <form method="post" action="${path}/state"><input type="hidden" name="state" value="qualified"><button class="button button-quiet">Mark qualified</button></form> |
| 194 | <form method="post" action="${path}/state"><input type="hidden" name="state" value="lost"><button class="button button-quiet">Mark lost</button></form> | |
| 197 | <form method="post" action="${path}/state"><input type="hidden" name="state" value="lost"> | |
| 198 | <label>Why? <select name="reason" required>${LOST_REASONS.map((r) => `<option value="${r}">${escape(REASON_LABEL[r])}</option>`).join("")}</select></label> | |
| 199 | <button class="button button-quiet">Mark lost</button></form> | |
| 195 | 200 | </section>` |
| 196 | 201 | : mayUpdate |
| 197 | 202 | ? `<section class="states"> |
src/quiet.test.ts +1 −1
| @@ -211,7 +211,7 @@ test("a held text of a lead since marked lost is set aside and never goes", () = | ||
| 211 | 211 | const db = fresh(); |
| 212 | 212 | const id = arrive(db); |
| 213 | 213 | value(approveReply(db, alice, { id }, at("22:30"))); |
| 214 | value(setState(db, alice, { id, state: "lost" })); | |
| 214 | value(setState(db, alice, { id, state: "lost", reason: "other" })); | |
| 215 | 215 | turn(db, at("08:00", "2026-06-11")); |
| 216 | 216 | expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("skipped"); |
| 217 | 217 | }); |
src/routes.ts +21 −6
| @@ -65,6 +65,7 @@ import { | ||
| 65 | 65 | import { MAX_NOTE, OUTCOMES } from "./calls.ts"; |
| 66 | 66 | import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts"; |
| 67 | 67 | import { MAX_EMAIL_TEXT } from "./intake.ts"; |
| 68 | import { LOST_REASONS, lostSaid } from "./lost.ts"; | |
| 68 | 69 | import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts"; |
| 69 | 70 | import { events } from "./live.ts"; |
| 70 | 71 | import { rpc } from "./mcp.ts"; |
| @@ -163,6 +164,15 @@ const LEAD_FIELDS = { | ||
| 163 | 164 | description: "When they asked to stop texts; consent is false from then on.", |
| 164 | 165 | }, |
| 165 | 166 | state: { enum: ["new", "contacted", "qualified", "lost"] }, |
| 167 | lostReason: { | |
| 168 | anyOf: [{ enum: [...LOST_REASONS] }, { type: "null" }], | |
| 169 | description: "Why the lead was lost; null unless it is lost, and for a lead lost before reasons were asked for.", | |
| 170 | }, | |
| 171 | lostAt: { | |
| 172 | type: ["string", "null"], | |
| 173 | format: "date-time", | |
| 174 | description: "When the lead was marked lost; null unless it is lost.", | |
| 175 | }, | |
| 166 | 176 | created_at: STAMP, |
| 167 | 177 | replied_at: { type: ["string", "null"], format: "date-time" }, |
| 168 | 178 | updated_at: STAMP, |
| @@ -476,6 +486,11 @@ const EDIT_FIELDS = { | ||
| 476 | 486 | phone: { type: "string", description: "7 to 20 digits; empty takes it away, if an email remains." }, |
| 477 | 487 | } as const; |
| 478 | 488 | |
| 489 | const REASON_FIELD = { | |
| 490 | enum: [...LOST_REASONS], | |
| 491 | description: "Why the lead is lost; required when state is lost.", | |
| 492 | } as const; | |
| 493 | ||
| 479 | 494 | const NOTE_FIELD = { |
| 480 | 495 | type: "string", |
| 481 | 496 | maxLength: MAX_LEAD_NOTE, |
| @@ -708,14 +723,14 @@ export const routes: readonly Route[] = [ | ||
| 708 | 723 | if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note })); |
| 709 | 724 | if (details) |
| 710 | 725 | return answer(editLead(c.db, c.who, { id: ID(c), ...contactOf(input) })); |
| 711 | return answer(setState(c.db, c.who, { id: ID(c), state: input.state })); | |
| 726 | return answer(setState(c.db, c.who, { id: ID(c), state: input.state, reason: input.reason })); | |
| 712 | 727 | }, |
| 713 | 728 | api: { |
| 714 | 729 | summary: |
| 715 | 730 | "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.", |
| 716 | 731 | body: { |
| 717 | 732 | type: "object", |
| 718 | properties: { state: { enum: ["qualified", "lost", "open"] }, ...EDIT_FIELDS, note: NOTE_FIELD }, | |
| 733 | properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD }, | |
| 719 | 734 | }, |
| 720 | 735 | answer: LEAD, |
| 721 | 736 | }, |
| @@ -885,17 +900,17 @@ export const routes: readonly Route[] = [ | ||
| 885 | 900 | handle: (c) => |
| 886 | 901 | posted( |
| 887 | 902 | c, |
| 888 | (input) => setState(c.db, c.who, { id: ID(c), state: input.state }), | |
| 903 | (input) => setState(c.db, c.who, { id: ID(c), state: input.state, reason: input.reason }), | |
| 889 | 904 | (lead) => ({ |
| 890 | 905 | to: `/leads/${ID(c)}`, |
| 891 | ...(lead === undefined ? {} : { said: lead.state === "qualified" || lead.state === "lost" ? `Marked ${lead.state}.` : "Back in follow-ups." }), | |
| 906 | ...(lead === undefined ? {} : { said: lead.state === "qualified" ? "Marked qualified." : lead.state === "lost" ? `Marked lost: ${lostSaid(lead)}.` : "Back in follow-ups." }), | |
| 892 | 907 | }), |
| 893 | 908 | ), |
| 894 | 909 | api: { |
| 895 | summary: "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 910 | summary: "Mark a lead qualified or lost (with a reason): it leaves the follow-up plan. 'open' puts a closed lead back in it.", | |
| 896 | 911 | body: { |
| 897 | 912 | type: "object", |
| 898 | properties: { state: { enum: ["qualified", "lost", "open"] } }, | |
| 913 | properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD }, | |
| 899 | 914 | required: ["state"], |
| 900 | 915 | }, |
| 901 | 916 | answer: LEAD, |
src/sample.test.ts +16 −1
| @@ -4,7 +4,10 @@ import { tmpdir } from "node:os"; | ||
| 4 | 4 | import { join } from "node:path"; |
| 5 | 5 | import { addSampleInquiry, getLead, listLeads, resetSample } from "./actions.ts"; |
| 6 | 6 | import { openDb } from "./db.ts"; |
| 7 | import { INQUIRIES, SAMPLES } from "./sample.ts"; | |
| 7 | import { lostCounts } from "./lost.ts"; | |
| 8 | import { activityPage } from "./pages/activity.ts"; | |
| 9 | import { currentAgent } from "./profile.ts"; | |
| 10 | import { INQUIRIES, SAMPLES, seed } from "./sample.ts"; | |
| 8 | 11 | import { terminal, plain } from "./terminal.ts"; |
| 9 | 12 | import type { Who } from "./who.ts"; |
| 10 | 13 | |
| @@ -87,3 +90,15 @@ test("the terminal key adds one", () => { | ||
| 87 | 90 | expect(names(db)).toHaveLength(1); |
| 88 | 91 | expect(t.screen(100).map(plain).join("\n")).toContain("clock is running"); |
| 89 | 92 | }); |
| 93 | ||
| 94 | test("the sample desk's lost leads carry real, varied reasons, and the Activity block counts them", () => { | |
| 95 | const db = openDb(mkdtempSync(join(tmpdir(), "app-sample-lost-"))); | |
| 96 | const now = new Date(); | |
| 97 | seed(db, now); | |
| 98 | const counts = lostCounts(db, now.getTime()); | |
| 99 | expect(counts.length).toBeGreaterThanOrEqual(3); | |
| 100 | expect(counts.every((c) => c.reason !== null)).toBe(true); | |
| 101 | const html = activityPage({ who: { role: "admin", id: "u0", name: "root" }, agent: currentAgent(db), rows: [], names: new Map(), older: undefined, lost: counts, sentOnly: false }); | |
| 102 | expect(html).toContain("bought with another agent"); | |
| 103 | expect(html).not.toContain("no reason given"); | |
| 104 | }); |
src/sample.ts +6 −2
| @@ -18,6 +18,7 @@ import { | ||
| 18 | 18 | readyFor, |
| 19 | 19 | send, |
| 20 | 20 | writeNote, |
| 21 | type Closing, | |
| 21 | 22 | type NewLead, |
| 22 | 23 | } from "./leads.ts"; |
| 23 | 24 | |
| @@ -28,7 +29,7 @@ interface Sample extends NewLead { | ||
| 28 | 29 | readonly answeredIn?: number; |
| 29 | 30 | /** The cadence days already sent. */ |
| 30 | 31 | readonly touched?: readonly number[]; |
| 31 | readonly closed?: "qualified" | "lost"; | |
| 32 | readonly closed?: Closing; | |
| 32 | 33 | /** The agent's private note on the lead, as of the first reply or the inquiry. */ |
| 33 | 34 | readonly note?: string; |
| 34 | 35 | } |
| @@ -70,8 +71,11 @@ export const SAMPLES: readonly Sample[] = [ | ||
| 70 | 71 | person("Marcus Lee", "zillow", true, "Can I tour 92 Harbor View Dr this week? Available most evenings after 6.", { ago: 2 * D + 3 * H, answeredIn: 48 * S, touched: [1], note: "Works nights: call after 6. Cash buyer, relocating from Austin; wants a short closing." }), |
| 71 | 72 | person("Rosa Alvarez", "referral", false, "My cousin Elena recommended you. We need a bigger place before the baby comes in March.", { ago: 4 * D + 2 * H, answeredIn: 3 * M + 20 * S, touched: [1] }), |
| 72 | 73 | person("Ethan Brooks", "realtor_com", true, "What would my 2-bed condo on Seaview Ave sell for? Considering upsizing next year.", { ago: 8 * D + 5 * H, answeredIn: 2 * M + 5 * S, touched: [1, 3] }), |
| 73 | person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: "qualified" }), | |
| 74 | person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: { state: "qualified" } }), | |
| 74 | 75 | person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14] }), |
| 76 | person("Owen Hart", "zillow", false, "Is 55 Cedar Ln still on the market? We'd like a second showing.", { ago: 9 * D, answeredIn: 2 * M + 40 * S, touched: [1, 3], closed: { state: "lost", reason: "bought_elsewhere" } }), | |
| 77 | person("Nadia Petrov", "website", true, "We might sell, but not before our kids finish school in two years. What should we do now?", { ago: 12 * D, answeredIn: 3 * M + 5 * S, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }), | |
| 78 | person("Carl Dunn", "referral", false, "A friend gave me your name. Call me about listing the duplex.", { ago: 20 * D, answeredIn: 5 * M, touched: [1, 3, 7], closed: { state: "lost", reason: "never_answered" } }), | |
| 75 | 79 | ]; |
| 76 | 80 | |
| 77 | 81 | /** Lay the samples out as of `now`. Returns how many. */ |
src/search.test.ts +2 −2
| @@ -37,8 +37,8 @@ test("a name, an email or a phone finds the lead, in any case", () => { | ||
| 37 | 37 | }); |
| 38 | 38 | |
| 39 | 39 | test("no search is the whole desk", () => { |
| 40 | expect(names({}).length).toBe(12); | |
| 41 | expect(names({ q: "" }).length).toBe(12); | |
| 40 | expect(names({}).length).toBe(15); | |
| 41 | expect(names({ q: "" }).length).toBe(15); | |
| 42 | 42 | }); |
| 43 | 43 | |
| 44 | 44 | test("a search combines with the view", () => { |
src/server.test.ts +2 −2
| @@ -247,7 +247,7 @@ test("POST /leads/:id/state and PATCH /leads/:id: qualified or lost leaves the c | ||
| 247 | 247 | const two = await created({ ...NEW, name: "Lose Me" }); |
| 248 | 248 | const patched = await api( |
| 249 | 249 | `/leads/${two.id}`, |
| 250 | { method: "PATCH", ...jsonBody({ state: "lost" }) }, | |
| 250 | { method: "PATCH", ...jsonBody({ state: "lost", reason: "other" }) }, | |
| 251 | 251 | alice, |
| 252 | 252 | ); |
| 253 | 253 | expect(patched.status).toBe(200); |
| @@ -651,7 +651,7 @@ test("GET /leads?q= is the desk's search as JSON, like the page", async () => { | ||
| 651 | 651 | test("a closed lead is put back in follow-ups from its page and the API; other states stay invalid", async () => { |
| 652 | 652 | const one = await created({ ...NEW, name: "Mis Tap" }); |
| 653 | 653 | await api(`/leads/${one.id}/reply`, { method: "POST", ...jsonBody({}) }, alice); |
| 654 | await api(`/leads/${one.id}/state`, { method: "POST", ...jsonBody({ state: "lost" }) }, alice); | |
| 654 | await api(`/leads/${one.id}/state`, { method: "POST", ...jsonBody({ state: "lost", reason: "other" }) }, alice); | |
| 655 | 655 | const page = await (await api(`/leads/${one.id}`, {}, alice)).text(); |
| 656 | 656 | expect(page).toContain("Put back in follow-ups"); |
| 657 | 657 | const back = await api( |
src/showings.test.ts +1 −1
| @@ -102,7 +102,7 @@ test("booking validates its inputs and asks permit", () => { | ||
| 102 | 102 | expect(refused(book({ when: "2026-03-07T10:00" }, anon))).toBe("signin_required"); |
| 103 | 103 | expect(refused(bookShowing(db, alice, { id: 999, when: "2026-03-07T10:00" }, at(1)))).toBe("not_found"); |
| 104 | 104 | |
| 105 | value(setState(db, alice, { id, state: "lost" }, at(1))); | |
| 105 | value(setState(db, alice, { id, state: "lost", reason: "other" }, at(1))); | |
| 106 | 106 | expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("invalid"); |
| 107 | 107 | }); |
| 108 | 108 |
src/skip.test.ts +1 −1
| @@ -127,7 +127,7 @@ test("reopening a lead does not resurrect a follow-up skipped by hand, but does | ||
| 127 | 127 | const id = answered(); |
| 128 | 128 | const three = day(id, 3); |
| 129 | 129 | must(skipFollowUp(db, alice, { id, messageId: three.id }, at(1))); |
| 130 | must(setState(db, alice, { id, state: "lost" }, at(2))); | |
| 130 | must(setState(db, alice, { id, state: "lost", reason: "other" }, at(2))); | |
| 131 | 131 | expect(restoreFollowUp(db, alice, { id, messageId: three.id }, at(2))).toMatchObject({ ok: false, error: "conflict" }); |
| 132 | 132 | must(setState(db, alice, { id, state: "open" }, at(3))); |
| 133 | 133 | expect(plan(id).map((m) => m.status)).toEqual(["scheduled", "skipped", "scheduled", "scheduled", "scheduled"]); |
src/terminal.test.ts +4 −2
| @@ -93,7 +93,8 @@ test("q and x close a lead from its screen", () => { | ||
| 93 | 93 | const t = terminal(db, alice); |
| 94 | 94 | t.key("\r"); |
| 95 | 95 | t.key("x"); |
| 96 | expect(read(t)).toContain("Maria Gonzalez: lost."); | |
| 96 | t.key("2"); | |
| 97 | expect(read(t)).toContain("Maria Gonzalez: lost, not ready yet."); | |
| 97 | 98 | expect(read(t)).not.toContain("s approve and send"); |
| 98 | 99 | }); |
| 99 | 100 | |
| @@ -363,6 +364,7 @@ test("o puts a closed lead back in follow-ups", () => { | ||
| 363 | 364 | const t = terminal(db, alice); |
| 364 | 365 | t.key("\r"); |
| 365 | 366 | t.key("x"); |
| 367 | t.key("5"); | |
| 366 | 368 | expect(read(t)).toContain("o put back in follow-ups"); |
| 367 | 369 | t.key("o"); |
| 368 | 370 | expect(read(t)).toContain("Maria Gonzalez: back in follow-ups."); |
| @@ -396,7 +398,7 @@ test("x on the desk shows the leads as CSV, for those who may list; esc goes bac | ||
| 396 | 398 | const t = terminal(db, alice); |
| 397 | 399 | t.key("x"); |
| 398 | 400 | const screen = read(t); |
| 399 | expect(screen).toContain("12 leads as CSV"); | |
| 401 | expect(screen).toContain("15 leads as CSV"); | |
| 400 | 402 | expect(screen).toContain("name,email,phone,source,status"); |
| 401 | 403 | expect(screen).toContain("Maria Gonzalez"); |
| 402 | 404 | t.key("\x1b"); |
src/terminal.ts +28 −7
| @@ -59,6 +59,7 @@ import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts"; | ||
| 59 | 59 | import { said as saidOf } from "./sentences.ts"; |
| 60 | 60 | import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel, type Source } from "./drafts.ts"; |
| 61 | 61 | import { ssh, title, where } from "./env.ts"; |
| 62 | import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts"; | |
| 62 | 63 | import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts"; |
| 63 | 64 | import { currentAgent } from "./profile.ts"; |
| 64 | 65 | import type { Who } from "./who.ts"; |
| @@ -150,6 +151,7 @@ type View = | ||
| 150 | 151 | | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string } |
| 151 | 152 | | { name: "wrote"; id: number; text: string; channel: Channel } |
| 152 | 153 | | { name: "note"; id: number; text: string } |
| 154 | | { name: "lost"; id: number } | |
| 153 | 155 | | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> } |
| 154 | 156 | | { name: "paste"; text: string } |
| 155 | 157 | | { name: "add"; step: number; typed: string; fields: Record<string, string>; found?: Record<string, string>; note?: string } |
| @@ -361,7 +363,7 @@ export function terminal( | ||
| 361 | 363 | lines.push( |
| 362 | 364 | dim( |
| 363 | 365 | l.state === "qualified" || l.state === "lost" |
| 364 | ? `Marked ${l.state}: out of the follow-up plan.` | |
| 366 | ? `Marked ${l.state}${l.state === "lost" ? ` — ${lostSaid(l)}` : ""}: out of the follow-up plan.` | |
| 365 | 367 | : next !== undefined |
| 366 | 368 | ? `Nothing to send now. ${titleOf(next)} comes due ${next.due_at.slice(0, 10)}.` |
| 367 | 369 | : "Every follow-up has gone out.", |
| @@ -628,6 +630,14 @@ export function terminal( | ||
| 628 | 630 | "", |
| 629 | 631 | dim("type a note · enter new line · ctrl-o outcome · ctrl-d log the call · esc cancel"), |
| 630 | 632 | ] |
| 633 | : view.name === "lost" | |
| 634 | ? [ | |
| 635 | bold(`Why was ${clean(lead(view.id)?.name ?? "the lead")} lost?`), | |
| 636 | "", | |
| 637 | ...LOST_REASONS.map((r, i) => ` ${i + 1} ${REASON_LABEL[r]}`), | |
| 638 | "", | |
| 639 | dim("1-5 mark it lost · esc cancel"), | |
| 640 | ] | |
| 631 | 641 | : view.name === "note" |
| 632 | 642 | ? [ |
| 633 | 643 | bold(`Your note on ${clean(lead(view.id)?.name ?? "the lead")} (private, never sent)`), |
| @@ -786,13 +796,12 @@ export function terminal( | ||
| 786 | 796 | const r = ready(l); |
| 787 | 797 | if (r === undefined) said = "Nothing is waiting to go to this lead right now."; |
| 788 | 798 | else view = { name: "edit", id, text: r.body }; |
| 789 | } else if (input === "q" || input === "x") { | |
| 790 | const marked = setState(db, me, { | |
| 791 | id, | |
| 792 | state: input === "q" ? "qualified" : "lost", | |
| 793 | }); | |
| 799 | } else if (input === "q") { | |
| 800 | const marked = setState(db, me, { id, state: "qualified" }); | |
| 794 | 801 | said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message; |
| 795 | } else if (input === "c" && l.phone !== "") | |
| 802 | } else if (input === "x" && !CLOSED.includes(l.state)) | |
| 803 | view = { name: "lost", id }; | |
| 804 | else if (input === "c" && l.phone !== "") | |
| 796 | 805 | view = { name: "call", id, outcome: "talked", text: "" }; |
| 797 | 806 | else if (input === "b" && !CLOSED.includes(l.state)) |
| 798 | 807 | view = { name: "showing", id, step: 0, typed: "", when: "" }; |
| @@ -905,6 +914,18 @@ export function terminal( | ||
| 905 | 914 | } |
| 906 | 915 | return; |
| 907 | 916 | } |
| 917 | case "lost": { | |
| 918 | const reason = LOST_REASONS[Number(input) - 1]; | |
| 919 | if (reason !== undefined && /^[1-9]$/.test(input)) { | |
| 920 | const marked = setState(db, me, { id: view.id, state: "lost", reason }); | |
| 921 | said = marked.ok ? `${marked.value.name}: lost, ${REASON_LABEL[reason]}.` : marked.message; | |
| 922 | view = { name: "lead", id: view.id }; | |
| 923 | } else if (input === "\x1b") { | |
| 924 | said = "Nothing changed."; | |
| 925 | view = { name: "lead", id: view.id }; | |
| 926 | } | |
| 927 | return; | |
| 928 | } | |
| 908 | 929 | case "note": { |
| 909 | 930 | if (input === "\x1b") { |
| 910 | 931 | said = "Note unchanged."; |
new above
offline
Default reason = null lets state 'lost' be stored with no reason; make it required for lost and pass sample reasons from src/sample.ts:95.