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

A buyer touring several homes can have more than one showing booked: each is listed on their page and the desk, and each gets its own day-before confirmation and morning-after follow-up #107

Merged opened this

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

Merged

mason/speed-to-lead:mason/106-a-buyer-touring-several-homes-can-have-m → main 1 commit fork

  • Merged. mason/106-a-buyer-touring-several-homes-can-have-m was merged into main as aba151a.

Review

Sign in to review this change.
18 files changed +595 −300
README.md +10 −7
@@ -64,7 +64,7 @@ what you see right after a restart. Do step 1 first.
6464 a day and time later this week (in your time zone from the profile), type an address and book it. The
6565 history says "Showing booked", his row on the desk carries a *Showing*
6666 badge, and his follow-up plan says which follow-ups wait until the day
67 after. Press "Cancel showing" and they return to their usual place. A
67 after. Press "Cancel showing" and (once it is the last) they return to their usual place. A
6868 booked showing also drafts a note for the morning after it, at 8:00 in
6969 your time zone: it asks how the home was, names the address, and offers
7070 another showing or talking numbers, by the lead's channel and signed with
@@ -364,16 +364,19 @@ the same permission as any change to a lead, and shows on the Activity page.
364364 press **Book a showing**, choose the date and time (in the future, at most 90
365365 days ahead, entered in your profile's time zone) and, if you like, the address (up to 200
366366 characters). The history says it ("Showing booked · Sat 10:00 · 12 Example
367 St") and the lead's row on the desk carries a *Showing* badge. A lead has one
368 showing: booking again moves it, and **Cancel showing** removes it. While a
369 showing is ahead, follow-ups due before it do not come to *Needs you* until
367 St") and the lead's row on the desk carries a *Showing* badge. A buyer touring
368 several homes can hold several showings (at most 20, never two at the same
369 time): each is listed on the lead's page in time order with its own **Cancel
370 showing**, and each gets its own "see you tomorrow" draft and its own
371 morning-after note; cancelling one withdraws only its drafts. While a
372 showing is ahead, follow-ups due before the last one do not come to *Needs you* until
370373 the day after it, so nobody gets "just checking in" before they have seen the
371374 house; the follow-up plan on the lead's page says which ones wait and until
372375 when. Cancelling puts them back where they were, ready at once if their day
373 has come. Nothing is sent. The same is `POST /leads/:id/showing` (`at`, an
376 has come. Nothing is sent. The same is `POST /leads/:id/showings` (`at`, an
374377 ISO 8601 time such as `2026-11-07T10:00`; `address`; form or JSON; `422` for a
375 past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP
376 tools `book_showing` and `cancel_showing`. It needs the same permission as any
378 past, malformed or too distant time), `DELETE /leads/:id/showings/:showingId` (leads carry a `showings` list), and the MCP
379 tools `book_showing` and `cancel_showing` (`showing_id`, optional with just one). It needs the same permission as any
377380 change to a lead, and shows on the Activity page.
378381
379382 **When a lead says "not until spring".** On an open lead whose first reply
contract/openapi.json +117 −96
@@ -1735,41 +1735,45 @@
17351735 ]
17361736 }
17371737 },
1738 "showing": {
1739 "type": [
1740 "object",
1741 "null"
1742 ],
1743 "description": "The showing booked on this lead, or null.",
1744 "properties": {
1745 "lead_id": {
1746 "type": "integer"
1738 "showings": {
1739 "type": "array",
1740 "description": "The showings booked on this lead, in time order.",
1741 "items": {
1742 "type": "object",
1743 "properties": {
1744 "id": {
1745 "type": "integer"
1746 },
1747 "lead_id": {
1748 "type": "integer"
1749 },
1750 "at": {
1751 "type": "string",
1752 "format": "date-time"
1753 },
1754 "address": {
1755 "type": "string",
1756 "maxLength": 200
1757 },
1758 "hold_until": {
1759 "type": "string",
1760 "format": "date-time",
1761 "description": "Follow-ups due before this wait until it."
1762 },
1763 "booked_at": {
1764 "type": "string",
1765 "format": "date-time"
1766 }
17471767 },
1748 "at": {
1749 "type": "string",
1750 "format": "date-time"
1751 },
1752 "address": {
1753 "type": "string",
1754 "maxLength": 200
1755 },
1756 "hold_until": {
1757 "type": "string",
1758 "format": "date-time",
1759 "description": "Follow-ups due before this wait until it."
1760 },
1761 "booked_at": {
1762 "type": "string",
1763 "format": "date-time"
1764 }
1765 },
1766 "required": [
1767 "lead_id",
1768 "at",
1769 "address",
1770 "hold_until",
1771 "booked_at"
1772 ]
1768 "required": [
1769 "id",
1770 "lead_id",
1771 "at",
1772 "address",
1773 "hold_until",
1774 "booked_at"
1775 ]
1776 }
17731777 },
17741778 "thanks": {
17751779 "type": [
@@ -2205,10 +2209,10 @@
22052209 }
22062210 }
22072211 },
2208 "/leads/{id}/showing": {
2212 "/leads/{id}/showings": {
22092213 "post": {
2210 "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.",
2211 "operationId": "postLeadsIdShowing",
2214 "summary": "Book a showing on an open lead, beside any it already has. Each gets its own confirmation draft the day before and its own note the morning after; follow-ups due before the last wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time, or a time the lead already has a showing at.",
2215 "operationId": "postLeadsIdShowings",
22122216 "parameters": [
22132217 {
22142218 "name": "id",
@@ -2245,7 +2249,7 @@
22452249 },
22462250 "responses": {
22472251 "200": {
2248 "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.",
2252 "description": "Book a showing on an open lead, beside any it already has. Each gets its own confirmation draft the day before and its own note the morning after; follow-ups due before the last wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time, or a time the lead already has a showing at.",
22492253 "content": {
22502254 "application/json": {
22512255 "schema": {
@@ -2265,10 +2269,12 @@
22652269 }
22662270 }
22672271 }
2268 },
2272 }
2273 },
2274 "/leads/{id}/showings/{sid}": {
22692275 "delete": {
2270 "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.",
2271 "operationId": "deleteLeadsIdShowing",
2276 "summary": "Cancel one of the lead's showings: only its drafts go. When it was the last, follow-ups held for it return to their usual place, and any whose day has come are ready at once.",
2277 "operationId": "deleteLeadsIdShowingsSid",
22722278 "parameters": [
22732279 {
22742280 "name": "id",
@@ -2277,11 +2283,19 @@
22772283 "schema": {
22782284 "type": "integer"
22792285 }
2286 },
2287 {
2288 "name": "sid",
2289 "in": "path",
2290 "required": true,
2291 "schema": {
2292 "type": "integer"
2293 }
22802294 }
22812295 ],
22822296 "responses": {
22832297 "200": {
2284 "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.",
2298 "description": "Cancel one of the lead's showings: only its drafts go. When it was the last, follow-ups held for it return to their usual place, and any whose day has come are ready at once.",
22852299 "content": {
22862300 "application/json": {
22872301 "schema": {
@@ -3574,41 +3588,45 @@
35743588 ]
35753589 }
35763590 },
3577 "showing": {
3578 "type": [
3579 "object",
3580 "null"
3581 ],
3582 "description": "The showing booked on this lead, or null.",
3583 "properties": {
3584 "lead_id": {
3585 "type": "integer"
3591 "showings": {
3592 "type": "array",
3593 "description": "The showings booked on this lead, in time order.",
3594 "items": {
3595 "type": "object",
3596 "properties": {
3597 "id": {
3598 "type": "integer"
3599 },
3600 "lead_id": {
3601 "type": "integer"
3602 },
3603 "at": {
3604 "type": "string",
3605 "format": "date-time"
3606 },
3607 "address": {
3608 "type": "string",
3609 "maxLength": 200
3610 },
3611 "hold_until": {
3612 "type": "string",
3613 "format": "date-time",
3614 "description": "Follow-ups due before this wait until it."
3615 },
3616 "booked_at": {
3617 "type": "string",
3618 "format": "date-time"
3619 }
35863620 },
3587 "at": {
3588 "type": "string",
3589 "format": "date-time"
3590 },
3591 "address": {
3592 "type": "string",
3593 "maxLength": 200
3594 },
3595 "hold_until": {
3596 "type": "string",
3597 "format": "date-time",
3598 "description": "Follow-ups due before this wait until it."
3599 },
3600 "booked_at": {
3601 "type": "string",
3602 "format": "date-time"
3603 }
3604 },
3605 "required": [
3606 "lead_id",
3607 "at",
3608 "address",
3609 "hold_until",
3610 "booked_at"
3611 ]
3621 "required": [
3622 "id",
3623 "lead_id",
3624 "at",
3625 "address",
3626 "hold_until",
3627 "booked_at"
3628 ]
3629 }
36123630 },
36133631 "thanks": {
36143632 "type": [
@@ -4036,25 +4054,28 @@
40364054 ],
40374055 "description": "Where the thank-you to the lead's referrer stands; null when nobody referred them."
40384056 },
4039 "showing": {
4040 "type": [
4041 "object",
4042 "null"
4043 ],
4044 "description": "The showing booked on this lead, if one is.",
4045 "properties": {
4046 "at": {
4047 "type": "string",
4048 "format": "date-time"
4049 },
4050 "address": {
4051 "type": "string",
4052 "maxLength": 200
4053 },
4054 "hold_until": {
4055 "type": "string",
4056 "format": "date-time",
4057 "description": "Follow-ups due before this wait until it."
4057 "showings": {
4058 "type": "array",
4059 "description": "The showings booked on this lead, in time order.",
4060 "items": {
4061 "type": "object",
4062 "properties": {
4063 "id": {
4064 "type": "integer"
4065 },
4066 "at": {
4067 "type": "string",
4068 "format": "date-time"
4069 },
4070 "address": {
4071 "type": "string",
4072 "maxLength": 200
4073 },
4074 "hold_until": {
4075 "type": "string",
4076 "format": "date-time",
4077 "description": "Follow-ups due before this wait until it."
4078 }
40584079 }
40594080 }
40604081 }
@@ -4085,7 +4106,7 @@
40854106 "ready",
40864107 "next_at",
40874108 "goes_at",
4088 "showing",
4109 "showings",
40894110 "thanks"
40904111 ]
40914112 },
docs/design/areas/lead.md +4
@@ -12,3 +12,7 @@ the agent's name, brokerage and license in `.brief-foot`) and `.printing` (on
1212 shifts. In `@media print` every other child of `#lead` is hidden, as are the
1313 header and footer, so the buttons, forms, drafts editor and follow-up controls
1414 never reach paper.
15
16 ## showings-booked
17
18 The list inside the lead page's "Showings" card: one row per booked showing (when and address), in time order, each with its own quiet "Cancel showing" button. The form to book another follows it.
src/actions.ts +24 −10
@@ -65,6 +65,7 @@ import {
6565 type Message,
6666 recordCall,
6767 bookShowing as bookShowingFor,
68 showingsOf,
6869 bringBack,
6970 putAway,
7071 setStar,
@@ -91,7 +92,7 @@ import { append, fill, REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLI
9192 import { nextInquiry, seed } from "./sample.ts";
9293 import { goesAt, isZone } from "./quiet.ts";
9394 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
94 import { MAX_ADDRESS, timeOf } from "./showings.ts";
95 import { MAX_ADDRESS, MAX_SHOWINGS, timeOf } from "./showings.ts";
9596 import { weekReport, type WeekReport } from "./report.ts";
9697 import { draftPriceChange, readChange, type Outcome as PriceChanged } from "./price-change.ts";
9798 import { dateOf } from "./putaway.ts";
@@ -1136,9 +1137,10 @@ function phoned(
11361137 }
11371138
11381139 /**
1139 * Book a showing on an open lead, or move the one it has: `when` is a
1140 * future date and time within 90 days, `address` optional. Follow-ups due
1141 * before it wait until the day after. Nothing is sent.
1140 * Book a showing on an open lead, beside any it has: `when` is a
1141 * future date and time within 90 days, `address` optional; two showings
1142 * cannot start at the same time. Follow-ups due before the last wait until
1143 * the day after it. Nothing is sent.
11421144 */
11431145 export const bookShowing = (
11441146 db: Database,
@@ -1172,6 +1174,10 @@ function booked(
11721174 return fail("invalid", `An address is at most ${MAX_ADDRESS} characters.`);
11731175 if (hasControl(address, false))
11741176 return fail("invalid", "An address is one line of plain text.");
1177 if (showingsOf(db, lead.id).some((s) => s.at === time.at))
1178 return fail("invalid", "This lead already has a showing at that time: pick another, or cancel that one first.");
1179 if (showingsOf(db, lead.id).length >= MAX_SHOWINGS)
1180 return fail("invalid", `A lead holds at most ${MAX_SHOWINGS} showings: cancel one first.`);
11751181 bookShowingFor(db, lead, time.at, address, now, currentAgent(db));
11761182 emit("lead.changed", { id: lead.id });
11771183 return ok(detail(db, lead.id)!);
@@ -1305,11 +1311,15 @@ export const priceChangeWords = (done: PriceChanged): string => {
13051311 return `${buyers(done.drafted)} asked about ${done.address} — ${done.drafted === 1 ? "the draft is" : "drafts are"} on the desk${had}.`;
13061312 };
13071313
1308 /** Take the showing off a lead; the follow-ups held for it return to their usual place. */
1314 /**
1315 * Take one showing off a lead (`showingId`, which may be left out when the
1316 * lead has just one); only its drafts go, and when it was the last the
1317 * follow-ups held for it return to their usual place.
1318 */
13091319 export const cancelShowing = (
13101320 db: Database,
13111321 who: Who,
1312 input: { id: number },
1322 input: { id: number; showingId?: number },
13131323 at?: Date,
13141324 ): Result<LeadDetail> =>
13151325 audited(db, who, "lead", "update", input.id, cancelled(db, who, input, at), "showing_off");
@@ -1317,7 +1327,7 @@ export const cancelShowing = (
13171327 function cancelled(
13181328 db: Database,
13191329 who: Who,
1320 input: { id: number },
1330 input: { id: number; showingId?: number },
13211331 at?: Date,
13221332 ): Result<LeadDetail> {
13231333 const found = leadFor(db, who, "update", input.id, {
@@ -1325,9 +1335,13 @@ function cancelled(
13251335 no: "You may not cancel a showing for this lead.",
13261336 });
13271337 if (!found.ok) return found;
1328 if (found.value.showing === null)
1329 return fail("not_found", "This lead has no showing booked.");
1330 cancelShowingFor(db, found.value, stamp(at));
1338 const booked = showingsOf(db, found.value.id);
1339 if (booked.length === 0) return fail("not_found", "This lead has no showing booked.");
1340 if (input.showingId === undefined && booked.length > 1)
1341 return fail("invalid", "This lead has several showings: say which one to cancel.");
1342 const which = booked.find((x) => input.showingId === undefined || x.id === input.showingId);
1343 if (which === undefined) return fail("not_found", "This lead has no such showing.");
1344 cancelShowingFor(db, found.value, which.id, stamp(at));
13311345 emit("lead.changed", { id: found.value.id });
13321346 return ok(detail(db, found.value.id)!);
13331347 }
src/after-showing.test.ts +12 −7
@@ -102,14 +102,17 @@ test("the other cadence days keep the hold, and the note is not held by it", ()
102102 expect(status[3]).toBe("scheduled");
103103 });
104104
105 test("a cancelled showing gets none, and a moved one only the one note", () => {
105 test("a cancelled showing gets none, and a second showing has its own note", () => {
106106 const db = fresh();
107107 const id = answered(db);
108108 book(db, id, "2026-03-03T10:00");
109 book(db, id, "2026-03-05T10:00", "9 Moved Ln");
109 const both = book(db, id, "2026-03-05T10:00", "9 Second Ln");
110 expect(notes(db, id)).toHaveLength(2);
111 expect(notes(db, id).map((m) => m.due_at)).toEqual(["2026-03-04T08:00:00.000Z", "2026-03-06T08:00:00.000Z"]);
112 expect(notes(db, id)[1]!.body).toContain("9 Second Ln");
113 value(cancelShowing(db, alice, { id, showingId: both.showings[0]!.id }, at(1)));
110114 expect(notes(db, id)).toHaveLength(1);
111 expect(notes(db, id)[0]!.due_at).toBe("2026-03-06T08:00:00.000Z");
112 expect(notes(db, id)[0]!.body).toContain("9 Moved Ln");
115 expect(notes(db, id)[0]!.body).toContain("9 Second Ln");
113116 value(cancelShowing(db, alice, { id }, at(1)));
114117 expect(notes(db, id)).toHaveLength(0);
115118 turn(db, new Date("2026-03-10T09:00:00Z"));
@@ -141,7 +144,7 @@ test("one note per showing, and it survives a restart", () => {
141144 expect(notes(again, id).map((m) => m.status)).toEqual(["sent", "due"]);
142145 });
143146
144 test("a note approved and held for quiet hours stays; moving the showing adds no second note", () => {
147 test("a note approved and held for quiet hours stays; another showing has a note of its own", () => {
145148 const db = fresh();
146149 const id = answered(db, true);
147150 book(db, id, "2026-03-03T10:00");
@@ -153,9 +156,11 @@ test("a note approved and held for quiet hours stays; moving the showing adds no
153156 if (was !== undefined) process.env.QUIET_HOURS = was;
154157 const [held] = notes(db, id);
155158 expect(held!.status).toBe("held");
156 value(bookShowing(db, alice, { id, when: "2026-03-09T10:00", address: "Moved Ln" }, new Date("2026-03-04T22:30:00Z")));
159 const other = value(bookShowing(db, alice, { id, when: "2026-03-09T10:00", address: "Second Ln" }, new Date("2026-03-04T22:30:00Z")));
160 expect(notes(db, id).map((m) => m.status)).toEqual(["held", "scheduled"]);
161 value(cancelShowing(db, alice, { id, showingId: other.showings[1]!.id }, new Date("2026-03-04T23:00:00Z")));
157162 expect(notes(db, id).map((m) => [m.id, m.status])).toEqual([[held!.id, "held"]]);
158 value(cancelShowing(db, alice, { id }, new Date("2026-03-04T23:00:00Z")));
163 value(cancelShowing(db, alice, { id }, new Date("2026-03-04T23:30:00Z")));
159164 expect(notes(db, id).map((m) => m.status)).toEqual(["held"]);
160165 });
161166
src/before-showing.test.ts +13 −8
@@ -95,17 +95,22 @@ test("less than a day ahead it is due at once; a passed showing gets none", () =
9595 expect(confirmations(db, other)).toHaveLength(0);
9696 });
9797
98 test("moving rewrites the unsent one, cancelling removes it, one per showing", () => {
98 test("each showing has its own confirmation; cancelling one removes only its own", () => {
9999 const db = fresh();
100100 const id = answered(db);
101 book(db, id, "2026-03-05T10:00");
102 book(db, id, "2026-03-09T15:30", "9 Moved Ln");
101 const first = book(db, id, "2026-03-05T10:00");
102 const second = book(db, id, "2026-03-09T15:30", "9 Second Ln");
103103 const list = confirmations(db, id);
104 expect(list).toHaveLength(1);
105 expect(list[0]!.due_at).toBe("2026-03-08T08:00:00.000Z");
106 expect(list[0]!.body).toContain("3:30 PM");
107 expect(list[0]!.body).toContain("9 Moved Ln");
108 value(cancelShowing(db, alice, { id }, at(1)));
104 expect(list).toHaveLength(2);
105 expect(list.map((m) => m.due_at)).toEqual(["2026-03-04T08:00:00.000Z", "2026-03-08T08:00:00.000Z"]);
106 expect(list[0]!.body).toContain("12 Example St");
107 expect(list[1]!.body).toContain("3:30 PM");
108 expect(list[1]!.body).toContain("9 Second Ln");
109 value(cancelShowing(db, alice, { id, showingId: first.showings[0]!.id }, at(1)));
110 const left = confirmations(db, id);
111 expect(left).toHaveLength(1);
112 expect(left[0]!.body).toContain("9 Second Ln");
113 value(cancelShowing(db, alice, { id, showingId: second.showings[1]!.id }, at(1)));
109114 expect(confirmations(db, id)).toHaveLength(0);
110115 });
111116
src/db.ts +21
@@ -312,6 +312,27 @@ export const migrations: string[] = [
312312 `UPDATE lead SET qualified_at = updated_at WHERE state = 'qualified'`,
313313 // A lead brought in from a spreadsheet: it has no inquiry clock and is not a lead in for the record or the report.
314314 `ALTER TABLE lead ADD COLUMN imported INTEGER NOT NULL DEFAULT 0 CHECK (imported IN (0, 1))`,
315 // A lead may hold several showings (a buyer tours more than one home): the
316 // table is rebuilt with its own id and one row per (lead, time). Each
317 // showing owns its unsent messages through `message.showing_id`. The
318 // existing showing keeps its row and its unsent messages.
319 `CREATE TABLE showing_many (
320 id INTEGER PRIMARY KEY,
321 lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE,
322 at TEXT NOT NULL,
323 address TEXT NOT NULL DEFAULT '' CHECK (length(address) <= 200),
324 hold_until TEXT NOT NULL,
325 booked_at TEXT NOT NULL,
326 UNIQUE (lead_id, at)
327 )`,
328 `INSERT INTO showing_many (lead_id, at, address, hold_until, booked_at)
329 SELECT lead_id, at, address, hold_until, booked_at FROM showing ORDER BY lead_id`,
330 `DROP TABLE showing`,
331 `ALTER TABLE showing_many RENAME TO showing`,
332 `CREATE INDEX showing_lead ON showing (lead_id, at)`,
333 `ALTER TABLE message ADD COLUMN showing_id INTEGER`,
334 `UPDATE message SET showing_id = (SELECT showing.id FROM showing WHERE showing.lead_id = message.lead_id)
335 WHERE day >= 400 AND day < 1000 AND status <> 'sent'`,
315336 ];
316337
317338 /**
src/leads.ts +82 −70
@@ -123,8 +123,8 @@ export interface LeadDetail extends Lead {
123123 readonly replies: readonly Inbound[];
124124 /** Calls the agent made, oldest first. */
125125 readonly calls: readonly Call[];
126 /** The showing booked on this lead; null when none. */
127 readonly showing: Showing | null;
126 /** The showings booked on this lead, in time order; empty when none. */
127 readonly showings: readonly Showing[];
128128 /** Every follow-up has gone out or been set aside and no one answered: the agent may close it out. */
129129 readonly finished: boolean;
130130 /** The thank-you drafted to the referrer (not the lead); null when nobody referred them. */
@@ -143,8 +143,8 @@ export interface DeskLead extends Lead {
143143 readonly next_at: string | null;
144144 /** When a text the agent approved goes, if one is held for quiet hours. */
145145 readonly goes_at: string | null;
146 /** The showing booked on this lead, if one is. */
147 readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null;
146 /** The showings booked on this lead, in time order; empty when none. */
147 readonly showings: readonly Pick<Showing, "id" | "at" | "address" | "hold_until">[];
148148 /** Every follow-up has gone out or been set aside and no one answered. */
149149 readonly finished: boolean;
150150 /** Where the thank-you to the lead's referrer stands (it goes to them, not the lead); null when nobody referred this lead. */
@@ -290,10 +290,25 @@ export const callsOf = (db: Database, id: number): Call[] =>
290290 >("SELECT * FROM phone_call WHERE lead_id = ?1 ORDER BY at, id")
291291 .all(id);
292292
293 export const showingOf = (db: Database, id: number): Showing | null =>
293 /** Every showing booked on a lead, in time order. */
294 export const showingsOf = (db: Database, id: number): Showing[] =>
294295 db
295 .query<Showing, [number]>("SELECT * FROM showing WHERE lead_id = ?1")
296 .get(id);
296 .query<Showing, [number]>("SELECT * FROM showing WHERE lead_id = ?1 ORDER BY at, id")
297 .all(id);
298
299 /** One showing of a lead, or null when it has no such one. */
300 export const showingOf = (db: Database, leadId: number, id: number): Showing | null =>
301 db
302 .query<Showing, [number, number]>("SELECT * FROM showing WHERE lead_id = ?1 AND id = ?2")
303 .get(leadId, id);
304
305 /** The showing a message belongs to, if it still has one. */
306 const showingOfMessage = (db: Database, leadId: number, day: number): Showing | null =>
307 db
308 .query<Showing, [number, number]>(
309 "SELECT showing.* FROM showing JOIN message ON message.showing_id = showing.id WHERE message.lead_id = ?1 AND message.day = ?2",
310 )
311 .get(leadId, day);
297312
298313 /** A showing still ahead, with the lead it is for. */
299314 export interface Ahead {
@@ -319,15 +334,15 @@ export function detail(db: Database, id: number): LeadDetail | null {
319334 const messages = messagesOf(db, id);
320335 const replies = repliesOf(db, id);
321336 const calls = callsOf(db, id);
322 const showing = showingOf(db, id);
337 const showings = showingsOf(db, id);
323338 return {
324339 ...found,
325340 messages,
326341 replies,
327342 calls,
328 showing,
343 showings,
329344 thanks: thanksOf(db, id),
330 finished: followUpsFinished(found, messages, replies.length + calls.length > 0, showing !== null),
345 finished: followUpsFinished(found, messages, replies.length + calls.length > 0, showings.length > 0),
331346 };
332347 }
333348
@@ -374,6 +389,11 @@ const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce(
374389 */
375390 export function desk(db: Database, limit: number, q = ""): DeskLead[] {
376391 const finishedIds = finishedLeads(db);
392 const showingsByLead = new Map<number, DeskLead["showings"][number][]>();
393 for (const s of db
394 .query<Showing, []>("SELECT * FROM showing ORDER BY at, id")
395 .all())
396 showingsByLead.set(s.lead_id, [...(showingsByLead.get(s.lead_id) ?? []), s]);
377397 const digits = /^[\d\s()+.\-]+$/.test(q) ? q.replace(/\D/g, "") : "";
378398 return db
379399 .query<
@@ -383,9 +403,6 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
383403 ready_since: string | null;
384404 next_at: string | null;
385405 goes_at: string | null;
386 show_at: string | null;
387 show_address: string | null;
388 show_hold: string | null;
389406 thanks_status: Thanks["status"] | null;
390407 },
391408 [number, string, string]
@@ -396,9 +413,6 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
396413 (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since,
397414 (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at,
398415 (SELECT min(goes_at) FROM message WHERE lead_id = lead.id AND status = 'held') AS goes_at,
399 (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at,
400 (SELECT address FROM showing WHERE lead_id = lead.id) AS show_address,
401 (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold,
402416 (SELECT status FROM referrer_thanks WHERE lead_id = lead.id) AS thanks_status
403417 FROM lead
404418 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
@@ -407,7 +421,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
407421 ORDER BY max(created_at, coalesce((SELECT max(at) FROM inbound WHERE lead_id = lead.id), '')) DESC, id DESC LIMIT ?1`,
408422 )
409423 .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`)
410 .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, thanks_status, ...row }) => ({
424 .map(({ ready_id, ready_day, ready_since, next_at, goes_at, thanks_status, ...row }) => ({
411425 ...lead(row),
412426 thanks: thanks_status,
413427 finished: finishedIds.has(row.id),
@@ -417,10 +431,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
417431 : { id: ready_id, day: ready_day, since: ready_since },
418432 next_at,
419433 goes_at,
420 showing:
421 show_at === null || show_address === null || show_hold === null
422 ? null
423 : { at: show_at, address: show_address, hold_until: show_hold },
434 showings: showingsByLead.get(row.id) ?? [],
424435 }));
425436 }
426437
@@ -972,7 +983,7 @@ const wordsFor = (db: Database, found: Lead, day: number, agent: Agent): string
972983 if (isCheckIn(day)) return checkInDraft(found);
973984 if (isPriceChange(day)) return priceChangeWords(db, found, day);
974985 if (!isAfterShowing(day) && !isBeforeShowing(day)) return draft(found, day, agent);
975 const showing = showingOf(db, found.id);
986 const showing = showingOfMessage(db, found.id, day);
976987 if (isAfterShowing(day)) return afterShowingDraft(found, showing?.address ?? "");
977988 return showing === null ? "" : confirmation(found, showing.at, showing.address, agent);
978989 };
@@ -1125,9 +1136,8 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
11251136 db.query(
11261137 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`,
11271138 ).run(found.id);
1128 const showing = showingOf(db, found.id);
1129 if (showing !== null)
1130 confirmShowing(db, findLead(db, found.id)!, showing.at, showing.address, at, agent);
1139 for (const showing of showingsOf(db, found.id))
1140 confirmShowing(db, findLead(db, found.id)!, showing, at, agent);
11311141 })();
11321142 }
11331143
@@ -1181,7 +1191,7 @@ export function advance(db: Database, at: string, only?: number): number[] {
11811191 db.query(
11821192 `UPDATE message SET status = 'skipped', goes_at = NULL
11831193 WHERE day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY} AND status IN ('draft', 'scheduled', 'due')
1184 AND lead_id IN (SELECT lead_id FROM showing WHERE at <= ?1)`,
1194 AND showing_id IN (SELECT id FROM showing WHERE at <= ?1)`,
11851195 ).run(at);
11861196 return db
11871197 .query<{ lead_id: number }, [string, number]>(
@@ -1191,7 +1201,7 @@ export function advance(db: Database, at: string, only?: number): number[] {
11911201 AND (day >= ${CHECK_IN_DAY} AND day < ${ANSWER_DAY}
11921202 OR lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1))
11931203 AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY}
1194 AND lead_id IN (SELECT lead_id FROM showing WHERE at <= ?1))
1204 AND showing_id IN (SELECT id FROM showing WHERE at <= ?1))
11951205 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status IN ('draft', 'held'))
11961206 RETURNING lead_id`,
11971207 )
@@ -1201,8 +1211,9 @@ export function advance(db: Database, at: string, only?: number): number[] {
12011211 }
12021212
12031213 /**
1204 * A showing is booked for `when` (booking again moves it). Follow-ups wait
1205 * until the day after it, so any already due go back to waiting.
1214 * A showing is booked for `when`, beside any the lead already has. Follow-ups
1215 * wait until the day after the last one, so any already due go back to
1216 * waiting. Returns the new showing.
12061217 */
12071218 export function bookShowing(
12081219 db: Database,
@@ -1211,18 +1222,20 @@ export function bookShowing(
12111222 address: string,
12121223 at: string,
12131224 agent: Agent,
1214 ): void {
1215 db.transaction(() => {
1225 ): Showing {
1226 return db.transaction(() => {
1227 const showing = db
1228 .query<Showing, [number, string, string, string, string]>(
1229 `INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING *`,
1230 )
1231 .get(found.id, when, address, holdUntil(when), at)!;
12161232 db.query(
1217 `INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (?1, ?2, ?3, ?4, ?5)
1218 ON CONFLICT (lead_id) DO UPDATE SET at = ?2, address = ?3, hold_until = ?4, booked_at = ?5`,
1219 ).run(found.id, when, address, holdUntil(when), at);
1220 db.query(
1221 `UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due' AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY})`,
1233 `UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due' AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${ANSWER_DAY})`,
12221234 ).run(found.id);
1223 noteAfterShowing(db, found, when, address, agent);
1224 confirmShowing(db, found, when, address, at, agent);
1235 noteAfterShowing(db, found, showing, agent);
1236 confirmShowing(db, found, showing, at, agent);
12251237 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id);
1238 return showing;
12261239 })();
12271240 }
12281241
@@ -1236,21 +1249,17 @@ const UNSENT_SQL = `(${UNSENT.map((status) => `'${status}'`).join(", ")})`;
12361249 * before its note went moves that note; one booked after it went gets a
12371250 * note of its own. A lead who can be reached nowhere gets none.
12381251 */
1239 function noteAfterShowing(
1240 db: Database,
1241 found: Lead,
1242 when: string,
1243 address: string,
1244 agent: Agent,
1245 ): void {
1252 function noteAfterShowing(db: Database, found: Lead, showing: Showing, agent: Agent): void {
12461253 placeShowingMessage(
12471254 db,
12481255 found,
12491256 AFTER_SHOWING_DAY,
12501257 ANSWER_DAY,
1251 () => afterShowingDraft(found, address),
1252 morningAfter(when, agent.timeZone),
1258 () => afterShowingDraft(found, showing.address),
1259 morningAfter(showing.at, agent.timeZone),
12531260 agent,
1261 false,
1262 showing.id,
12541263 );
12551264 }
12561265
@@ -1260,14 +1269,9 @@ function noteAfterShowing(
12601269 * less than that far off; none for a showing already past. Moving the
12611270 * showing rewrites the unsent one. It is a draft until the agent approves it.
12621271 */
1263 function confirmShowing(
1264 db: Database,
1265 found: Lead,
1266 when: string,
1267 address: string,
1268 at: string,
1269 agent: Agent,
1270 ): void {
1272 function confirmShowing(db: Database, found: Lead, showing: Showing, at: string, agent: Agent): void {
1273 const when = showing.at;
1274 const address = showing.address;
12711275 const open = found.state !== "qualified" && found.state !== "lost";
12721276 const ahead = Date.parse(when) > Date.parse(at);
12731277 const due = morningBefore(when, agent.timeZone);
@@ -1281,12 +1285,13 @@ function confirmShowing(
12811285 goes,
12821286 agent,
12831287 !open || !ahead,
1288 showing.id,
12841289 );
12851290 const mine = db
1286 .query<{ id: number }, [number, number, number]>(
1287 "SELECT id FROM message WHERE lead_id = ?1 AND day >= ?2 AND day < ?3 AND status = 'scheduled' ORDER BY day DESC LIMIT 1",
1291 .query<{ id: number }, [number]>(
1292 `SELECT id FROM message WHERE showing_id = ?1 AND day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'scheduled' ORDER BY day DESC LIMIT 1`,
12881293 )
1289 .get(found.id, BEFORE_SHOWING_DAY, AFTER_SHOWING_DAY);
1294 .get(showing.id);
12901295 if (mine !== null) advance(db, at, mine.id);
12911296 }
12921297
@@ -1305,12 +1310,16 @@ function placeShowingMessage(
13051310 due: string,
13061311 agent: Agent,
13071312 none = false,
1313 owner: number | null = null,
13081314 ): void {
1309 const last = db
1310 .query<{ id: number; day: number; status: string }, [number, number, number]>(
1311 "SELECT id, day, status FROM message WHERE lead_id = ?1 AND day >= ?2 AND day < ?3 ORDER BY day DESC LIMIT 1",
1315 const range = db
1316 .query<{ id: number; day: number; status: string; showing_id: number | null }, [number, number, number]>(
1317 "SELECT id, day, status, showing_id FROM message WHERE lead_id = ?1 AND day >= ?2 AND day < ?3 ORDER BY day DESC",
13121318 )
1313 .get(found.id, from, end);
1319 .all(found.id, from, end);
1320 // A showing's message is its own (the newest it has); the others' are not touched.
1321 const last = (owner === null ? range[0] : range.find((m) => m.showing_id === owner)) ?? null;
1322 const newest = range[0] ?? null;
13141323 // Approved and held for 8:00 (quiet hours): it goes as approved, and a moved showing does not get a second.
13151324 if (last?.status === "held") return;
13161325 const unsent = last !== null && UNSENT.includes(last.status);
@@ -1327,11 +1336,11 @@ function placeShowingMessage(
13271336 ).run(channel, body, sig, due, last.id);
13281337 return;
13291338 }
1330 const day = last === null ? from : last.day + 1;
1339 const day = newest === null ? from : newest.day + 1;
13311340 if (day >= end) return;
13321341 db.query(
1333 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, 'scheduled', ?6)",
1334 ).run(found.id, day, channel, body, sig, due);
1342 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at, showing_id) VALUES (?1, ?2, ?3, ?4, ?5, 'scheduled', ?6, ?7)",
1343 ).run(found.id, day, channel, body, sig, due, owner);
13351344 }
13361345
13371346 /** Someone the agent can write to: they can be texted, or there is an email to write to. */
@@ -1386,13 +1395,16 @@ export function bringBack(db: Database, found: Lead, at: string): void {
13861395 })();
13871396 }
13881397
1389 /** The showing is off: follow-ups whose day has come are due again at once. */
1390 export function cancelShowing(db: Database, found: Lead, at: string): void {
1398 /**
1399 * One showing is off: only its unsent messages go. When it was the last,
1400 * follow-ups whose day has come are due again at once.
1401 */
1402 export function cancelShowing(db: Database, found: Lead, showingId: number, at: string): void {
13911403 db.transaction(() => {
1392 db.query("DELETE FROM showing WHERE lead_id = ?1").run(found.id);
13931404 db.query(
1394 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${BEFORE_SHOWING_DAY} AND day < ${ANSWER_DAY} AND status IN ${UNSENT_SQL}`,
1395 ).run(found.id);
1405 `DELETE FROM message WHERE showing_id = ?1 AND status IN ${UNSENT_SQL}`,
1406 ).run(showingId);
1407 db.query("DELETE FROM showing WHERE id = ?1 AND lead_id = ?2").run(showingId, found.id);
13961408 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id);
13971409 advance(db, at);
13981410 })();
src/many-showings.test.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * A buyer touring several homes: a lead holds several showings, each with its
3 * own confirmation and morning-after note; cancelling one leaves the others;
4 * follow-ups wait for the last; an existing single showing migrates in place.
5 */
6 import { Database } from "bun:sqlite";
7 import { expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { addLead, bookShowing, cancelShowing, getLead, sendReply, turn, type Result } from "./actions.ts";
12 import { check, migrate, migrations, openDb } from "./db.ts";
13 import { showingsAhead } from "./leads.ts";
14 import { deskPage } from "./pages/desk.ts";
15 import { leadPage } from "./pages/lead.ts";
16 import { currentAgent, storeAgent } from "./profile.ts";
17 import { weekReport } from "./report.ts";
18 import { AFTER_SHOWING_DAY, BEFORE_SHOWING_DAY } from "./drafts.ts";
19 import type { Who } from "./who.ts";
20
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const T0 = new Date("2026-03-01T10:00:00Z");
23 const DAY = 86_400_000;
24 const at = (days: number) => new Date(T0.getTime() + days * DAY);
25 const must = <T>(r: Result<T>): T => {
26 if (!r.ok) throw new Error(r.message);
27 return r.value;
28 };
29
30 function setup() {
31 const db = openDb(mkdtempSync(join(tmpdir(), "app-many-")));
32 storeAgent(db, { ...currentAgent(db), timeZone: "America/Chicago" }, "test", T0.toISOString());
33 const { id } = must(
34 addLead(db, alice, { name: "Dana Reyes", email: "[email protected]", phone: "", source: "zillow", message: "Can I see 12 Oak Street?", consent: false }, T0),
35 ) as { id: number };
36 must(sendReply(db, alice, { id }, T0));
37 return { db, id };
38 }
39 const book = (db: Database, id: number, when: string, address: string) =>
40 must(bookShowing(db, alice, { id, when, address }, at(0.1)));
41 const own = (db: Database, id: number, from: number, to: number) =>
42 must(getLead(db, alice, { id })).messages.filter((m) => m.day >= from && m.day < to);
43
44 test("two showings on one lead each produce their own reminders, in the agent's zone", () => {
45 const { db, id } = setup();
46 book(db, id, "2026-03-05T10:00", "12 Oak St");
47 book(db, id, "2026-03-06T14:30", "9 Elm St");
48 const before = own(db, id, BEFORE_SHOWING_DAY, AFTER_SHOWING_DAY);
49 const after = own(db, id, AFTER_SHOWING_DAY, 1000);
50 expect(before).toHaveLength(2);
51 expect(after).toHaveLength(2);
52 expect(before[0]!.body).toContain("12 Oak St");
53 expect(before[0]!.body).toContain("10:00 AM");
54 expect(before[1]!.body).toContain("9 Elm St");
55 expect(before[1]!.body).toContain("2:30 PM");
56 expect(before.map((m) => m.due_at)).toEqual(["2026-03-04T14:00:00.000Z", "2026-03-05T14:00:00.000Z"]);
57 expect(after.map((m) => m.due_at)).toEqual(["2026-03-06T14:00:00.000Z", "2026-03-07T14:00:00.000Z"]);
58 expect(after[1]!.body).toContain("9 Elm St");
59 });
60
61 test("cancelling one showing leaves the other and its drafts", () => {
62 const { db, id } = setup();
63 const both = book(db, id, "2026-03-05T10:00", "12 Oak St");
64 const two = book(db, id, "2026-03-06T14:30", "9 Elm St");
65 expect(two.showings.map((s) => s.address)).toEqual(["12 Oak St", "9 Elm St"]);
66 const left = must(cancelShowing(db, alice, { id, showingId: both.showings[0]!.id }, at(0.2)));
67 expect(left.showings.map((s) => s.address)).toEqual(["9 Elm St"]);
68 expect(own(db, id, BEFORE_SHOWING_DAY, 1000).map((m) => m.body.includes("9 Elm St"))).toEqual([true, true]);
69 });
70
71 test("follow-ups wait until the day after the last showing; cancelling the last puts them back", () => {
72 const { db, id } = setup();
73 const first = book(db, id, "2026-03-03T10:00", "12 Oak St");
74 const last = book(db, id, "2026-03-08T10:00", "9 Elm St");
75 const status = () => Object.fromEntries(must(getLead(db, alice, { id })).messages.filter((m) => m.day > 0 && m.day < 100).map((m) => [m.day, m.status]));
76 turn(db, at(5)); // past the first showing's day after, before the last showing
77 expect(status()).toMatchObject({ 1: "scheduled", 3: "scheduled" });
78 turn(db, at(7.5)); // the day of the last showing: still held
79 expect(status()[1]).toBe("scheduled");
80 turn(db, at(8.5));
81 expect(status()).toMatchObject({ 1: "due", 3: "due" });
82 // Booking again sends due ones back; cancelling the last releases them.
83 const third = book(db, id, "2026-03-15T10:00", "3 Pine St");
84 expect(status()).toMatchObject({ 1: "scheduled", 3: "scheduled" });
85 must(cancelShowing(db, alice, { id, showingId: third.showings[2]!.id }, at(8.6)));
86 expect(status()).toMatchObject({ 1: "due", 3: "due" });
87 expect(first.showings).toHaveLength(1);
88 expect(last.showings).toHaveLength(2);
89 });
90
91 test("the same time twice is refused with a sentence; another address at another time is fine", () => {
92 const { db, id } = setup();
93 book(db, id, "2026-03-05T10:00", "12 Oak St");
94 const again = bookShowing(db, alice, { id, when: "2026-03-05T10:00", address: "9 Elm St" }, at(0.1));
95 expect(again.ok).toBe(false);
96 if (!again.ok) expect(again.message).toBe("This lead already has a showing at that time: pick another, or cancel that one first.");
97 expect(book(db, id, "2026-03-05T11:00", "12 Oak St").showings).toHaveLength(2);
98 });
99
100 test("the lead's page lists every showing in time order with its own Cancel; the desk lists each; the brief and the report count both", () => {
101 const { db, id } = setup();
102 book(db, id, "2026-03-06T14:30", "9 Elm St");
103 book(db, id, "2026-03-05T10:00", "12 Oak St");
104 const lead = must(getLead(db, alice, { id }));
105 const now = T0.getTime() + 1000;
106 const page = leadPage({ who: alice, agent: currentAgent(db), lead, mayUpdate: true, next: null, now });
107 expect(page.indexOf("12 Oak St")).toBeLessThan(page.indexOf("9 Elm St"));
108 for (const s of lead.showings) expect(page).toContain(`action="/leads/${id}/showings/${s.id}/cancel"`);
109 const brief = page.slice(page.indexOf('<article class="brief"'), page.indexOf("</article>"));
110 expect(brief).toContain("12 Oak St");
111 expect(brief).toContain("9 Elm St");
112 const ahead = showingsAhead(db, now);
113 expect(ahead.map((a) => a.address)).toEqual(["12 Oak St", "9 Elm St"]);
114 const desk = deskPage({ who: alice, agent: currentAgent(db), leads: [], ahead, mayAdd: false, mayReset: false });
115 expect(desk).toContain("12 Oak St");
116 expect(desk).toContain("9 Elm St");
117 expect(desk.match(new RegExp(`href="/leads/${id}"`, "g"))).toHaveLength(2);
118 expect(weekReport(db, T0.getTime() + DAY, "America/Chicago").this_week.showings_booked).toBe(2);
119 });
120
121 test("the migration keeps a lead's one existing showing and its unsent drafts", () => {
122 const db = new Database(":memory:");
123 const upto = migrations.findIndex((m) => m.startsWith("CREATE TABLE showing_many"));
124 expect(upto).toBeGreaterThan(0);
125 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
126 migrations.slice(0, upto).forEach((sql, i) => {
127 try {
128 db.exec(sql);
129 } catch (e) {
130 if (!/duplicate column/.test(String(e))) throw e;
131 }
132 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1);
133 });
134 db.exec("INSERT INTO lead (id, name, email, source, message, consent, state) VALUES (4, 'Old Lead', '[email protected]', 'zillow', 'Is it open?', 0, 'contacted')");
135 db.exec("INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (4, '2026-03-05T10:00:00.000Z', '12 Oak St', '2026-03-06T10:00:00.000Z', '2026-03-01T10:00:00.000Z')");
136 for (const [day, status] of [[400, "scheduled"], [500, "scheduled"], [1, "scheduled"]] as const)
137 db.query("INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (4, ?1, 'email', 'x', 's', ?2, '2026-03-04T08:00:00.000Z')").run(day, status);
138 migrate(db);
139 expect(db.query("SELECT lead_id, at, address, hold_until FROM showing").all()).toEqual([
140 { lead_id: 4, at: "2026-03-05T10:00:00.000Z", address: "12 Oak St", hold_until: "2026-03-06T10:00:00.000Z" },
141 ]);
142 const id = (db.query("SELECT id FROM showing").get() as { id: number }).id;
143 expect(db.query("SELECT day, showing_id FROM message ORDER BY day").all()).toEqual([
144 { day: 1, showing_id: null },
145 { day: 400, showing_id: id },
146 { day: 500, showing_id: id },
147 ]);
148 // It can now hold a second one at another time, and not at the same time.
149 db.exec("INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (4, '2026-03-06T10:00:00.000Z', '', 'x', 'y')");
150 expect(() => db.exec("INSERT INTO showing (lead_id, at, address, hold_until, booked_at) VALUES (4, '2026-03-06T10:00:00.000Z', '', 'x', 'y')")).toThrow();
151 expect(check(db).integrity).toBe("ok");
152 });
src/mcp.ts +8 −4
@@ -284,7 +284,7 @@ export const tools: readonly Tool[] = [
284284 {
285285 name: "book_showing",
286286 description:
287 "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.",
287 "A lead agreed to a showing: book it beside any the lead already has (two cannot start at the same time) 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.",
288288 inputSchema: {
289289 type: "object",
290290 properties: {
@@ -343,13 +343,17 @@ export const tools: readonly Tool[] = [
343343 {
344344 name: "cancel_showing",
345345 description:
346 "Cancel a lead's showing: the follow-ups held for it return to their usual place.",
346 "Cancel one of a lead's showings (showing_id from the lead's showings; optional when it has just one): only its drafts go, and when it was the last the follow-ups held for it return to their usual place.",
347347 inputSchema: {
348348 type: "object",
349 properties: { id: { type: "integer" } },
349 properties: { id: { type: "integer" }, showing_id: { type: "integer" } },
350350 required: ["id"],
351351 },
352 run: (db, who, args) => cancelShowing(db, who, { id: Number(args.id) }),
352 run: (db, who, args) =>
353 cancelShowing(db, who, {
354 id: Number(args.id),
355 ...(args.showing_id === undefined ? {} : { showingId: Number(args.showing_id) }),
356 }),
353357 },
354358 {
355359 name: "mark_lead",
src/pages/desk.ts +14 −9
@@ -184,16 +184,21 @@ function showingsList(ahead: readonly Ahead[], now: number, zone: string): strin
184184 </section>`;
185185 }
186186
187 /** A follow-up due while a showing is ahead waits until the day after it. */
188 const held = (lead: DeskLead, due: string): string =>
189 lead.showing !== null && due < lead.showing.hold_until ? lead.showing.hold_until : due;
187 /** A follow-up due while a showing is ahead waits until the day after the last. */
188 const held = (lead: DeskLead, due: string): string => {
189 const last = lead.showings.reduce((m, s) => (s.hold_until > m ? s.hold_until : m), "");
190 return last !== "" && due < last ? last : due;
191 };
190192
191 const showingBadge = (lead: DeskLead, now: number, zone: string): string =>
192 lead.showing === null || Date.parse(lead.showing.hold_until) <= now
193 ? ""
194 : `<span class="badge" data-showing title="Showing booked: follow-ups wait until the day after">${escape(
195 ["Showing", showingWhen(lead.showing.at, now, zone), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "),
196 )}</span>`;
193 const showingBadge = (lead: DeskLead, now: number, zone: string): string => {
194 const ahead = lead.showings.filter((s) => Date.parse(s.hold_until) > now);
195 const next = ahead[0];
196 if (next === undefined) return "";
197 const text = ["Showing", showingWhen(next.at, now, zone), ...(next.address === "" ? [] : [next.address])].join(" · ");
198 return `<span class="badge" data-showing title="Showing booked: follow-ups wait until the day after the last">${escape(
199 ahead.length > 1 ? `${text} (+${ahead.length - 1} more)` : text,
200 )}</span>`;
201 };
197202
198203 const backBadge = (lead: DeskLead): string =>
199204 lead.back_on === null || (lead.ready !== null && isCheckIn(lead.ready.day))
src/pages/lead.ts +25 −16
@@ -11,7 +11,7 @@ import { escape } from "../http.ts";
1111 import { referrerAddress } from "../thanks.ts";
1212 import { handoff } from "../handoff.ts";
1313 import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts";
14 import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen } from "../showings.ts";
14 import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen, type Showing } from "../showings.ts";
1515 import { elapsed, between } from "../clock.ts";
1616 import { goesLabel, isQuiet, nextOpening } from "../quiet.ts";
1717 import { answerSince, MAX_INBOUND, MAX_LEAD_NOTE, type LeadDetail, type Message, type NextLead } from "../leads.ts";
@@ -144,7 +144,7 @@ export function leadPage(input: {
144144 ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })),
145145 ...lead.replies.map((r) => ({ at: r.at, theirs: r })),
146146 ...lead.calls.map((c) => ({ at: c.at, call: c })),
147 ...(lead.showing === null ? [] : [{ at: lead.showing.booked_at, showing: lead.showing }]),
147 ...lead.showings.map((sh) => ({ at: sh.booked_at, showing: sh })),
148148 ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
149149 const link = (m: Message): string => {
150150 const h = handoff(m, lead);
@@ -176,15 +176,16 @@ export function leadPage(input: {
176176 )
177177 .join("")}</ol></section>`;
178178
179 const holding = lead.showing !== null && Date.parse(lead.showing.hold_until) > now;
179 const lastShowing = lead.showings.reduce<Showing | null>((m, s) => (m === null || s.hold_until > m.hold_until ? s : m), null);
180 const holding = lastShowing !== null && Date.parse(lastShowing.hold_until) > now;
180181 const waits = (m: Message): boolean =>
181 holding && (m.status === "scheduled" || m.status === "due") && m.due_at < lead.showing!.hold_until;
182 holding && (m.status === "scheduled" || m.status === "due") && m.due_at < lastShowing!.hold_until;
182183 const plan =
183184 cadence.length === 0
184185 ? `<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>`
185186 : `<section class="card"><h2>Follow-up plan</h2>${
186187 cadence.some(waits)
187 ? `<p class="hint">Follow-ups due before the showing (${escape(showingWhen(lead.showing!.at, now, agent.timeZone))}) wait until the day after it, ${escape(day(lead.showing!.hold_until, agent.timeZone))}.</p>`
188 ? `<p class="hint">Follow-ups due before the ${lead.showings.length > 1 ? "last showing" : "showing"} (${escape(showingWhen(lastShowing!.at, now, agent.timeZone))}) wait until the day after it, ${escape(day(lastShowing!.hold_until, agent.timeZone))}.</p>`
188189 : ""
189190 }<ol class="plan">${cadence
190191 .map(
@@ -260,21 +261,29 @@ export function leadPage(input: {
260261
261262 const min = localInput(now, agent.timeZone);
262263 const max = localInput(now + MAX_AHEAD_DAYS * 86_400_000, agent.timeZone);
264 const booked = lead.showings.filter((sh) => Date.parse(sh.at) > now);
263265 const showing =
264266 mayUpdate && !closed
265 ? `<details class="card add record" id="book-showing"${lead.showing === null ? "" : " open"}>
266 <summary>${lead.showing === null ? "Book a showing" : "Move the showing"}</summary>
267 <form class="stack" method="post" action="${path}/showing">
268 <label>Date and time (${escape(agent.timeZone)}) <input class="input" type="datetime-local" name="at" required min="${min}" max="${max}"${lead.showing === null ? "" : ` value="${escape(localInput(Date.parse(lead.showing.at), agent.timeZone))}"`}></label>
269 <label>Address (optional) <input class="input" name="address" maxlength="${MAX_ADDRESS}" autocomplete="off"${lead.showing === null ? "" : ` value="${escape(lead.showing.address)}"`}></label>
270 <p class="hint">Follow-ups due before the showing wait until the day after it. Nothing is sent.</p>
271 <button class="button">${lead.showing === null ? "Book the showing" : "Move the showing"}</button>
272 </form>${
273 lead.showing === null
267 ? `<details class="card add record" id="book-showing"${booked.length === 0 ? "" : " open"}>
268 <summary>${lead.showings.length === 0 ? "Book a showing" : "Showings"}</summary>${
269 lead.showings.length === 0
274270 ? ""
275271 : `
276 <form method="post" action="${path}/showing/cancel"><button class="button button-quiet">Cancel showing</button></form>`
272 <ol class="showings-booked">${lead.showings
273 .map(
274 (sh) => `
275 <li data-showing-id="${sh.id}"><span>${escape(showingWhen(sh.at, now, agent.timeZone))}${sh.address === "" ? "" : ` · ${escape(sh.address)}`}</span>
276 <form method="post" action="${path}/showings/${sh.id}/cancel"><button class="button button-quiet">Cancel showing</button></form></li>`,
277 )
278 .join("")}
279 </ol>`
277280 }
281 <form class="stack" method="post" action="${path}/showings">
282 <label>Date and time (${escape(agent.timeZone)}) <input class="input" type="datetime-local" name="at" required min="${min}" max="${max}"></label>
283 <label>Address (optional) <input class="input" name="address" maxlength="${MAX_ADDRESS}" autocomplete="off"></label>
284 <p class="hint">Follow-ups due before the last showing wait until the day after it. Each showing gets its own confirmation and thank-you drafts. Nothing is sent.</p>
285 <button class="button">${lead.showings.length === 0 ? "Book the showing" : "Book another showing"}</button>
286 </form>
278287 </details>`
279288 : "";
280289
@@ -390,7 +399,7 @@ function briefCard(lead: LeadDetail, agent: Agent, now: number): string {
390399 ${item("Phone", lead.phone === "" ? "none" : escape(lead.phone))}
391400 ${item("Texts", texts)}
392401 ${item("Source", escape(SOURCE_LABEL[lead.source]))}
393 ${item("Showing", lead.showing === null ? "none booked" : escape(showingLine(lead.showing, now, zone)))}
402 ${item(lead.showings.length > 1 ? "Showings" : "Showing", lead.showings.length === 0 ? "none booked" : lead.showings.map((sh) => escape(showingLine(sh, now, zone))).join("<br>"))}
394403 </dl>
395404 <h2>They asked <span class="muted">· ${escape(when(lead.created_at, zone))}</span></h2>
396405 <p class="body">${escape(lead.message)}</p>
src/price-change.ts +11 −6
@@ -86,7 +86,7 @@ export interface Outcome {
8686 interface Candidate extends Asker {
8787 readonly id: number;
8888 readonly email: string;
89 readonly showing: string | null;
89 readonly showings: readonly string[];
9090 }
9191
9292 /**
@@ -99,17 +99,22 @@ export function draftPriceChange(db: Database, change: Change, at: string, agent
9999 const key = streetKey(change.address);
100100 return db.transaction(() => {
101101 const open = db
102 .query<Omit<Candidate, "consent"> & { consent: number }, []>(
103 `SELECT lead.id, lead.name, lead.email, lead.phone, lead.source, lead.message, lead.consent, showing.address AS showing
104 FROM lead LEFT JOIN showing ON showing.lead_id = lead.id
102 .query<Omit<Candidate, "consent" | "showings"> & { consent: number }, []>(
103 `SELECT lead.id, lead.name, lead.email, lead.phone, lead.source, lead.message, lead.consent
104 FROM lead
105105 WHERE lead.state IN ('new', 'contacted') AND lead.back_on IS NULL ORDER BY lead.id`,
106106 )
107107 .all();
108 const booked = db.query<{ lead_id: number; address: string }, []>("SELECT lead_id, address FROM showing").all();
108109 const leads: number[] = [];
109110 let matched = 0;
110111 for (const row of open) {
111 const lead: Candidate = { ...row, consent: row.consent === 1 };
112 if (!names(lead.message, key) && !(lead.showing !== null && names(lead.showing, key))) continue;
112 const lead: Candidate = {
113 ...row,
114 consent: row.consent === 1,
115 showings: booked.filter((b) => b.lead_id === row.id).map((b) => b.address),
116 };
117 if (!names(lead.message, key) && !lead.showings.some((address) => names(address, key))) continue;
113118 const channel = channelFor(lead);
114119 if (channel === "email" && lead.email === "") continue;
115120 matched++;
src/routes.ts +19 −15
@@ -240,16 +240,16 @@ const CALL: Schema = {
240240 required: ["id", "lead_id", "outcome", "note", "at"],
241241 };
242242 const SHOWING: Schema = {
243 type: ["object", "null"],
244 description: "The showing booked on this lead, or null.",
243 type: "object",
245244 properties: {
245 id: { type: "integer" },
246246 lead_id: { type: "integer" },
247247 at: STAMP,
248248 address: { type: "string", maxLength: MAX_ADDRESS },
249249 hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." },
250250 booked_at: STAMP,
251251 },
252 required: ["lead_id", "at", "address", "hold_until", "booked_at"],
252 required: ["id", "lead_id", "at", "address", "hold_until", "booked_at"],
253253 };
254254 export const LEAD: Schema = {
255255 type: "object",
@@ -266,7 +266,7 @@ export const LEAD: Schema = {
266266 description: "Phone calls you logged, oldest first.",
267267 items: CALL,
268268 },
269 showing: SHOWING,
269 showings: { type: "array", description: "The showings booked on this lead, in time order.", items: SHOWING },
270270 thanks: {
271271 type: ["object", "null"],
272272 description: "The thank-you drafted to the lead's referrer (it goes to the referrer, never the lead); null when nobody referred them.",
@@ -320,17 +320,21 @@ export const DESK_LEAD: Schema = {
320320 next_at: { type: ["string", "null"], format: "date-time" },
321321 goes_at: { type: ["string", "null"], format: "date-time", description: "When a text you approved goes, if one is held for quiet hours." },
322322 thanks: { anyOf: [{ enum: ["draft", "held", "sent", "skipped"] }, { type: "null" }], description: "Where the thank-you to the lead's referrer stands; null when nobody referred them." },
323 showing: {
324 type: ["object", "null"],
325 description: "The showing booked on this lead, if one is.",
323 showings: {
324 type: "array",
325 description: "The showings booked on this lead, in time order.",
326 items: {
327 type: "object",
326328 properties: {
329 id: { type: "integer" },
327330 at: STAMP,
328331 address: { type: "string", maxLength: MAX_ADDRESS },
329332 hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." },
330333 },
334 },
331335 },
332336 },
333 required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing", "thanks"],
337 required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showings", "thanks"],
334338 };
335339 const SHOW: Schema = {
336340 enum: [...VIEWS],
@@ -1505,7 +1509,7 @@ export const routes: readonly Route[] = [
15051509 },
15061510 {
15071511 method: "POST",
1508 path: "/leads/:id/showing",
1512 path: "/leads/:id/showings",
15091513 handle: (c) =>
15101514 posted(
15111515 c,
@@ -1522,7 +1526,7 @@ export const routes: readonly Route[] = [
15221526 ),
15231527 api: {
15241528 summary:
1525 "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.",
1529 "Book a showing on an open lead, beside any it already has. Each gets its own confirmation draft the day before and its own note the morning after; follow-ups due before the last wait until the day after it. Nothing is sent. 422 for a past, malformed or too distant time, or a time the lead already has a showing at.",
15261530 body: {
15271531 type: "object",
15281532 properties: {
@@ -1580,22 +1584,22 @@ export const routes: readonly Route[] = [
15801584 },
15811585 {
15821586 method: "DELETE",
1583 path: "/leads/:id/showing",
1584 handle: (c) => answer(cancelShowing(c.db, c.who, { id: ID(c) })),
1587 path: "/leads/:id/showings/:sid",
1588 handle: (c) => answer(cancelShowing(c.db, c.who, { id: ID(c), showingId: Number(c.params.sid) })),
15851589 api: {
15861590 summary:
1587 "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.",
1591 "Cancel one of the lead's showings: only its drafts go. When it was the last, follow-ups held for it return to their usual place, and any whose day has come are ready at once.",
15881592 answer: LEAD,
15891593 },
15901594 },
15911595 {
15921596 // The page's form for the DELETE above: a form can only post.
15931597 method: "POST",
1594 path: "/leads/:id/showing/cancel",
1598 path: "/leads/:id/showings/:sid/cancel",
15951599 handle: (c) =>
15961600 posted(
15971601 c,
1598 () => cancelShowing(c.db, c.who, { id: ID(c) }),
1602 () => cancelShowing(c.db, c.who, { id: ID(c), showingId: Number(c.params.sid) }),
15991603 () => ({ to: `/leads/${ID(c)}`, said: "Showing cancelled." }),
16001604 ),
16011605 },
src/showings.test.ts +50 −36
@@ -143,7 +143,8 @@ test("booking validates its inputs and asks permit", () => {
143143 expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(201) }))).toBe("invalid");
144144 expect(refused(book({ when: "2026-03-07T10:00", address: "a\nb" }))).toBe("invalid");
145145 expect(refused(book({ when: "2026-03-07T10:00", address: 4 }))).toBe("invalid");
146 expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(200) }))).toBe("ok");
146 expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(200) }))).toBe("invalid"); // same time as the first
147 expect(refused(book({ when: "2026-03-07T11:00", address: "x".repeat(200) }))).toBe("ok");
147148 expect(refused(book({ when: "2026-03-07T10:00" }, anon))).toBe("signin_required");
148149 expect(refused(bookShowing(db, alice, { id: 999, when: "2026-03-07T10:00" }, at(1)))).toBe("not_found");
149150
@@ -151,16 +152,24 @@ test("booking validates its inputs and asks permit", () => {
151152 expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("invalid");
152153 });
153154
154 test("one showing per lead: booking again moves it; cancelling removes it", () => {
155 test("a lead holds several showings in time order; the same time twice is refused; cancelling removes one", () => {
155156 const db = fresh();
156157 const id = answered(db);
157 value(bookShowing(db, alice, { id, when: "2026-03-07T10:00", address: "12 Example St" }, at(1)));
158 const moved = value(bookShowing(db, alice, { id, when: "2026-03-09T15:30" }, at(1)));
159 expect(moved.showing?.at).toBe("2026-03-09T15:30:00.000Z");
160 expect(moved.showing?.address).toBe("");
161 expect(db.query("SELECT count(*) AS n FROM showing").get()).toEqual({ n: 1 });
158 value(bookShowing(db, alice, { id, when: "2026-03-09T15:30", address: "9 Elm St" }, at(1)));
159 const two = value(bookShowing(db, alice, { id, when: "2026-03-07T10:00", address: "12 Example St" }, at(1)));
160 expect(two.showings.map((s) => s.address)).toEqual(["12 Example St", "9 Elm St"]);
161 const twice = bookShowing(db, alice, { id, when: "2026-03-07T10:00", address: "somewhere else" }, at(1));
162 expect(refused(twice)).toBe("invalid");
163 expect(twice.ok ? "" : twice.message).toContain("already has a showing at that time");
164 expect(db.query("SELECT count(*) AS n FROM showing").get()).toEqual({ n: 2 });
162165 expect(refused(cancelShowing(db, anon, { id }))).toBe("signin_required");
163 expect(value(cancelShowing(db, alice, { id }, at(1))).showing).toBeNull();
166 // With two, which one to cancel must be said.
167 expect(refused(cancelShowing(db, alice, { id }, at(1)))).toBe("invalid");
168 expect(refused(cancelShowing(db, alice, { id, showingId: 9999 }, at(1)))).toBe("not_found");
169 const left = value(cancelShowing(db, alice, { id, showingId: two.showings[0]!.id }, at(1)));
170 expect(left.showings.map((s) => s.address)).toEqual(["9 Elm St"]);
171 // With just one, it may be left unsaid.
172 expect(value(cancelShowing(db, alice, { id }, at(1))).showings).toEqual([]);
164173 expect(refused(cancelShowing(db, alice, { id }, at(1)))).toBe("not_found");
165174 });
166175
@@ -180,12 +189,13 @@ test("follow-ups due before the showing wait until the day after; cancelling rel
180189 expect(value(listLeads(db, alice, { show: "needs" })).leads.map((l) => l.id)).toEqual([id]);
181190
182191 // A follow-up already due goes back to waiting when a showing is booked.
183 value(bookShowing(db, alice, { id, when: "2026-03-12T10:00" }, at(6.2)));
192 const later = value(bookShowing(db, alice, { id, when: "2026-03-12T10:00" }, at(6.2)));
184193 expect(statuses(db, id)).toMatchObject({ 1: "scheduled", 3: "scheduled" });
185 expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(0);
194 // Only the first showing's morning-after note is left to answer.
195 expect(value(getLead(db, alice, { id })).messages.filter((m) => m.status === "due").map((m) => m.day)).toEqual([500]);
186196
187 // Cancelling puts them back where they were: due at once.
188 value(cancelShowing(db, alice, { id }, at(6.3)));
197 // Cancelling the last showing puts them back where they were: due at once.
198 value(cancelShowing(db, alice, { id, showingId: later.showings[1]!.id }, at(6.3)));
189199 expect(statuses(db, id)).toMatchObject({ 1: "due", 3: "due" });
190200 expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(1);
191201 });
@@ -217,7 +227,7 @@ test("the terminal books, shows and cancels a showing, and a refused time is typ
217227 type("12 <b>Example</b> St");
218228 t.key("\r");
219229 expect(read()).toContain("A showing is booked in the future");
220 expect(value(getLead(db, alice, { id })).showing).toBeNull();
230 expect(value(getLead(db, alice, { id })).showings).toEqual([]);
221231
222232 const when = new Date(Date.now() + 3 * DAY).toISOString().slice(0, 16);
223233 // Back on the time step with the refused text still typed: clear it.
@@ -227,7 +237,7 @@ test("the terminal books, shows and cancels a showing, and a refused time is typ
227237 type("12 Example St");
228238 t.key("\r");
229239 const booked = value(getLead(db, alice, { id }));
230 expect(booked.showing).toMatchObject({ at: `${when}:00.000Z`, address: "12 Example St" });
240 expect(booked.showings[0]).toMatchObject({ at: `${when}:00.000Z`, address: "12 Example St" });
231241 const screen = read();
232242 expect(screen).toContain("Showing booked ·");
233243 expect(screen).toContain("12 Example St");
@@ -237,7 +247,7 @@ test("the terminal books, shows and cancels a showing, and a refused time is typ
237247 expect(read()).toContain("showing");
238248 t.key("\r");
239249 t.key("u");
240 expect(value(getLead(db, alice, { id })).showing).toBeNull();
250 expect(value(getLead(db, alice, { id })).showings).toEqual([]);
241251
242252 // permit gates the keys like the page: a signed-out caller cannot book.
243253 const guest = terminal(db, anon);
@@ -293,14 +303,15 @@ test("the API books, moves and cancels; a bad time is 422; the page and desk sho
293303 const id = await served();
294304 const page0 = await (await api(`/leads/${id}`)).text();
295305 expect(page0).toContain("Book a showing");
296 expect(page0).toContain(`action="/leads/${id}/showing"`);
306 expect(page0).toContain(`action="/leads/${id}/showings"`);
297307
298 const booked = await send("POST", `/leads/${id}/showing`, {
308 const booked = await send("POST", `/leads/${id}/showings`, {
299309 at: ahead(2),
300310 address: "<script>alert(1)</script> 12 Example St",
301311 });
302312 expect(booked.status).toBe(200);
303 expect(((await booked.json()) as { showing: { address: string } }).showing.address).toContain("12 Example St");
313 const made = ((await booked.json()) as { showings: { id: number; address: string }[] }).showings;
314 expect(made[0]!.address).toContain("12 Example St");
304315
305316 const page = await (await api(`/leads/${id}`)).text();
306317 expect(page).toContain("Showing booked ·");
@@ -320,12 +331,12 @@ test("the API books, moves and cancels; a bad time is 422; the page and desk sho
320331 {},
321332 { at: ahead(2), address: "x".repeat(201) },
322333 ])
323 expect((await send("POST", `/leads/${id}/showing`, bad)).status).toBe(422);
334 expect((await send("POST", `/leads/${id}/showings`, bad)).status).toBe(422);
324335
325 const gone = await send("DELETE", `/leads/${id}/showing`);
336 const gone = await send("DELETE", `/leads/${id}/showings/${made[0]!.id}`);
326337 expect(gone.status).toBe(200);
327 expect(((await gone.json()) as { showing: unknown }).showing).toBeNull();
328 expect((await send("DELETE", `/leads/${id}/showing`)).status).toBe(404);
338 expect(((await gone.json()) as { showings: unknown[] }).showings).toEqual([]);
339 expect((await send("DELETE", `/leads/${id}/showings/${made[0]!.id}`)).status).toBe(404);
329340 expect(await (await api("/", { headers: { accept: "text/html" } })).text()).not.toContain("data-showing");
330341 });
331342
@@ -341,23 +352,26 @@ test("a form books and cancels, and a cross-origin post is refused", async () =>
341352 },
342353 headers,
343354 );
344 expect((await form(`/leads/${id}/showing`, { at: ahead(3), address: "9 Elm" })).status).toBe(303);
355 expect((await form(`/leads/${id}/showings`, { at: ahead(3), address: "9 Elm" })).status).toBe(303);
345356 expect(await (await api(`/leads/${id}`)).text()).toContain("Showing booked · ");
357 const sid = (
358 (await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { showings: { id: number }[] }
359 ).showings[0]!.id;
346360
347361 const evil = { origin: "https://evil.example", "sec-fetch-site": "cross-site" };
348 expect((await form(`/leads/${id}/showing`, { at: ahead(4) }, evil)).status).toBe(403);
349 expect((await form(`/leads/${id}/showing/cancel`, {}, evil)).status).toBe(403);
350 const crossDelete = await api(`/leads/${id}/showing`, { method: "DELETE" }, evil);
362 expect((await form(`/leads/${id}/showings`, { at: ahead(4) }, evil)).status).toBe(403);
363 expect((await form(`/leads/${id}/showings/${sid}/cancel`, {}, evil)).status).toBe(403);
364 const crossDelete = await api(`/leads/${id}/showings/${sid}`, { method: "DELETE" }, evil);
351365 expect(crossDelete.status).toBe(403);
352 expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { showing: unknown }).showing).not.toBeNull();
366 expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { showings: unknown[] }).showings).toHaveLength(1);
353367
354 expect((await form(`/leads/${id}/showing/cancel`, {})).status).toBe(303);
368 expect((await form(`/leads/${id}/showings/${sid}/cancel`, {})).status).toBe(303);
355369 expect(await (await api(`/leads/${id}`)).text()).not.toContain("Cancel showing");
356370 });
357371
358372 test("a signed-out caller is turned away", async () => {
359373 const id = await served();
360 const res = await fetch(`${base}/leads/${id}/showing`, {
374 const res = await fetch(`${base}/leads/${id}/showings`, {
361375 method: "POST",
362376 headers: { "content-type": "application/json" },
363377 body: JSON.stringify({ at: ahead(2) }),
@@ -369,8 +383,8 @@ test("/openapi.json and MCP carry it", async () => {
369383 const spec = (await (await api("/openapi.json")).json()) as {
370384 paths: Record<string, Record<string, unknown>>;
371385 };
372 expect(spec.paths["/leads/{id}/showing"]!.post).toBeDefined();
373 expect(spec.paths["/leads/{id}/showing"]!.delete).toBeDefined();
386 expect(spec.paths["/leads/{id}/showings"]!.post).toBeDefined();
387 expect(spec.paths["/leads/{id}/showings/{sid}"]!.delete).toBeDefined();
374388
375389 const id = await served();
376390 const call = async (name: string, args: unknown) =>
@@ -384,10 +398,10 @@ test("/openapi.json and MCP carry it", async () => {
384398 ).json()) as { result: { isError?: boolean; content: { text: string }[] } };
385399 const booked = await call("book_showing", { id, at: ahead(2), address: "1 Main" });
386400 expect(booked.result.isError).toBeUndefined();
387 expect(JSON.parse(booked.result.content[0]!.text).showing.address).toBe("1 Main");
401 expect(JSON.parse(booked.result.content[0]!.text).showings[0].address).toBe("1 Main");
388402 expect((await call("book_showing", { id, at: "never" })).result.isError).toBe(true);
389403 const off = await call("cancel_showing", { id });
390 expect(JSON.parse(off.result.content[0]!.text).showing).toBeNull();
404 expect(JSON.parse(off.result.content[0]!.text).showings).toEqual([]);
391405 });
392406
393407 test("booking reads a time with no offset in the profile's zone, and holds follow-ups from that instant", () => {
@@ -395,10 +409,10 @@ test("booking reads a time with no offset in the profile's zone, and holds follo
395409 storeAgent(db, { ...currentAgent(db), timeZone: "America/Chicago" }, "test", T0.toISOString());
396410 const id = answered(db);
397411 const booked = value(bookShowing(db, alice, { id, when: "2026-03-07T10:00" }, at(1)));
398 expect(booked.showing?.at).toBe("2026-03-07T16:00:00.000Z");
399 expect(booked.showing?.hold_until).toBe("2026-03-08T16:00:00.000Z");
412 expect(booked.showings[0]?.at).toBe("2026-03-07T16:00:00.000Z");
413 expect(booked.showings[0]?.hold_until).toBe("2026-03-08T16:00:00.000Z");
400414 const explicit = value(bookShowing(db, alice, { id, when: "2026-03-07T10:00:00Z" }, at(1)));
401 expect(explicit.showing?.at).toBe("2026-03-07T10:00:00.000Z");
415 expect(explicit.showings.map((s) => s.at)).toEqual(["2026-03-07T10:00:00.000Z", "2026-03-07T16:00:00.000Z"]);
402416 });
403417
404418 describe("the desk's list of upcoming showings", () => {
src/showings.ts +7 −3
@@ -1,6 +1,6 @@
11 /**
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
2 * A showing booked on a lead: when, and where. While any is ahead, the
3 * lead's follow-ups wait until the day after the last (`holdUntil`); cancelling
44 * puts them back. Nothing here is sent anywhere.
55 */
66
@@ -9,13 +9,17 @@ export const MAX_ADDRESS = 200;
99 /** How far ahead a showing may be booked. */
1010 export const MAX_AHEAD_DAYS = 90;
1111
12 /** The most showings one lead holds at once. */
13 export const MAX_SHOWINGS = 20;
14
1215 /** How many upcoming showings the desk lists before "and N more". */
1316 export const MAX_LISTED = 5;
1417
1518 const DAY_MS = 86_400_000;
1619
17 /** A showing as stored: one per lead. */
20 /** A showing as stored: a lead may hold several, each at its own time. */
1821 export interface Showing {
22 readonly id: number;
1923 readonly lead_id: number;
2024 /** When it happens, an ISO instant. */
2125 readonly at: string;
src/terminal.ts +12 −13
@@ -332,10 +332,11 @@ export function terminal(
332332 ? "wrote back · answer drafted"
333333 : isPriceChange(l.ready.day) ? "price change · note ready" : isCheckIn(l.ready.day) ? "check-in ready" : isBeforeShowing(l.ready.day) ? "before the showing · confirmation ready" : isAfterShowing(l.ready.day) ? "after the showing · note ready" : `day ${l.ready.day} follow-up ready`;
334334 const name = `${l.starred ? "★ " : ""}${clean(l.name)}`.padEnd(18).slice(0, 18);
335 const next1 = l.showings[0];
335336 const showing =
336 l.showing === null
337 next1 === undefined
337338 ? ""
338 : dim(` · showing ${showingWhen(l.showing.at, now(), currentAgent(db).timeZone)}${l.showing.address === "" ? "" : ` ${clean(l.showing.address)}`}`);
339 : dim(` · showing ${showingWhen(next1.at, now(), currentAgent(db).timeZone)}${next1.address === "" ? "" : ` ${clean(next1.address)}`}${l.showings.length > 1 ? ` (+${l.showings.length - 1} more)` : ""}`);
339340 lines.push(
340341 `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}${showing}`,
341342 );
@@ -489,13 +490,11 @@ export function terminal(
489490 ...wrap(r.signature, width).map((s) => dim(` ${s}`)),
490491 );
491492 }
492 if (l.showing !== null)
493 lines.push(
494 dim(clean(showingLine(l.showing, now(), currentAgent(db).timeZone))),
495 ...(Date.parse(l.showing.hold_until) > now()
496 ? [dim(` Follow-ups due before it wait until ${showingWhen(l.showing.hold_until, now(), currentAgent(db).timeZone)}.`)]
497 : []),
498 );
493 for (const sh of l.showings)
494 lines.push(dim(clean(showingLine(sh, now(), currentAgent(db).timeZone))));
495 const lastHold = l.showings.reduce((m, sh) => (sh.hold_until > m ? sh.hold_until : m), "");
496 if (lastHold !== "" && Date.parse(lastHold) > now())
497 lines.push(dim(` Follow-ups due before ${l.showings.length > 1 ? "the last showing" : "it"} wait until ${showingWhen(lastHold, now(), currentAgent(db).timeZone)}.`));
499498 if (l.back_on !== null)
500499 lines.push(dim(`Put away until ${dateName(l.back_on)}: no follow-ups; a check-in draft waits that morning at 8:00.`));
501500 const sent = l.messages.filter((m) => m.status === "sent").length;
@@ -522,8 +521,8 @@ export function terminal(
522521 ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]),
523522 ...(l.phone === "" ? [] : ["c log a call"]),
524523 ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []),
525 ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]),
526 ...(l.showing === null || CLOSED.includes(l.state) ? [] : ["u cancel the showing"]),
524 ...(CLOSED.includes(l.state) ? [] : [l.showings.length === 0 ? "b book a showing" : "b book another showing"]),
525 ...(l.showings.length === 0 || CLOSED.includes(l.state) ? [] : [l.showings.length > 1 ? "u cancel the next showing" : "u cancel the showing"]),
527526 ...(l.replied_at === null || CLOSED.includes(l.state) ? [] : [l.back_on === null ? "a put away until a date" : "a move the date"]),
528527 ...(l.back_on === null ? [] : ["A bring back now"]),
529528 ...(l.state === "qualified" || l.state === "lost"
@@ -1045,8 +1044,8 @@ export function terminal(
10451044 } else if (input === "*" && mayStar(l)) {
10461045 const starred = setStarred(db, me, { id, starred: !l.starred });
10471046 said = starred.ok ? `${l.name}: ${starred.value.starred ? "starred" : "star taken off"}.` : starred.message;
1048 } else if (input === "u" && l.showing !== null) {
1049 const off = cancelShowing(db, me, { id });
1047 } else if (input === "u" && l.showings.length > 0) {
1048 const off = cancelShowing(db, me, { id, showingId: l.showings[0]!.id });
10501049 said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message;
10511050 } else if (input === "w")
10521051 view = { name: "wrote", id, text: "", channel: "email" };
static/app.css +14
@@ -860,3 +860,17 @@ label.check input {
860860 #lead.printing .brief {
861861 display: block;
862862 }
863
864 .showings-booked {
865 list-style: none;
866 margin: 0 0 var(--space-3, 12px);
867 padding: 0;
868 }
869 .showings-booked li {
870 display: flex;
871 flex-wrap: wrap;
872 align-items: center;
873 justify-content: space-between;
874 gap: var(--space-2, 8px);
875 padding: var(--space-2, 8px) 0;
876 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs