Public: anyone can read this; the crew can change it.
Log a phone call on a lead so a reply by phone stops the clock and shows in the history #34
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/25-log-a-phone-call-on-a-lead-so-a-reply-by → main 2 commits fork 1 thread · 1 unresolved
16 files
changed +761
−31
AGENTS.md +5
| @@ -113,6 +113,11 @@ Speed to Lead is one realtor's desk. The concepts, one module each: | ||
| 113 | 113 | the `inbound` table, and answered by a message numbered `ANSWER_DAY` + its |
| 114 | 114 | id (`isAnswer` in `src/drafts.ts`) that pauses unsent follow-ups until |
| 115 | 115 | sent; `respace` in `src/leads.ts` restarts them, as `reopen` does. |
| 116 | - Calls: a phone call the agent made (`logCall`, `src/calls.ts` for the | |
| 117 | outcomes, `phone_call` table). Talked or a voicemail on an unanswered lead | |
| 118 | is its first answer (`recordCall` stops the clock through the same | |
| 119 | `startCadence` a sent first reply uses, and sets the draft aside as | |
| 120 | `skipped`); no answer is history only. | |
| 116 | 121 | - `src/drafts.ts` — the words: templates filled from the inquiry and the |
| 117 | 122 | agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*` |
| 118 | 123 | defaults of `agent` in `src/env.ts`), the signature every message |
README.md +15
| @@ -155,6 +155,21 @@ answered. The same is `POST /leads/:id/inbound` (`body`, `channel`; form or | ||
| 155 | 155 | JSON), the MCP `log_lead_reply` tool, and `w` on a lead's terminal screen |
| 156 | 156 | (ctrl-t switches text and email, ctrl-d records). |
| 157 | 157 | |
| 158 | **When you phone a lead.** Many realtors answer by phone, and the app sends | |
| 159 | nothing, so you say how the call went. On a lead that has a phone number, | |
| 160 | press **Log a call** beside the number, choose *Talked*, *Left a voicemail* or | |
| 161 | *No answer*, and add a note if you like (up to 500 characters). The history | |
| 162 | shows it with its time ("You called · Left a voicemail"). *Talked* or *Left a | |
| 163 | voicemail* on a lead not yet answered is its first answer: the response clock | |
| 164 | stops at the call, the day 1, 3, 7, 14 and 30 follow-ups start from it exactly | |
| 165 | as after a sent first reply, the drafted first reply is set aside (never | |
| 166 | sent), and the response record counts the lead as answered, once, at the | |
| 167 | earlier of the sent reply and the call. *No answer* is only written down. The | |
| 168 | same is `POST /leads/:id/call` (`outcome`: `talked`, `voicemail` or | |
| 169 | `no_answer`; `note`; form or JSON), the MCP `log_call` tool, and `c` on a | |
| 170 | lead's terminal screen (ctrl-o changes the outcome, ctrl-d logs it). It needs | |
| 171 | the same permission as any change to a lead, and shows on the Activity page. | |
| 172 | ||
| 158 | 173 | **Sample leads.** The app starts with twelve sample leads so you can see it |
| 159 | 174 | work: two just in, two waiting a while, three gone red, and five already |
| 160 | 175 | answered and partway through their follow-ups. An admin can restart them |
contract/openapi.json +143 −1
| @@ -453,6 +453,43 @@ | ||
| 453 | 453 | ] |
| 454 | 454 | } |
| 455 | 455 | }, |
| 456 | "calls": { | |
| 457 | "type": "array", | |
| 458 | "description": "Phone calls you logged, oldest first.", | |
| 459 | "items": { | |
| 460 | "type": "object", | |
| 461 | "properties": { | |
| 462 | "id": { | |
| 463 | "type": "integer" | |
| 464 | }, | |
| 465 | "lead_id": { | |
| 466 | "type": "integer" | |
| 467 | }, | |
| 468 | "outcome": { | |
| 469 | "enum": [ | |
| 470 | "talked", | |
| 471 | "voicemail", | |
| 472 | "no_answer" | |
| 473 | ] | |
| 474 | }, | |
| 475 | "note": { | |
| 476 | "type": "string", | |
| 477 | "maxLength": 500 | |
| 478 | }, | |
| 479 | "at": { | |
| 480 | "type": "string", | |
| 481 | "format": "date-time" | |
| 482 | } | |
| 483 | }, | |
| 484 | "required": [ | |
| 485 | "id", | |
| 486 | "lead_id", | |
| 487 | "outcome", | |
| 488 | "note", | |
| 489 | "at" | |
| 490 | ] | |
| 491 | } | |
| 492 | }, | |
| 456 | 493 | "next": { |
| 457 | 494 | "type": [ |
| 458 | 495 | "object", |
| @@ -488,6 +525,7 @@ | ||
| 488 | 525 | "updated_at", |
| 489 | 526 | "messages", |
| 490 | 527 | "replies", |
| 528 | "calls", | |
| 491 | 529 | "next" |
| 492 | 530 | ] |
| 493 | 531 | } |
| @@ -574,6 +612,72 @@ | ||
| 574 | 612 | } |
| 575 | 613 | } |
| 576 | 614 | }, |
| 615 | "/leads/{id}/call": { | |
| 616 | "post": { | |
| 617 | "summary": "You phoned the lead: the call joins the history. Talked or voicemail on a lead not yet answered stops its response clock at the call, starts the follow-up plan and sets the drafted first reply aside; no answer only goes in the history. Nothing is sent.", | |
| 618 | "operationId": "postLeadsIdCall", | |
| 619 | "parameters": [ | |
| 620 | { | |
| 621 | "name": "id", | |
| 622 | "in": "path", | |
| 623 | "required": true, | |
| 624 | "schema": { | |
| 625 | "type": "integer" | |
| 626 | } | |
| 627 | } | |
| 628 | ], | |
| 629 | "requestBody": { | |
| 630 | "required": true, | |
| 631 | "content": { | |
| 632 | "application/json": { | |
| 633 | "schema": { | |
| 634 | "type": "object", | |
| 635 | "properties": { | |
| 636 | "outcome": { | |
| 637 | "enum": [ | |
| 638 | "talked", | |
| 639 | "voicemail", | |
| 640 | "no_answer" | |
| 641 | ], | |
| 642 | "description": "talked, voicemail (left a voicemail) or no_answer." | |
| 643 | }, | |
| 644 | "note": { | |
| 645 | "type": "string", | |
| 646 | "maxLength": 500, | |
| 647 | "description": "Optional, trimmed, plain text." | |
| 648 | } | |
| 649 | }, | |
| 650 | "required": [ | |
| 651 | "outcome" | |
| 652 | ] | |
| 653 | } | |
| 654 | } | |
| 655 | } | |
| 656 | }, | |
| 657 | "responses": { | |
| 658 | "200": { | |
| 659 | "description": "You phoned the lead: the call joins the history. Talked or voicemail on a lead not yet answered stops its response clock at the call, starts the follow-up plan and sets the drafted first reply aside; no answer only goes in the history. Nothing is sent.", | |
| 660 | "content": { | |
| 661 | "application/json": { | |
| 662 | "schema": { | |
| 663 | "$ref": "#/components/schemas/Lead" | |
| 664 | } | |
| 665 | } | |
| 666 | } | |
| 667 | }, | |
| 668 | "default": { | |
| 669 | "description": "{ error, message }: why not", | |
| 670 | "content": { | |
| 671 | "application/json": { | |
| 672 | "schema": { | |
| 673 | "$ref": "#/components/schemas/Error" | |
| 674 | } | |
| 675 | } | |
| 676 | } | |
| 677 | } | |
| 678 | } | |
| 679 | } | |
| 680 | }, | |
| 577 | 681 | "/leads/{id}/state": { |
| 578 | 682 | "post": { |
| 579 | 683 | "summary": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.", |
| @@ -1223,6 +1327,43 @@ | ||
| 1223 | 1327 | "at" |
| 1224 | 1328 | ] |
| 1225 | 1329 | } |
| 1330 | }, | |
| 1331 | "calls": { | |
| 1332 | "type": "array", | |
| 1333 | "description": "Phone calls you logged, oldest first.", | |
| 1334 | "items": { | |
| 1335 | "type": "object", | |
| 1336 | "properties": { | |
| 1337 | "id": { | |
| 1338 | "type": "integer" | |
| 1339 | }, | |
| 1340 | "lead_id": { | |
| 1341 | "type": "integer" | |
| 1342 | }, | |
| 1343 | "outcome": { | |
| 1344 | "enum": [ | |
| 1345 | "talked", | |
| 1346 | "voicemail", | |
| 1347 | "no_answer" | |
| 1348 | ] | |
| 1349 | }, | |
| 1350 | "note": { | |
| 1351 | "type": "string", | |
| 1352 | "maxLength": 500 | |
| 1353 | }, | |
| 1354 | "at": { | |
| 1355 | "type": "string", | |
| 1356 | "format": "date-time" | |
| 1357 | } | |
| 1358 | }, | |
| 1359 | "required": [ | |
| 1360 | "id", | |
| 1361 | "lead_id", | |
| 1362 | "outcome", | |
| 1363 | "note", | |
| 1364 | "at" | |
| 1365 | ] | |
| 1366 | } | |
| 1226 | 1367 | } |
| 1227 | 1368 | }, |
| 1228 | 1369 | "required": [ |
| @@ -1239,7 +1380,8 @@ | ||
| 1239 | 1380 | "replied_at", |
| 1240 | 1381 | "updated_at", |
| 1241 | 1382 | "messages", |
| 1242 | "replies" | |
| 1383 | "replies", | |
| 1384 | "calls" | |
| 1243 | 1385 | ] |
| 1244 | 1386 | }, |
| 1245 | 1387 | "Desk": { |
src/actions.ts +45
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import { record, type Act, type AuditRow } from "./audit.ts"; |
| 11 | import { MAX_NOTE, outcomeOf } from "./calls.ts"; | |
| 11 | 12 | import { permit } from "./contract.ts"; |
| 12 | 13 | import { channelFor, MAX_BODY, SOURCES, type Channel, type Source } from "./drafts.ts"; |
| 13 | 14 | import type { Agent } from "./env.ts"; |
| @@ -29,6 +30,7 @@ import { | ||
| 29 | 30 | optOut, |
| 30 | 31 | nextNeeding, |
| 31 | 32 | readyFor, |
| 33 | recordCall, | |
| 32 | 34 | recordInbound, |
| 33 | 35 | redraftUnsent, |
| 34 | 36 | removeLead, |
| @@ -383,6 +385,49 @@ function inbound( | ||
| 383 | 385 | return ok(detail(db, lead.id)!); |
| 384 | 386 | } |
| 385 | 387 | |
| 388 | /** | |
| 389 | * The agent phoned the lead and says how it went. The call joins the | |
| 390 | * history; talking or a voicemail answers a lead not yet answered (the | |
| 391 | * clock stops at the call, the follow-ups start, the drafted first reply is | |
| 392 | * set aside), no answer only goes in the history. Nothing is sent. | |
| 393 | */ | |
| 394 | export const logCall = ( | |
| 395 | db: Database, | |
| 396 | who: Who, | |
| 397 | input: { id: number; outcome?: unknown; note?: unknown }, | |
| 398 | at?: Date, | |
| 399 | ): Result<LeadDetail> => | |
| 400 | audited(db, who, "lead", "update", input.id, phoned(db, who, input, at), "call"); | |
| 401 | ||
| 402 | function phoned( | |
| 403 | db: Database, | |
| 404 | who: Who, | |
| 405 | input: { id: number; outcome?: unknown; note?: unknown }, | |
| 406 | at?: Date, | |
| 407 | ): Result<LeadDetail> { | |
| 408 | const found = leadFor(db, who, "update", input.id, { | |
| 409 | signIn: "Sign in to log a call.", | |
| 410 | no: "You may not log a call for this lead.", | |
| 411 | }); | |
| 412 | if (!found.ok) return found; | |
| 413 | const lead = found.value; | |
| 414 | const outcome = outcomeOf(input.outcome); | |
| 415 | if (outcome === undefined) | |
| 416 | return fail("invalid", "The outcome is talked, voicemail or no_answer."); | |
| 417 | if (input.note !== undefined && input.note !== null && typeof input.note !== "string") | |
| 418 | return fail("invalid", "A note is text."); | |
| 419 | const note = lines(input.note ?? "").trim(); | |
| 420 | if (note.length > MAX_NOTE) | |
| 421 | return fail("invalid", `A note is at most ${MAX_NOTE} characters.`); | |
| 422 | if (hasControl(note, true)) | |
| 423 | return fail("invalid", "A note is plain text: no control characters."); | |
| 424 | if (lead.phone === "") | |
| 425 | return fail("invalid", "This lead left no phone number to call."); | |
| 426 | recordCall(db, lead, outcome, note, stamp(at), currentAgent(db)); | |
| 427 | emit("lead.changed", { id: lead.id }); | |
| 428 | return ok(detail(db, lead.id)!); | |
| 429 | } | |
| 430 | ||
| 386 | 431 | /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */ |
| 387 | 432 | export const setState = ( |
| 388 | 433 | db: Database, |
src/audit.ts +2 −2
| @@ -32,8 +32,8 @@ export interface AuditRow { | ||
| 32 | 32 | readonly act: string | null; |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in. */ | |
| 36 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound"] as const; | |
| 35 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged. */ | |
| 36 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call"] as const; | |
| 37 | 37 | export type Act = (typeof ACTS)[number]; |
| 38 | 38 | |
| 39 | 39 | export interface Attempt { |
src/calls.test.ts added +283
| @@ -0,0 +1,283 @@ | ||
| 1 | /** | |
| 2 | * A phone call logged on a lead: each outcome recorded, a call that | |
| 3 | * answers stops the clock like a sent first reply, one that does not | |
| 4 | * changes nothing else; at every door. | |
| 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 { | |
| 11 | addLead, | |
| 12 | getLead, | |
| 13 | listLeads, | |
| 14 | logCall, | |
| 15 | sendReply, | |
| 16 | setState, | |
| 17 | turn, | |
| 18 | } from "./actions.ts"; | |
| 19 | import { MAX_NOTE } from "./calls.ts"; | |
| 20 | import { openDb } from "./db.ts"; | |
| 21 | import { serve } from "./server.ts"; | |
| 22 | import { plain, terminal } from "./terminal.ts"; | |
| 23 | import { sign } from "./who.ts"; | |
| 24 | import type { Who } from "./who.ts"; | |
| 25 | ||
| 26 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 27 | const anon: Who = { role: "anon" }; | |
| 28 | const T0 = new Date("2026-03-01T10:00:00Z"); | |
| 29 | const at = (ms: number) => new Date(T0.getTime() + ms); | |
| 30 | const MIN = 60_000; | |
| 31 | const DAY = 86_400_000; | |
| 32 | ||
| 33 | const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-calls-"))); | |
| 34 | const arrive = (db: ReturnType<typeof fresh>, phone = "(206) 555-0199") => { | |
| 35 | const made = addLead( | |
| 36 | db, | |
| 37 | alice, | |
| 38 | { | |
| 39 | name: "Dana Reyes", | |
| 40 | email: "[email protected]", | |
| 41 | phone, | |
| 42 | source: "zillow", | |
| 43 | message: "Can I see 12 Oak Street this week?", | |
| 44 | consent: true, | |
| 45 | }, | |
| 46 | T0, | |
| 47 | ); | |
| 48 | if (!made.ok) throw new Error(made.message); | |
| 49 | return made.value.id; | |
| 50 | }; | |
| 51 | const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => { | |
| 52 | if (!r.ok) throw new Error(r.message); | |
| 53 | return r.value as T; | |
| 54 | }; | |
| 55 | ||
| 56 | test("each outcome is recorded with its time and note", () => { | |
| 57 | for (const outcome of ["talked", "voicemail", "no_answer"]) { | |
| 58 | const db = fresh(); | |
| 59 | const id = arrive(db); | |
| 60 | const lead = value(logCall(db, alice, { id, outcome, note: " Saturday at ten " }, at(MIN))); | |
| 61 | expect(lead.calls.map((c) => [c.outcome, c.note, c.at])).toEqual([ | |
| 62 | [outcome, "Saturday at ten", at(MIN).toISOString()], | |
| 63 | ]); | |
| 64 | } | |
| 65 | }); | |
| 66 | ||
| 67 | test("talking stops a red clock at the call and queues the cadence; the first reply is set aside", () => { | |
| 68 | const db = fresh(); | |
| 69 | const id = arrive(db); | |
| 70 | const lead = value(logCall(db, alice, { id, outcome: "talked" }, at(20 * MIN))); | |
| 71 | expect(lead.replied_at).toBe(at(20 * MIN).toISOString()); | |
| 72 | expect(lead.state).toBe("contacted"); | |
| 73 | const first = lead.messages.find((m) => m.day === 0)!; | |
| 74 | expect(first.status).toBe("skipped"); | |
| 75 | expect(first.sent_at).toBeNull(); | |
| 76 | for (const day of [1, 3, 7, 14, 30]) { | |
| 77 | const m = lead.messages.find((x) => x.day === day)!; | |
| 78 | expect(m.status).toBe("scheduled"); | |
| 79 | expect(m.due_at).toBe(new Date(at(20 * MIN).getTime() + day * DAY).toISOString()); | |
| 80 | } | |
| 81 | // Answered: not on the desk's Needs you, and the record counts it, once. | |
| 82 | const desk = value(listLeads(db, alice, { show: "needs", now: at(DAY).getTime() })); | |
| 83 | expect(desk.leads).toEqual([]); | |
| 84 | expect(desk.record).toMatchObject({ leads: 1, replied: 1, median_ms: 20 * MIN }); | |
| 85 | // The days come due as after a sent reply. | |
| 86 | turn(db, at(20 * MIN + DAY)); | |
| 87 | expect(value(getLead(db, alice, { id })).messages.find((m) => m.day === 1)!.status).toBe("due"); | |
| 88 | }); | |
| 89 | ||
| 90 | test("a voicemail answers too; a second call changes nothing about the first", () => { | |
| 91 | const db = fresh(); | |
| 92 | const id = arrive(db); | |
| 93 | value(logCall(db, alice, { id, outcome: "voicemail" }, at(5 * MIN))); | |
| 94 | const again = value(logCall(db, alice, { id, outcome: "talked" }, at(9 * MIN))); | |
| 95 | expect(again.replied_at).toBe(at(5 * MIN).toISOString()); | |
| 96 | expect(again.calls.length).toBe(2); | |
| 97 | expect(again.messages.filter((m) => m.day > 0).length).toBe(5); | |
| 98 | }); | |
| 99 | ||
| 100 | test("no answer is recorded and stops nothing", () => { | |
| 101 | const db = fresh(); | |
| 102 | const id = arrive(db); | |
| 103 | const lead = value(logCall(db, alice, { id, outcome: "no_answer" }, at(MIN))); | |
| 104 | expect(lead.replied_at).toBeNull(); | |
| 105 | expect(lead.state).toBe("new"); | |
| 106 | expect(lead.messages.map((m) => [m.day, m.status])).toEqual([[0, "draft"]]); | |
| 107 | expect(value(listLeads(db, alice, { show: "needs" })).leads.length).toBe(1); | |
| 108 | expect(value(listLeads(db, alice)).record.replied).toBe(0); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a call after a sent first reply is history only: the record keeps the earlier answer", () => { | |
| 112 | const db = fresh(); | |
| 113 | const id = arrive(db); | |
| 114 | value(sendReply(db, alice, { id }, at(MIN))); | |
| 115 | const lead = value(logCall(db, alice, { id, outcome: "talked" }, at(2 * MIN))); | |
| 116 | expect(lead.replied_at).toBe(at(MIN).toISOString()); | |
| 117 | expect(lead.messages.filter((m) => m.status === "sent").length).toBe(1); | |
| 118 | }); | |
| 119 | ||
| 120 | test("a closed lead that was called can be put back without its first reply returning", () => { | |
| 121 | const db = fresh(); | |
| 122 | const id = arrive(db); | |
| 123 | value(logCall(db, alice, { id, outcome: "talked" }, at(MIN))); | |
| 124 | value(setState(db, alice, { id, state: "lost" }, at(2 * MIN))); | |
| 125 | const back = value(setState(db, alice, { id, state: "open" }, at(DAY))); | |
| 126 | expect(back.state).toBe("contacted"); | |
| 127 | expect(back.messages.find((m) => m.day === 0)!.status).toBe("skipped"); | |
| 128 | expect(back.messages.find((m) => m.day === 1)!.status).toBe("scheduled"); | |
| 129 | expect(value(listLeads(db, alice, { show: "needs" })).leads).toEqual([]); | |
| 130 | }); | |
| 131 | ||
| 132 | test("an unknown outcome, an over-long or odd note, and a lead without a phone are refused", () => { | |
| 133 | const db = fresh(); | |
| 134 | const id = arrive(db); | |
| 135 | const bad = (input: Record<string, unknown>) => logCall(db, alice, { id, ...input }, at(MIN)); | |
| 136 | for (const outcome of ["answered", "", "TALKED", undefined, 5]) | |
| 137 | expect(bad({ outcome }).ok).toBe(false); | |
| 138 | for (const note of ["x".repeat(MAX_NOTE + 1), "bell\x07", "esc\x1b[2J", 7]) | |
| 139 | expect(bad({ outcome: "talked", note }).ok).toBe(false); | |
| 140 | expect(bad({ outcome: "talked", note: "x".repeat(MAX_NOTE) }).ok).toBe(true); | |
| 141 | const none = arrive(db, ""); | |
| 142 | expect(logCall(db, alice, { id: none, outcome: "talked" }).ok).toBe(false); | |
| 143 | expect(value(getLead(db, alice, { id: none })).calls).toEqual([]); | |
| 144 | }); | |
| 145 | ||
| 146 | test("a call is audited, and a stranger is refused", () => { | |
| 147 | const db = fresh(); | |
| 148 | const id = arrive(db); | |
| 149 | expect(logCall(db, anon, { id, outcome: "talked" }).ok).toBe(false); | |
| 150 | value(logCall(db, alice, { id, outcome: "talked" })); | |
| 151 | const rows = db.query("SELECT act, who_name, outcome FROM audit WHERE act = 'call'").all(); | |
| 152 | expect(rows).toContainEqual({ act: "call", who_name: "alice", outcome: "ok" }); | |
| 153 | expect(value(getLead(db, alice, { id })).calls.length).toBe(1); | |
| 154 | }); | |
| 155 | ||
| 156 | // The doors. | |
| 157 | const KEY = "a-key-only-the-forge-holds"; | |
| 158 | const server = serve({ | |
| 159 | port: 0, | |
| 160 | dataDir: mkdtempSync(join(tmpdir(), "app-calls-srv-")), | |
| 161 | identityKey: KEY, | |
| 162 | sample: false, | |
| 163 | }); | |
| 164 | const base = `http://${server.hostname}:${server.port}`; | |
| 165 | afterAll(() => server.stop(true)); | |
| 166 | let grants = 0; | |
| 167 | const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => { | |
| 168 | const identity = `calls-${++grants}|alice|user|${Date.now() + 60_000}`; | |
| 169 | return fetch(base + path, { | |
| 170 | redirect: "manual", | |
| 171 | ...init, | |
| 172 | headers: { | |
| 173 | ...(init.headers as Record<string, string>), | |
| 174 | ...headers, | |
| 175 | "x-forge-identity": identity, | |
| 176 | "x-forge-signature": sign(identity, KEY), | |
| 177 | }, | |
| 178 | }); | |
| 179 | }; | |
| 180 | const json = (path: string, body: unknown) => | |
| 181 | api(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); | |
| 182 | const served = async (phone = "206 555 0111"): Promise<number> => { | |
| 183 | const made = await json("/leads", { | |
| 184 | name: "Pat <i>Lee</i>", | |
| 185 | email: "[email protected]", | |
| 186 | phone, | |
| 187 | source: "website", | |
| 188 | message: "Do you have time to talk this week?", | |
| 189 | consent: false, | |
| 190 | }); | |
| 191 | if (made.status !== 201) throw new Error(`${made.status} ${await made.text()}`); | |
| 192 | return ((await made.json()) as { id: number }).id; | |
| 193 | }; | |
| 194 | ||
| 195 | test("the page offers the form only with a phone; the API and a form log a call, escaped", async () => { | |
| 196 | const id = await served(); | |
| 197 | const before = await (await api(`/leads/${id}`)).text(); | |
| 198 | expect(before).toContain(`action="/leads/${id}/call"`); | |
| 199 | expect(before).toContain("Log a call"); | |
| 200 | ||
| 201 | const done = await json(`/leads/${id}/call`, { outcome: "voicemail", note: "<b>left word</b>" }); | |
| 202 | expect(done.status).toBe(200); | |
| 203 | const body = (await done.json()) as { calls: { outcome: string }[]; replied_at: string }; | |
| 204 | expect(body.calls[0]!.outcome).toBe("voicemail"); | |
| 205 | expect(body.replied_at).not.toBeNull(); | |
| 206 | ||
| 207 | const form = await api(`/leads/${id}/call`, { | |
| 208 | method: "POST", | |
| 209 | body: (() => { | |
| 210 | const f = new FormData(); | |
| 211 | f.set("outcome", "no_answer"); | |
| 212 | f.set("note", "rang out"); | |
| 213 | return f; | |
| 214 | })(), | |
| 215 | }); | |
| 216 | expect(form.status).toBe(303); | |
| 217 | ||
| 218 | const page = await (await api(`/leads/${id}`)).text(); | |
| 219 | expect(page).toContain("You called · Left a voicemail"); | |
| 220 | expect(page).toContain("You called · No answer"); | |
| 221 | expect(page).toContain("<b>left word</b>"); | |
| 222 | expect(page).not.toContain("<b>left word"); | |
| 223 | ||
| 224 | expect((await json(`/leads/${id}/call`, { outcome: "nope" })).status).toBe(422); | |
| 225 | expect((await json(`/leads/${id}/call`, { outcome: "talked", note: "x".repeat(501) })).status).toBe(422); | |
| 226 | const crossed = await api( | |
| 227 | `/leads/${id}/call`, | |
| 228 | { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "outcome=talked" }, | |
| 229 | { origin: "https://evil.example", "sec-fetch-site": "cross-site" }, | |
| 230 | ); | |
| 231 | expect(crossed.status).toBe(403); | |
| 232 | ||
| 233 | const noPhone = await served(""); | |
| 234 | expect(await (await api(`/leads/${noPhone}`)).text()).not.toContain(`/leads/${noPhone}/call`); | |
| 235 | expect((await json(`/leads/${noPhone}/call`, { outcome: "talked" })).status).toBe(422); | |
| 236 | }); | |
| 237 | ||
| 238 | test("/openapi.json describes the route", async () => { | |
| 239 | const spec = (await (await api("/openapi.json")).json()) as { | |
| 240 | paths: Record<string, Record<string, { requestBody?: unknown }>>; | |
| 241 | }; | |
| 242 | expect(spec.paths["/leads/{id}/call"]!.post!.requestBody).toBeDefined(); | |
| 243 | }); | |
| 244 | ||
| 245 | test("MCP log_call logs one", async () => { | |
| 246 | const id = await served(); | |
| 247 | const res = await api("/mcp", { | |
| 248 | method: "POST", | |
| 249 | headers: { "content-type": "application/json" }, | |
| 250 | body: JSON.stringify({ | |
| 251 | jsonrpc: "2.0", | |
| 252 | id: 1, | |
| 253 | method: "tools/call", | |
| 254 | params: { name: "log_call", arguments: { id, outcome: "talked", note: "Sunday" } }, | |
| 255 | }), | |
| 256 | }); | |
| 257 | const out = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } }; | |
| 258 | expect(out.result.isError).toBeUndefined(); | |
| 259 | expect(JSON.parse(out.result.content[0]!.text).calls[0].note).toBe("Sunday"); | |
| 260 | }); | |
| 261 | ||
| 262 | test("the terminal logs one with c, and offers it only with a phone", () => { | |
| 263 | const db = fresh(); | |
| 264 | const id = arrive(db); | |
| 265 | const t = terminal(db, alice); | |
| 266 | const read = () => t.screen(100).map(plain).join("\n"); | |
| 267 | t.key("\r"); | |
| 268 | expect(read()).toContain("c log a call"); | |
| 269 | t.key("c"); | |
| 270 | t.key("\x0f"); // talked → voicemail | |
| 271 | for (const ch of "left word") t.key(ch); | |
| 272 | t.key("\x04"); | |
| 273 | const screen = read(); | |
| 274 | expect(screen).toContain("You called · Left a voicemail"); | |
| 275 | expect(screen).toContain("left word"); | |
| 276 | expect(value(getLead(db, alice, { id })).calls[0]!.outcome).toBe("voicemail"); | |
| 277 | ||
| 278 | const other = fresh(); | |
| 279 | arrive(other, ""); | |
| 280 | const u = terminal(other, alice); | |
| 281 | u.key("\r"); | |
| 282 | expect(u.screen(100).map(plain).join("\n")).not.toContain("c log a call"); | |
| 283 | }); |
src/calls.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * A phone call the agent made to a lead, and what it came to. Talking to | |
| 3 | * them or leaving a voicemail answers the lead as a sent first reply does; | |
| 4 | * ringing with no answer is only written down. Nothing here sends anything. | |
| 5 | */ | |
| 6 | ||
| 7 | export const OUTCOMES = ["talked", "voicemail", "no_answer"] as const; | |
| 8 | export type Outcome = (typeof OUTCOMES)[number]; | |
| 9 | ||
| 10 | /** How a realtor says each outcome. */ | |
| 11 | export const OUTCOME_LABEL: Readonly<Record<Outcome, string>> = { | |
| 12 | talked: "Talked", | |
| 13 | voicemail: "Left a voicemail", | |
| 14 | no_answer: "No answer", | |
| 15 | }; | |
| 16 | ||
| 17 | /** The most a call's note may hold. */ | |
| 18 | export const MAX_NOTE = 500; | |
| 19 | ||
| 20 | /** An outcome from user text; undefined when it is none of the three. */ | |
| 21 | export const outcomeOf = (value: unknown): Outcome | undefined => | |
| 22 | OUTCOMES.find((o) => o === value); | |
| 23 | ||
| 24 | /** Did the lead hear from the agent? Then the response clock stops. */ | |
| 25 | export const answers = (outcome: Outcome): boolean => outcome !== "no_answer"; | |
| 26 | ||
| 27 | /** What a call is in the history: "You called · Left a voicemail". */ | |
| 28 | export const callLine = (outcome: Outcome): string => | |
| 29 | `You called · ${OUTCOME_LABEL[outcome]}`; | |
| 30 | ||
| 31 | /** A call as stored. */ | |
| 32 | export interface Call { | |
| 33 | readonly id: number; | |
| 34 | readonly lead_id: number; | |
| 35 | readonly outcome: Outcome; | |
| 36 | readonly note: string; | |
| 37 | readonly at: string; | |
| 38 | } |
src/contract.test.ts +5
| @@ -17,6 +17,7 @@ import { | ||
| 17 | 17 | getProfile, |
| 18 | 18 | listAudit, |
| 19 | 19 | listLeads, |
| 20 | logCall, | |
| 20 | 21 | logLeadReply, |
| 21 | 22 | saveProfile, |
| 22 | 23 | setState, |
| @@ -109,8 +110,12 @@ const doors: Record< | ||
| 109 | 110 | body: "Yes please", |
| 110 | 111 | channel: "email", |
| 111 | 112 | }).ok; |
| 113 | // So is logging a phone call (POST /leads/:id/call and the MCP tool log_call). | |
| 114 | db.query("UPDATE lead SET phone = '206 555 0100' WHERE id = ?1").run(replied); | |
| 115 | const called = logCall(db, who, { id: replied, outcome: "no_answer" }).ok; | |
| 112 | 116 | const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok; |
| 113 | 117 | expect(logged).toBe(changed); |
| 118 | expect(called).toBe(changed); | |
| 114 | 119 | return changed; |
| 115 | 120 | }, |
| 116 | 121 | delete: (who, authorId) => deleteLead(db, who, { id: aLead(authorId) }).ok, |
src/db.ts +10
| @@ -116,6 +116,16 @@ export const migrations: string[] = [ | ||
| 116 | 116 | `CREATE TRIGGER IF NOT EXISTS inbound_text_needs_consent BEFORE INSERT ON inbound |
| 117 | 117 | WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0 |
| 118 | 118 | BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`, |
| 119 | // Phone calls the agent made to a lead, append-only. Nothing is dialled | |
| 120 | // from here; the agent says how it went. | |
| 121 | `CREATE TABLE IF NOT EXISTS phone_call ( | |
| 122 | id INTEGER PRIMARY KEY, | |
| 123 | lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE, | |
| 124 | outcome TEXT NOT NULL CHECK (outcome IN ('talked', 'voicemail', 'no_answer')), | |
| 125 | note TEXT NOT NULL DEFAULT '' CHECK (length(note) <= 500), | |
| 126 | at TEXT NOT NULL | |
| 127 | )`, | |
| 128 | `CREATE INDEX IF NOT EXISTS phone_call_lead ON phone_call (lead_id, at)`, | |
| 119 | 129 | ]; |
| 120 | 130 | |
| 121 | 131 | export function openDb(dir = dataDir): Database { |
src/leads.ts +70 −21
| @@ -23,6 +23,7 @@ import { | ||
| 23 | 23 | type Channel, |
| 24 | 24 | type Source, |
| 25 | 25 | } from "./drafts.ts"; |
| 26 | import { answers, type Call, type Outcome } from "./calls.ts"; | |
| 26 | 27 | import { GREEN_MS } from "./clock.ts"; |
| 27 | 28 | import type { Agent } from "./env.ts"; |
| 28 | 29 | |
| @@ -77,6 +78,8 @@ export interface LeadDetail extends Lead { | ||
| 77 | 78 | readonly messages: readonly Message[]; |
| 78 | 79 | /** What they wrote back, oldest first. */ |
| 79 | 80 | readonly replies: readonly Inbound[]; |
| 81 | /** Calls the agent made, oldest first. */ | |
| 82 | readonly calls: readonly Call[]; | |
| 80 | 83 | } |
| 81 | 84 | |
| 82 | 85 | /** When the lead began to wait on our answer to what they wrote back; null when no answer is owed. */ |
| @@ -179,11 +182,19 @@ export const repliesOf = (db: Database, id: number): Inbound[] => | ||
| 179 | 182 | >("SELECT * FROM inbound WHERE lead_id = ?1 ORDER BY at, id") |
| 180 | 183 | .all(id); |
| 181 | 184 | |
| 185 | export const callsOf = (db: Database, id: number): Call[] => | |
| 186 | db | |
| 187 | .query< | |
| 188 | Call, | |
| 189 | [number] | |
| 190 | >("SELECT * FROM phone_call WHERE lead_id = ?1 ORDER BY at, id") | |
| 191 | .all(id); | |
| 192 | ||
| 182 | 193 | export function detail(db: Database, id: number): LeadDetail | null { |
| 183 | 194 | const found = findLead(db, id); |
| 184 | 195 | return found === null |
| 185 | 196 | ? null |
| 186 | : { ...found, messages: messagesOf(db, id), replies: repliesOf(db, id) }; | |
| 197 | : { ...found, messages: messagesOf(db, id), replies: repliesOf(db, id), calls: callsOf(db, id) }; | |
| 187 | 198 | } |
| 188 | 199 | |
| 189 | 200 | export const MAX_QUERY = 80; |
| @@ -389,23 +400,7 @@ export function send( | ||
| 389 | 400 | "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4 WHERE id = ?5", |
| 390 | 401 | ).run(body, signature(message.channel, agent), at, by, message.id); |
| 391 | 402 | if (message.day === 0) { |
| 392 | db.query( | |
| 393 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 394 | ).run(at, found.id); | |
| 395 | const channel = channelFor(found); | |
| 396 | const open = !CLOSED.includes(found.state); | |
| 397 | for (const day of CADENCE) | |
| 398 | db.query( | |
| 399 | "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 400 | ).run( | |
| 401 | found.id, | |
| 402 | day, | |
| 403 | channel, | |
| 404 | draft(found, day, agent), | |
| 405 | signature(channel, agent), | |
| 406 | open ? "scheduled" : "skipped", | |
| 407 | later(at, day), | |
| 408 | ); | |
| 403 | startCadence(db, found, at, agent); | |
| 409 | 404 | } else { |
| 410 | 405 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run( |
| 411 | 406 | at, |
| @@ -417,6 +412,60 @@ export function send( | ||
| 417 | 412 | })(); |
| 418 | 413 | } |
| 419 | 414 | |
| 415 | /** The first answer is out at `at`: the clock stops and the follow-ups are drafted and scheduled from it. */ | |
| 416 | function startCadence(db: Database, found: Lead, at: string, agent: Agent): void { | |
| 417 | db.query( | |
| 418 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 419 | ).run(at, found.id); | |
| 420 | const channel = channelFor(found); | |
| 421 | const open = !CLOSED.includes(found.state); | |
| 422 | for (const day of CADENCE) | |
| 423 | db.query( | |
| 424 | "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 425 | ).run( | |
| 426 | found.id, | |
| 427 | day, | |
| 428 | channel, | |
| 429 | draft(found, day, agent), | |
| 430 | signature(channel, agent), | |
| 431 | open ? "scheduled" : "skipped", | |
| 432 | later(at, day), | |
| 433 | ); | |
| 434 | } | |
| 435 | ||
| 436 | /** | |
| 437 | * The agent called the lead at `at`. The call joins the history. If they | |
| 438 | * talked or a voicemail was left and no first reply had gone out, that is | |
| 439 | * their first answer: the clock stops at the call, the follow-ups start as | |
| 440 | * after a sent reply, and the drafted first reply is set aside, unsent. | |
| 441 | * Returns the call's id. | |
| 442 | */ | |
| 443 | export function recordCall( | |
| 444 | db: Database, | |
| 445 | found: Lead, | |
| 446 | outcome: Outcome, | |
| 447 | note: string, | |
| 448 | at: string, | |
| 449 | agent: Agent, | |
| 450 | ): number { | |
| 451 | return db.transaction(() => { | |
| 452 | const { id } = db | |
| 453 | .query<{ id: number }, [number, Outcome, string, string]>( | |
| 454 | "INSERT INTO phone_call (lead_id, outcome, note, at) VALUES (?1, ?2, ?3, ?4) RETURNING id", | |
| 455 | ) | |
| 456 | .get(found.id, outcome, note, at)!; | |
| 457 | if (answers(outcome) && found.replied_at === null) { | |
| 458 | db.query( | |
| 459 | "UPDATE message SET status = 'skipped' WHERE lead_id = ?1 AND day = 0 AND status IN ('draft', 'due')", | |
| 460 | ).run(found.id); | |
| 461 | startCadence(db, found, at, agent); | |
| 462 | } else { | |
| 463 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); | |
| 464 | } | |
| 465 | return id; | |
| 466 | })(); | |
| 467 | } | |
| 468 | ||
| 420 | 469 | /** Touches not yet sent come due on the cadence's days counted from `at`. */ |
| 421 | 470 | function respace(db: Database, id: number, at: string): void { |
| 422 | 471 | const waiting = db |
| @@ -576,10 +625,10 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi | ||
| 576 | 625 | ); |
| 577 | 626 | const channel = channelFor(found); |
| 578 | 627 | const skipped = db |
| 579 | .query<{ id: number; day: number; due_at: string }, [number, number]>( | |
| 580 | "SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND day < ?2", | |
| 628 | .query<{ id: number; day: number; due_at: string }, [number, number, number]>( | |
| 629 | "SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND day < ?2 AND NOT (day = 0 AND ?3 = 1)", | |
| 581 | 630 | ) |
| 582 | .all(found.id, ANSWER_DAY); | |
| 631 | .all(found.id, ANSWER_DAY, replied ? 1 : 0); | |
| 583 | 632 | for (const m of skipped) |
| 584 | 633 | db.query( |
| 585 | 634 | "UPDATE message SET status = ?1, channel = ?2, body = ?3, signature = ?4, due_at = ?5 WHERE id = ?6", |
src/mcp.ts +18
| @@ -17,9 +17,11 @@ import { | ||
| 17 | 17 | optOutTexts, |
| 18 | 18 | approveReply, |
| 19 | 19 | setState, |
| 20 | logCall, | |
| 20 | 21 | logLeadReply, |
| 21 | 22 | type Result, |
| 22 | 23 | } from "./actions.ts"; |
| 24 | import { MAX_NOTE, OUTCOMES } from "./calls.ts"; | |
| 23 | 25 | import { SOURCES } from "./drafts.ts"; |
| 24 | 26 | import { title } from "./env.ts"; |
| 25 | 27 | import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts"; |
| @@ -128,6 +130,22 @@ export const tools: readonly Tool[] = [ | ||
| 128 | 130 | run: (db, who, args) => |
| 129 | 131 | logLeadReply(db, who, { id: Number(args.id), body: args.body, channel: args.channel }), |
| 130 | 132 | }, |
| 133 | { | |
| 134 | name: "log_call", | |
| 135 | description: | |
| 136 | "You phoned a lead: record how it went (talked, voicemail, no_answer) and an optional note. Talked or voicemail on a lead not yet answered stops its response clock at the call, starts the follow-up plan and sets the drafted first reply aside; no_answer only goes in the history. Nothing is sent. The lead needs a phone number.", | |
| 137 | inputSchema: { | |
| 138 | type: "object", | |
| 139 | properties: { | |
| 140 | id: { type: "integer" }, | |
| 141 | outcome: { enum: [...OUTCOMES] }, | |
| 142 | note: { type: "string", maxLength: MAX_NOTE }, | |
| 143 | }, | |
| 144 | required: ["id", "outcome"], | |
| 145 | }, | |
| 146 | run: (db, who, args) => | |
| 147 | logCall(db, who, { id: Number(args.id), outcome: args.outcome, note: args.note }), | |
| 148 | }, | |
| 131 | 149 | { |
| 132 | 150 | name: "mark_lead", |
| 133 | 151 | description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it.", |
src/pages/lead.ts +35 −5
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * follow-ups to come. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts"; | |
| 7 | 8 | import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts"; |
| 8 | 9 | import { escape } from "../http.ts"; |
| 9 | 10 | import { elapsed, between } from "../clock.ts"; |
| @@ -15,8 +16,9 @@ import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts"; | ||
| 15 | 16 | |
| 16 | 17 | /** One line of the thread: something we sent, or something they wrote back. */ |
| 17 | 18 | type HistoryEntry = |
| 18 | | { at: string; ours: Message; theirs?: undefined } | |
| 19 | | { at: string; theirs: LeadDetail["replies"][number]; ours?: undefined }; | |
| 19 | | { at: string; ours: Message; theirs?: undefined; call?: undefined } | |
| 20 | | { at: string; theirs: LeadDetail["replies"][number]; ours?: undefined; call?: undefined } | |
| 21 | | { at: string; call: LeadDetail["calls"][number]; ours?: undefined; theirs?: undefined }; | |
| 20 | 22 | |
| 21 | 23 | const CHANNEL = { text: "text", email: "email" } as const; |
| 22 | 24 | |
| @@ -95,13 +97,19 @@ export function leadPage(input: { | ||
| 95 | 97 | const history: HistoryEntry[] = [ |
| 96 | 98 | ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })), |
| 97 | 99 | ...lead.replies.map((r) => ({ at: r.at, theirs: r })), |
| 100 | ...lead.calls.map((c) => ({ at: c.at, call: c })), | |
| 98 | 101 | ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); |
| 99 | 102 | const thread = |
| 100 | 103 | history.length === 0 |
| 101 | 104 | ? "" |
| 102 | 105 | : `<section class="card"><h2>History</h2><ol class="thread">${history |
| 103 | .map(({ ours: m, theirs: r }) => | |
| 104 | r !== undefined | |
| 106 | .map(({ ours: m, theirs: r, call: c }) => | |
| 107 | c !== undefined | |
| 108 | ? `<li data-from="call"> | |
| 109 | <p class="meta">${callLine(c.outcome)} · <time datetime="${escape(c.at)}">${escape(when(c.at))}</time></p> | |
| 110 | ${c.note === "" ? "" : `<p class="body">${escape(c.note)}</p>`} | |
| 111 | </li>` | |
| 112 | : r !== undefined | |
| 105 | 113 | ? `<li data-from="lead"> |
| 106 | 114 | <p class="meta">${escape(lead.name)} wrote back · ${CHANNEL[r.channel]} · <time datetime="${escape(r.at)}">${escape(when(r.at))}</time></p> |
| 107 | 115 | <p class="body">${escape(r.body)}</p> |
| @@ -155,6 +163,23 @@ export function leadPage(input: { | ||
| 155 | 163 | </details>` |
| 156 | 164 | : ""; |
| 157 | 165 | |
| 166 | const call = | |
| 167 | mayUpdate && lead.phone !== "" | |
| 168 | ? `<details class="card add record" id="log-call"> | |
| 169 | <summary>Log a call</summary> | |
| 170 | <form class="stack" method="post" action="${path}/call"> | |
| 171 | <label>How it went | |
| 172 | <select class="input" name="outcome">${OUTCOMES.map((o) => ` | |
| 173 | <option value="${o}">${OUTCOME_LABEL[o]}</option>`).join("")} | |
| 174 | </select> | |
| 175 | </label> | |
| 176 | <label>Note (optional) <textarea class="input" name="note" rows="2" maxlength="${MAX_NOTE}"></textarea></label> | |
| 177 | ${lead.replied_at === null ? '<p class="hint">Talked or a voicemail counts as your first answer: the clock stops now, the drafted first reply is set aside and the follow-ups begin. Nothing is sent.</p>' : ""} | |
| 178 | <button class="button">Log the call</button> | |
| 179 | </form> | |
| 180 | </details>` | |
| 181 | : ""; | |
| 182 | ||
| 158 | 183 | const stop = |
| 159 | 184 | mayUpdate && lead.consent |
| 160 | 185 | ? `<section class="states"> |
| @@ -186,7 +211,11 @@ export function leadPage(input: { | ||
| 186 | 211 | <div> |
| 187 | 212 | <h1>${escape(lead.name)}</h1> |
| 188 | 213 | <p class="tags">${source(lead)}${consent(lead)}<span class="chip" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span></p> |
| 189 | <p class="contact">${contact}</p> | |
| 214 | <p class="contact">${contact}${ | |
| 215 | mayUpdate && lead.phone !== "" | |
| 216 | ? ` · <a href="#log-call">Log a call</a>` | |
| 217 | : "" | |
| 218 | }</p> | |
| 190 | 219 | </div> |
| 191 | 220 | ${clock(lead, now, owed)} |
| 192 | 221 | </header> |
| @@ -198,6 +227,7 @@ export function leadPage(input: { | ||
| 198 | 227 | ${draft} |
| 199 | 228 | </div> |
| 200 | 229 | ${thread} |
| 230 | ${call} | |
| 201 | 231 | ${record} |
| 202 | 232 | ${plan} |
| 203 | 233 | ${states} |
src/routes.ts +49 −1
| @@ -29,6 +29,7 @@ import { | ||
| 29 | 29 | approveReply, |
| 30 | 30 | nextLead, |
| 31 | 31 | setState, |
| 32 | logCall, | |
| 32 | 33 | logLeadReply, |
| 33 | 34 | tick, |
| 34 | 35 | type Failure, |
| @@ -51,6 +52,7 @@ import { | ||
| 51 | 52 | staticFile, |
| 52 | 53 | text, |
| 53 | 54 | } from "./http.ts"; |
| 55 | import { MAX_NOTE, OUTCOMES } from "./calls.ts"; | |
| 54 | 56 | import { MAX_INBOUND, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts"; |
| 55 | 57 | import { events } from "./live.ts"; |
| 56 | 58 | import { rpc } from "./mcp.ts"; |
| @@ -148,6 +150,17 @@ const INBOUND: Schema = { | ||
| 148 | 150 | }, |
| 149 | 151 | required: ["id", "lead_id", "channel", "body", "at"], |
| 150 | 152 | }; |
| 153 | const CALL: Schema = { | |
| 154 | type: "object", | |
| 155 | properties: { | |
| 156 | id: { type: "integer" }, | |
| 157 | lead_id: { type: "integer" }, | |
| 158 | outcome: { enum: [...OUTCOMES] }, | |
| 159 | note: { type: "string", maxLength: MAX_NOTE }, | |
| 160 | at: STAMP, | |
| 161 | }, | |
| 162 | required: ["id", "lead_id", "outcome", "note", "at"], | |
| 163 | }; | |
| 151 | 164 | export const LEAD: Schema = { |
| 152 | 165 | type: "object", |
| 153 | 166 | properties: { |
| @@ -158,8 +171,13 @@ export const LEAD: Schema = { | ||
| 158 | 171 | description: "What the lead wrote back, oldest first.", |
| 159 | 172 | items: INBOUND, |
| 160 | 173 | }, |
| 174 | calls: { | |
| 175 | type: "array", | |
| 176 | description: "Phone calls you logged, oldest first.", | |
| 177 | items: CALL, | |
| 178 | }, | |
| 161 | 179 | }, |
| 162 | required: [...LEAD_REQUIRED, "messages", "replies"], | |
| 180 | required: [...LEAD_REQUIRED, "messages", "replies", "calls"], | |
| 163 | 181 | }; |
| 164 | 182 | export const APPROVED: Schema = { |
| 165 | 183 | type: "object", |
| @@ -578,6 +596,36 @@ export const routes: readonly Route[] = [ | ||
| 578 | 596 | answer: LEAD, |
| 579 | 597 | }, |
| 580 | 598 | }, |
| 599 | { | |
| 600 | method: "POST", | |
| 601 | path: "/leads/:id/call", | |
| 602 | handle: (c) => | |
| 603 | posted( | |
| 604 | c, | |
| 605 | (input) => | |
| 606 | logCall(c.db, c.who, { id: ID(c), outcome: input.outcome, note: input.note }), | |
| 607 | (lead) => ({ | |
| 608 | to: `/leads/${ID(c)}`, | |
| 609 | said: | |
| 610 | lead !== undefined && lead.calls.at(-1)?.outcome === "no_answer" | |
| 611 | ? "Call logged." | |
| 612 | : "Call logged. They count as answered.", | |
| 613 | }), | |
| 614 | ), | |
| 615 | api: { | |
| 616 | summary: | |
| 617 | "You phoned the lead: the call joins the history. Talked or voicemail on a lead not yet answered stops its response clock at the call, starts the follow-up plan and sets the drafted first reply aside; no answer only goes in the history. Nothing is sent.", | |
| 618 | body: { | |
| 619 | type: "object", | |
| 620 | properties: { | |
| 621 | outcome: { enum: [...OUTCOMES], description: "talked, voicemail (left a voicemail) or no_answer." }, | |
| 622 | note: { type: "string", maxLength: MAX_NOTE, description: "Optional, trimmed, plain text." }, | |
| 623 | }, | |
| 624 | required: ["outcome"], | |
| 625 | }, | |
| 626 | answer: LEAD, | |
| 627 | }, | |
| 628 | }, | |
| 581 | 629 | { |
| 582 | 630 | method: "POST", |
| 583 | 631 | path: "/leads/:id/state", |
src/sentences.ts +5
| @@ -35,6 +35,11 @@ export function deed( | ||
| 35 | 35 | done: `logged what ${lead} wrote back`, |
| 36 | 36 | tried: `log what ${lead} wrote back`, |
| 37 | 37 | }; |
| 38 | if (row.act === "call") | |
| 39 | return { | |
| 40 | done: `logged a call with ${lead}`, | |
| 41 | tried: `log a call with ${lead}`, | |
| 42 | }; | |
| 38 | 43 | if (row.act === "reopened") |
| 39 | 44 | return { |
| 40 | 45 | done: `put ${lead} back in follow-ups`, |
src/server.test.ts +1
| @@ -288,6 +288,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 288 | 288 | "new_sample_inquiry", |
| 289 | 289 | "send_reply", |
| 290 | 290 | "log_lead_reply", |
| 291 | "log_call", | |
| 291 | 292 | "mark_lead", |
| 292 | 293 | "opt_out_texts", |
| 293 | 294 | "get_profile", |
src/terminal.ts +37 −1
| @@ -34,10 +34,12 @@ import { | ||
| 34 | 34 | resetSample, |
| 35 | 35 | saveProfile, |
| 36 | 36 | approveReply, |
| 37 | logCall, | |
| 37 | 38 | logLeadReply, |
| 38 | 39 | nextLead, |
| 39 | 40 | setState, |
| 40 | 41 | } from "./actions.ts"; |
| 42 | import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts"; | |
| 41 | 43 | import { between, elapsed, recordLine, tone } from "./clock.ts"; |
| 42 | 44 | import { permit } from "./contract.ts"; |
| 43 | 45 | import { said as saidOf } from "./sentences.ts"; |
| @@ -114,6 +116,7 @@ type View = | ||
| 114 | 116 | | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> } |
| 115 | 117 | | { name: "lead"; id: number } |
| 116 | 118 | | { name: "edit"; id: number; text: string } |
| 119 | | { name: "call"; id: number; outcome: Outcome; text: string } | |
| 117 | 120 | | { name: "wrote"; id: number; text: string; channel: Channel } |
| 118 | 121 | | { name: "add"; step: number; typed: string; fields: Record<string, string> } |
| 119 | 122 | | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View }; |
| @@ -293,6 +296,8 @@ export function terminal( | ||
| 293 | 296 | ); |
| 294 | 297 | } |
| 295 | 298 | const sent = l.messages.filter((m) => m.status === "sent").length; |
| 299 | for (const c of l.calls) | |
| 300 | lines.push(dim(`${callLine(c.outcome)} — ${c.at.slice(0, 16).replace("T", " ")}${c.note === "" ? "" : `: ${clean(c.note)}`}`)); | |
| 296 | 301 | lines.push( |
| 297 | 302 | "", |
| 298 | 303 | dim( |
| @@ -307,6 +312,7 @@ export function terminal( | ||
| 307 | 312 | : dim( |
| 308 | 313 | [ |
| 309 | 314 | ...(r === undefined ? [] : ["s approve and send", "e edit"]), |
| 315 | ...(l.phone === "" ? [] : ["c log a call"]), | |
| 310 | 316 | ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []), |
| 311 | 317 | ...(l.state === "qualified" || l.state === "lost" |
| 312 | 318 | ? ["o put back in follow-ups"] |
| @@ -451,6 +457,15 @@ export function terminal( | ||
| 451 | 457 | "", |
| 452 | 458 | dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"), |
| 453 | 459 | ] |
| 460 | : view.name === "call" | |
| 461 | ? [ | |
| 462 | bold(`Your call with ${clean(lead(view.id)?.name ?? "the lead")} — ${OUTCOME_LABEL[view.outcome]}`), | |
| 463 | "", | |
| 464 | dim("A note (optional):"), | |
| 465 | ...wrap(`${view.text}█`, w).map((s) => ` ${s}`), | |
| 466 | "", | |
| 467 | dim("type a note · enter new line · ctrl-o outcome · ctrl-d log the call · esc cancel"), | |
| 468 | ] | |
| 454 | 469 | : view.name === "add" |
| 455 | 470 | ? addScreen(view) |
| 456 | 471 | : [ |
| @@ -580,7 +595,9 @@ export function terminal( | ||
| 580 | 595 | state: input === "q" ? "qualified" : "lost", |
| 581 | 596 | }); |
| 582 | 597 | said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message; |
| 583 | } else if (input === "w") | |
| 598 | } else if (input === "c" && l.phone !== "") | |
| 599 | view = { name: "call", id, outcome: "talked", text: "" }; | |
| 600 | else if (input === "w") | |
| 584 | 601 | view = { name: "wrote", id, text: "", channel: "email" }; |
| 585 | 602 | else if (input === "o" && CLOSED.includes(l.state)) { |
| 586 | 603 | const back = setState(db, me, { id, state: "open" }); |
| @@ -603,6 +620,25 @@ export function terminal( | ||
| 603 | 620 | } |
| 604 | 621 | return; |
| 605 | 622 | } |
| 623 | case "call": { | |
| 624 | if (input === "\x1b") { | |
| 625 | said = "No call logged."; | |
| 626 | view = { name: "lead", id: view.id }; | |
| 627 | } else if (input === "\x0f") { | |
| 628 | view = { ...view, outcome: OUTCOMES[(OUTCOMES.indexOf(view.outcome) + 1) % OUTCOMES.length]! }; | |
| 629 | } else if (input === "\x04") { | |
| 630 | const logged = logCall(db, me, { id: view.id, outcome: view.outcome, note: view.text }); | |
| 631 | said = logged.ok | |
| 632 | ? `Call logged: ${OUTCOME_LABEL[view.outcome]}.${answers(view.outcome) ? " They count as answered." : ""}` | |
| 633 | : logged.message; | |
| 634 | if (logged.ok) view = { name: "lead", id: view.id }; | |
| 635 | } else if (input === "\r") view = { ...view, text: `${view.text}\n` }; | |
| 636 | else { | |
| 637 | const next = typing(view.text, input.replace(/\r\n?/g, "\n")); | |
| 638 | if (next !== undefined) view = { ...view, text: next }; | |
| 639 | } | |
| 640 | return; | |
| 641 | } | |
| 606 | 642 | case "wrote": { |
| 607 | 643 | if (input === "\x1b") { |
| 608 | 644 | said = "Nothing recorded."; |
new above
offline
This action is a new door on the lead/update cell. Add it to the
updatedoor in src/contract.test.ts (the same way logLeadReply is) so the contract audit covers it.