Public: anyone can read this; the crew can change it.
Book a showing on a lead: it shows on the desk and follow-ups wait until the day after #37
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/33-book-a-showing-on-a-lead-it-shows-on-the → main 2 commits fork
18 files
changed +1055
−25
AGENTS.md +6
| @@ -118,6 +118,12 @@ Speed to Lead is one realtor's desk. The concepts, one module each: | ||
| 118 | 118 | is its first answer (`recordCall` stops the clock through the same |
| 119 | 119 | `startCadence` a sent first reply uses, and sets the draft aside as |
| 120 | 120 | `skipped`); no answer is history only. |
| 121 | - Showings: a showing booked on an open lead (`src/showings.ts` for the time | |
| 122 | rules and the words, `showing` table, one per lead). `advance` leaves a | |
| 123 | lead's follow-ups scheduled while its `hold_until` (the day after the | |
| 124 | showing) is ahead; booking sets due ones back, `cancelShowing` deletes the | |
| 125 | row and advances. It is the same hold `advance` already keeps for a pending | |
| 126 | answer, not a second mechanism. | |
| 121 | 127 | - `src/drafts.ts` — the words: templates filled from the inquiry and the |
| 122 | 128 | agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*` |
| 123 | 129 | defaults of `agent` in `src/env.ts`), the signature every message |
README.md +30 −5
| @@ -15,9 +15,9 @@ goes.** | ||
| 15 | 15 | For the sales meeting. The names below are the sample leads on the desk. |
| 16 | 16 | |
| 17 | 17 | Before you start: Press "Sign in" on the desk. Anyone signed in can read |
| 18 | and answer leads (steps 2 to 6). Restarting the samples (step 1) and saving | |
| 19 | your profile (step 7) need an admin; if you are not one, ask the person who | |
| 20 | runs the app to do step 1 just before the meeting, and read step 7 aloud. | |
| 18 | and answer leads (steps 2 to 7). Restarting the samples (step 1) and saving | |
| 19 | your profile (step 8) need an admin; if you are not one, ask the person who | |
| 20 | runs the app to do step 1 just before the meeting, and read step 8 aloud. | |
| 21 | 21 | |
| 22 | 22 | The clocks keep running while the app sits idle, so the colours below are only |
| 23 | 23 | what you see right after a restart. Do step 1 first. |
| @@ -51,11 +51,16 @@ what you see right after a restart. Do step 1 first. | ||
| 51 | 51 | Back on **Marcus Lee**, open "They wrote back", paste "Yes, Saturday |
| 52 | 52 | works" and record it: he is in "Needs you" with a fresh green clock and an |
| 53 | 53 | answer drafted, and his upcoming follow-ups wait until you send it. |
| 54 | 7. Set your profile (admin to save). Press "Your profile" at the top, fill | |
| 54 | 7. Book a showing. Open **Marcus Lee** again, press "Book a showing", pick | |
| 55 | a day and time later this week (UTC), type an address and book it. The | |
| 56 | history says "Showing booked", his row on the desk carries a *Showing* | |
| 57 | badge, and his follow-up plan says which follow-ups wait until the day | |
| 58 | after. Press "Cancel showing" and they return to their usual place. | |
| 59 | 8. Set your profile (admin to save). Press "Your profile" at the top, fill | |
| 55 | 60 | in your name, brokerage, license number, phone and email, and save. Every |
| 56 | 61 | draft not yet sent takes it at once. |
| 57 | 62 | |
| 58 | 8. Watch a lead arrive live. Press "Bring in a new inquiry", beside "Log a | |
| 63 | 9. Watch a lead arrive live. Press "Bring in a new inquiry", beside "Log a | |
| 59 | 64 | lead by hand". A new person is at the top of the desk with a green clock |
| 60 | 65 | at 0:00 and a reply already drafted. Open the lead, press "Approve and |
| 61 | 66 | send", and see the clock stop well under a minute. Press the button again |
| @@ -170,6 +175,22 @@ same is `POST /leads/:id/call` (`outcome`: `talked`, `voicemail` or | ||
| 170 | 175 | lead's terminal screen (ctrl-o changes the outcome, ctrl-d logs it). It needs |
| 171 | 176 | the same permission as any change to a lead, and shows on the Activity page. |
| 172 | 177 | |
| 178 | **When a lead agrees to a showing.** "Saturday at 10 works": on an open lead, | |
| 179 | press **Book a showing**, choose the date and time (in the future, at most 90 | |
| 180 | days ahead, entered in UTC) and, if you like, the address (up to 200 | |
| 181 | characters). The history says it ("Showing booked · Sat 10:00 · 12 Example | |
| 182 | St") and the lead's row on the desk carries a *Showing* badge. A lead has one | |
| 183 | showing: booking again moves it, and **Cancel showing** removes it. While a | |
| 184 | showing is ahead, follow-ups due before it do not come to *Needs you* until | |
| 185 | the day after it, so nobody gets "just checking in" before they have seen the | |
| 186 | house; the follow-up plan on the lead's page says which ones wait and until | |
| 187 | when. Cancelling puts them back where they were, ready at once if their day | |
| 188 | has come. Nothing is sent. The same is `POST /leads/:id/showing` (`at`, an | |
| 189 | ISO 8601 time such as `2026-11-07T10:00`; `address`; form or JSON; `422` for a | |
| 190 | past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP | |
| 191 | tools `book_showing` and `cancel_showing`. It needs the same permission as any | |
| 192 | change to a lead, and shows on the Activity page. | |
| 193 | ||
| 173 | 194 | **Sample leads.** The app starts with twelve sample leads so you can see it |
| 174 | 195 | work: two just in, two waiting a while, three gone red, and five already |
| 175 | 196 | answered and partway through their follow-ups. An admin can restart them |
| @@ -269,6 +290,10 @@ until you press a key on this screen: | ||
| 269 | 290 | - `e` lets you edit it first: type, enter for a new line, backspace to |
| 270 | 291 | delete, then `ctrl-d` to approve and send — or `esc` to send nothing. |
| 271 | 292 | - `q` marks the lead qualified, `x` lost. |
| 293 | - `b` books a showing (or moves the one it has) on an open lead: type the | |
| 294 | time in UTC like `2026-11-07T10:00` and press enter, then the address (or | |
| 295 | nothing) and press enter. A refused time asks again. `u` cancels the showing. The lead's | |
| 296 | screen and its desk row show the showing. | |
| 272 | 297 | - `D` removes the lead (admins only; asks first). |
| 273 | 298 | - `esc` goes back to the desk. |
| 274 | 299 |
contract/openapi.json +197 −2
| @@ -490,6 +490,42 @@ | ||
| 490 | 490 | ] |
| 491 | 491 | } |
| 492 | 492 | }, |
| 493 | "showing": { | |
| 494 | "type": [ | |
| 495 | "object", | |
| 496 | "null" | |
| 497 | ], | |
| 498 | "description": "The showing booked on this lead, or null.", | |
| 499 | "properties": { | |
| 500 | "lead_id": { | |
| 501 | "type": "integer" | |
| 502 | }, | |
| 503 | "at": { | |
| 504 | "type": "string", | |
| 505 | "format": "date-time" | |
| 506 | }, | |
| 507 | "address": { | |
| 508 | "type": "string", | |
| 509 | "maxLength": 200 | |
| 510 | }, | |
| 511 | "hold_until": { | |
| 512 | "type": "string", | |
| 513 | "format": "date-time", | |
| 514 | "description": "Follow-ups due before this wait until it." | |
| 515 | }, | |
| 516 | "booked_at": { | |
| 517 | "type": "string", | |
| 518 | "format": "date-time" | |
| 519 | } | |
| 520 | }, | |
| 521 | "required": [ | |
| 522 | "lead_id", | |
| 523 | "at", | |
| 524 | "address", | |
| 525 | "hold_until", | |
| 526 | "booked_at" | |
| 527 | ] | |
| 528 | }, | |
| 493 | 529 | "next": { |
| 494 | 530 | "type": [ |
| 495 | 531 | "object", |
| @@ -526,6 +562,7 @@ | ||
| 526 | 562 | "messages", |
| 527 | 563 | "replies", |
| 528 | 564 | "calls", |
| 565 | "showing", | |
| 529 | 566 | "next" |
| 530 | 567 | ] |
| 531 | 568 | } |
| @@ -678,6 +715,104 @@ | ||
| 678 | 715 | } |
| 679 | 716 | } |
| 680 | 717 | }, |
| 718 | "/leads/{id}/showing": { | |
| 719 | "post": { | |
| 720 | "summary": "Book a showing on an open lead, or move the one it has (one per lead). Follow-ups due before it wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time.", | |
| 721 | "operationId": "postLeadsIdShowing", | |
| 722 | "parameters": [ | |
| 723 | { | |
| 724 | "name": "id", | |
| 725 | "in": "path", | |
| 726 | "required": true, | |
| 727 | "schema": { | |
| 728 | "type": "integer" | |
| 729 | } | |
| 730 | } | |
| 731 | ], | |
| 732 | "requestBody": { | |
| 733 | "required": true, | |
| 734 | "content": { | |
| 735 | "application/json": { | |
| 736 | "schema": { | |
| 737 | "type": "object", | |
| 738 | "properties": { | |
| 739 | "at": { | |
| 740 | "type": "string", | |
| 741 | "description": "A date and time in the future, at most 90 days ahead: ISO 8601, like 2026-11-07T10:00 (UTC) or 2026-11-07T10:00:00-08:00." | |
| 742 | }, | |
| 743 | "address": { | |
| 744 | "type": "string", | |
| 745 | "maxLength": 200, | |
| 746 | "description": "Optional, one line." | |
| 747 | } | |
| 748 | }, | |
| 749 | "required": [ | |
| 750 | "at" | |
| 751 | ] | |
| 752 | } | |
| 753 | } | |
| 754 | } | |
| 755 | }, | |
| 756 | "responses": { | |
| 757 | "200": { | |
| 758 | "description": "Book a showing on an open lead, or move the one it has (one per lead). Follow-ups due before it wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time.", | |
| 759 | "content": { | |
| 760 | "application/json": { | |
| 761 | "schema": { | |
| 762 | "$ref": "#/components/schemas/Lead" | |
| 763 | } | |
| 764 | } | |
| 765 | } | |
| 766 | }, | |
| 767 | "default": { | |
| 768 | "description": "{ error, message }: why not", | |
| 769 | "content": { | |
| 770 | "application/json": { | |
| 771 | "schema": { | |
| 772 | "$ref": "#/components/schemas/Error" | |
| 773 | } | |
| 774 | } | |
| 775 | } | |
| 776 | } | |
| 777 | } | |
| 778 | }, | |
| 779 | "delete": { | |
| 780 | "summary": "Cancel the lead's showing: follow-ups held for it return to their usual place, and any whose day has come are ready at once.", | |
| 781 | "operationId": "deleteLeadsIdShowing", | |
| 782 | "parameters": [ | |
| 783 | { | |
| 784 | "name": "id", | |
| 785 | "in": "path", | |
| 786 | "required": true, | |
| 787 | "schema": { | |
| 788 | "type": "integer" | |
| 789 | } | |
| 790 | } | |
| 791 | ], | |
| 792 | "responses": { | |
| 793 | "200": { | |
| 794 | "description": "Cancel the lead's showing: follow-ups held for it return to their usual place, and any whose day has come are ready at once.", | |
| 795 | "content": { | |
| 796 | "application/json": { | |
| 797 | "schema": { | |
| 798 | "$ref": "#/components/schemas/Lead" | |
| 799 | } | |
| 800 | } | |
| 801 | } | |
| 802 | }, | |
| 803 | "default": { | |
| 804 | "description": "{ error, message }: why not", | |
| 805 | "content": { | |
| 806 | "application/json": { | |
| 807 | "schema": { | |
| 808 | "$ref": "#/components/schemas/Error" | |
| 809 | } | |
| 810 | } | |
| 811 | } | |
| 812 | } | |
| 813 | } | |
| 814 | } | |
| 815 | }, | |
| 681 | 816 | "/leads/{id}/state": { |
| 682 | 817 | "post": { |
| 683 | 818 | "summary": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.", |
| @@ -1364,6 +1499,42 @@ | ||
| 1364 | 1499 | "at" |
| 1365 | 1500 | ] |
| 1366 | 1501 | } |
| 1502 | }, | |
| 1503 | "showing": { | |
| 1504 | "type": [ | |
| 1505 | "object", | |
| 1506 | "null" | |
| 1507 | ], | |
| 1508 | "description": "The showing booked on this lead, or null.", | |
| 1509 | "properties": { | |
| 1510 | "lead_id": { | |
| 1511 | "type": "integer" | |
| 1512 | }, | |
| 1513 | "at": { | |
| 1514 | "type": "string", | |
| 1515 | "format": "date-time" | |
| 1516 | }, | |
| 1517 | "address": { | |
| 1518 | "type": "string", | |
| 1519 | "maxLength": 200 | |
| 1520 | }, | |
| 1521 | "hold_until": { | |
| 1522 | "type": "string", | |
| 1523 | "format": "date-time", | |
| 1524 | "description": "Follow-ups due before this wait until it." | |
| 1525 | }, | |
| 1526 | "booked_at": { | |
| 1527 | "type": "string", | |
| 1528 | "format": "date-time" | |
| 1529 | } | |
| 1530 | }, | |
| 1531 | "required": [ | |
| 1532 | "lead_id", | |
| 1533 | "at", | |
| 1534 | "address", | |
| 1535 | "hold_until", | |
| 1536 | "booked_at" | |
| 1537 | ] | |
| 1367 | 1538 | } |
| 1368 | 1539 | }, |
| 1369 | 1540 | "required": [ |
| @@ -1381,7 +1552,8 @@ | ||
| 1381 | 1552 | "updated_at", |
| 1382 | 1553 | "messages", |
| 1383 | 1554 | "replies", |
| 1384 | "calls" | |
| 1555 | "calls", | |
| 1556 | "showing" | |
| 1385 | 1557 | ] |
| 1386 | 1558 | }, |
| 1387 | 1559 | "Desk": { |
| @@ -1569,6 +1741,28 @@ | ||
| 1569 | 1741 | "null" |
| 1570 | 1742 | ], |
| 1571 | 1743 | "format": "date-time" |
| 1744 | }, | |
| 1745 | "showing": { | |
| 1746 | "type": [ | |
| 1747 | "object", | |
| 1748 | "null" | |
| 1749 | ], | |
| 1750 | "description": "The showing booked on this lead, if one is.", | |
| 1751 | "properties": { | |
| 1752 | "at": { | |
| 1753 | "type": "string", | |
| 1754 | "format": "date-time" | |
| 1755 | }, | |
| 1756 | "address": { | |
| 1757 | "type": "string", | |
| 1758 | "maxLength": 200 | |
| 1759 | }, | |
| 1760 | "hold_until": { | |
| 1761 | "type": "string", | |
| 1762 | "format": "date-time", | |
| 1763 | "description": "Follow-ups due before this wait until it." | |
| 1764 | } | |
| 1765 | } | |
| 1572 | 1766 | } |
| 1573 | 1767 | }, |
| 1574 | 1768 | "required": [ |
| @@ -1585,7 +1779,8 @@ | ||
| 1585 | 1779 | "replied_at", |
| 1586 | 1780 | "updated_at", |
| 1587 | 1781 | "ready", |
| 1588 | "next_at" | |
| 1782 | "next_at", | |
| 1783 | "showing" | |
| 1589 | 1784 | ] |
| 1590 | 1785 | }, |
| 1591 | 1786 | "Message": { |
src/actions.ts +72
| @@ -31,6 +31,8 @@ import { | ||
| 31 | 31 | nextNeeding, |
| 32 | 32 | readyFor, |
| 33 | 33 | recordCall, |
| 34 | bookShowing as bookShowingFor, | |
| 35 | cancelShowing as cancelShowingFor, | |
| 34 | 36 | recordInbound, |
| 35 | 37 | redraftUnsent, |
| 36 | 38 | removeLead, |
| @@ -45,6 +47,7 @@ import { | ||
| 45 | 47 | import { emit } from "./live.ts"; |
| 46 | 48 | import { currentAgent, storeAgent } from "./profile.ts"; |
| 47 | 49 | import { nextInquiry, seed } from "./sample.ts"; |
| 50 | import { MAX_ADDRESS, timeOf } from "./showings.ts"; | |
| 48 | 51 | import type { Who } from "./who.ts"; |
| 49 | 52 | |
| 50 | 53 | export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid"; |
| @@ -428,6 +431,75 @@ function phoned( | ||
| 428 | 431 | return ok(detail(db, lead.id)!); |
| 429 | 432 | } |
| 430 | 433 | |
| 434 | /** | |
| 435 | * Book a showing on an open lead, or move the one it has: `when` is a | |
| 436 | * future date and time within 90 days, `address` optional. Follow-ups due | |
| 437 | * before it wait until the day after. Nothing is sent. | |
| 438 | */ | |
| 439 | export const bookShowing = ( | |
| 440 | db: Database, | |
| 441 | who: Who, | |
| 442 | input: { id: number; when?: unknown; address?: unknown }, | |
| 443 | at?: Date, | |
| 444 | ): Result<LeadDetail> => | |
| 445 | audited(db, who, "lead", "update", input.id, booked(db, who, input, at), "showing"); | |
| 446 | ||
| 447 | function booked( | |
| 448 | db: Database, | |
| 449 | who: Who, | |
| 450 | input: { id: number; when?: unknown; address?: unknown }, | |
| 451 | at?: Date, | |
| 452 | ): Result<LeadDetail> { | |
| 453 | const found = leadFor(db, who, "update", input.id, { | |
| 454 | signIn: "Sign in to book a showing.", | |
| 455 | no: "You may not book a showing for this lead.", | |
| 456 | }); | |
| 457 | if (!found.ok) return found; | |
| 458 | const lead = found.value; | |
| 459 | if (CLOSED.includes(lead.state)) | |
| 460 | return fail("invalid", "A qualified or lost lead has no showings: put it back first."); | |
| 461 | const now = stamp(at); | |
| 462 | const time = timeOf(input.when, Date.parse(now)); | |
| 463 | if ("error" in time) return fail("invalid", time.error); | |
| 464 | if (input.address !== undefined && input.address !== null && typeof input.address !== "string") | |
| 465 | return fail("invalid", "An address is text."); | |
| 466 | const address = (input.address ?? "").trim(); | |
| 467 | if (address.length > MAX_ADDRESS) | |
| 468 | return fail("invalid", `An address is at most ${MAX_ADDRESS} characters.`); | |
| 469 | if (hasControl(address, false)) | |
| 470 | return fail("invalid", "An address is one line of plain text."); | |
| 471 | bookShowingFor(db, lead, time.at, address, now); | |
| 472 | emit("lead.changed", { id: lead.id }); | |
| 473 | return ok(detail(db, lead.id)!); | |
| 474 | } | |
| 475 | ||
| 476 | /** Take the showing off a lead; the follow-ups held for it return to their usual place. */ | |
| 477 | export const cancelShowing = ( | |
| 478 | db: Database, | |
| 479 | who: Who, | |
| 480 | input: { id: number }, | |
| 481 | at?: Date, | |
| 482 | ): Result<LeadDetail> => | |
| 483 | audited(db, who, "lead", "update", input.id, cancelled(db, who, input, at), "showing_off"); | |
| 484 | ||
| 485 | function cancelled( | |
| 486 | db: Database, | |
| 487 | who: Who, | |
| 488 | input: { id: number }, | |
| 489 | at?: Date, | |
| 490 | ): Result<LeadDetail> { | |
| 491 | const found = leadFor(db, who, "update", input.id, { | |
| 492 | signIn: "Sign in to cancel a showing.", | |
| 493 | no: "You may not cancel a showing for this lead.", | |
| 494 | }); | |
| 495 | if (!found.ok) return found; | |
| 496 | if (found.value.showing === null) | |
| 497 | return fail("not_found", "This lead has no showing booked."); | |
| 498 | cancelShowingFor(db, found.value, stamp(at)); | |
| 499 | emit("lead.changed", { id: found.value.id }); | |
| 500 | return ok(detail(db, found.value.id)!); | |
| 501 | } | |
| 502 | ||
| 431 | 503 | /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */ |
| 432 | 504 | export const setState = ( |
| 433 | 505 | 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; `call` is a phone call the agent logged. */ | |
| 36 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call"] 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; `showing` books or moves a showing, `showing_off` cancels it. */ | |
| 36 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off"] as const; | |
| 37 | 37 | export type Act = (typeof ACTS)[number]; |
| 38 | 38 | |
| 39 | 39 | export interface Attempt { |
src/contract.test.ts +9
| @@ -18,6 +18,8 @@ import { | ||
| 18 | 18 | listAudit, |
| 19 | 19 | listLeads, |
| 20 | 20 | logCall, |
| 21 | bookShowing, | |
| 22 | cancelShowing, | |
| 21 | 23 | logLeadReply, |
| 22 | 24 | saveProfile, |
| 23 | 25 | setState, |
| @@ -113,7 +115,14 @@ const doors: Record< | ||
| 113 | 115 | // So is logging a phone call (POST /leads/:id/call and the MCP tool log_call). |
| 114 | 116 | db.query("UPDATE lead SET phone = '206 555 0100' WHERE id = ?1").run(replied); |
| 115 | 117 | const called = logCall(db, who, { id: replied, outcome: "no_answer" }).ok; |
| 118 | // And so is booking or cancelling a showing (POST|DELETE /leads/:id/showing, | |
| 119 | // the MCP tools book_showing and cancel_showing). | |
| 120 | const week = new Date(Date.now() + 7 * 86_400_000).toISOString(); | |
| 121 | const showing = bookShowing(db, who, { id: replied, when: week }).ok; | |
| 122 | const off = cancelShowing(db, who, { id: replied }).ok; | |
| 116 | 123 | const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok; |
| 124 | expect(showing).toBe(changed); | |
| 125 | expect(off).toBe(changed); | |
| 117 | 126 | expect(logged).toBe(changed); |
| 118 | 127 | expect(called).toBe(changed); |
| 119 | 128 | return changed; |
src/db.ts +9
| @@ -126,6 +126,15 @@ export const migrations: string[] = [ | ||
| 126 | 126 | at TEXT NOT NULL |
| 127 | 127 | )`, |
| 128 | 128 | `CREATE INDEX IF NOT EXISTS phone_call_lead ON phone_call (lead_id, at)`, |
| 129 | // A showing booked on a lead, one at most. Until `hold_until` (the day | |
| 130 | // after it) the lead's follow-ups wait; deleting the row releases them. | |
| 131 | `CREATE TABLE IF NOT EXISTS showing ( | |
| 132 | lead_id INTEGER PRIMARY KEY REFERENCES lead (id) ON DELETE CASCADE, | |
| 133 | at TEXT NOT NULL, | |
| 134 | address TEXT NOT NULL DEFAULT '' CHECK (length(address) <= 200), | |
| 135 | hold_until TEXT NOT NULL, | |
| 136 | booked_at TEXT NOT NULL | |
| 137 | )`, | |
| 129 | 138 | ]; |
| 130 | 139 | |
| 131 | 140 | export function openDb(dir = dataDir): Database { |
src/leads.ts +62 −3
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | import { answers, type Call, type Outcome } from "./calls.ts"; |
| 27 | 27 | import { GREEN_MS } from "./clock.ts"; |
| 28 | 28 | import type { Agent } from "./env.ts"; |
| 29 | import { holdUntil, type Showing } from "./showings.ts"; | |
| 29 | 30 | |
| 30 | 31 | export type State = "new" | "contacted" | "qualified" | "lost"; |
| 31 | 32 | export const CLOSED: readonly State[] = ["qualified", "lost"]; |
| @@ -80,6 +81,8 @@ export interface LeadDetail extends Lead { | ||
| 80 | 81 | readonly replies: readonly Inbound[]; |
| 81 | 82 | /** Calls the agent made, oldest first. */ |
| 82 | 83 | readonly calls: readonly Call[]; |
| 84 | /** The showing booked on this lead; null when none. */ | |
| 85 | readonly showing: Showing | null; | |
| 83 | 86 | } |
| 84 | 87 | |
| 85 | 88 | /** When the lead began to wait on our answer to what they wrote back; null when no answer is owed. */ |
| @@ -92,6 +95,8 @@ export interface DeskLead extends Lead { | ||
| 92 | 95 | readonly ready: { readonly id: number; readonly day: number; readonly since: string } | null; |
| 93 | 96 | /** When the next scheduled touch comes due, if one is. */ |
| 94 | 97 | readonly next_at: string | null; |
| 98 | /** The showing booked on this lead, if one is. */ | |
| 99 | readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null; | |
| 95 | 100 | } |
| 96 | 101 | |
| 97 | 102 | /** |
| @@ -190,11 +195,22 @@ export const callsOf = (db: Database, id: number): Call[] => | ||
| 190 | 195 | >("SELECT * FROM phone_call WHERE lead_id = ?1 ORDER BY at, id") |
| 191 | 196 | .all(id); |
| 192 | 197 | |
| 198 | export const showingOf = (db: Database, id: number): Showing | null => | |
| 199 | db | |
| 200 | .query<Showing, [number]>("SELECT * FROM showing WHERE lead_id = ?1") | |
| 201 | .get(id); | |
| 202 | ||
| 193 | 203 | export function detail(db: Database, id: number): LeadDetail | null { |
| 194 | 204 | const found = findLead(db, id); |
| 195 | 205 | return found === null |
| 196 | 206 | ? null |
| 197 | : { ...found, messages: messagesOf(db, id), replies: repliesOf(db, id), calls: callsOf(db, id) }; | |
| 207 | : { | |
| 208 | ...found, | |
| 209 | messages: messagesOf(db, id), | |
| 210 | replies: repliesOf(db, id), | |
| 211 | calls: callsOf(db, id), | |
| 212 | showing: showingOf(db, id), | |
| 213 | }; | |
| 198 | 214 | } |
| 199 | 215 | |
| 200 | 216 | export const MAX_QUERY = 80; |
| @@ -237,6 +253,9 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 237 | 253 | ready_day: number | null; |
| 238 | 254 | ready_since: string | null; |
| 239 | 255 | next_at: string | null; |
| 256 | show_at: string | null; | |
| 257 | show_address: string | null; | |
| 258 | show_hold: string | null; | |
| 240 | 259 | }, |
| 241 | 260 | [number, string, string] |
| 242 | 261 | >( |
| @@ -244,20 +263,27 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 244 | 263 | (SELECT id FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_id, |
| 245 | 264 | (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day, |
| 246 | 265 | (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since, |
| 247 | (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at | |
| 266 | (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at, | |
| 267 | (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at, | |
| 268 | (SELECT address FROM showing WHERE lead_id = lead.id) AS show_address, | |
| 269 | (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold | |
| 248 | 270 | FROM lead |
| 249 | 271 | WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\' |
| 250 | 272 | OR (?3 <> '' AND ${DIGITS} LIKE ?3) |
| 251 | 273 | ORDER BY created_at DESC, id DESC LIMIT ?1`, |
| 252 | 274 | ) |
| 253 | 275 | .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`) |
| 254 | .map(({ ready_id, ready_day, ready_since, next_at, ...row }) => ({ | |
| 276 | .map(({ ready_id, ready_day, ready_since, next_at, show_at, show_address, show_hold, ...row }) => ({ | |
| 255 | 277 | ...lead(row), |
| 256 | 278 | ready: |
| 257 | 279 | ready_id === null || ready_day === null || ready_since === null |
| 258 | 280 | ? null |
| 259 | 281 | : { id: ready_id, day: ready_day, since: ready_since }, |
| 260 | 282 | next_at, |
| 283 | showing: | |
| 284 | show_at === null || show_address === null || show_hold === null | |
| 285 | ? null | |
| 286 | : { at: show_at, address: show_address, hold_until: show_hold }, | |
| 261 | 287 | })); |
| 262 | 288 | } |
| 263 | 289 | |
| @@ -651,6 +677,7 @@ export function advance(db: Database, at: string): number[] { | ||
| 651 | 677 | `UPDATE message SET status = 'due' |
| 652 | 678 | WHERE status = 'scheduled' AND due_at <= ?1 |
| 653 | 679 | AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted') |
| 680 | AND lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1) | |
| 654 | 681 | AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status = 'draft') |
| 655 | 682 | RETURNING lead_id`, |
| 656 | 683 | ) |
| @@ -659,6 +686,38 @@ export function advance(db: Database, at: string): number[] { | ||
| 659 | 686 | .filter((id, i, all) => all.indexOf(id) === i); |
| 660 | 687 | } |
| 661 | 688 | |
| 689 | /** | |
| 690 | * A showing is booked for `when` (booking again moves it). Follow-ups wait | |
| 691 | * until the day after it, so any already due go back to waiting. | |
| 692 | */ | |
| 693 | export function bookShowing( | |
| 694 | db: Database, | |
| 695 | found: Lead, | |
| 696 | when: string, | |
| 697 | address: string, | |
| 698 | at: string, | |
| 699 | ): void { | |
| 700 | db.transaction(() => { | |
| 701 | db.query( | |
| 702 | `INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (?1, ?2, ?3, ?4, ?5) | |
| 703 | ON CONFLICT (lead_id) DO UPDATE SET at = ?2, address = ?3, hold_until = ?4, booked_at = ?5`, | |
| 704 | ).run(found.id, when, address, holdUntil(when), at); | |
| 705 | db.query( | |
| 706 | "UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due'", | |
| 707 | ).run(found.id); | |
| 708 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); | |
| 709 | })(); | |
| 710 | } | |
| 711 | ||
| 712 | /** The showing is off: follow-ups whose day has come are due again at once. */ | |
| 713 | export function cancelShowing(db: Database, found: Lead, at: string): void { | |
| 714 | db.transaction(() => { | |
| 715 | db.query("DELETE FROM showing WHERE lead_id = ?1").run(found.id); | |
| 716 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); | |
| 717 | advance(db, at); | |
| 718 | })(); | |
| 719 | } | |
| 720 | ||
| 662 | 721 | export const removeLead = (db: Database, id: number): void => { |
| 663 | 722 | db.query("DELETE FROM lead WHERE id = ?1").run(id); |
| 664 | 723 | }; |
src/mcp.ts +30
| @@ -18,10 +18,13 @@ import { | ||
| 18 | 18 | approveReply, |
| 19 | 19 | setState, |
| 20 | 20 | logCall, |
| 21 | bookShowing, | |
| 22 | cancelShowing, | |
| 21 | 23 | logLeadReply, |
| 22 | 24 | type Result, |
| 23 | 25 | } from "./actions.ts"; |
| 24 | 26 | import { MAX_NOTE, OUTCOMES } from "./calls.ts"; |
| 27 | import { MAX_ADDRESS } from "./showings.ts"; | |
| 25 | 28 | import { SOURCES } from "./drafts.ts"; |
| 26 | 29 | import { title } from "./env.ts"; |
| 27 | 30 | import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts"; |
| @@ -146,6 +149,33 @@ export const tools: readonly Tool[] = [ | ||
| 146 | 149 | run: (db, who, args) => |
| 147 | 150 | logCall(db, who, { id: Number(args.id), outcome: args.outcome, note: args.note }), |
| 148 | 151 | }, |
| 152 | { | |
| 153 | name: "book_showing", | |
| 154 | description: | |
| 155 | "A lead agreed to a showing: book it (or move the one it has) for a future date and time within 90 days, with an optional address. Follow-ups due before it wait until the day after it. Open leads only. Nothing is sent.", | |
| 156 | inputSchema: { | |
| 157 | type: "object", | |
| 158 | properties: { | |
| 159 | id: { type: "integer" }, | |
| 160 | at: { type: "string", description: "ISO 8601, like 2026-11-07T10:00 (UTC)." }, | |
| 161 | address: { type: "string", maxLength: MAX_ADDRESS }, | |
| 162 | }, | |
| 163 | required: ["id", "at"], | |
| 164 | }, | |
| 165 | run: (db, who, args) => | |
| 166 | bookShowing(db, who, { id: Number(args.id), when: args.at, address: args.address }), | |
| 167 | }, | |
| 168 | { | |
| 169 | name: "cancel_showing", | |
| 170 | description: | |
| 171 | "Cancel a lead's showing: the follow-ups held for it return to their usual place.", | |
| 172 | inputSchema: { | |
| 173 | type: "object", | |
| 174 | properties: { id: { type: "integer" } }, | |
| 175 | required: ["id"], | |
| 176 | }, | |
| 177 | run: (db, who, args) => cancelShowing(db, who, { id: Number(args.id) }), | |
| 178 | }, | |
| 149 | 179 | { |
| 150 | 180 | name: "mark_lead", |
| 151 | 181 | description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it.", |
src/pages/desk.ts +14 −2
| @@ -8,6 +8,7 @@ import { layout } from "./layout.ts"; | ||
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import { recordLine } from "../clock.ts"; |
| 10 | 10 | import { isAnswer } from "../drafts.ts"; |
| 11 | import { showingWhen } from "../showings.ts"; | |
| 11 | 12 | import type { DeskLead, ResponseRecord, View } from "../leads.ts"; |
| 12 | 13 | import type { Agent } from "../env.ts"; |
| 13 | 14 | import type { Who } from "../who.ts"; |
| @@ -135,6 +136,17 @@ const EMPTY: Record<View, string> = { | ||
| 135 | 136 | all: "No leads yet. New inquiries appear here the moment they arrive.", |
| 136 | 137 | }; |
| 137 | 138 | |
| 139 | /** A follow-up due while a showing is ahead waits until the day after it. */ | |
| 140 | const held = (lead: DeskLead, due: string): string => | |
| 141 | lead.showing !== null && due < lead.showing.hold_until ? lead.showing.hold_until : due; | |
| 142 | ||
| 143 | const showingBadge = (lead: DeskLead, now: number): string => | |
| 144 | lead.showing === null || Date.parse(lead.showing.hold_until) <= now | |
| 145 | ? "" | |
| 146 | : `<span class="badge" data-showing title="Showing booked: follow-ups wait until the day after">${escape( | |
| 147 | ["Showing", showingWhen(lead.showing.at, now), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "), | |
| 148 | )}</span>`; | |
| 149 | ||
| 138 | 150 | function status(lead: DeskLead): string { |
| 139 | 151 | if (lead.state === "qualified" || lead.state === "lost") |
| 140 | 152 | return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`; |
| @@ -145,7 +157,7 @@ function status(lead: DeskLead): string { | ||
| 145 | 157 | if (lead.ready !== null) |
| 146 | 158 | return `<span class="status" data-ready>Day ${lead.ready.day} follow-up ready</span>`; |
| 147 | 159 | if (lead.next_at !== null) |
| 148 | return `<span class="status">Next follow-up ${escape(day(lead.next_at))}</span>`; | |
| 160 | return `<span class="status">Next follow-up ${escape(day(held(lead, lead.next_at)))}</span>`; | |
| 149 | 161 | return `<span class="status">Follow-ups done</span>`; |
| 150 | 162 | } |
| 151 | 163 | |
| @@ -153,7 +165,7 @@ const row = (lead: DeskLead, now: number): string => `<li> | ||
| 153 | 165 | <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}> |
| 154 | 166 | <span class="lead-main"> |
| 155 | 167 | <span class="lead-name">${escape(lead.name)}</span> |
| 156 | <span class="tags">${source(lead)}${consent(lead)}</span> | |
| 168 | <span class="tags">${source(lead)}${consent(lead)}${showingBadge(lead, now)}</span> | |
| 157 | 169 | <span class="ask">${escape(lead.message)}</span> |
| 158 | 170 | ${status(lead)} |
| 159 | 171 | </span> |
src/pages/lead.ts +42 −7
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts"; |
| 8 | 8 | import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts"; |
| 9 | 9 | import { escape } from "../http.ts"; |
| 10 | import { MAX_ADDRESS, MAX_AHEAD_DAYS, showingLine, showingWhen } from "../showings.ts"; | |
| 10 | 11 | import { elapsed, between } from "../clock.ts"; |
| 11 | 12 | import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts"; |
| 12 | 13 | import type { Agent } from "../env.ts"; |
| @@ -16,9 +17,10 @@ import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts"; | ||
| 16 | 17 | |
| 17 | 18 | /** One line of the thread: something we sent, or something they wrote back. */ |
| 18 | 19 | type HistoryEntry = |
| 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 | | { at: string; ours: Message; theirs?: undefined; call?: undefined; showing?: undefined } | |
| 21 | | { at: string; theirs: LeadDetail["replies"][number]; ours?: undefined; call?: undefined; showing?: undefined } | |
| 22 | | { at: string; call: LeadDetail["calls"][number]; ours?: undefined; theirs?: undefined; showing?: undefined } | |
| 23 | | { at: string; showing: NonNullable<LeadDetail["showing"]>; ours?: undefined; theirs?: undefined; call?: undefined }; | |
| 22 | 24 | |
| 23 | 25 | const CHANNEL = { text: "text", email: "email" } as const; |
| 24 | 26 | |
| @@ -98,13 +100,18 @@ export function leadPage(input: { | ||
| 98 | 100 | ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })), |
| 99 | 101 | ...lead.replies.map((r) => ({ at: r.at, theirs: r })), |
| 100 | 102 | ...lead.calls.map((c) => ({ at: c.at, call: c })), |
| 103 | ...(lead.showing === null ? [] : [{ at: lead.showing.booked_at, showing: lead.showing }]), | |
| 101 | 104 | ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); |
| 102 | 105 | const thread = |
| 103 | 106 | history.length === 0 |
| 104 | 107 | ? "" |
| 105 | 108 | : `<section class="card"><h2>History</h2><ol class="thread">${history |
| 106 | .map(({ ours: m, theirs: r, call: c }) => | |
| 107 | c !== undefined | |
| 109 | .map(({ ours: m, theirs: r, call: c, showing: sh }) => | |
| 110 | sh !== undefined | |
| 111 | ? `<li data-from="showing"> | |
| 112 | <p class="meta">${escape(showingLine(sh, now))}</p> | |
| 113 | </li>` | |
| 114 | : c !== undefined | |
| 108 | 115 | ? `<li data-from="call"> |
| 109 | 116 | <p class="meta">${callLine(c.outcome)} · <time datetime="${escape(c.at)}">${escape(when(c.at))}</time></p> |
| 110 | 117 | ${c.note === "" ? "" : `<p class="body">${escape(c.note)}</p>`} |
| @@ -121,15 +128,22 @@ export function leadPage(input: { | ||
| 121 | 128 | ) |
| 122 | 129 | .join("")}</ol></section>`; |
| 123 | 130 | |
| 131 | const holding = lead.showing !== null && Date.parse(lead.showing.hold_until) > now; | |
| 132 | const waits = (m: Message): boolean => | |
| 133 | holding && (m.status === "scheduled" || m.status === "due") && m.due_at < lead.showing!.hold_until; | |
| 124 | 134 | const plan = |
| 125 | 135 | cadence.length === 0 |
| 126 | 136 | ? `<section class="card"><h2>Follow-up plan</h2><p class="muted">Day 1, 3, 7, 14 and 30 follow-ups are drafted the moment the first reply goes out.</p></section>` |
| 127 | : `<section class="card"><h2>Follow-up plan</h2><ol class="plan">${cadence | |
| 137 | : `<section class="card"><h2>Follow-up plan</h2>${ | |
| 138 | cadence.some(waits) | |
| 139 | ? `<p class="hint">Follow-ups due before the showing (${escape(showingWhen(lead.showing!.at, now))}) wait until the day after it, ${escape(day(lead.showing!.hold_until))}.</p>` | |
| 140 | : "" | |
| 141 | }<ol class="plan">${cadence | |
| 128 | 142 | .map( |
| 129 | 143 | (m) => `<li data-status="${m.status}"> |
| 130 | 144 | <span class="plan-day">Day ${m.day}</span> |
| 131 | 145 | <span class="plan-when">${escape(day(m.sent_at ?? m.due_at))}</span> |
| 132 | <span class="plan-status">${PLAN[m.status]}</span> | |
| 146 | <span class="plan-status">${waits(m) ? "Waits for the showing" : PLAN[m.status]}</span> | |
| 133 | 147 | ${m.status === "scheduled" ? `<details class="peek"><summary>Preview</summary>${words(m)}</details>` : ""} |
| 134 | 148 | </li>`, |
| 135 | 149 | ) |
| @@ -180,6 +194,26 @@ export function leadPage(input: { | ||
| 180 | 194 | </details>` |
| 181 | 195 | : ""; |
| 182 | 196 | |
| 197 | const min = new Date(now).toISOString().slice(0, 16); | |
| 198 | const max = new Date(now + MAX_AHEAD_DAYS * 86_400_000).toISOString().slice(0, 16); | |
| 199 | const showing = | |
| 200 | mayUpdate && !closed | |
| 201 | ? `<details class="card add record" id="book-showing"${lead.showing === null ? "" : " open"}> | |
| 202 | <summary>${lead.showing === null ? "Book a showing" : "Move the showing"}</summary> | |
| 203 | <form class="stack" method="post" action="${path}/showing"> | |
| 204 | <label>Date and time (UTC) <input class="input" type="datetime-local" name="at" required min="${min}" max="${max}"${lead.showing === null ? "" : ` value="${escape(lead.showing.at.slice(0, 16))}"`}></label> | |
| 205 | <label>Address (optional) <input class="input" name="address" maxlength="${MAX_ADDRESS}" autocomplete="off"${lead.showing === null ? "" : ` value="${escape(lead.showing.address)}"`}></label> | |
| 206 | <p class="hint">Follow-ups due before the showing wait until the day after it. Nothing is sent.</p> | |
| 207 | <button class="button">${lead.showing === null ? "Book the showing" : "Move the showing"}</button> | |
| 208 | </form>${ | |
| 209 | lead.showing === null | |
| 210 | ? "" | |
| 211 | : ` | |
| 212 | <form method="post" action="${path}/showing/cancel"><button class="button button-quiet">Cancel showing</button></form>` | |
| 213 | } | |
| 214 | </details>` | |
| 215 | : ""; | |
| 216 | ||
| 183 | 217 | const stop = |
| 184 | 218 | mayUpdate && lead.consent |
| 185 | 219 | ? `<section class="states"> |
| @@ -228,6 +262,7 @@ export function leadPage(input: { | ||
| 228 | 262 | </div> |
| 229 | 263 | ${thread} |
| 230 | 264 | ${call} |
| 265 | ${showing} | |
| 231 | 266 | ${record} |
| 232 | 267 | ${plan} |
| 233 | 268 | ${states} |
src/routes.ts +82 −2
| @@ -30,6 +30,8 @@ import { | ||
| 30 | 30 | nextLead, |
| 31 | 31 | setState, |
| 32 | 32 | logCall, |
| 33 | bookShowing, | |
| 34 | cancelShowing, | |
| 33 | 35 | logLeadReply, |
| 34 | 36 | tick, |
| 35 | 37 | type Failure, |
| @@ -53,6 +55,7 @@ import { | ||
| 53 | 55 | text, |
| 54 | 56 | } from "./http.ts"; |
| 55 | 57 | import { MAX_NOTE, OUTCOMES } from "./calls.ts"; |
| 58 | import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts"; | |
| 56 | 59 | import { MAX_INBOUND, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts"; |
| 57 | 60 | import { events } from "./live.ts"; |
| 58 | 61 | import { rpc } from "./mcp.ts"; |
| @@ -161,6 +164,18 @@ const CALL: Schema = { | ||
| 161 | 164 | }, |
| 162 | 165 | required: ["id", "lead_id", "outcome", "note", "at"], |
| 163 | 166 | }; |
| 167 | const SHOWING: Schema = { | |
| 168 | type: ["object", "null"], | |
| 169 | description: "The showing booked on this lead, or null.", | |
| 170 | properties: { | |
| 171 | lead_id: { type: "integer" }, | |
| 172 | at: STAMP, | |
| 173 | address: { type: "string", maxLength: MAX_ADDRESS }, | |
| 174 | hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." }, | |
| 175 | booked_at: STAMP, | |
| 176 | }, | |
| 177 | required: ["lead_id", "at", "address", "hold_until", "booked_at"], | |
| 178 | }; | |
| 164 | 179 | export const LEAD: Schema = { |
| 165 | 180 | type: "object", |
| 166 | 181 | properties: { |
| @@ -176,8 +191,9 @@ export const LEAD: Schema = { | ||
| 176 | 191 | description: "Phone calls you logged, oldest first.", |
| 177 | 192 | items: CALL, |
| 178 | 193 | }, |
| 194 | showing: SHOWING, | |
| 179 | 195 | }, |
| 180 | required: [...LEAD_REQUIRED, "messages", "replies", "calls"], | |
| 196 | required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing"], | |
| 181 | 197 | }; |
| 182 | 198 | export const APPROVED: Schema = { |
| 183 | 199 | type: "object", |
| @@ -207,8 +223,17 @@ export const DESK_LEAD: Schema = { | ||
| 207 | 223 | }, |
| 208 | 224 | }, |
| 209 | 225 | next_at: { type: ["string", "null"], format: "date-time" }, |
| 226 | showing: { | |
| 227 | type: ["object", "null"], | |
| 228 | description: "The showing booked on this lead, if one is.", | |
| 229 | properties: { | |
| 230 | at: STAMP, | |
| 231 | address: { type: "string", maxLength: MAX_ADDRESS }, | |
| 232 | hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." }, | |
| 233 | }, | |
| 234 | }, | |
| 210 | 235 | }, |
| 211 | required: [...LEAD_REQUIRED, "ready", "next_at"], | |
| 236 | required: [...LEAD_REQUIRED, "ready", "next_at", "showing"], | |
| 212 | 237 | }; |
| 213 | 238 | const SHOW: Schema = { |
| 214 | 239 | enum: [...VIEWS], |
| @@ -626,6 +651,61 @@ export const routes: readonly Route[] = [ | ||
| 626 | 651 | answer: LEAD, |
| 627 | 652 | }, |
| 628 | 653 | }, |
| 654 | { | |
| 655 | method: "POST", | |
| 656 | path: "/leads/:id/showing", | |
| 657 | handle: (c) => | |
| 658 | posted( | |
| 659 | c, | |
| 660 | (input) => | |
| 661 | bookShowing(c.db, c.who, { | |
| 662 | id: ID(c), | |
| 663 | when: input.at ?? input.when, | |
| 664 | address: input.address, | |
| 665 | }), | |
| 666 | () => ({ | |
| 667 | to: `/leads/${ID(c)}`, | |
| 668 | said: "Showing booked. Follow-ups due before it wait until the day after.", | |
| 669 | }), | |
| 670 | ), | |
| 671 | api: { | |
| 672 | summary: | |
| 673 | "Book a showing on an open lead, or move the one it has (one per lead). Follow-ups due before it wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time.", | |
| 674 | body: { | |
| 675 | type: "object", | |
| 676 | properties: { | |
| 677 | at: { | |
| 678 | type: "string", | |
| 679 | description: `A date and time in the future, at most ${MAX_AHEAD_DAYS} days ahead: ISO 8601, like 2026-11-07T10:00 (UTC) or 2026-11-07T10:00:00-08:00.`, | |
| 680 | }, | |
| 681 | address: { type: "string", maxLength: MAX_ADDRESS, description: "Optional, one line." }, | |
| 682 | }, | |
| 683 | required: ["at"], | |
| 684 | }, | |
| 685 | answer: LEAD, | |
| 686 | }, | |
| 687 | }, | |
| 688 | { | |
| 689 | method: "DELETE", | |
| 690 | path: "/leads/:id/showing", | |
| 691 | handle: (c) => answer(cancelShowing(c.db, c.who, { id: ID(c) })), | |
| 692 | api: { | |
| 693 | summary: | |
| 694 | "Cancel the lead's showing: follow-ups held for it return to their usual place, and any whose day has come are ready at once.", | |
| 695 | answer: LEAD, | |
| 696 | }, | |
| 697 | }, | |
| 698 | { | |
| 699 | // The page's form for the DELETE above: a form can only post. | |
| 700 | method: "POST", | |
| 701 | path: "/leads/:id/showing/cancel", | |
| 702 | handle: (c) => | |
| 703 | posted( | |
| 704 | c, | |
| 705 | () => cancelShowing(c.db, c.who, { id: ID(c) }), | |
| 706 | () => ({ to: `/leads/${ID(c)}`, said: "Showing cancelled." }), | |
| 707 | ), | |
| 708 | }, | |
| 629 | 709 | { |
| 630 | 710 | method: "POST", |
| 631 | 711 | path: "/leads/:id/state", |
src/sentences.ts +10
| @@ -40,6 +40,16 @@ export function deed( | ||
| 40 | 40 | done: `logged a call with ${lead}`, |
| 41 | 41 | tried: `log a call with ${lead}`, |
| 42 | 42 | }; |
| 43 | if (row.act === "showing") | |
| 44 | return { | |
| 45 | done: `booked a showing with ${lead}`, | |
| 46 | tried: `book a showing with ${lead}`, | |
| 47 | }; | |
| 48 | if (row.act === "showing_off") | |
| 49 | return { | |
| 50 | done: `cancelled the showing with ${lead}`, | |
| 51 | tried: `cancel the showing with ${lead}`, | |
| 52 | }; | |
| 43 | 53 | if (row.act === "reopened") |
| 44 | 54 | return { |
| 45 | 55 | done: `put ${lead} back in follow-ups`, |
src/server.test.ts +2
| @@ -289,6 +289,8 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 289 | 289 | "send_reply", |
| 290 | 290 | "log_lead_reply", |
| 291 | 291 | "log_call", |
| 292 | "book_showing", | |
| 293 | "cancel_showing", | |
| 292 | 294 | "mark_lead", |
| 293 | 295 | "opt_out_texts", |
| 294 | 296 | "get_profile", |
src/showings.test.ts added +345
| @@ -0,0 +1,345 @@ | ||
| 1 | /** | |
| 2 | * A showing booked on a lead: validated at the boundary, follow-ups due | |
| 3 | * before it held until the day after and released on cancel, the history | |
| 4 | * and the desk badge escaped; 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 | bookShowing, | |
| 13 | cancelShowing, | |
| 14 | getLead, | |
| 15 | listLeads, | |
| 16 | sendReply, | |
| 17 | setState, | |
| 18 | turn, | |
| 19 | } from "./actions.ts"; | |
| 20 | import { openDb } from "./db.ts"; | |
| 21 | import { serve } from "./server.ts"; | |
| 22 | import { showingLine, timeOf } from "./showings.ts"; | |
| 23 | import { plain, terminal } from "./terminal.ts"; | |
| 24 | import { sign } from "./who.ts"; | |
| 25 | import type { Who } from "./who.ts"; | |
| 26 | ||
| 27 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 28 | const anon: Who = { role: "anon" }; | |
| 29 | const T0 = new Date("2026-03-01T10:00:00Z"); | |
| 30 | const DAY = 86_400_000; | |
| 31 | const at = (days: number) => new Date(T0.getTime() + days * DAY); | |
| 32 | ||
| 33 | const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-showing-"))); | |
| 34 | const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => { | |
| 35 | if (!r.ok) throw new Error(r.message); | |
| 36 | return r.value as T; | |
| 37 | }; | |
| 38 | /** A lead answered at T0, so its day 1, 3, 7, 14 and 30 follow-ups are scheduled. */ | |
| 39 | const answered = (db: ReturnType<typeof fresh>) => { | |
| 40 | const id = value( | |
| 41 | addLead( | |
| 42 | db, | |
| 43 | alice, | |
| 44 | { | |
| 45 | name: "Dana Reyes", | |
| 46 | email: "[email protected]", | |
| 47 | phone: "", | |
| 48 | source: "zillow", | |
| 49 | message: "Can I see 12 Oak Street?", | |
| 50 | consent: false, | |
| 51 | }, | |
| 52 | T0, | |
| 53 | ), | |
| 54 | ).id; | |
| 55 | value(sendReply(db, alice, { id }, T0)); | |
| 56 | return id; | |
| 57 | }; | |
| 58 | const refused = (r: { ok: boolean; error?: string }) => (r.ok ? "ok" : r.error); | |
| 59 | const statuses = (db: ReturnType<typeof fresh>, id: number) => | |
| 60 | Object.fromEntries( | |
| 61 | value(getLead(db, alice, { id })) | |
| 62 | .messages.filter((m) => m.day > 0) | |
| 63 | .map((m) => [m.day, m.status]), | |
| 64 | ); | |
| 65 | ||
| 66 | test("a time must be a real date, in the future, within 90 days", () => { | |
| 67 | const now = T0.getTime(); | |
| 68 | expect(timeOf("2026-03-07T10:00", now)).toEqual({ at: "2026-03-07T10:00:00.000Z" }); | |
| 69 | expect(timeOf("2026-03-07T10:00:00-08:00", now)).toEqual({ at: "2026-03-07T18:00:00.000Z" }); | |
| 70 | for (const bad of ["", "Saturday", "2026-02-30T10:00", "2026-03-07", "2026-13-01T10:00", 5, null, undefined]) | |
| 71 | expect("error" in timeOf(bad, now)).toBe(true); | |
| 72 | expect("error" in timeOf("2026-03-01T09:00", now)).toBe(true); // past | |
| 73 | expect("error" in timeOf("2026-03-01T10:00", now)).toBe(true); // now is not ahead | |
| 74 | expect("error" in timeOf("2026-05-30T10:00", now)).toBe(false); // 90 days less a bit | |
| 75 | expect("error" in timeOf("2026-06-01T10:00", now)).toBe(true); // beyond 90 days | |
| 76 | }); | |
| 77 | ||
| 78 | test("the history line reads 'Showing booked · Sat 10:00 · address'", () => { | |
| 79 | const sat = new Date("2026-03-07T10:00:00Z"); | |
| 80 | expect(showingLine({ at: sat.toISOString(), address: "12 Example St" }, sat.getTime() - DAY)).toBe( | |
| 81 | "Showing booked · Sat 10:00 · 12 Example St", | |
| 82 | ); | |
| 83 | expect(showingLine({ at: sat.toISOString(), address: "" }, sat.getTime() - DAY)).toBe( | |
| 84 | "Showing booked · Sat 10:00", | |
| 85 | ); | |
| 86 | }); | |
| 87 | ||
| 88 | test("booking validates its inputs and asks permit", () => { | |
| 89 | const db = fresh(); | |
| 90 | const id = answered(db); | |
| 91 | const book = (input: { when?: unknown; address?: unknown }, who = alice) => | |
| 92 | bookShowing(db, who, { id, ...input }, at(1)); | |
| 93 | expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("ok"); | |
| 94 | expect(refused(book({ when: "2026-02-28T10:00" }))).toBe("invalid"); | |
| 95 | expect(refused(book({ when: "soon" }))).toBe("invalid"); | |
| 96 | expect(refused(book({}))).toBe("invalid"); | |
| 97 | expect(refused(book({ when: "2026-06-01T10:00" }))).toBe("invalid"); | |
| 98 | expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(201) }))).toBe("invalid"); | |
| 99 | expect(refused(book({ when: "2026-03-07T10:00", address: "a\nb" }))).toBe("invalid"); | |
| 100 | expect(refused(book({ when: "2026-03-07T10:00", address: 4 }))).toBe("invalid"); | |
| 101 | expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(200) }))).toBe("ok"); | |
| 102 | expect(refused(book({ when: "2026-03-07T10:00" }, anon))).toBe("signin_required"); | |
| 103 | expect(refused(bookShowing(db, alice, { id: 999, when: "2026-03-07T10:00" }, at(1)))).toBe("not_found"); | |
| 104 | ||
| 105 | value(setState(db, alice, { id, state: "lost" }, at(1))); | |
| 106 | expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("invalid"); | |
| 107 | }); | |
| 108 | ||
| 109 | test("one showing per lead: booking again moves it; cancelling removes it", () => { | |
| 110 | const db = fresh(); | |
| 111 | const id = answered(db); | |
| 112 | value(bookShowing(db, alice, { id, when: "2026-03-07T10:00", address: "12 Example St" }, at(1))); | |
| 113 | const moved = value(bookShowing(db, alice, { id, when: "2026-03-09T15:30" }, at(1))); | |
| 114 | expect(moved.showing?.at).toBe("2026-03-09T15:30:00.000Z"); | |
| 115 | expect(moved.showing?.address).toBe(""); | |
| 116 | expect(db.query("SELECT count(*) AS n FROM showing").get()).toEqual({ n: 1 }); | |
| 117 | expect(refused(cancelShowing(db, anon, { id }))).toBe("signin_required"); | |
| 118 | expect(value(cancelShowing(db, alice, { id }, at(1))).showing).toBeNull(); | |
| 119 | expect(refused(cancelShowing(db, alice, { id }, at(1)))).toBe("not_found"); | |
| 120 | }); | |
| 121 | ||
| 122 | test("follow-ups due before the showing wait until the day after; cancelling releases them", () => { | |
| 123 | const db = fresh(); | |
| 124 | const id = answered(db); | |
| 125 | // Showing on day 5: the day 1 and 3 follow-ups are held, day 7 is not. | |
| 126 | value(bookShowing(db, alice, { id, when: "2026-03-06T10:00" }, at(0.5))); | |
| 127 | turn(db, at(4)); | |
| 128 | expect(statuses(db, id)).toMatchObject({ 1: "scheduled", 3: "scheduled" }); | |
| 129 | expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(0); | |
| 130 | turn(db, at(5.2)); // the showing's day: still held | |
| 131 | expect(statuses(db, id)[1]).toBe("scheduled"); | |
| 132 | turn(db, at(6.1)); // the day after the showing | |
| 133 | expect(statuses(db, id)).toMatchObject({ 1: "due", 3: "due", 7: "scheduled" }); | |
| 134 | expect(value(listLeads(db, alice, { show: "needs" })).leads.map((l) => l.id)).toEqual([id]); | |
| 135 | ||
| 136 | // A follow-up already due goes back to waiting when a showing is booked. | |
| 137 | value(bookShowing(db, alice, { id, when: "2026-03-12T10:00" }, at(6.2))); | |
| 138 | expect(statuses(db, id)).toMatchObject({ 1: "scheduled", 3: "scheduled" }); | |
| 139 | expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(0); | |
| 140 | ||
| 141 | // Cancelling puts them back where they were: due at once. | |
| 142 | value(cancelShowing(db, alice, { id }, at(6.3))); | |
| 143 | expect(statuses(db, id)).toMatchObject({ 1: "due", 3: "due" }); | |
| 144 | expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(1); | |
| 145 | }); | |
| 146 | ||
| 147 | test("the audit trail names a booking and a cancellation", () => { | |
| 148 | const db = fresh(); | |
| 149 | const id = answered(db); | |
| 150 | value(bookShowing(db, alice, { id, when: "2026-03-07T10:00" }, at(1))); | |
| 151 | value(cancelShowing(db, alice, { id }, at(1))); | |
| 152 | expect(db.query("SELECT act FROM audit WHERE act LIKE 'showing%' ORDER BY id").all()).toEqual([ | |
| 153 | { act: "showing" }, | |
| 154 | { act: "showing_off" }, | |
| 155 | ]); | |
| 156 | }); | |
| 157 | ||
| 158 | test("the terminal books, shows and cancels a showing, and a refused time is typed again", () => { | |
| 159 | const db = fresh(); | |
| 160 | const id = answered(db); | |
| 161 | const t = terminal(db, alice); | |
| 162 | const read = () => t.screen(100).map(plain).join("\n"); | |
| 163 | const type = (text: string) => { | |
| 164 | for (const ch of text) t.key(ch); | |
| 165 | }; | |
| 166 | t.key("\r"); | |
| 167 | expect(read()).toContain("b book a showing"); | |
| 168 | t.key("b"); | |
| 169 | type("2020-01-01T10:00"); // the past | |
| 170 | t.key("\r"); | |
| 171 | type("12 <b>Example</b> St"); | |
| 172 | t.key("\r"); | |
| 173 | expect(read()).toContain("A showing is booked in the future"); | |
| 174 | expect(value(getLead(db, alice, { id })).showing).toBeNull(); | |
| 175 | ||
| 176 | const when = new Date(Date.now() + 3 * DAY).toISOString().slice(0, 16); | |
| 177 | // Back on the time step with the refused text still typed: clear it. | |
| 178 | for (let i = 0; i < "2020-01-01T10:00".length; i++) t.key("\x7f"); | |
| 179 | type(when); | |
| 180 | t.key("\r"); | |
| 181 | type("12 Example St"); | |
| 182 | t.key("\r"); | |
| 183 | const booked = value(getLead(db, alice, { id })); | |
| 184 | expect(booked.showing).toMatchObject({ at: `${when}:00.000Z`, address: "12 Example St" }); | |
| 185 | const screen = read(); | |
| 186 | expect(screen).toContain("Showing booked ·"); | |
| 187 | expect(screen).toContain("12 Example St"); | |
| 188 | expect(screen).toContain("u cancel the showing"); | |
| 189 | ||
| 190 | t.key("\x1b"); | |
| 191 | expect(read()).toContain("showing"); | |
| 192 | t.key("\r"); | |
| 193 | t.key("u"); | |
| 194 | expect(value(getLead(db, alice, { id })).showing).toBeNull(); | |
| 195 | ||
| 196 | // permit gates the keys like the page: a signed-out caller cannot book. | |
| 197 | const guest = terminal(db, anon); | |
| 198 | guest.key("\r"); | |
| 199 | expect(guest.screen(100).map(plain).join("\n")).not.toContain("book a showing"); | |
| 200 | }); | |
| 201 | ||
| 202 | // The doors. | |
| 203 | const KEY = "a-key-only-the-forge-holds"; | |
| 204 | const server = serve({ | |
| 205 | port: 0, | |
| 206 | dataDir: mkdtempSync(join(tmpdir(), "app-showing-srv-")), | |
| 207 | identityKey: KEY, | |
| 208 | sample: false, | |
| 209 | }); | |
| 210 | const base = `http://${server.hostname}:${server.port}`; | |
| 211 | afterAll(() => server.stop(true)); | |
| 212 | let grants = 0; | |
| 213 | const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => { | |
| 214 | const identity = `showing-${++grants}|alice|user|${Date.now() + 60_000}`; | |
| 215 | return fetch(base + path, { | |
| 216 | redirect: "manual", | |
| 217 | ...init, | |
| 218 | headers: { | |
| 219 | ...(init.headers as Record<string, string>), | |
| 220 | ...headers, | |
| 221 | "x-forge-identity": identity, | |
| 222 | "x-forge-signature": sign(identity, KEY), | |
| 223 | }, | |
| 224 | }); | |
| 225 | }; | |
| 226 | const send = (method: string, path: string, body?: unknown) => | |
| 227 | api(path, { | |
| 228 | method, | |
| 229 | headers: { "content-type": "application/json" }, | |
| 230 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 231 | }); | |
| 232 | const served = async (): Promise<number> => { | |
| 233 | const made = await send("POST", "/leads", { | |
| 234 | name: "Pat <i>Lee</i>", | |
| 235 | email: "[email protected]", | |
| 236 | phone: "", | |
| 237 | source: "website", | |
| 238 | message: "Can we see it this week?", | |
| 239 | consent: false, | |
| 240 | }); | |
| 241 | if (made.status !== 201) throw new Error(`${made.status} ${await made.text()}`); | |
| 242 | return ((await made.json()) as { id: number }).id; | |
| 243 | }; | |
| 244 | const ahead = (days: number) => new Date(Date.now() + days * DAY).toISOString().slice(0, 16); | |
| 245 | ||
| 246 | test("the API books, moves and cancels; a bad time is 422; the page and desk show it escaped", async () => { | |
| 247 | const id = await served(); | |
| 248 | const page0 = await (await api(`/leads/${id}`)).text(); | |
| 249 | expect(page0).toContain("Book a showing"); | |
| 250 | expect(page0).toContain(`action="/leads/${id}/showing"`); | |
| 251 | ||
| 252 | const booked = await send("POST", `/leads/${id}/showing`, { | |
| 253 | at: ahead(2), | |
| 254 | address: "<script>alert(1)</script> 12 Example St", | |
| 255 | }); | |
| 256 | expect(booked.status).toBe(200); | |
| 257 | expect(((await booked.json()) as { showing: { address: string } }).showing.address).toContain("12 Example St"); | |
| 258 | ||
| 259 | const page = await (await api(`/leads/${id}`)).text(); | |
| 260 | expect(page).toContain("Showing booked ·"); | |
| 261 | expect(page).toContain("<script>alert(1)</script> 12 Example St"); | |
| 262 | expect(page).not.toContain("<script>alert(1)"); | |
| 263 | expect(page).toContain("Cancel showing"); | |
| 264 | ||
| 265 | const desk = await (await api("/", { headers: { accept: "text/html" } })).text(); | |
| 266 | expect(desk).toContain('data-showing'); | |
| 267 | expect(desk).toContain("<script>alert(1)</script> 12 Example St"); | |
| 268 | expect(desk).not.toContain("<script>alert(1)"); | |
| 269 | ||
| 270 | for (const bad of [ | |
| 271 | { at: ahead(-1) }, | |
| 272 | { at: "tomorrow" }, | |
| 273 | { at: ahead(91) }, | |
| 274 | {}, | |
| 275 | { at: ahead(2), address: "x".repeat(201) }, | |
| 276 | ]) | |
| 277 | expect((await send("POST", `/leads/${id}/showing`, bad)).status).toBe(422); | |
| 278 | ||
| 279 | const gone = await send("DELETE", `/leads/${id}/showing`); | |
| 280 | expect(gone.status).toBe(200); | |
| 281 | expect(((await gone.json()) as { showing: unknown }).showing).toBeNull(); | |
| 282 | expect((await send("DELETE", `/leads/${id}/showing`)).status).toBe(404); | |
| 283 | expect(await (await api("/", { headers: { accept: "text/html" } })).text()).not.toContain("data-showing"); | |
| 284 | }); | |
| 285 | ||
| 286 | test("a form books and cancels, and a cross-origin post is refused", async () => { | |
| 287 | const id = await served(); | |
| 288 | const form = (path: string, fields: Record<string, string>, headers: Record<string, string> = {}) => | |
| 289 | api( | |
| 290 | path, | |
| 291 | { | |
| 292 | method: "POST", | |
| 293 | headers: { "content-type": "application/x-www-form-urlencoded" }, | |
| 294 | body: new URLSearchParams(fields).toString(), | |
| 295 | }, | |
| 296 | headers, | |
| 297 | ); | |
| 298 | expect((await form(`/leads/${id}/showing`, { at: ahead(3), address: "9 Elm" })).status).toBe(303); | |
| 299 | expect(await (await api(`/leads/${id}`)).text()).toContain("Showing booked · "); | |
| 300 | ||
| 301 | const evil = { origin: "https://evil.example", "sec-fetch-site": "cross-site" }; | |
| 302 | expect((await form(`/leads/${id}/showing`, { at: ahead(4) }, evil)).status).toBe(403); | |
| 303 | expect((await form(`/leads/${id}/showing/cancel`, {}, evil)).status).toBe(403); | |
| 304 | const crossDelete = await api(`/leads/${id}/showing`, { method: "DELETE" }, evil); | |
| 305 | expect(crossDelete.status).toBe(403); | |
| 306 | expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { showing: unknown }).showing).not.toBeNull(); | |
| 307 | ||
| 308 | expect((await form(`/leads/${id}/showing/cancel`, {})).status).toBe(303); | |
| 309 | expect(await (await api(`/leads/${id}`)).text()).not.toContain("Cancel showing"); | |
| 310 | }); | |
| 311 | ||
| 312 | test("a signed-out caller is turned away", async () => { | |
| 313 | const id = await served(); | |
| 314 | const res = await fetch(`${base}/leads/${id}/showing`, { | |
| 315 | method: "POST", | |
| 316 | headers: { "content-type": "application/json" }, | |
| 317 | body: JSON.stringify({ at: ahead(2) }), | |
| 318 | }); | |
| 319 | expect([401, 403]).toContain(res.status); | |
| 320 | }); | |
| 321 | ||
| 322 | test("/openapi.json and MCP carry it", async () => { | |
| 323 | const spec = (await (await api("/openapi.json")).json()) as { | |
| 324 | paths: Record<string, Record<string, unknown>>; | |
| 325 | }; | |
| 326 | expect(spec.paths["/leads/{id}/showing"]!.post).toBeDefined(); | |
| 327 | expect(spec.paths["/leads/{id}/showing"]!.delete).toBeDefined(); | |
| 328 | ||
| 329 | const id = await served(); | |
| 330 | const call = async (name: string, args: unknown) => | |
| 331 | (await ( | |
| 332 | await send("POST", "/mcp", { | |
| 333 | jsonrpc: "2.0", | |
| 334 | id: 1, | |
| 335 | method: "tools/call", | |
| 336 | params: { name, arguments: args }, | |
| 337 | }) | |
| 338 | ).json()) as { result: { isError?: boolean; content: { text: string }[] } }; | |
| 339 | const booked = await call("book_showing", { id, at: ahead(2), address: "1 Main" }); | |
| 340 | expect(booked.result.isError).toBeUndefined(); | |
| 341 | expect(JSON.parse(booked.result.content[0]!.text).showing.address).toBe("1 Main"); | |
| 342 | expect((await call("book_showing", { id, at: "never" })).result.isError).toBe(true); | |
| 343 | const off = await call("cancel_showing", { id }); | |
| 344 | expect(JSON.parse(off.result.content[0]!.text).showing).toBeNull(); | |
| 345 | }); |
src/showings.ts added +83
| @@ -0,0 +1,83 @@ | ||
| 1 | /** | |
| 2 | * A showing booked on a lead: when, and where. While one is ahead, the | |
| 3 | * lead's follow-ups wait until the day after it (`holdUntil`); cancelling | |
| 4 | * puts them back. Nothing here is sent anywhere. | |
| 5 | */ | |
| 6 | ||
| 7 | /** The most an address may hold. */ | |
| 8 | export const MAX_ADDRESS = 200; | |
| 9 | /** How far ahead a showing may be booked. */ | |
| 10 | export const MAX_AHEAD_DAYS = 90; | |
| 11 | ||
| 12 | const DAY_MS = 86_400_000; | |
| 13 | ||
| 14 | /** A showing as stored: one per lead. */ | |
| 15 | export interface Showing { | |
| 16 | readonly lead_id: number; | |
| 17 | /** When it happens, an ISO instant. */ | |
| 18 | readonly at: string; | |
| 19 | /** Where; empty when none was given. */ | |
| 20 | readonly address: string; | |
| 21 | /** The day after it: follow-ups due before then wait. */ | |
| 22 | readonly hold_until: string; | |
| 23 | readonly booked_at: string; | |
| 24 | } | |
| 25 | ||
| 26 | /** | |
| 27 | * A showing time from user text: an ISO instant, or `YYYY-MM-DDTHH:MM` as a | |
| 28 | * date-and-time field sends it (read as UTC). Returns the instant as ISO, | |
| 29 | * or the reason it is refused: malformed, in the past, or beyond 90 days. | |
| 30 | */ | |
| 31 | export function timeOf( | |
| 32 | text: unknown, | |
| 33 | now: number, | |
| 34 | ): { at: string } | { error: string } { | |
| 35 | const bad = { error: "A showing time is a date and time, like 2026-11-07T10:00." }; | |
| 36 | if (typeof text !== "string") return bad; | |
| 37 | const m = | |
| 38 | /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/.exec( | |
| 39 | text.trim(), | |
| 40 | ); | |
| 41 | if (m === null) return bad; | |
| 42 | const ms = Date.parse( | |
| 43 | `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6] ?? "00"}${m[7] ?? "Z"}`, | |
| 44 | ); | |
| 45 | if (Number.isNaN(ms)) return bad; | |
| 46 | // Date.parse rolls 02-30 over to March; a real date reads back as itself. | |
| 47 | if (new Date(Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!)).getUTCDate() !== +m[3]!) | |
| 48 | return bad; | |
| 49 | if (ms <= now) return { error: "A showing is booked in the future." }; | |
| 50 | if (ms > now + MAX_AHEAD_DAYS * DAY_MS) | |
| 51 | return { error: `A showing is at most ${MAX_AHEAD_DAYS} days ahead.` }; | |
| 52 | return { at: new Date(ms).toISOString() }; | |
| 53 | } | |
| 54 | ||
| 55 | /** When the follow-ups wait until: a day after the showing. */ | |
| 56 | export const holdUntil = (at: string): string => | |
| 57 | new Date(Date.parse(at) + DAY_MS).toISOString(); | |
| 58 | ||
| 59 | /** In UTC, as the form takes it: "Sat 10:00", or "Sat Dec 12 10:00" beyond the coming week. */ | |
| 60 | export function showingWhen(at: string, now = Date.now()): string { | |
| 61 | const d = new Date(at); | |
| 62 | const wd = d.toLocaleDateString("en-US", { weekday: "short", timeZone: "UTC" }); | |
| 63 | const time = d.toLocaleTimeString("en-US", { | |
| 64 | hour: "2-digit", | |
| 65 | minute: "2-digit", | |
| 66 | hourCycle: "h23", | |
| 67 | timeZone: "UTC", | |
| 68 | }); | |
| 69 | if (Math.abs(d.getTime() - now) < 6 * DAY_MS) return `${wd} ${time}`; | |
| 70 | const date = d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }); | |
| 71 | return `${wd} ${date} ${time}`; | |
| 72 | } | |
| 73 | ||
| 74 | /** "Showing booked · Sat 10:00 · 12 Example St". */ | |
| 75 | export const showingLine = ( | |
| 76 | s: Pick<Showing, "at" | "address">, | |
| 77 | now = Date.now(), | |
| 78 | ): string => | |
| 79 | [ | |
| 80 | "Showing booked", | |
| 81 | showingWhen(s.at, now), | |
| 82 | ...(s.address === "" ? [] : [s.address]), | |
| 83 | ].join(" · "); |
src/terminal.ts +55 −2
| @@ -35,10 +35,13 @@ import { | ||
| 35 | 35 | saveProfile, |
| 36 | 36 | approveReply, |
| 37 | 37 | logCall, |
| 38 | bookShowing, | |
| 39 | cancelShowing, | |
| 38 | 40 | logLeadReply, |
| 39 | 41 | nextLead, |
| 40 | 42 | setState, |
| 41 | 43 | } from "./actions.ts"; |
| 44 | import { showingLine, showingWhen } from "./showings.ts"; | |
| 42 | 45 | import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts"; |
| 43 | 46 | import { between, elapsed, recordLine, tone } from "./clock.ts"; |
| 44 | 47 | import { permit } from "./contract.ts"; |
| @@ -117,6 +120,7 @@ type View = | ||
| 117 | 120 | | { name: "lead"; id: number } |
| 118 | 121 | | { name: "edit"; id: number; text: string } |
| 119 | 122 | | { name: "call"; id: number; outcome: Outcome; text: string } |
| 123 | | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string } | |
| 120 | 124 | | { name: "wrote"; id: number; text: string; channel: Channel } |
| 121 | 125 | | { name: "add"; step: number; typed: string; fields: Record<string, string> } |
| 122 | 126 | | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View }; |
| @@ -228,8 +232,12 @@ export function terminal( | ||
| 228 | 232 | ? "wrote back · answer drafted" |
| 229 | 233 | : `day ${l.ready.day} follow-up ready`; |
| 230 | 234 | const name = clean(l.name).padEnd(18).slice(0, 18); |
| 235 | const showing = | |
| 236 | l.showing === null | |
| 237 | ? "" | |
| 238 | : dim(` · showing ${showingWhen(l.showing.at, now())}${l.showing.address === "" ? "" : ` ${clean(l.showing.address)}`}`); | |
| 231 | 239 | lines.push( |
| 232 | `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}`, | |
| 240 | `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}${showing}`, | |
| 233 | 241 | ); |
| 234 | 242 | }); |
| 235 | 243 | lines.push( |
| @@ -295,6 +303,13 @@ export function terminal( | ||
| 295 | 303 | ...wrap(r.signature, width).map((s) => dim(` ${s}`)), |
| 296 | 304 | ); |
| 297 | 305 | } |
| 306 | if (l.showing !== null) | |
| 307 | lines.push( | |
| 308 | dim(clean(showingLine(l.showing, now()))), | |
| 309 | ...(Date.parse(l.showing.hold_until) > now() | |
| 310 | ? [dim(` Follow-ups due before it wait until ${l.showing.hold_until.slice(0, 16).replace("T", " ")} UTC.`)] | |
| 311 | : []), | |
| 312 | ); | |
| 298 | 313 | const sent = l.messages.filter((m) => m.status === "sent").length; |
| 299 | 314 | for (const c of l.calls) |
| 300 | 315 | lines.push(dim(`${callLine(c.outcome)} — ${c.at.slice(0, 16).replace("T", " ")}${c.note === "" ? "" : `: ${clean(c.note)}`}`)); |
| @@ -314,6 +329,8 @@ export function terminal( | ||
| 314 | 329 | ...(r === undefined ? [] : ["s approve and send", "e edit"]), |
| 315 | 330 | ...(l.phone === "" ? [] : ["c log a call"]), |
| 316 | 331 | ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []), |
| 332 | ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]), | |
| 333 | ...(l.showing === null || CLOSED.includes(l.state) ? [] : ["u cancel the showing"]), | |
| 317 | 334 | ...(l.state === "qualified" || l.state === "lost" |
| 318 | 335 | ? ["o put back in follow-ups"] |
| 319 | 336 | : ["q qualified", "x lost"]), |
| @@ -457,6 +474,17 @@ export function terminal( | ||
| 457 | 474 | "", |
| 458 | 475 | dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"), |
| 459 | 476 | ] |
| 477 | : view.name === "showing" | |
| 478 | ? [ | |
| 479 | bold(`A showing with ${clean(lead(view.id)?.name ?? "the lead")}`), | |
| 480 | "", | |
| 481 | view.step === 0 | |
| 482 | ? `When (UTC, like 2026-11-07T10:00, at most 90 days ahead): ${clean(view.typed)}█` | |
| 483 | : `When: ${clean(view.when)}`, | |
| 484 | ...(view.step === 1 ? [`Address (optional): ${clean(view.typed)}█`] : []), | |
| 485 | "", | |
| 486 | dim("enter next · esc cancel"), | |
| 487 | ] | |
| 460 | 488 | : view.name === "call" |
| 461 | 489 | ? [ |
| 462 | 490 | bold(`Your call with ${clean(lead(view.id)?.name ?? "the lead")} — ${OUTCOME_LABEL[view.outcome]}`), |
| @@ -597,7 +625,12 @@ export function terminal( | ||
| 597 | 625 | said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message; |
| 598 | 626 | } else if (input === "c" && l.phone !== "") |
| 599 | 627 | view = { name: "call", id, outcome: "talked", text: "" }; |
| 600 | else if (input === "w") | |
| 628 | else if (input === "b" && !CLOSED.includes(l.state)) | |
| 629 | view = { name: "showing", id, step: 0, typed: "", when: "" }; | |
| 630 | else if (input === "u" && l.showing !== null) { | |
| 631 | const off = cancelShowing(db, me, { id }); | |
| 632 | said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message; | |
| 633 | } else if (input === "w") | |
| 601 | 634 | view = { name: "wrote", id, text: "", channel: "email" }; |
| 602 | 635 | else if (input === "o" && CLOSED.includes(l.state)) { |
| 603 | 636 | const back = setState(db, me, { id, state: "open" }); |
| @@ -620,6 +653,26 @@ export function terminal( | ||
| 620 | 653 | } |
| 621 | 654 | return; |
| 622 | 655 | } |
| 656 | case "showing": { | |
| 657 | if (input === "\x1b") { | |
| 658 | said = "No showing booked."; | |
| 659 | view = { name: "lead", id: view.id }; | |
| 660 | } else if (input === "\r") { | |
| 661 | if (view.step === 0) view = { ...view, step: 1, when: view.typed.trim(), typed: "" }; | |
| 662 | else { | |
| 663 | const booked = bookShowing(db, me, { id: view.id, when: view.when, address: view.typed }); | |
| 664 | said = booked.ok | |
| 665 | ? `Showing booked. Follow-ups due before it wait until the day after.` | |
| 666 | : booked.message; | |
| 667 | // A refused time is typed again; anything else goes back to the lead. | |
| 668 | view = booked.ok || booked.error !== "invalid" ? { name: "lead", id: view.id } : { ...view, step: 0, typed: view.when }; | |
| 669 | } | |
| 670 | } else { | |
| 671 | const next = typing(view.typed, input); | |
| 672 | if (next !== undefined) view = { ...view, typed: next }; | |
| 673 | } | |
| 674 | return; | |
| 675 | } | |
| 623 | 676 | case "call": { |
| 624 | 677 | if (input === "\x1b") { |
| 625 | 678 | said = "No call logged."; |
static/app.css +5
| @@ -249,6 +249,11 @@ footer { | ||
| 249 | 249 | color: var(); |
| 250 | 250 | white-space: nowrap; |
| 251 | 251 | } |
| 252 | .badge[data-showing] { | |
| 253 | white-space: normal; | |
| 254 | overflow-wrap: anywhere; | |
| 255 | color: var(); | |
| 256 | } | |
| 252 | 257 | .badge[data-consent="text"] { |
| 253 | 258 | color: var(); |
| 254 | 259 | background: var(); |
new above
offline