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

Merged opened this

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

Merged

mason/speed-to-lead:mason/33-book-a-showing-on-a-lead-it-shows-on-the → main 2 commits fork

  • Merged. mason/33-book-a-showing-on-a-lead-it-shows-on-the was merged into main as a59448b.

Review

Sign in to review this change.
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:
118118 is its first answer (`recordCall` stops the clock through the same
119119 `startCadence` a sent first reply uses, and sets the draft aside as
120120 `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.
121127 - `src/drafts.ts` — the words: templates filled from the inquiry and the
122128 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
123129 defaults of `agent` in `src/env.ts`), the signature every message
README.md +30 −5
@@ -15,9 +15,9 @@ goes.**
1515 For the sales meeting. The names below are the sample leads on the desk.
1616
1717 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.
2121
2222 The clocks keep running while the app sits idle, so the colours below are only
2323 what you see right after a restart. Do step 1 first.
@@ -51,11 +51,16 @@ what you see right after a restart. Do step 1 first.
5151 Back on **Marcus Lee**, open "They wrote back", paste "Yes, Saturday
5252 works" and record it: he is in "Needs you" with a fresh green clock and an
5353 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
5560 in your name, brokerage, license number, phone and email, and save. Every
5661 draft not yet sent takes it at once.
5762
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
5964 lead by hand". A new person is at the top of the desk with a green clock
6065 at 0:00 and a reply already drafted. Open the lead, press "Approve and
6166 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
170175 lead's terminal screen (ctrl-o changes the outcome, ctrl-d logs it). It needs
171176 the same permission as any change to a lead, and shows on the Activity page.
172177
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
173194 **Sample leads.** The app starts with twelve sample leads so you can see it
174195 work: two just in, two waiting a while, three gone red, and five already
175196 answered and partway through their follow-ups. An admin can restart them
@@ -269,6 +290,10 @@ until you press a key on this screen:
269290 - `e` lets you edit it first: type, enter for a new line, backspace to
270291 delete, then `ctrl-d` to approve and send — or `esc` to send nothing.
271292 - `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.
272297 - `D` removes the lead (admins only; asks first).
273298 - `esc` goes back to the desk.
274299
contract/openapi.json +197 −2
@@ -490,6 +490,42 @@
490490 ]
491491 }
492492 },
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 },
493529 "next": {
494530 "type": [
495531 "object",
@@ -526,6 +562,7 @@
526562 "messages",
527563 "replies",
528564 "calls",
565 "showing",
529566 "next"
530567 ]
531568 }
@@ -678,6 +715,104 @@
678715 }
679716 }
680717 },
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 },
681816 "/leads/{id}/state": {
682817 "post": {
683818 "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 @@
13641499 "at"
13651500 ]
13661501 }
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 ]
13671538 }
13681539 },
13691540 "required": [
@@ -1381,7 +1552,8 @@
13811552 "updated_at",
13821553 "messages",
13831554 "replies",
1384 "calls"
1555 "calls",
1556 "showing"
13851557 ]
13861558 },
13871559 "Desk": {
@@ -1569,6 +1741,28 @@
15691741 "null"
15701742 ],
15711743 "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 }
15721766 }
15731767 },
15741768 "required": [
@@ -1585,7 +1779,8 @@
15851779 "replied_at",
15861780 "updated_at",
15871781 "ready",
1588 "next_at"
1782 "next_at",
1783 "showing"
15891784 ]
15901785 },
15911786 "Message": {
src/actions.ts +72
@@ -31,6 +31,8 @@ import {
3131 nextNeeding,
3232 readyFor,
3333 recordCall,
34 bookShowing as bookShowingFor,
35 cancelShowing as cancelShowingFor,
3436 recordInbound,
3537 redraftUnsent,
3638 removeLead,
@@ -45,6 +47,7 @@ import {
4547 import { emit } from "./live.ts";
4648 import { currentAgent, storeAgent } from "./profile.ts";
4749 import { nextInquiry, seed } from "./sample.ts";
50 import { MAX_ADDRESS, timeOf } from "./showings.ts";
4851 import type { Who } from "./who.ts";
4952
5053 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
@@ -428,6 +431,75 @@ function phoned(
428431 return ok(detail(db, lead.id)!);
429432 }
430433
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
431503 /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */
432504 export const setState = (
433505 db: Database,
src/audit.ts +2 −2
@@ -32,8 +32,8 @@ export interface AuditRow {
3232 readonly act: string | null;
3333 }
3434
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `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;
3737 export type Act = (typeof ACTS)[number];
3838
3939 export interface Attempt {
src/contract.test.ts +9
@@ -18,6 +18,8 @@ import {
1818 listAudit,
1919 listLeads,
2020 logCall,
21 bookShowing,
22 cancelShowing,
2123 logLeadReply,
2224 saveProfile,
2325 setState,
@@ -113,7 +115,14 @@ const doors: Record<
113115 // So is logging a phone call (POST /leads/:id/call and the MCP tool log_call).
114116 db.query("UPDATE lead SET phone = '206 555 0100' WHERE id = ?1").run(replied);
115117 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;
116123 const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok;
124 expect(showing).toBe(changed);
125 expect(off).toBe(changed);
117126 expect(logged).toBe(changed);
118127 expect(called).toBe(changed);
119128 return changed;
src/db.ts +9
@@ -126,6 +126,15 @@ export const migrations: string[] = [
126126 at TEXT NOT NULL
127127 )`,
128128 `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 )`,
129138 ];
130139
131140 export function openDb(dir = dataDir): Database {
src/leads.ts +62 −3
@@ -26,6 +26,7 @@ import {
2626 import { answers, type Call, type Outcome } from "./calls.ts";
2727 import { GREEN_MS } from "./clock.ts";
2828 import type { Agent } from "./env.ts";
29 import { holdUntil, type Showing } from "./showings.ts";
2930
3031 export type State = "new" | "contacted" | "qualified" | "lost";
3132 export const CLOSED: readonly State[] = ["qualified", "lost"];
@@ -80,6 +81,8 @@ export interface LeadDetail extends Lead {
8081 readonly replies: readonly Inbound[];
8182 /** Calls the agent made, oldest first. */
8283 readonly calls: readonly Call[];
84 /** The showing booked on this lead; null when none. */
85 readonly showing: Showing | null;
8386 }
8487
8588 /** 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 {
9295 readonly ready: { readonly id: number; readonly day: number; readonly since: string } | null;
9396 /** When the next scheduled touch comes due, if one is. */
9497 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;
95100 }
96101
97102 /**
@@ -190,11 +195,22 @@ export const callsOf = (db: Database, id: number): Call[] =>
190195 >("SELECT * FROM phone_call WHERE lead_id = ?1 ORDER BY at, id")
191196 .all(id);
192197
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
193203 export function detail(db: Database, id: number): LeadDetail | null {
194204 const found = findLead(db, id);
195205 return found === null
196206 ? 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 };
198214 }
199215
200216 export const MAX_QUERY = 80;
@@ -237,6 +253,9 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
237253 ready_day: number | null;
238254 ready_since: string | null;
239255 next_at: string | null;
256 show_at: string | null;
257 show_address: string | null;
258 show_hold: string | null;
240259 },
241260 [number, string, string]
242261 >(
@@ -244,20 +263,27 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
244263 (SELECT id FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_id,
245264 (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day,
246265 (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
248270 FROM lead
249271 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
250272 OR (?3 <> '' AND ${DIGITS} LIKE ?3)
251273 ORDER BY created_at DESC, id DESC LIMIT ?1`,
252274 )
253275 .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 }) => ({
255277 ...lead(row),
256278 ready:
257279 ready_id === null || ready_day === null || ready_since === null
258280 ? null
259281 : { id: ready_id, day: ready_day, since: ready_since },
260282 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 },
261287 }));
262288 }
263289
@@ -651,6 +677,7 @@ export function advance(db: Database, at: string): number[] {
651677 `UPDATE message SET status = 'due'
652678 WHERE status = 'scheduled' AND due_at <= ?1
653679 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)
654681 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status = 'draft')
655682 RETURNING lead_id`,
656683 )
@@ -659,6 +686,38 @@ export function advance(db: Database, at: string): number[] {
659686 .filter((id, i, all) => all.indexOf(id) === i);
660687 }
661688
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
662721 export const removeLead = (db: Database, id: number): void => {
663722 db.query("DELETE FROM lead WHERE id = ?1").run(id);
664723 };
src/mcp.ts +30
@@ -18,10 +18,13 @@ import {
1818 approveReply,
1919 setState,
2020 logCall,
21 bookShowing,
22 cancelShowing,
2123 logLeadReply,
2224 type Result,
2325 } from "./actions.ts";
2426 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
27 import { MAX_ADDRESS } from "./showings.ts";
2528 import { SOURCES } from "./drafts.ts";
2629 import { title } from "./env.ts";
2730 import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
@@ -146,6 +149,33 @@ export const tools: readonly Tool[] = [
146149 run: (db, who, args) =>
147150 logCall(db, who, { id: Number(args.id), outcome: args.outcome, note: args.note }),
148151 },
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 },
149179 {
150180 name: "mark_lead",
151181 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";
88 import { escape } from "../http.ts";
99 import { recordLine } from "../clock.ts";
1010 import { isAnswer } from "../drafts.ts";
11 import { showingWhen } from "../showings.ts";
1112 import type { DeskLead, ResponseRecord, View } from "../leads.ts";
1213 import type { Agent } from "../env.ts";
1314 import type { Who } from "../who.ts";
@@ -135,6 +136,17 @@ const EMPTY: Record<View, string> = {
135136 all: "No leads yet. New inquiries appear here the moment they arrive.",
136137 };
137138
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
138150 function status(lead: DeskLead): string {
139151 if (lead.state === "qualified" || lead.state === "lost")
140152 return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`;
@@ -145,7 +157,7 @@ function status(lead: DeskLead): string {
145157 if (lead.ready !== null)
146158 return `<span class="status" data-ready>Day ${lead.ready.day} follow-up ready</span>`;
147159 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>`;
149161 return `<span class="status">Follow-ups done</span>`;
150162 }
151163
@@ -153,7 +165,7 @@ const row = (lead: DeskLead, now: number): string => `<li>
153165 <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}>
154166 <span class="lead-main">
155167 <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>
157169 <span class="ask">${escape(lead.message)}</span>
158170 ${status(lead)}
159171 </span>
src/pages/lead.ts +42 −7
@@ -7,6 +7,7 @@
77 import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts";
88 import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts";
99 import { escape } from "../http.ts";
10 import { MAX_ADDRESS, MAX_AHEAD_DAYS, showingLine, showingWhen } from "../showings.ts";
1011 import { elapsed, between } from "../clock.ts";
1112 import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts";
1213 import type { Agent } from "../env.ts";
@@ -16,9 +17,10 @@ import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts";
1617
1718 /** One line of the thread: something we sent, or something they wrote back. */
1819 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 };
2224
2325 const CHANNEL = { text: "text", email: "email" } as const;
2426
@@ -98,13 +100,18 @@ export function leadPage(input: {
98100 ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })),
99101 ...lead.replies.map((r) => ({ at: r.at, theirs: r })),
100102 ...lead.calls.map((c) => ({ at: c.at, call: c })),
103 ...(lead.showing === null ? [] : [{ at: lead.showing.booked_at, showing: lead.showing }]),
101104 ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
102105 const thread =
103106 history.length === 0
104107 ? ""
105108 : `<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
108115 ? `<li data-from="call">
109116 <p class="meta">${callLine(c.outcome)} · <time datetime="${escape(c.at)}">${escape(when(c.at))}</time></p>
110117 ${c.note === "" ? "" : `<p class="body">${escape(c.note)}</p>`}
@@ -121,15 +128,22 @@ export function leadPage(input: {
121128 )
122129 .join("")}</ol></section>`;
123130
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;
124134 const plan =
125135 cadence.length === 0
126136 ? `<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
128142 .map(
129143 (m) => `<li data-status="${m.status}">
130144 <span class="plan-day">Day ${m.day}</span>
131145 <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>
133147 ${m.status === "scheduled" ? `<details class="peek"><summary>Preview</summary>${words(m)}</details>` : ""}
134148 </li>`,
135149 )
@@ -180,6 +194,26 @@ export function leadPage(input: {
180194 </details>`
181195 : "";
182196
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
183217 const stop =
184218 mayUpdate && lead.consent
185219 ? `<section class="states">
@@ -228,6 +262,7 @@ export function leadPage(input: {
228262 </div>
229263 ${thread}
230264 ${call}
265 ${showing}
231266 ${record}
232267 ${plan}
233268 ${states}
src/routes.ts +82 −2
@@ -30,6 +30,8 @@ import {
3030 nextLead,
3131 setState,
3232 logCall,
33 bookShowing,
34 cancelShowing,
3335 logLeadReply,
3436 tick,
3537 type Failure,
@@ -53,6 +55,7 @@ import {
5355 text,
5456 } from "./http.ts";
5557 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
58 import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
5659 import { MAX_INBOUND, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
5760 import { events } from "./live.ts";
5861 import { rpc } from "./mcp.ts";
@@ -161,6 +164,18 @@ const CALL: Schema = {
161164 },
162165 required: ["id", "lead_id", "outcome", "note", "at"],
163166 };
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 };
164179 export const LEAD: Schema = {
165180 type: "object",
166181 properties: {
@@ -176,8 +191,9 @@ export const LEAD: Schema = {
176191 description: "Phone calls you logged, oldest first.",
177192 items: CALL,
178193 },
194 showing: SHOWING,
179195 },
180 required: [...LEAD_REQUIRED, "messages", "replies", "calls"],
196 required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing"],
181197 };
182198 export const APPROVED: Schema = {
183199 type: "object",
@@ -207,8 +223,17 @@ export const DESK_LEAD: Schema = {
207223 },
208224 },
209225 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 },
210235 },
211 required: [...LEAD_REQUIRED, "ready", "next_at"],
236 required: [...LEAD_REQUIRED, "ready", "next_at", "showing"],
212237 };
213238 const SHOW: Schema = {
214239 enum: [...VIEWS],
@@ -626,6 +651,61 @@ export const routes: readonly Route[] = [
626651 answer: LEAD,
627652 },
628653 },
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 },
629709 {
630710 method: "POST",
631711 path: "/leads/:id/state",
src/sentences.ts +10
@@ -40,6 +40,16 @@ export function deed(
4040 done: `logged a call with ${lead}`,
4141 tried: `log a call with ${lead}`,
4242 };
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 };
4353 if (row.act === "reopened")
4454 return {
4555 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 () =>
289289 "send_reply",
290290 "log_lead_reply",
291291 "log_call",
292 "book_showing",
293 "cancel_showing",
292294 "mark_lead",
293295 "opt_out_texts",
294296 "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("&lt;script&gt;alert(1)&lt;/script&gt; 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("&lt;script&gt;alert(1)&lt;/script&gt; 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 {
3535 saveProfile,
3636 approveReply,
3737 logCall,
38 bookShowing,
39 cancelShowing,
3840 logLeadReply,
3941 nextLead,
4042 setState,
4143 } from "./actions.ts";
44 import { showingLine, showingWhen } from "./showings.ts";
4245 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
4346 import { between, elapsed, recordLine, tone } from "./clock.ts";
4447 import { permit } from "./contract.ts";
@@ -117,6 +120,7 @@ type View =
117120 | { name: "lead"; id: number }
118121 | { name: "edit"; id: number; text: string }
119122 | { name: "call"; id: number; outcome: Outcome; text: string }
123 | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string }
120124 | { name: "wrote"; id: number; text: string; channel: Channel }
121125 | { name: "add"; step: number; typed: string; fields: Record<string, string> }
122126 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
@@ -228,8 +232,12 @@ export function terminal(
228232 ? "wrote back · answer drafted"
229233 : `day ${l.ready.day} follow-up ready`;
230234 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)}`}`);
231239 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}`,
233241 );
234242 });
235243 lines.push(
@@ -295,6 +303,13 @@ export function terminal(
295303 ...wrap(r.signature, width).map((s) => dim(` ${s}`)),
296304 );
297305 }
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 );
298313 const sent = l.messages.filter((m) => m.status === "sent").length;
299314 for (const c of l.calls)
300315 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(
314329 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
315330 ...(l.phone === "" ? [] : ["c log a call"]),
316331 ...(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"]),
317334 ...(l.state === "qualified" || l.state === "lost"
318335 ? ["o put back in follow-ups"]
319336 : ["q qualified", "x lost"]),
@@ -457,6 +474,17 @@ export function terminal(
457474 "",
458475 dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"),
459476 ]
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 ]
460488 : view.name === "call"
461489 ? [
462490 bold(`Your call with ${clean(lead(view.id)?.name ?? "the lead")} — ${OUTCOME_LABEL[view.outcome]}`),
@@ -597,7 +625,12 @@ export function terminal(
597625 said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message;
598626 } else if (input === "c" && l.phone !== "")
599627 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")
601634 view = { name: "wrote", id, text: "", channel: "email" };
602635 else if (input === "o" && CLOSED.includes(l.state)) {
603636 const back = setState(db, me, { id, state: "open" });
@@ -620,6 +653,26 @@ export function terminal(
620653 }
621654 return;
622655 }
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 }
623676 case "call": {
624677 if (input === "\x1b") {
625678 said = "No call logged.";
static/app.css +5
@@ -249,6 +249,11 @@ footer {
249249 color: var(--color-muted);
250250 white-space: nowrap;
251251 }
252 .badge[data-showing] {
253 white-space: normal;
254 overflow-wrap: anywhere;
255 color: var(--color-fg);
256 }
252257 .badge[data-consent="text"] {
253258 color: var(--color-ok);
254259 background: var(--color-ok-bg);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs