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

Merged opened this

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

Merged

mason/speed-to-lead:mason/51-mark-a-lead-lost-with-a-reason-bought-wi → main 5 commits fork 1 thread · 1 unresolved

  • Merged. mason/51-mark-a-lead-lost-with-a-reason-bought-wi was merged into main as 3cdba72.

Review

Sign in to review this change.
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
2323 what you see right after a restart. Do step 1 first.
2424
2525 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
2727 again with fresh clocks.
2828 2. Read the desk. The newest leads are at the top. **Maria Gonzalez** and
2929 **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
220220 scheduled from that moment at day 1, 3, 7, 14 and 30, skipping those already
221221 sent.
222222
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
223234 **When a lead answers.** The app sends nothing, so it never sees their
224235 reply: you paste it in. On the lead's page open **They wrote back**, paste
225236 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
298309 skips the next follow-up in the plan (it says which day) and `K` brings back the
299310 first one you skipped. Activity shows both.
300311
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
302313 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
304315 from the bottom of the desk, so the clocks read fresh for a demonstration.
305316
306317 ## What is real and what is not, in this prototype
@@ -448,7 +459,7 @@ says who may do what.
448459 | `src/leads.ts` | leads and messages: arrive, send, follow up, close |
449460 | `src/drafts.ts` | the drafted words, the signature, the consent rule |
450461 | `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 |
452463 | `src/pages/` | the desk and the lead page, server-rendered |
453464 | `src/routes.ts` | every path, each API route described beside it |
454465 | `src/security.ts`, `src/http.ts` | the door and the floor: rationing, same origin, headers |
contract/openapi.json +103 −2
@@ -351,6 +351,16 @@
351351 "open"
352352 ]
353353 },
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 },
354364 "name": {
355365 "type": "string",
356366 "minLength": 1,
@@ -555,6 +565,31 @@
555565 "lost"
556566 ]
557567 },
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 },
558593 "created_at": {
559594 "type": "string",
560595 "format": "date-time"
@@ -723,6 +758,8 @@
723758 "noteUpdatedAt",
724759 "opted_out_at",
725760 "state",
761 "lostReason",
762 "lostAt",
726763 "created_at",
727764 "replied_at",
728765 "updated_at",
@@ -982,7 +1019,7 @@
9821019 },
9831020 "/leads/{id}/state": {
9841021 "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.",
9861023 "operationId": "postLeadsIdState",
9871024 "parameters": [
9881025 {
@@ -1007,6 +1044,16 @@
10071044 "lost",
10081045 "open"
10091046 ]
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."
10101057 }
10111058 },
10121059 "required": [
@@ -1018,7 +1065,7 @@
10181065 },
10191066 "responses": {
10201067 "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.",
10221069 "content": {
10231070 "application/json": {
10241071 "schema": {
@@ -1938,6 +1985,31 @@
19381985 "lost"
19391986 ]
19401987 },
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 },
19412013 "created_at": {
19422014 "type": "string",
19432015 "format": "date-time"
@@ -2082,6 +2154,8 @@
20822154 "noteUpdatedAt",
20832155 "opted_out_at",
20842156 "state",
2157 "lostReason",
2158 "lostAt",
20852159 "created_at",
20862160 "replied_at",
20872161 "updated_at",
@@ -2281,6 +2355,31 @@
22812355 "lost"
22822356 ]
22832357 },
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 },
22842383 "created_at": {
22852384 "type": "string",
22862385 "format": "date-time"
@@ -2366,6 +2465,8 @@
23662465 "noteUpdatedAt",
23672466 "opted_out_at",
23682467 "state",
2468 "lostReason",
2469 "lostAt",
23692470 "created_at",
23702471 "replied_at",
23712472 "updated_at",
src/actions.test.ts +9 −9
@@ -221,19 +221,19 @@ test("qualified or lost leaves the cadence", () => {
221221 const odd = setState(db, alice, { id: lead.id, state: "contacted" });
222222 expect(odd.ok).toBe(false);
223223 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" });
225225 expect(gone.ok).toBe(false);
226226 if (!gone.ok) expect(gone.error).toBe("not_found");
227227 });
228228
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", () => {
230230 const sampleDb = openDb(mkdtempSync(join(tmpdir(), "app-sample-")));
231231 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);
233233 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);
237237 const desk = listed.leads;
238238 expect(desk).toHaveLength(SAMPLES.length);
239239 expect(desk[0]!.name).toBe("Maria Gonzalez");
@@ -285,7 +285,7 @@ test("reopening a closed lead reschedules the unsent cadence from now, never in
285285 must(sendReply(db, alice, { id: lead.id }, at(0)));
286286 must(tick(db, alice, at(1, 1)));
287287 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)));
289289 expect(setState(db, alice, { id: lead.id, state: "open" }, at(2)).ok).toBe(true);
290290 const back = must(getLead(db, alice, { id: lead.id }));
291291 expect(back.state).toBe("contacted");
@@ -303,7 +303,7 @@ test("reopening a closed lead reschedules the unsent cadence from now, never in
303303
304304 test("reopening a lead that was never answered makes it new with its first reply drafted", () => {
305305 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" }));
307307 expect(must(getLead(db, alice, { id: lead.id })).messages[0]!.status).toBe("skipped");
308308 const back = must(setState(db, alice, { id: lead.id, state: "open" }));
309309 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
340340 must(optOutTexts(db, alice, { id: lead.id }, at(0, 5)));
341341 must(tick(db, alice, at(40)));
342342 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)));
344344 const back = must(setState(db, alice, { id: lead.id, state: "open" }, at(42)));
345345 expect(back.messages.filter((m) => m.status !== "sent").every((m) => m.channel === "email")).toBe(true);
346346 // 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 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { REASON_HELP, lostCounts, reasonOf, type LostCount } from "./lost.ts";
1011 import { csvName, leadsCsv } from "./export.ts";
1112 import { mergeDetail, record, type Act, type AuditRow } from "./audit.ts";
1213 import { MAX_NOTE, outcomeOf } from "./calls.ts";
@@ -826,11 +827,11 @@ function restoring(
826827 return ok(detail(db, found.value.id)!);
827828 }
828829
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. */
830831 export const setState = (
831832 db: Database,
832833 who: Who,
833 input: { id: number; state: unknown },
834 input: { id: number; state: unknown; reason?: unknown },
834835 at?: Date,
835836 ): Result<LeadDetail> =>
836837 audited(
@@ -850,7 +851,7 @@ export const setState = (
850851 function mark(
851852 db: Database,
852853 who: Who,
853 input: { id: number; state: unknown },
854 input: { id: number; state: unknown; reason?: unknown },
854855 at?: Date,
855856 ): Result<LeadDetail> {
856857 const found = leadFor(db, who, "update", input.id, {
@@ -867,7 +868,14 @@ function mark(
867868 }
868869 if (input.state !== "qualified" && input.state !== "lost")
869870 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 );
871879 emit("lead.changed", { id: found.value.id });
872880 return ok(detail(db, found.value.id)!);
873881 }
@@ -1195,6 +1203,8 @@ export interface Activity {
11951203 readonly names: ReadonlyMap<number, string>;
11961204 /** The id to page back from, when older rows exist. */
11971205 readonly older: number | undefined;
1206 /** Leads lost in the last 30 days, by reason. */
1207 readonly lost: readonly LostCount[];
11981208 }
11991209
12001210 /** One page of the audit trail with the leads' names looked up, for the Activity page. */
@@ -1227,6 +1237,7 @@ export function activity(
12271237 names,
12281238 older:
12291239 found.value.length > ACTIVITY_PAGE ? rows[rows.length - 1]!.id : undefined,
1240 lost: lostCounts(db, Date.now()),
12301241 });
12311242 }
12321243
src/audit.test.ts +3 −3
@@ -207,7 +207,7 @@ test("/activity: an admin reads a sent reply and a refused attempt in sentences;
207207 await call("/leads", { method: "POST", body: JSON.stringify({ ...NEW, name: "Maria <script>x</script>", email: "[email protected]" }) }, alice)
208208 ).json()) as { id: number };
209209 await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" }, root);
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);
211211 const refused = await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" });
212212 expect(refused.status).toBe(401);
213213
@@ -266,7 +266,7 @@ test("act is recorded as first_reply, reply, qualified and lost", () => {
266266 db.query("UPDATE message SET status = 'due' WHERE lead_id = ?1 AND status = 'scheduled'").run(one.value.id);
267267 sendReply(db, admin0, { id: one.value.id }, later);
268268 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" });
270270 const acts = db
271271 .query<{ act: string | null }, []>("SELECT act FROM audit WHERE verb = 'update' ORDER BY id")
272272 .all()
@@ -279,7 +279,7 @@ test("listAudit sentOnly keeps only sent replies; without it every row comes", (
279279 const one = addLead(db, admin0, NEW);
280280 if (!one.ok) throw new Error("setup");
281281 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" });
283283 const sent = listAudit(db, admin0, { sentOnly: true });
284284 expect(sent.ok && sent.value.map((r) => r.act)).toEqual(["first_reply"]);
285285 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
123123 const db = fresh();
124124 const id = arrive(db);
125125 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)));
127127 const back = value(setState(db, alice, { id, state: "open" }, at(DAY)));
128128 expect(back.state).toBe("contacted");
129129 expect(back.messages.find((m) => m.day === 0)!.status).toBe("skipped");
src/contract.test.ts +1 −1
@@ -166,7 +166,7 @@ const doors: Record<
166166 .get(skipId)!.id;
167167 const skipped = skipFollowUp(db, who, { id: skipId, messageId: upcoming }).ok;
168168 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;
170170 expect(skipped).toBe(changed);
171171 expect(restored).toBe(changed);
172172 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
7474 expect(() => db.exec("INSERT INTO lead (name, email, source, message, consent) VALUES ('Y', '[email protected]', 'trulia', 'hi', 1)")).toThrow();
7575 expect(check(db).integrity).toBe("ok");
7676 });
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[] = [
254254 ALTER TABLE lead_new RENAME TO lead;
255255 PRAGMA legacy_alter_table = OFF`,
256256 `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'`,
257263 ];
258264
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
259282 /** An `ALTER TABLE … ADD COLUMN` whose column the table already has: nothing to do. */
260283 function alreadyAdded(db: Database, sql: string): boolean {
261284 const added = /^ALTER TABLE (\w+) ADD COLUMN (\w+)/.exec(sql);
@@ -287,12 +310,13 @@ export function migrate(db: Database): number {
287310 "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')))",
288311 );
289312 const version = db.transaction(() => {
290 const current = db
313 const recorded = db
291314 .query<
292315 { version: number },
293316 []
294317 >("SELECT coalesce(max(version), 0) AS version FROM schema_version")
295318 .get()!.version;
319 const current = rebuildStart(db, recorded);
296320 migrations.slice(current).forEach((sql, i) => {
297321 if (!alreadyAdded(db, sql)) db.exec(sql);
298322 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
129129 .query<AuditRow, []>("SELECT * FROM audit WHERE verb = 'update' AND allowed = 0")
130130 .all();
131131 expect(refusal).toHaveLength(1);
132 must(setState(db, alice, { id, state: "lost" }));
132 must(setState(db, alice, { id, state: "lost", reason: "other" }));
133133 expect(editLead(db, alice, { id, name: "Late" }).ok).toBe(false);
134134 expect(editLead(db, alice, { id: 9999, name: "Nobody" }).ok).toBe(false);
135135 });
@@ -182,7 +182,7 @@ test("PATCH /leads/:id and POST /leads/:id/edit correct the details; bad input i
182182 expect((await patch({ name: "X" }, {})).status).toBe(401);
183183 expect((await patch({ name: "X" }, undefined, { "sec-fetch-site": "cross-site" })).status).toBe(403);
184184 // 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);
186186
187187 const other = await made();
188188 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
216216 f.set("email", "[email protected]");
217217 f.set("phone", "");
218218 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);
220220 expect(closed.status).toBe(200);
221221 expect(await (await call(`/leads/${id}`, {}, alice)).text()).not.toContain("Edit details");
222222
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
5656 expect(rows[0]).toEqual([...COLUMNS]);
5757 const all = await (await get("/leads")).json();
5858 expect(rows.length).toBe(1 + all.leads.length);
59 expect(all.leads.length).toBe(12);
59 expect(all.leads.length).toBe(15);
6060 expect(rows[1]!.length).toBe(COLUMNS.length);
6161 expect(["yes", "no"]).toContain(rows[1]![9]!);
6262 expect(["open", "qualified", "lost"]).toContain(rows[1]![4]!);
@@ -169,9 +169,10 @@ test("minutes to first reply, texts allowed, and last message", () => {
169169 "3",
170170 "2026-11-02T11:00:00.000Z",
171171 "yes",
172 "",
172173 ]);
173174 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", ""]);
175176 expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv");
176177 });
177178
src/export.ts +2
@@ -17,6 +17,7 @@ export const COLUMNS = [
1717 "minutes to first reply",
1818 "last message at",
1919 "texts allowed",
20 "lost_reason",
2021 ] as const;
2122
2223 /** 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(
5758 : String(Math.max(0, Math.round(between(lead.created_at, lead.replied_at) / 60_000))),
5859 lastMessageAt.get(lead.id) ?? "",
5960 lead.consent ? "yes" : "no",
61 lead.state === "lost" ? (lead.lostReason ?? "no reason given") : "",
6062 ]);
6163 return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone")).join(",")).join("\r\n") + "\r\n";
6264 }
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
153153 const fresher = arrive(db, true);
154154 const early = logLeadReply(db, alice, { id: fresher, body: "hi", channel: "email" });
155155 expect(!early.ok && early.message).toContain("first reply");
156 setState(db, alice, { id, state: "lost" });
156 setState(db, alice, { id, state: "lost", reason: "other" });
157157 const closed = logLeadReply(db, alice, { id, body: "hi", channel: "email" });
158158 expect(!closed.ok && closed.message).toContain("put it back");
159159 // 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", ()
175175 test("marking lost skips the answer; putting it back does not revive it", () => {
176176 const { db, id } = answered();
177177 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" });
179179 setState(db, alice, { id, state: "open" }, at(2 * DAY));
180180 const lead = value(getLead(db, alice, { id }));
181181 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", () => {
133133 const db = fresh();
134134 const old = arrive(db, { email: "[email protected]" });
135135 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" });
137137 const open = insertLead(db, { name: "Kim", email: "[email protected]", phone: "", source: "website", message: "hi", consent: false }, new Date(NOW).toISOString(), agent);
138138 expect(findMatch(db, { name: "Kim", email: "[email protected]", phone: "" })?.id).toBe(open);
139139 });
src/leads.ts +25 −12
@@ -27,6 +27,7 @@ import { answers, type Call, type Outcome } from "./calls.ts";
2727 import { GREEN_MS } from "./clock.ts";
2828 import type { Agent } from "./env.ts";
2929 import { isQuiet, nextOpening } from "./quiet.ts";
30 import { type LostReason } from "./lost.ts";
3031 import { holdUntil, type Showing } from "./showings.ts";
3132
3233 export type State = "new" | "contacted" | "qualified" | "lost";
@@ -52,6 +53,10 @@ export interface Lead {
5253 readonly note: string;
5354 /** When the note was last written; null while there is none. */
5455 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;
5560 }
5661
5762 export interface Message {
@@ -169,14 +174,18 @@ export type NewLead = {
169174 readonly consent: boolean;
170175 };
171176
172 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt"> & {
177 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt"> & {
173178 consent: number;
174179 note_updated_at: string | null;
180 lost_reason: LostReason | null;
181 lost_at: string | null;
175182 };
176 const lead = ({ note_updated_at, ...row }: LeadRecord): Lead => ({
183 const lead = ({ note_updated_at, lost_reason, lost_at, ...row }: LeadRecord): Lead => ({
177184 ...row,
178185 consent: row.consent === 1,
179186 noteUpdatedAt: note_updated_at,
187 lostReason: lost_reason,
188 lostAt: lost_at,
180189 });
181190
182191 const DAY_MS = 86_400_000;
@@ -852,18 +861,20 @@ function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): voi
852861 }
853862 }
854863
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 {
862869 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",
outdated

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.

872 ).run(
873 closing.state,
865874 at,
866875 id,
876 closing.state === "lost" ? closing.reason : null,
877 closing.state === "lost" ? at : null,
867878 );
868879 db.query(
869880 "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(
880891 export function reopen(db: Database, found: Lead, at: string, agent: Agent): void {
881892 db.transaction(() => {
882893 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(
884897 replied ? "contacted" : "new",
885898 at,
886899 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";
3636 import { OPENER_MAX, SOURCES } from "./drafts.ts";
3737 import { title } from "./env.ts";
3838 import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
39 import { LOST_REASONS } from "./lost.ts";
3940 import { fields } from "./http.ts";
4041 import type { Who } from "./who.ts";
4142
@@ -210,17 +211,18 @@ export const tools: readonly Tool[] = [
210211 },
211212 {
212213 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.",
214215 inputSchema: {
215216 type: "object",
216217 properties: {
217218 id: { type: "integer" },
218219 state: { enum: ["qualified", "lost", "open"] },
220 reason: { enum: [...LOST_REASONS], description: "Why the lead is lost; required when state is lost." },
219221 },
220222 required: ["id", "state"],
221223 },
222224 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 }),
224226 },
225227 {
226228 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
8585 test("a closed lead's page shows the link; a lead that needs you does not", async () => {
8686 const a = await arrive("Dee <i>Closed</i>");
8787 const b = await arrive("Eve Waiting");
88 await post(`/leads/${a}/state`, { state: "lost" });
88 await post(`/leads/${a}/state`, { state: "lost", reason: "other" });
8989 const closed = await (await api(`/leads/${a}`)).text();
9090 expect(closed).toContain(`Next: <a href="/leads/${b}">Eve Waiting, waiting`);
9191 const waiting = await (await api(`/leads/${b}`)).text();
9292 expect(waiting).not.toContain("Next: <a");
9393 // 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" });
9595 const c = await arrive("<script>alert(1)</script>");
9696 const page = await (await api(`/leads/${a}`)).text();
9797 expect(page).toContain(`&lt;script&gt;alert(1)&lt;/script&gt;, waiting`);
src/notes.test.ts +2 −2
@@ -76,7 +76,7 @@ test("a note works on a qualified or lost lead", () => {
7676 const db = fresh();
7777 for (const state of ["qualified", "lost"] as const) {
7878 const id = arrive(db);
79 must(setState(db, alice, { id, state }));
79 must(setState(db, alice, { id, state, reason: "other" }));
8080 expect(must(setNote(db, alice, { id, note: "Call in spring." })).note).toBe("Call in spring.");
8181 }
8282 });
@@ -202,7 +202,7 @@ test("PATCH /leads/:id keeps, clears and refuses a note; POST /leads/:id/note wo
202202
203203 const tooLong = await patch({ note: "x".repeat(MAX_LEAD_NOTE + 1) });
204204 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);
206206 expect(await patch({ note: 5 })).toHaveProperty("status", 422);
207207 expect(await patch({ note: "x" }, {})).toHaveProperty("status", 401);
208208 expect(await patch({ note: "x" }, undefined, { "sec-fetch-site": "cross-site" })).toHaveProperty("status", 403);
src/pages/activity.ts +16 −1
@@ -3,6 +3,7 @@
33 * Every name is escaped; a lead that has since been removed is "a removed lead".
44 */
55
6 import type { LostCount } from "../lost.ts";
67 import type { Activity } from "../actions.ts";
78 import type { AuditRow } from "../audit.ts";
89 import type { Agent } from "../env.ts";
@@ -10,6 +11,7 @@ import { escape } from "../http.ts";
1011 import { said } from "../sentences.ts";
1112 import type { Who } from "../who.ts";
1213 import { layout } from "./layout.ts";
14 import { REASON_LABEL } from "../lost.ts";
1315 import { when } from "./parts.ts";
1416
1517 /** 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 {
2931 return `<li class="activity-row">${text}${refused} <span class="muted">· ${escape(when(row.at))}</span></li>`;
3032 }
3133
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
3245 export function activityPage(input: {
3346 who: Who;
3447 agent: Agent;
3548 rows: readonly AuditRow[];
3649 names: ReadonlyMap<number, string>;
3750 older: number | undefined;
51 lost: readonly LostCount[];
3852 sentOnly: boolean;
3953 }): string {
40 const { who, agent, rows, names, older, sentOnly } = input;
54 const { who, agent, rows, names, older, lost, sentOnly } = input;
4155 const filter = sentOnly ? "&amp;show=sent" : "";
4256 const links = `<nav class="row" aria-label="Filter">
4357 <a class="button button-quiet" href="/activity"${sentOnly ? "" : ' aria-current="page"'}>Everything</a>
@@ -55,6 +69,7 @@ export function activityPage(input: {
5569 body: `<p><a class="backlink" href="/">← All leads</a></p>
5670 <h1>Activity</h1>
5771 <p class="muted">Every change, newest first, and who made it. Refused attempts are shown too.</p>
72 ${lostBlock(lost)}
5873 ${links}
5974 ${list}
6075 ${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,
1515 import type { Agent } from "../env.ts";
1616 import type { Who } from "../who.ts";
1717 import { layout } from "./layout.ts";
18 import { LOST_REASONS, REASON_LABEL, lostSaid } from "../lost.ts";
1819 import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts";
1920
2021 /** One line of the thread: something we sent, or something they wrote back. */
@@ -85,7 +86,9 @@ export function leadPage(input: {
8586 : ready === undefined
8687 ? `<div class="pane ours"><h2>Nothing to send right now</h2><p class="muted">${
8788 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.`
8992 : lead.messages.some((m) => m.status === "scheduled")
9093 ? "The next follow-up is drafted below and comes due on its day."
9194 : "Every follow-up has gone out."
@@ -191,7 +194,9 @@ export function leadPage(input: {
191194 mayUpdate && !closed
192195 ? `<section class="states">
193196 <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>
195200 </section>`
196201 : mayUpdate
197202 ? `<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", () =
211211 const db = fresh();
212212 const id = arrive(db);
213213 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" }));
215215 turn(db, at("08:00", "2026-06-11"));
216216 expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("skipped");
217217 });
src/routes.ts +21 −6
@@ -65,6 +65,7 @@ import {
6565 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
6666 import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
6767 import { MAX_EMAIL_TEXT } from "./intake.ts";
68 import { LOST_REASONS, lostSaid } from "./lost.ts";
6869 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts";
6970 import { events } from "./live.ts";
7071 import { rpc } from "./mcp.ts";
@@ -163,6 +164,15 @@ const LEAD_FIELDS = {
163164 description: "When they asked to stop texts; consent is false from then on.",
164165 },
165166 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 },
166176 created_at: STAMP,
167177 replied_at: { type: ["string", "null"], format: "date-time" },
168178 updated_at: STAMP,
@@ -476,6 +486,11 @@ const EDIT_FIELDS = {
476486 phone: { type: "string", description: "7 to 20 digits; empty takes it away, if an email remains." },
477487 } as const;
478488
489 const REASON_FIELD = {
490 enum: [...LOST_REASONS],
491 description: "Why the lead is lost; required when state is lost.",
492 } as const;
493
479494 const NOTE_FIELD = {
480495 type: "string",
481496 maxLength: MAX_LEAD_NOTE,
@@ -708,14 +723,14 @@ export const routes: readonly Route[] = [
708723 if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note }));
709724 if (details)
710725 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 }));
712727 },
713728 api: {
714729 summary:
715730 "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.",
716731 body: {
717732 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 },
719734 },
720735 answer: LEAD,
721736 },
@@ -885,17 +900,17 @@ export const routes: readonly Route[] = [
885900 handle: (c) =>
886901 posted(
887902 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 }),
889904 (lead) => ({
890905 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." }),
892907 }),
893908 ),
894909 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.",
896911 body: {
897912 type: "object",
898 properties: { state: { enum: ["qualified", "lost", "open"] } },
913 properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD },
899914 required: ["state"],
900915 },
901916 answer: LEAD,
src/sample.test.ts +16 −1
@@ -4,7 +4,10 @@ import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { addSampleInquiry, getLead, listLeads, resetSample } from "./actions.ts";
66 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";
811 import { terminal, plain } from "./terminal.ts";
912 import type { Who } from "./who.ts";
1013
@@ -87,3 +90,15 @@ test("the terminal key adds one", () => {
8790 expect(names(db)).toHaveLength(1);
8891 expect(t.screen(100).map(plain).join("\n")).toContain("clock is running");
8992 });
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 {
1818 readyFor,
1919 send,
2020 writeNote,
21 type Closing,
2122 type NewLead,
2223 } from "./leads.ts";
2324
@@ -28,7 +29,7 @@ interface Sample extends NewLead {
2829 readonly answeredIn?: number;
2930 /** The cadence days already sent. */
3031 readonly touched?: readonly number[];
31 readonly closed?: "qualified" | "lost";
32 readonly closed?: Closing;
3233 /** The agent's private note on the lead, as of the first reply or the inquiry. */
3334 readonly note?: string;
3435 }
@@ -70,8 +71,11 @@ export const SAMPLES: readonly Sample[] = [
7071 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." }),
7172 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] }),
7273 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" } }),
7475 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" } }),
7579 ];
7680
7781 /** 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", () => {
3737 });
3838
3939 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);
4242 });
4343
4444 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
247247 const two = await created({ ...NEW, name: "Lose Me" });
248248 const patched = await api(
249249 `/leads/${two.id}`,
250 { method: "PATCH", ...jsonBody({ state: "lost" }) },
250 { method: "PATCH", ...jsonBody({ state: "lost", reason: "other" }) },
251251 alice,
252252 );
253253 expect(patched.status).toBe(200);
@@ -651,7 +651,7 @@ test("GET /leads?q= is the desk's search as JSON, like the page", async () => {
651651 test("a closed lead is put back in follow-ups from its page and the API; other states stay invalid", async () => {
652652 const one = await created({ ...NEW, name: "Mis Tap" });
653653 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);
655655 const page = await (await api(`/leads/${one.id}`, {}, alice)).text();
656656 expect(page).toContain("Put back in follow-ups");
657657 const back = await api(
src/showings.test.ts +1 −1
@@ -102,7 +102,7 @@ test("booking validates its inputs and asks permit", () => {
102102 expect(refused(book({ when: "2026-03-07T10:00" }, anon))).toBe("signin_required");
103103 expect(refused(bookShowing(db, alice, { id: 999, when: "2026-03-07T10:00" }, at(1)))).toBe("not_found");
104104
105 value(setState(db, alice, { id, state: "lost" }, at(1)));
105 value(setState(db, alice, { id, state: "lost", reason: "other" }, at(1)));
106106 expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("invalid");
107107 });
108108
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
127127 const id = answered();
128128 const three = day(id, 3);
129129 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)));
131131 expect(restoreFollowUp(db, alice, { id, messageId: three.id }, at(2))).toMatchObject({ ok: false, error: "conflict" });
132132 must(setState(db, alice, { id, state: "open" }, at(3)));
133133 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", () => {
9393 const t = terminal(db, alice);
9494 t.key("\r");
9595 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.");
9798 expect(read(t)).not.toContain("s approve and send");
9899 });
99100
@@ -363,6 +364,7 @@ test("o puts a closed lead back in follow-ups", () => {
363364 const t = terminal(db, alice);
364365 t.key("\r");
365366 t.key("x");
367 t.key("5");
366368 expect(read(t)).toContain("o put back in follow-ups");
367369 t.key("o");
368370 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
396398 const t = terminal(db, alice);
397399 t.key("x");
398400 const screen = read(t);
399 expect(screen).toContain("12 leads as CSV");
401 expect(screen).toContain("15 leads as CSV");
400402 expect(screen).toContain("name,email,phone,source,status");
401403 expect(screen).toContain("Maria Gonzalez");
402404 t.key("\x1b");
src/terminal.ts +28 −7
@@ -59,6 +59,7 @@ import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
5959 import { said as saidOf } from "./sentences.ts";
6060 import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel, type Source } from "./drafts.ts";
6161 import { ssh, title, where } from "./env.ts";
62 import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts";
6263 import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
6364 import { currentAgent } from "./profile.ts";
6465 import type { Who } from "./who.ts";
@@ -150,6 +151,7 @@ type View =
150151 | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string }
151152 | { name: "wrote"; id: number; text: string; channel: Channel }
152153 | { name: "note"; id: number; text: string }
154 | { name: "lost"; id: number }
153155 | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> }
154156 | { name: "paste"; text: string }
155157 | { name: "add"; step: number; typed: string; fields: Record<string, string>; found?: Record<string, string>; note?: string }
@@ -361,7 +363,7 @@ export function terminal(
361363 lines.push(
362364 dim(
363365 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.`
365367 : next !== undefined
366368 ? `Nothing to send now. ${titleOf(next)} comes due ${next.due_at.slice(0, 10)}.`
367369 : "Every follow-up has gone out.",
@@ -628,6 +630,14 @@ export function terminal(
628630 "",
629631 dim("type a note · enter new line · ctrl-o outcome · ctrl-d log the call · esc cancel"),
630632 ]
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 ]
631641 : view.name === "note"
632642 ? [
633643 bold(`Your note on ${clean(lead(view.id)?.name ?? "the lead")} (private, never sent)`),
@@ -786,13 +796,12 @@ export function terminal(
786796 const r = ready(l);
787797 if (r === undefined) said = "Nothing is waiting to go to this lead right now.";
788798 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" });
794801 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 !== "")
796805 view = { name: "call", id, outcome: "talked", text: "" };
797806 else if (input === "b" && !CLOSED.includes(l.state))
798807 view = { name: "showing", id, step: 0, typed: "", when: "" };
@@ -905,6 +914,18 @@ export function terminal(
905914 }
906915 return;
907916 }
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 }
908929 case "note": {
909930 if (input === "\x1b") {
910931 said = "Note unchanged.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs