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

Put a lead marked qualified or lost back into follow-ups #23

Merged opened this

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

Merged

mason/speed-to-lead:mason/5-put-a-lead-marked-qualified-or-lost-back → main 1 commit fork

  • Merged. mason/5-put-a-lead-marked-qualified-or-lost-back was merged into main as 5a6ecc4.

Review

Sign in to review this change.
13 files changed +146 −20
README.md +6 −1
@@ -103,7 +103,12 @@ Texts also say "Reply STOP to opt out."
103103 drafts five follow-ups for **day 1, 3, 7, 14 and 30**. Each shows on the
104104 lead's page as upcoming; on its day it appears on the desk as ready, and
105105 you approve and send it like the first. **Mark qualified** or **Mark lost**
106 takes a lead out of the plan.
106 takes a lead out of the plan. A mis-tap is undoable: a closed lead's page
107 offers **Put back in follow-ups** (`o` in the terminal, `{"state":"open"}` to
108 the API and MCP). The lead returns to *contacted* (or *new* if no first reply
109 was ever sent), and the follow-ups not yet sent are drafted again and
110 scheduled from that moment at day 1, 3, 7, 14 and 30, skipping those already
111 sent.
107112
108113 **Sample leads.** The app starts with twelve sample leads so you can see it
109114 work: two just in, two waiting a while, three gone red, and five already
contract/openapi.json +6 −4
@@ -217,7 +217,8 @@
217217 "state": {
218218 "enum": [
219219 "qualified",
220 "lost"
220 "lost",
221 "open"
221222 ]
222223 }
223224 },
@@ -364,7 +365,7 @@
364365 },
365366 "/leads/{id}/state": {
366367 "post": {
367 "summary": "Mark a lead qualified or lost: it leaves the follow-up plan.",
368 "summary": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.",
368369 "operationId": "postLeadsIdState",
369370 "parameters": [
370371 {
@@ -386,7 +387,8 @@
386387 "state": {
387388 "enum": [
388389 "qualified",
389 "lost"
390 "lost",
391 "open"
390392 ]
391393 }
392394 },
@@ -399,7 +401,7 @@
399401 },
400402 "responses": {
401403 "200": {
402 "description": "Mark a lead qualified or lost: it leaves the follow-up plan.",
404 "description": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.",
403405 "content": {
404406 "application/json": {
405407 "schema": {
src/actions.test.ts +31
@@ -270,3 +270,34 @@ test("the desk's views: each lists exactly its leads, counts add up, a bad value
270270 for (const bad of ["nope", "", undefined, null, 7]) expect(ids(show(bad))).toEqual(ids({ leads: everyone }));
271271 expect(show("nope").show).toBe("all");
272272 });
273
274 test("reopening a closed lead reschedules the unsent cadence from now, never in a burst", () => {
275 const lead = must(addLead(db, alice, { ...maria, name: "Comes Back" }, at(0)));
276 must(sendReply(db, alice, { id: lead.id }, at(0)));
277 must(tick(db, alice, at(1, 1)));
278 must(sendReply(db, alice, { id: lead.id }, at(1, 1)));
279 must(setState(db, alice, { id: lead.id, state: "lost" }, at(2)));
280 expect(setState(db, alice, { id: lead.id, state: "open" }, at(2)).ok).toBe(true);
281 const back = must(getLead(db, alice, { id: lead.id }));
282 expect(back.state).toBe("contacted");
283 const plan = back.messages.filter((m) => m.day > 0);
284 expect(plan.map((m) => m.status)).toEqual(["sent", "scheduled", "scheduled", "scheduled", "scheduled"]);
285 expect(plan.slice(1).map((m) => m.due_at)).toEqual(
286 [3, 7, 14, 30].map((d) => new Date(at(2).getTime() + d * 86_400_000).toISOString()),
287 );
288 expect(must(tick(db, alice, at(2, 1))).leads).not.toContain(lead.id);
289 expect(must(getLead(db, alice, { id: lead.id })).messages.some((m) => m.status === "due")).toBe(false);
290 // An open lead cannot be "put back".
291 const again = setState(db, alice, { id: lead.id, state: "open" });
292 expect(again.ok).toBe(false);
293 });
294
295 test("reopening a lead that was never answered makes it new with its first reply drafted", () => {
296 const lead = must(addLead(db, alice, { ...maria, name: "Never Answered" }, at(0)));
297 must(setState(db, alice, { id: lead.id, state: "lost" }));
298 expect(must(getLead(db, alice, { id: lead.id })).messages[0]!.status).toBe("skipped");
299 const back = must(setState(db, alice, { id: lead.id, state: "open" }));
300 expect(back.state).toBe("new");
301 expect(back.messages[0]!.status).toBe("draft");
302 expect(setState(db, anon, { id: lead.id, state: "open" }).ok).toBe(false);
303 });
src/actions.ts +14 −3
@@ -14,6 +14,7 @@ import type { Agent } from "./env.ts";
1414 import {
1515 advance,
1616 clearLeads,
17 CLOSED,
1718 close,
1819 countViews,
1920 desk,
@@ -21,6 +22,7 @@ import {
2122 findLead,
2223 inView,
2324 queryOf,
25 reopen,
2426 MAX_QUERY,
2527 insertLead,
2628 readyFor,
@@ -289,7 +291,7 @@ function reply(
289291 return ok(detail(db, found.value.id)!);
290292 }
291293
292 /** Qualified or lost: the lead leaves the cadence. */
294 /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */
293295 export const setState = (
294296 db: Database,
295297 who: Who,
@@ -305,7 +307,9 @@ export const setState = (
305307 mark(db, who, input, at),
306308 input.state === "qualified" || input.state === "lost"
307309 ? input.state
308 : undefined,
310 : input.state === "open"
311 ? "reopened"
312 : undefined,
309313 );
310314
311315 function mark(
@@ -319,8 +323,15 @@ function mark(
319323 no: "You may not update this lead.",
320324 });
321325 if (!found.ok) return found;
326 if (input.state === "open") {
327 if (!CLOSED.includes(found.value.state))
328 return fail("invalid", "Only a qualified or lost lead can be put back.");
329 reopen(db, found.value, stamp(at), currentAgent(db));
330 emit("lead.changed", { id: found.value.id });
331 return ok(detail(db, found.value.id)!);
332 }
322333 if (input.state !== "qualified" && input.state !== "lost")
323 return fail("invalid", "A lead is marked qualified or lost.");
334 return fail("invalid", "A lead is marked qualified or lost, or put back as open.");
324335 close(db, found.value.id, input.state, stamp(at));
325336 emit("lead.changed", { id: found.value.id });
326337 return ok(detail(db, found.value.id)!);
src/audit.ts +2 −2
@@ -32,8 +32,8 @@ export interface AuditRow {
3232 readonly act: string | null;
3333 }
3434
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost"] as const;
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened"] as const;
3737 export type Act = (typeof ACTS)[number];
3838
3939 export interface Attempt {
src/leads.ts +35 −1
@@ -8,7 +8,7 @@
88 * reply goes out, the cadence's touches are drafted and scheduled for days
99 * 1, 3, 7, 14 and 30 after it; `advance` makes each one due when its day
1010 * comes, and each is sent only when a person approves it. Marking a lead
11 * qualified or lost takes it out of the cadence.
11 * qualified or lost takes it out of the cadence; `reopen` puts it back.
1212 */
1313
1414 import type { Database } from "bun:sqlite";
@@ -397,6 +397,40 @@ export function close(
397397 })();
398398 }
399399
400 /**
401 * A closed lead goes back in follow-ups: `contacted` if a first reply was
402 * ever sent, else `new`. Touches never sent are drafted again for `agent`
403 * (consent may have changed what channel they go by) and scheduled from
404 * `at` on the cadence's spacing, so none comes due at once.
405 */
406 export function reopen(db: Database, found: Lead, at: string, agent: Agent): void {
407 db.transaction(() => {
408 const replied = found.replied_at !== null;
409 db.query("UPDATE lead SET state = ?1, updated_at = ?2 WHERE id = ?3").run(
410 replied ? "contacted" : "new",
411 at,
412 found.id,
413 );
414 const channel = channelFor(found);
415 const skipped = db
416 .query<{ id: number; day: number }, [number]>(
417 "SELECT id, day FROM message WHERE lead_id = ?1 AND status = 'skipped'",
418 )
419 .all(found.id);
420 for (const m of skipped)
421 db.query(
422 "UPDATE message SET status = ?1, channel = ?2, body = ?3, signature = ?4, due_at = ?5 WHERE id = ?6",
423 ).run(
424 m.day === 0 ? "draft" : "scheduled",
425 channel,
426 draft(found, m.day, agent),
427 signature(channel, agent),
428 m.day === 0 ? found.created_at : later(at, m.day),
429 m.id,
430 );
431 })();
432 }
433
400434 /** Every scheduled touch whose day has come is due now. Returns the ids of the leads it touched. */
401435 export function advance(db: Database, at: string): number[] {
402436 return db
src/mcp.ts +2 −2
@@ -104,12 +104,12 @@ export const tools: readonly Tool[] = [
104104 },
105105 {
106106 name: "mark_lead",
107 description: "Mark a lead qualified or lost; it leaves the follow-up plan.",
107 description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it.",
108108 inputSchema: {
109109 type: "object",
110110 properties: {
111111 id: { type: "integer" },
112 state: { enum: ["qualified", "lost"] },
112 state: { enum: ["qualified", "lost", "open"] },
113113 },
114114 required: ["id", "state"],
115115 },
src/pages/lead.ts +5 −1
@@ -110,7 +110,11 @@ export function leadPage(input: {
110110 <form method="post" action="${path}/state"><input type="hidden" name="state" value="qualified"><button class="button button-quiet">Mark qualified</button></form>
111111 <form method="post" action="${path}/state"><input type="hidden" name="state" value="lost"><button class="button button-quiet">Mark lost</button></form>
112112 </section>`
113 : "";
113 : mayUpdate
114 ? `<section class="states">
115 <form method="post" action="${path}/state"><input type="hidden" name="state" value="open"><button class="button">Put back in follow-ups</button></form>
116 </section>`
117 : "";
114118
115119 return layout({
116120 who,
src/routes.ts +4 −4
@@ -440,7 +440,7 @@ export const routes: readonly Route[] = [
440440 summary: "Mark a lead qualified or lost (the same as POST /leads/{id}/state).",
441441 body: {
442442 type: "object",
443 properties: { state: { enum: ["qualified", "lost"] } },
443 properties: { state: { enum: ["qualified", "lost", "open"] } },
444444 required: ["state"],
445445 },
446446 answer: LEAD,
@@ -498,14 +498,14 @@ export const routes: readonly Route[] = [
498498 (input) => setState(c.db, c.who, { id: ID(c), state: input.state }),
499499 (lead) => ({
500500 to: `/leads/${ID(c)}`,
501 ...(lead === undefined ? {} : { said: `Marked ${lead.state}.` }),
501 ...(lead === undefined ? {} : { said: lead.state === "qualified" || lead.state === "lost" ? `Marked ${lead.state}.` : "Back in follow-ups." }),
502502 }),
503503 ),
504504 api: {
505 summary: "Mark a lead qualified or lost: it leaves the follow-up plan.",
505 summary: "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.",
506506 body: {
507507 type: "object",
508 properties: { state: { enum: ["qualified", "lost"] } },
508 properties: { state: { enum: ["qualified", "lost", "open"] } },
509509 required: ["state"],
510510 },
511511 answer: LEAD,
src/sentences.ts +5
@@ -30,6 +30,11 @@ export function deed(
3030 done: `marked ${lead} ${row.act}`,
3131 tried: `mark ${lead} ${row.act}`,
3232 };
33 if (row.act === "reopened")
34 return {
35 done: `put ${lead} back in follow-ups`,
36 tried: `put ${lead} back in follow-ups`,
37 };
3338 if (row.verb === "create")
3439 return { done: "added a lead", tried: "add a lead" };
3540 if (row.verb === "delete")
src/server.test.ts +20
@@ -622,3 +622,23 @@ test("GET /leads?q= is the desk's search as JSON, like the page", async () => {
622622 expect(JSON.stringify(tool)).toContain("Maria Gonzalez");
623623 expect(JSON.stringify(tool)).not.toContain("David Chen");
624624 });
625
626 test("a closed lead is put back in follow-ups from its page and the API; other states stay invalid", async () => {
627 const one = await created({ ...NEW, name: "Mis Tap" });
628 await api(`/leads/${one.id}/reply`, { method: "POST", ...jsonBody({}) }, alice);
629 await api(`/leads/${one.id}/state`, { method: "POST", ...jsonBody({ state: "lost" }) }, alice);
630 const page = await (await api(`/leads/${one.id}`, {}, alice)).text();
631 expect(page).toContain("Put back in follow-ups");
632 const back = await api(
633 `/leads/${one.id}/state`,
634 { method: "POST", body: form({ state: "open" }), redirect: "manual" },
635 alice,
636 );
637 expect(back.status).toBe(303);
638 const after = await lead(one.id);
639 expect(after.state).toBe("contacted");
640 expect(after.messages.filter((m) => m.day > 0).every((m) => m.status === "scheduled")).toBe(true);
641 expect(
642 (await api(`/leads/${one.id}/state`, { method: "POST", ...jsonBody({ state: "reopen" }) }, alice)).status,
643 ).toBe(422);
644 });
src/terminal.test.ts +11
@@ -317,3 +317,14 @@ test("a opens Activity: an admin reads sentences and filters to messages sent; a
317317 expect(read(other)).toMatch(/Sign in|Only an admin/);
318318 }
319319 });
320
321 test("o puts a closed lead back in follow-ups", () => {
322 const db = fresh();
323 const t = terminal(db, alice);
324 t.key("\r");
325 t.key("x");
326 expect(read(t)).toContain("o put back in follow-ups");
327 t.key("o");
328 expect(read(t)).toContain("Maria Gonzalez: back in follow-ups.");
329 expect(read(t)).toContain("q qualified");
330 });
src/terminal.ts +5 −2
@@ -38,7 +38,7 @@ import { permit } from "./contract.ts";
3838 import { said as saidOf } from "./sentences.ts";
3939 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
4040 import { ssh, title, where } from "./env.ts";
41 import { MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
41 import { CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
4242 import { currentAgent } from "./profile.ts";
4343 import type { Who } from "./who.ts";
4444
@@ -280,7 +280,7 @@ export function terminal(
280280 [
281281 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
282282 ...(l.state === "qualified" || l.state === "lost"
283 ? []
283 ? ["o put back in follow-ups"]
284284 : ["q qualified", "x lost"]),
285285 ...(admin() ? ["D remove"] : []),
286286 "esc back",
@@ -526,6 +526,9 @@ export function terminal(
526526 state: input === "q" ? "qualified" : "lost",
527527 });
528528 said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message;
529 } else if (input === "o" && CLOSED.includes(l.state)) {
530 const back = setState(db, me, { id, state: "open" });
531 said = back.ok ? `${l.name}: back in follow-ups.` : back.message;
529532 } else if (input === "D")
530533 view = { name: "confirm", what: "remove", id, back: view };
531534 return;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs