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
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/106-a-buyer-touring-several-homes-can-have-m → main 1 commit fork
18 files
changed +595
−300
README.md +10 −7
| @@ -64,7 +64,7 @@ what you see right after a restart. Do step 1 first. | ||
| 64 | 64 | a day and time later this week (in your time zone from the profile), type an address and book it. The |
| 65 | 65 | history says "Showing booked", his row on the desk carries a *Showing* |
| 66 | 66 | 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 | |
| 68 | 68 | booked showing also drafts a note for the morning after it, at 8:00 in |
| 69 | 69 | your time zone: it asks how the home was, names the address, and offers |
| 70 | 70 | 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. | ||
| 364 | 364 | press **Book a showing**, choose the date and time (in the future, at most 90 |
| 365 | 365 | days ahead, entered in your profile's time zone) and, if you like, the address (up to 200 |
| 366 | 366 | 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 | |
| 370 | 373 | the day after it, so nobody gets "just checking in" before they have seen the |
| 371 | 374 | house; the follow-up plan on the lead's page says which ones wait and until |
| 372 | 375 | 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 | |
| 374 | 377 | 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 | |
| 377 | 380 | change to a lead, and shows on the Activity page. |
| 378 | 381 | |
| 379 | 382 | **When a lead says "not until spring".** On an open lead whose first reply |
contract/openapi.json +117 −96
| @@ -1735,41 +1735,45 @@ | ||
| 1735 | 1735 | ] |
| 1736 | 1736 | } |
| 1737 | 1737 | }, |
| 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 | } | |
| 1747 | 1767 | }, |
| 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 | } | |
| 1773 | 1777 | }, |
| 1774 | 1778 | "thanks": { |
| 1775 | 1779 | "type": [ |
| @@ -2205,10 +2209,10 @@ | ||
| 2205 | 2209 | } |
| 2206 | 2210 | } |
| 2207 | 2211 | }, |
| 2208 | "/leads/{id}/showing": { | |
| 2212 | "/leads/{id}/showings": { | |
| 2209 | 2213 | "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", | |
| 2212 | 2216 | "parameters": [ |
| 2213 | 2217 | { |
| 2214 | 2218 | "name": "id", |
| @@ -2245,7 +2249,7 @@ | ||
| 2245 | 2249 | }, |
| 2246 | 2250 | "responses": { |
| 2247 | 2251 | "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.", | |
| 2249 | 2253 | "content": { |
| 2250 | 2254 | "application/json": { |
| 2251 | 2255 | "schema": { |
| @@ -2265,10 +2269,12 @@ | ||
| 2265 | 2269 | } |
| 2266 | 2270 | } |
| 2267 | 2271 | } |
| 2268 | }, | |
| 2272 | } | |
| 2273 | }, | |
| 2274 | "/leads/{id}/showings/{sid}": { | |
| 2269 | 2275 | "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", | |
| 2272 | 2278 | "parameters": [ |
| 2273 | 2279 | { |
| 2274 | 2280 | "name": "id", |
| @@ -2277,11 +2283,19 @@ | ||
| 2277 | 2283 | "schema": { |
| 2278 | 2284 | "type": "integer" |
| 2279 | 2285 | } |
| 2286 | }, | |
| 2287 | { | |
| 2288 | "name": "sid", | |
| 2289 | "in": "path", | |
| 2290 | "required": true, | |
| 2291 | "schema": { | |
| 2292 | "type": "integer" | |
| 2293 | } | |
| 2280 | 2294 | } |
| 2281 | 2295 | ], |
| 2282 | 2296 | "responses": { |
| 2283 | 2297 | "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.", | |
| 2285 | 2299 | "content": { |
| 2286 | 2300 | "application/json": { |
| 2287 | 2301 | "schema": { |
| @@ -3574,41 +3588,45 @@ | ||
| 3574 | 3588 | ] |
| 3575 | 3589 | } |
| 3576 | 3590 | }, |
| 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 | } | |
| 3586 | 3620 | }, |
| 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 | } | |
| 3612 | 3630 | }, |
| 3613 | 3631 | "thanks": { |
| 3614 | 3632 | "type": [ |
| @@ -4036,25 +4054,28 @@ | ||
| 4036 | 4054 | ], |
| 4037 | 4055 | "description": "Where the thank-you to the lead's referrer stands; null when nobody referred them." |
| 4038 | 4056 | }, |
| 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 | } | |
| 4058 | 4079 | } |
| 4059 | 4080 | } |
| 4060 | 4081 | } |
| @@ -4085,7 +4106,7 @@ | ||
| 4085 | 4106 | "ready", |
| 4086 | 4107 | "next_at", |
| 4087 | 4108 | "goes_at", |
| 4088 | "showing", | |
| 4109 | "showings", | |
| 4089 | 4110 | "thanks" |
| 4090 | 4111 | ] |
| 4091 | 4112 | }, |
docs/design/areas/lead.md +4
| @@ -12,3 +12,7 @@ the agent's name, brokerage and license in `.brief-foot`) and `.printing` (on | ||
| 12 | 12 | shifts. In `@media print` every other child of `#lead` is hidden, as are the |
| 13 | 13 | header and footer, so the buttons, forms, drafts editor and follow-up controls |
| 14 | 14 | 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 { | ||
| 65 | 65 | type Message, |
| 66 | 66 | recordCall, |
| 67 | 67 | bookShowing as bookShowingFor, |
| 68 | showingsOf, | |
| 68 | 69 | bringBack, |
| 69 | 70 | putAway, |
| 70 | 71 | setStar, |
| @@ -91,7 +92,7 @@ import { append, fill, REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLI | ||
| 91 | 92 | import { nextInquiry, seed } from "./sample.ts"; |
| 92 | 93 | import { goesAt, isZone } from "./quiet.ts"; |
| 93 | 94 | 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"; | |
| 95 | 96 | import { weekReport, type WeekReport } from "./report.ts"; |
| 96 | 97 | import { draftPriceChange, readChange, type Outcome as PriceChanged } from "./price-change.ts"; |
| 97 | 98 | import { dateOf } from "./putaway.ts"; |
| @@ -1136,9 +1137,10 @@ function phoned( | ||
| 1136 | 1137 | } |
| 1137 | 1138 | |
| 1138 | 1139 | /** |
| 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. | |
| 1142 | 1144 | */ |
| 1143 | 1145 | export const bookShowing = ( |
| 1144 | 1146 | db: Database, |
| @@ -1172,6 +1174,10 @@ function booked( | ||
| 1172 | 1174 | return fail("invalid", `An address is at most ${MAX_ADDRESS} characters.`); |
| 1173 | 1175 | if (hasControl(address, false)) |
| 1174 | 1176 | 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.`); | |
| 1175 | 1181 | bookShowingFor(db, lead, time.at, address, now, currentAgent(db)); |
| 1176 | 1182 | emit("lead.changed", { id: lead.id }); |
| 1177 | 1183 | return ok(detail(db, lead.id)!); |
| @@ -1305,11 +1311,15 @@ export const priceChangeWords = (done: PriceChanged): string => { | ||
| 1305 | 1311 | return `${buyers(done.drafted)} asked about ${done.address} — ${done.drafted === 1 ? "the draft is" : "drafts are"} on the desk${had}.`; |
| 1306 | 1312 | }; |
| 1307 | 1313 | |
| 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 | */ | |
| 1309 | 1319 | export const cancelShowing = ( |
| 1310 | 1320 | db: Database, |
| 1311 | 1321 | who: Who, |
| 1312 | input: { id: number }, | |
| 1322 | input: { id: number; showingId?: number }, | |
| 1313 | 1323 | at?: Date, |
| 1314 | 1324 | ): Result<LeadDetail> => |
| 1315 | 1325 | audited(db, who, "lead", "update", input.id, cancelled(db, who, input, at), "showing_off"); |
| @@ -1317,7 +1327,7 @@ export const cancelShowing = ( | ||
| 1317 | 1327 | function cancelled( |
| 1318 | 1328 | db: Database, |
| 1319 | 1329 | who: Who, |
| 1320 | input: { id: number }, | |
| 1330 | input: { id: number; showingId?: number }, | |
| 1321 | 1331 | at?: Date, |
| 1322 | 1332 | ): Result<LeadDetail> { |
| 1323 | 1333 | const found = leadFor(db, who, "update", input.id, { |
| @@ -1325,9 +1335,13 @@ function cancelled( | ||
| 1325 | 1335 | no: "You may not cancel a showing for this lead.", |
| 1326 | 1336 | }); |
| 1327 | 1337 | 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)); | |
| 1331 | 1345 | emit("lead.changed", { id: found.value.id }); |
| 1332 | 1346 | return ok(detail(db, found.value.id)!); |
| 1333 | 1347 | } |
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", () | ||
| 102 | 102 | expect(status[3]).toBe("scheduled"); |
| 103 | 103 | }); |
| 104 | 104 | |
| 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", () => { | |
| 106 | 106 | const db = fresh(); |
| 107 | 107 | const id = answered(db); |
| 108 | 108 | 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))); | |
| 110 | 114 | 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"); | |
| 113 | 116 | value(cancelShowing(db, alice, { id }, at(1))); |
| 114 | 117 | expect(notes(db, id)).toHaveLength(0); |
| 115 | 118 | turn(db, new Date("2026-03-10T09:00:00Z")); |
| @@ -141,7 +144,7 @@ test("one note per showing, and it survives a restart", () => { | ||
| 141 | 144 | expect(notes(again, id).map((m) => m.status)).toEqual(["sent", "due"]); |
| 142 | 145 | }); |
| 143 | 146 | |
| 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", () => { | |
| 145 | 148 | const db = fresh(); |
| 146 | 149 | const id = answered(db, true); |
| 147 | 150 | 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 | ||
| 153 | 156 | if (was !== undefined) process.env.QUIET_HOURS = was; |
| 154 | 157 | const [held] = notes(db, id); |
| 155 | 158 | 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"))); | |
| 157 | 162 | 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"))); | |
| 159 | 164 | expect(notes(db, id).map((m) => m.status)).toEqual(["held"]); |
| 160 | 165 | }); |
| 161 | 166 |
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", () = | ||
| 95 | 95 | expect(confirmations(db, other)).toHaveLength(0); |
| 96 | 96 | }); |
| 97 | 97 | |
| 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", () => { | |
| 99 | 99 | const db = fresh(); |
| 100 | 100 | 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"); | |
| 103 | 103 | 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))); | |
| 109 | 114 | expect(confirmations(db, id)).toHaveLength(0); |
| 110 | 115 | }); |
| 111 | 116 |
src/db.ts +21
| @@ -312,6 +312,27 @@ export const migrations: string[] = [ | ||
| 312 | 312 | `UPDATE lead SET qualified_at = updated_at WHERE state = 'qualified'`, |
| 313 | 313 | // A lead brought in from a spreadsheet: it has no inquiry clock and is not a lead in for the record or the report. |
| 314 | 314 | `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'`, | |
| 315 | 336 | ]; |
| 316 | 337 | |
| 317 | 338 | /** |
src/leads.ts +82 −70
| @@ -123,8 +123,8 @@ export interface LeadDetail extends Lead { | ||
| 123 | 123 | readonly replies: readonly Inbound[]; |
| 124 | 124 | /** Calls the agent made, oldest first. */ |
| 125 | 125 | 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[]; | |
| 128 | 128 | /** Every follow-up has gone out or been set aside and no one answered: the agent may close it out. */ |
| 129 | 129 | readonly finished: boolean; |
| 130 | 130 | /** The thank-you drafted to the referrer (not the lead); null when nobody referred them. */ |
| @@ -143,8 +143,8 @@ export interface DeskLead extends Lead { | ||
| 143 | 143 | readonly next_at: string | null; |
| 144 | 144 | /** When a text the agent approved goes, if one is held for quiet hours. */ |
| 145 | 145 | 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">[]; | |
| 148 | 148 | /** Every follow-up has gone out or been set aside and no one answered. */ |
| 149 | 149 | readonly finished: boolean; |
| 150 | 150 | /** 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[] => | ||
| 290 | 290 | >("SELECT * FROM phone_call WHERE lead_id = ?1 ORDER BY at, id") |
| 291 | 291 | .all(id); |
| 292 | 292 | |
| 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[] => | |
| 294 | 295 | 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); | |
| 297 | 312 | |
| 298 | 313 | /** A showing still ahead, with the lead it is for. */ |
| 299 | 314 | export interface Ahead { |
| @@ -319,15 +334,15 @@ export function detail(db: Database, id: number): LeadDetail | null { | ||
| 319 | 334 | const messages = messagesOf(db, id); |
| 320 | 335 | const replies = repliesOf(db, id); |
| 321 | 336 | const calls = callsOf(db, id); |
| 322 | const showing = showingOf(db, id); | |
| 337 | const showings = showingsOf(db, id); | |
| 323 | 338 | return { |
| 324 | 339 | ...found, |
| 325 | 340 | messages, |
| 326 | 341 | replies, |
| 327 | 342 | calls, |
| 328 | showing, | |
| 343 | showings, | |
| 329 | 344 | 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), | |
| 331 | 346 | }; |
| 332 | 347 | } |
| 333 | 348 | |
| @@ -374,6 +389,11 @@ const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce( | ||
| 374 | 389 | */ |
| 375 | 390 | export function desk(db: Database, limit: number, q = ""): DeskLead[] { |
| 376 | 391 | 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]); | |
| 377 | 397 | const digits = /^[\d\s()+.\-]+$/.test(q) ? q.replace(/\D/g, "") : ""; |
| 378 | 398 | return db |
| 379 | 399 | .query< |
| @@ -383,9 +403,6 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 383 | 403 | ready_since: string | null; |
| 384 | 404 | next_at: string | null; |
| 385 | 405 | goes_at: string | null; |
| 386 | show_at: string | null; | |
| 387 | show_address: string | null; | |
| 388 | show_hold: string | null; | |
| 389 | 406 | thanks_status: Thanks["status"] | null; |
| 390 | 407 | }, |
| 391 | 408 | [number, string, string] |
| @@ -396,9 +413,6 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 396 | 413 | (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since, |
| 397 | 414 | (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at, |
| 398 | 415 | (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, | |
| 402 | 416 | (SELECT status FROM referrer_thanks WHERE lead_id = lead.id) AS thanks_status |
| 403 | 417 | FROM lead |
| 404 | 418 | 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[] { | ||
| 407 | 421 | ORDER BY max(created_at, coalesce((SELECT max(at) FROM inbound WHERE lead_id = lead.id), '')) DESC, id DESC LIMIT ?1`, |
| 408 | 422 | ) |
| 409 | 423 | .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 }) => ({ | |
| 411 | 425 | ...lead(row), |
| 412 | 426 | thanks: thanks_status, |
| 413 | 427 | finished: finishedIds.has(row.id), |
| @@ -417,10 +431,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 417 | 431 | : { id: ready_id, day: ready_day, since: ready_since }, |
| 418 | 432 | next_at, |
| 419 | 433 | 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) ?? [], | |
| 424 | 435 | })); |
| 425 | 436 | } |
| 426 | 437 | |
| @@ -972,7 +983,7 @@ const wordsFor = (db: Database, found: Lead, day: number, agent: Agent): string | ||
| 972 | 983 | if (isCheckIn(day)) return checkInDraft(found); |
| 973 | 984 | if (isPriceChange(day)) return priceChangeWords(db, found, day); |
| 974 | 985 | 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); | |
| 976 | 987 | if (isAfterShowing(day)) return afterShowingDraft(found, showing?.address ?? ""); |
| 977 | 988 | return showing === null ? "" : confirmation(found, showing.at, showing.address, agent); |
| 978 | 989 | }; |
| @@ -1125,9 +1136,8 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi | ||
| 1125 | 1136 | db.query( |
| 1126 | 1137 | `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`, |
| 1127 | 1138 | ).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); | |
| 1131 | 1141 | })(); |
| 1132 | 1142 | } |
| 1133 | 1143 | |
| @@ -1181,7 +1191,7 @@ export function advance(db: Database, at: string, only?: number): number[] { | ||
| 1181 | 1191 | db.query( |
| 1182 | 1192 | `UPDATE message SET status = 'skipped', goes_at = NULL |
| 1183 | 1193 | 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)`, | |
| 1185 | 1195 | ).run(at); |
| 1186 | 1196 | return db |
| 1187 | 1197 | .query<{ lead_id: number }, [string, number]>( |
| @@ -1191,7 +1201,7 @@ export function advance(db: Database, at: string, only?: number): number[] { | ||
| 1191 | 1201 | AND (day >= ${CHECK_IN_DAY} AND day < ${ANSWER_DAY} |
| 1192 | 1202 | OR lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1)) |
| 1193 | 1203 | 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)) | |
| 1195 | 1205 | AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status IN ('draft', 'held')) |
| 1196 | 1206 | RETURNING lead_id`, |
| 1197 | 1207 | ) |
| @@ -1201,8 +1211,9 @@ export function advance(db: Database, at: string, only?: number): number[] { | ||
| 1201 | 1211 | } |
| 1202 | 1212 | |
| 1203 | 1213 | /** |
| 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. | |
| 1206 | 1217 | */ |
| 1207 | 1218 | export function bookShowing( |
| 1208 | 1219 | db: Database, |
| @@ -1211,18 +1222,20 @@ export function bookShowing( | ||
| 1211 | 1222 | address: string, |
| 1212 | 1223 | at: string, |
| 1213 | 1224 | 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)!; | |
| 1216 | 1232 | 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})`, | |
| 1222 | 1234 | ).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); | |
| 1225 | 1237 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); |
| 1238 | return showing; | |
| 1226 | 1239 | })(); |
| 1227 | 1240 | } |
| 1228 | 1241 | |
| @@ -1236,21 +1249,17 @@ const UNSENT_SQL = `(${UNSENT.map((status) => `'${status}'`).join(", ")})`; | ||
| 1236 | 1249 | * before its note went moves that note; one booked after it went gets a |
| 1237 | 1250 | * note of its own. A lead who can be reached nowhere gets none. |
| 1238 | 1251 | */ |
| 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 { | |
| 1246 | 1253 | placeShowingMessage( |
| 1247 | 1254 | db, |
| 1248 | 1255 | found, |
| 1249 | 1256 | AFTER_SHOWING_DAY, |
| 1250 | 1257 | ANSWER_DAY, |
| 1251 | () => afterShowingDraft(found, address), | |
| 1252 | morningAfter(when, agent.timeZone), | |
| 1258 | () => afterShowingDraft(found, showing.address), | |
| 1259 | morningAfter(showing.at, agent.timeZone), | |
| 1253 | 1260 | agent, |
| 1261 | false, | |
| 1262 | showing.id, | |
| 1254 | 1263 | ); |
| 1255 | 1264 | } |
| 1256 | 1265 | |
| @@ -1260,14 +1269,9 @@ function noteAfterShowing( | ||
| 1260 | 1269 | * less than that far off; none for a showing already past. Moving the |
| 1261 | 1270 | * showing rewrites the unsent one. It is a draft until the agent approves it. |
| 1262 | 1271 | */ |
| 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; | |
| 1271 | 1275 | const open = found.state !== "qualified" && found.state !== "lost"; |
| 1272 | 1276 | const ahead = Date.parse(when) > Date.parse(at); |
| 1273 | 1277 | const due = morningBefore(when, agent.timeZone); |
| @@ -1281,12 +1285,13 @@ function confirmShowing( | ||
| 1281 | 1285 | goes, |
| 1282 | 1286 | agent, |
| 1283 | 1287 | !open || !ahead, |
| 1288 | showing.id, | |
| 1284 | 1289 | ); |
| 1285 | 1290 | 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`, | |
| 1288 | 1293 | ) |
| 1289 | .get(found.id, BEFORE_SHOWING_DAY, AFTER_SHOWING_DAY); | |
| 1294 | .get(showing.id); | |
| 1290 | 1295 | if (mine !== null) advance(db, at, mine.id); |
| 1291 | 1296 | } |
| 1292 | 1297 | |
| @@ -1305,12 +1310,16 @@ function placeShowingMessage( | ||
| 1305 | 1310 | due: string, |
| 1306 | 1311 | agent: Agent, |
| 1307 | 1312 | none = false, |
| 1313 | owner: number | null = null, | |
| 1308 | 1314 | ): 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", | |
| 1312 | 1318 | ) |
| 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; | |
| 1314 | 1323 | // Approved and held for 8:00 (quiet hours): it goes as approved, and a moved showing does not get a second. |
| 1315 | 1324 | if (last?.status === "held") return; |
| 1316 | 1325 | const unsent = last !== null && UNSENT.includes(last.status); |
| @@ -1327,11 +1336,11 @@ function placeShowingMessage( | ||
| 1327 | 1336 | ).run(channel, body, sig, due, last.id); |
| 1328 | 1337 | return; |
| 1329 | 1338 | } |
| 1330 | const day = last === null ? from : last.day + 1; | |
| 1339 | const day = newest === null ? from : newest.day + 1; | |
| 1331 | 1340 | if (day >= end) return; |
| 1332 | 1341 | 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); | |
| 1335 | 1344 | } |
| 1336 | 1345 | |
| 1337 | 1346 | /** 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 { | ||
| 1386 | 1395 | })(); |
| 1387 | 1396 | } |
| 1388 | 1397 | |
| 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 { | |
| 1391 | 1403 | db.transaction(() => { |
| 1392 | db.query("DELETE FROM showing WHERE lead_id = ?1").run(found.id); | |
| 1393 | 1404 | 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); | |
| 1396 | 1408 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); |
| 1397 | 1409 | advance(db, at); |
| 1398 | 1410 | })(); |
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[] = [ | ||
| 284 | 284 | { |
| 285 | 285 | name: "book_showing", |
| 286 | 286 | 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.", | |
| 288 | 288 | inputSchema: { |
| 289 | 289 | type: "object", |
| 290 | 290 | properties: { |
| @@ -343,13 +343,17 @@ export const tools: readonly Tool[] = [ | ||
| 343 | 343 | { |
| 344 | 344 | name: "cancel_showing", |
| 345 | 345 | 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.", | |
| 347 | 347 | inputSchema: { |
| 348 | 348 | type: "object", |
| 349 | properties: { id: { type: "integer" } }, | |
| 349 | properties: { id: { type: "integer" }, showing_id: { type: "integer" } }, | |
| 350 | 350 | required: ["id"], |
| 351 | 351 | }, |
| 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 | }), | |
| 353 | 357 | }, |
| 354 | 358 | { |
| 355 | 359 | name: "mark_lead", |
src/pages/desk.ts +14 −9
| @@ -184,16 +184,21 @@ function showingsList(ahead: readonly Ahead[], now: number, zone: string): strin | ||
| 184 | 184 | </section>`; |
| 185 | 185 | } |
| 186 | 186 | |
| 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 | }; | |
| 190 | 192 | |
| 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 | }; | |
| 197 | 202 | |
| 198 | 203 | const backBadge = (lead: DeskLead): string => |
| 199 | 204 | 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"; | ||
| 11 | 11 | import { referrerAddress } from "../thanks.ts"; |
| 12 | 12 | import { handoff } from "../handoff.ts"; |
| 13 | 13 | 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"; | |
| 15 | 15 | import { elapsed, between } from "../clock.ts"; |
| 16 | 16 | import { goesLabel, isQuiet, nextOpening } from "../quiet.ts"; |
| 17 | 17 | import { answerSince, MAX_INBOUND, MAX_LEAD_NOTE, type LeadDetail, type Message, type NextLead } from "../leads.ts"; |
| @@ -144,7 +144,7 @@ export function leadPage(input: { | ||
| 144 | 144 | ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })), |
| 145 | 145 | ...lead.replies.map((r) => ({ at: r.at, theirs: r })), |
| 146 | 146 | ...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 })), | |
| 148 | 148 | ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); |
| 149 | 149 | const link = (m: Message): string => { |
| 150 | 150 | const h = handoff(m, lead); |
| @@ -176,15 +176,16 @@ export function leadPage(input: { | ||
| 176 | 176 | ) |
| 177 | 177 | .join("")}</ol></section>`; |
| 178 | 178 | |
| 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; | |
| 180 | 181 | 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; | |
| 182 | 183 | const plan = |
| 183 | 184 | cadence.length === 0 |
| 184 | 185 | ? `<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>` |
| 185 | 186 | : `<section class="card"><h2>Follow-up plan</h2>${ |
| 186 | 187 | 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>` | |
| 188 | 189 | : "" |
| 189 | 190 | }<ol class="plan">${cadence |
| 190 | 191 | .map( |
| @@ -260,21 +261,29 @@ export function leadPage(input: { | ||
| 260 | 261 | |
| 261 | 262 | const min = localInput(now, agent.timeZone); |
| 262 | 263 | const max = localInput(now + MAX_AHEAD_DAYS * 86_400_000, agent.timeZone); |
| 264 | const booked = lead.showings.filter((sh) => Date.parse(sh.at) > now); | |
| 263 | 265 | const showing = |
| 264 | 266 | 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 | |
| 274 | 270 | ? "" |
| 275 | 271 | : ` |
| 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>` | |
| 277 | 280 | } |
| 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> | |
| 278 | 287 | </details>` |
| 279 | 288 | : ""; |
| 280 | 289 | |
| @@ -390,7 +399,7 @@ function briefCard(lead: LeadDetail, agent: Agent, now: number): string { | ||
| 390 | 399 | ${item("Phone", lead.phone === "" ? "none" : escape(lead.phone))} |
| 391 | 400 | ${item("Texts", texts)} |
| 392 | 401 | ${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>"))} | |
| 394 | 403 | </dl> |
| 395 | 404 | <h2>They asked <span class="muted">· ${escape(when(lead.created_at, zone))}</span></h2> |
| 396 | 405 | <p class="body">${escape(lead.message)}</p> |
src/price-change.ts +11 −6
| @@ -86,7 +86,7 @@ export interface Outcome { | ||
| 86 | 86 | interface Candidate extends Asker { |
| 87 | 87 | readonly id: number; |
| 88 | 88 | readonly email: string; |
| 89 | readonly showing: string | null; | |
| 89 | readonly showings: readonly string[]; | |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | /** |
| @@ -99,17 +99,22 @@ export function draftPriceChange(db: Database, change: Change, at: string, agent | ||
| 99 | 99 | const key = streetKey(change.address); |
| 100 | 100 | return db.transaction(() => { |
| 101 | 101 | 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 | |
| 105 | 105 | WHERE lead.state IN ('new', 'contacted') AND lead.back_on IS NULL ORDER BY lead.id`, |
| 106 | 106 | ) |
| 107 | 107 | .all(); |
| 108 | const booked = db.query<{ lead_id: number; address: string }, []>("SELECT lead_id, address FROM showing").all(); | |
| 108 | 109 | const leads: number[] = []; |
| 109 | 110 | let matched = 0; |
| 110 | 111 | 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; | |
| 113 | 118 | const channel = channelFor(lead); |
| 114 | 119 | if (channel === "email" && lead.email === "") continue; |
| 115 | 120 | matched++; |
src/routes.ts +19 −15
| @@ -240,16 +240,16 @@ const CALL: Schema = { | ||
| 240 | 240 | required: ["id", "lead_id", "outcome", "note", "at"], |
| 241 | 241 | }; |
| 242 | 242 | const SHOWING: Schema = { |
| 243 | type: ["object", "null"], | |
| 244 | description: "The showing booked on this lead, or null.", | |
| 243 | type: "object", | |
| 245 | 244 | properties: { |
| 245 | id: { type: "integer" }, | |
| 246 | 246 | lead_id: { type: "integer" }, |
| 247 | 247 | at: STAMP, |
| 248 | 248 | address: { type: "string", maxLength: MAX_ADDRESS }, |
| 249 | 249 | hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." }, |
| 250 | 250 | booked_at: STAMP, |
| 251 | 251 | }, |
| 252 | required: ["lead_id", "at", "address", "hold_until", "booked_at"], | |
| 252 | required: ["id", "lead_id", "at", "address", "hold_until", "booked_at"], | |
| 253 | 253 | }; |
| 254 | 254 | export const LEAD: Schema = { |
| 255 | 255 | type: "object", |
| @@ -266,7 +266,7 @@ export const LEAD: Schema = { | ||
| 266 | 266 | description: "Phone calls you logged, oldest first.", |
| 267 | 267 | items: CALL, |
| 268 | 268 | }, |
| 269 | showing: SHOWING, | |
| 269 | showings: { type: "array", description: "The showings booked on this lead, in time order.", items: SHOWING }, | |
| 270 | 270 | thanks: { |
| 271 | 271 | type: ["object", "null"], |
| 272 | 272 | 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 = { | ||
| 320 | 320 | next_at: { type: ["string", "null"], format: "date-time" }, |
| 321 | 321 | goes_at: { type: ["string", "null"], format: "date-time", description: "When a text you approved goes, if one is held for quiet hours." }, |
| 322 | 322 | 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", | |
| 326 | 328 | properties: { |
| 329 | id: { type: "integer" }, | |
| 327 | 330 | at: STAMP, |
| 328 | 331 | address: { type: "string", maxLength: MAX_ADDRESS }, |
| 329 | 332 | hold_until: { ...STAMP, description: "Follow-ups due before this wait until it." }, |
| 330 | 333 | }, |
| 334 | }, | |
| 331 | 335 | }, |
| 332 | 336 | }, |
| 333 | required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing", "thanks"], | |
| 337 | required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showings", "thanks"], | |
| 334 | 338 | }; |
| 335 | 339 | const SHOW: Schema = { |
| 336 | 340 | enum: [...VIEWS], |
| @@ -1505,7 +1509,7 @@ export const routes: readonly Route[] = [ | ||
| 1505 | 1509 | }, |
| 1506 | 1510 | { |
| 1507 | 1511 | method: "POST", |
| 1508 | path: "/leads/:id/showing", | |
| 1512 | path: "/leads/:id/showings", | |
| 1509 | 1513 | handle: (c) => |
| 1510 | 1514 | posted( |
| 1511 | 1515 | c, |
| @@ -1522,7 +1526,7 @@ export const routes: readonly Route[] = [ | ||
| 1522 | 1526 | ), |
| 1523 | 1527 | api: { |
| 1524 | 1528 | 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.", | |
| 1526 | 1530 | body: { |
| 1527 | 1531 | type: "object", |
| 1528 | 1532 | properties: { |
| @@ -1580,22 +1584,22 @@ export const routes: readonly Route[] = [ | ||
| 1580 | 1584 | }, |
| 1581 | 1585 | { |
| 1582 | 1586 | 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) })), | |
| 1585 | 1589 | api: { |
| 1586 | 1590 | 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.", | |
| 1588 | 1592 | answer: LEAD, |
| 1589 | 1593 | }, |
| 1590 | 1594 | }, |
| 1591 | 1595 | { |
| 1592 | 1596 | // The page's form for the DELETE above: a form can only post. |
| 1593 | 1597 | method: "POST", |
| 1594 | path: "/leads/:id/showing/cancel", | |
| 1598 | path: "/leads/:id/showings/:sid/cancel", | |
| 1595 | 1599 | handle: (c) => |
| 1596 | 1600 | posted( |
| 1597 | 1601 | c, |
| 1598 | () => cancelShowing(c.db, c.who, { id: ID(c) }), | |
| 1602 | () => cancelShowing(c.db, c.who, { id: ID(c), showingId: Number(c.params.sid) }), | |
| 1599 | 1603 | () => ({ to: `/leads/${ID(c)}`, said: "Showing cancelled." }), |
| 1600 | 1604 | ), |
| 1601 | 1605 | }, |
src/showings.test.ts +50 −36
| @@ -143,7 +143,8 @@ test("booking validates its inputs and asks permit", () => { | ||
| 143 | 143 | expect(refused(book({ when: "2026-03-07T10:00", address: "x".repeat(201) }))).toBe("invalid"); |
| 144 | 144 | expect(refused(book({ when: "2026-03-07T10:00", address: "a\nb" }))).toBe("invalid"); |
| 145 | 145 | 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"); | |
| 147 | 148 | expect(refused(book({ when: "2026-03-07T10:00" }, anon))).toBe("signin_required"); |
| 148 | 149 | expect(refused(bookShowing(db, alice, { id: 999, when: "2026-03-07T10:00" }, at(1)))).toBe("not_found"); |
| 149 | 150 | |
| @@ -151,16 +152,24 @@ test("booking validates its inputs and asks permit", () => { | ||
| 151 | 152 | expect(refused(book({ when: "2026-03-07T10:00" }))).toBe("invalid"); |
| 152 | 153 | }); |
| 153 | 154 | |
| 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", () => { | |
| 155 | 156 | const db = fresh(); |
| 156 | 157 | 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 }); | |
| 162 | 165 | 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([]); | |
| 164 | 173 | expect(refused(cancelShowing(db, alice, { id }, at(1)))).toBe("not_found"); |
| 165 | 174 | }); |
| 166 | 175 | |
| @@ -180,12 +189,13 @@ test("follow-ups due before the showing wait until the day after; cancelling rel | ||
| 180 | 189 | expect(value(listLeads(db, alice, { show: "needs" })).leads.map((l) => l.id)).toEqual([id]); |
| 181 | 190 | |
| 182 | 191 | // 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))); | |
| 184 | 193 | 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]); | |
| 186 | 196 | |
| 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))); | |
| 189 | 199 | expect(statuses(db, id)).toMatchObject({ 1: "due", 3: "due" }); |
| 190 | 200 | expect(value(listLeads(db, alice, { show: "needs" })).leads).toHaveLength(1); |
| 191 | 201 | }); |
| @@ -217,7 +227,7 @@ test("the terminal books, shows and cancels a showing, and a refused time is typ | ||
| 217 | 227 | type("12 <b>Example</b> St"); |
| 218 | 228 | t.key("\r"); |
| 219 | 229 | 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([]); | |
| 221 | 231 | |
| 222 | 232 | const when = new Date(Date.now() + 3 * DAY).toISOString().slice(0, 16); |
| 223 | 233 | // 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 | ||
| 227 | 237 | type("12 Example St"); |
| 228 | 238 | t.key("\r"); |
| 229 | 239 | 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" }); | |
| 231 | 241 | const screen = read(); |
| 232 | 242 | expect(screen).toContain("Showing booked ·"); |
| 233 | 243 | 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 | ||
| 237 | 247 | expect(read()).toContain("showing"); |
| 238 | 248 | t.key("\r"); |
| 239 | 249 | t.key("u"); |
| 240 | expect(value(getLead(db, alice, { id })).showing).toBeNull(); | |
| 250 | expect(value(getLead(db, alice, { id })).showings).toEqual([]); | |
| 241 | 251 | |
| 242 | 252 | // permit gates the keys like the page: a signed-out caller cannot book. |
| 243 | 253 | 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 | ||
| 293 | 303 | const id = await served(); |
| 294 | 304 | const page0 = await (await api(`/leads/${id}`)).text(); |
| 295 | 305 | expect(page0).toContain("Book a showing"); |
| 296 | expect(page0).toContain(`action="/leads/${id}/showing"`); | |
| 306 | expect(page0).toContain(`action="/leads/${id}/showings"`); | |
| 297 | 307 | |
| 298 | const booked = await send("POST", `/leads/${id}/showing`, { | |
| 308 | const booked = await send("POST", `/leads/${id}/showings`, { | |
| 299 | 309 | at: ahead(2), |
| 300 | 310 | address: "<script>alert(1)</script> 12 Example St", |
| 301 | 311 | }); |
| 302 | 312 | 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"); | |
| 304 | 315 | |
| 305 | 316 | const page = await (await api(`/leads/${id}`)).text(); |
| 306 | 317 | 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 | ||
| 320 | 331 | {}, |
| 321 | 332 | { at: ahead(2), address: "x".repeat(201) }, |
| 322 | 333 | ]) |
| 323 | expect((await send("POST", `/leads/${id}/showing`, bad)).status).toBe(422); | |
| 334 | expect((await send("POST", `/leads/${id}/showings`, bad)).status).toBe(422); | |
| 324 | 335 | |
| 325 | const gone = await send("DELETE", `/leads/${id}/showing`); | |
| 336 | const gone = await send("DELETE", `/leads/${id}/showings/${made[0]!.id}`); | |
| 326 | 337 | 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); | |
| 329 | 340 | expect(await (await api("/", { headers: { accept: "text/html" } })).text()).not.toContain("data-showing"); |
| 330 | 341 | }); |
| 331 | 342 | |
| @@ -341,23 +352,26 @@ test("a form books and cancels, and a cross-origin post is refused", async () => | ||
| 341 | 352 | }, |
| 342 | 353 | headers, |
| 343 | 354 | ); |
| 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); | |
| 345 | 356 | 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; | |
| 346 | 360 | |
| 347 | 361 | 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); | |
| 351 | 365 | 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); | |
| 353 | 367 | |
| 354 | expect((await form(`/leads/${id}/showing/cancel`, {})).status).toBe(303); | |
| 368 | expect((await form(`/leads/${id}/showings/${sid}/cancel`, {})).status).toBe(303); | |
| 355 | 369 | expect(await (await api(`/leads/${id}`)).text()).not.toContain("Cancel showing"); |
| 356 | 370 | }); |
| 357 | 371 | |
| 358 | 372 | test("a signed-out caller is turned away", async () => { |
| 359 | 373 | const id = await served(); |
| 360 | const res = await fetch(`${base}/leads/${id}/showing`, { | |
| 374 | const res = await fetch(`${base}/leads/${id}/showings`, { | |
| 361 | 375 | method: "POST", |
| 362 | 376 | headers: { "content-type": "application/json" }, |
| 363 | 377 | body: JSON.stringify({ at: ahead(2) }), |
| @@ -369,8 +383,8 @@ test("/openapi.json and MCP carry it", async () => { | ||
| 369 | 383 | const spec = (await (await api("/openapi.json")).json()) as { |
| 370 | 384 | paths: Record<string, Record<string, unknown>>; |
| 371 | 385 | }; |
| 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(); | |
| 374 | 388 | |
| 375 | 389 | const id = await served(); |
| 376 | 390 | const call = async (name: string, args: unknown) => |
| @@ -384,10 +398,10 @@ test("/openapi.json and MCP carry it", async () => { | ||
| 384 | 398 | ).json()) as { result: { isError?: boolean; content: { text: string }[] } }; |
| 385 | 399 | const booked = await call("book_showing", { id, at: ahead(2), address: "1 Main" }); |
| 386 | 400 | 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"); | |
| 388 | 402 | expect((await call("book_showing", { id, at: "never" })).result.isError).toBe(true); |
| 389 | 403 | 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([]); | |
| 391 | 405 | }); |
| 392 | 406 | |
| 393 | 407 | 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 | ||
| 395 | 409 | storeAgent(db, { ...currentAgent(db), timeZone: "America/Chicago" }, "test", T0.toISOString()); |
| 396 | 410 | const id = answered(db); |
| 397 | 411 | 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"); | |
| 400 | 414 | 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"]); | |
| 402 | 416 | }); |
| 403 | 417 | |
| 404 | 418 | describe("the desk's list of upcoming showings", () => { |
src/showings.ts +7 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | 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 | |
| 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 | |
| 4 | 4 | * puts them back. Nothing here is sent anywhere. |
| 5 | 5 | */ |
| 6 | 6 | |
| @@ -9,13 +9,17 @@ export const MAX_ADDRESS = 200; | ||
| 9 | 9 | /** How far ahead a showing may be booked. */ |
| 10 | 10 | export const MAX_AHEAD_DAYS = 90; |
| 11 | 11 | |
| 12 | /** The most showings one lead holds at once. */ | |
| 13 | export const MAX_SHOWINGS = 20; | |
| 14 | ||
| 12 | 15 | /** How many upcoming showings the desk lists before "and N more". */ |
| 13 | 16 | export const MAX_LISTED = 5; |
| 14 | 17 | |
| 15 | 18 | const DAY_MS = 86_400_000; |
| 16 | 19 | |
| 17 | /** A showing as stored: one per lead. */ | |
| 20 | /** A showing as stored: a lead may hold several, each at its own time. */ | |
| 18 | 21 | export interface Showing { |
| 22 | readonly id: number; | |
| 19 | 23 | readonly lead_id: number; |
| 20 | 24 | /** When it happens, an ISO instant. */ |
| 21 | 25 | readonly at: string; |
src/terminal.ts +12 −13
| @@ -332,10 +332,11 @@ export function terminal( | ||
| 332 | 332 | ? "wrote back · answer drafted" |
| 333 | 333 | : 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`; |
| 334 | 334 | const name = `${l.starred ? "★ " : ""}${clean(l.name)}`.padEnd(18).slice(0, 18); |
| 335 | const next1 = l.showings[0]; | |
| 335 | 336 | const showing = |
| 336 | l.showing === null | |
| 337 | next1 === undefined | |
| 337 | 338 | ? "" |
| 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)` : ""}`); | |
| 339 | 340 | lines.push( |
| 340 | 341 | `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}${showing}`, |
| 341 | 342 | ); |
| @@ -489,13 +490,11 @@ export function terminal( | ||
| 489 | 490 | ...wrap(r.signature, width).map((s) => dim(` ${s}`)), |
| 490 | 491 | ); |
| 491 | 492 | } |
| 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)}.`)); | |
| 499 | 498 | if (l.back_on !== null) |
| 500 | 499 | lines.push(dim(`Put away until ${dateName(l.back_on)}: no follow-ups; a check-in draft waits that morning at 8:00.`)); |
| 501 | 500 | const sent = l.messages.filter((m) => m.status === "sent").length; |
| @@ -522,8 +521,8 @@ export function terminal( | ||
| 522 | 521 | ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]), |
| 523 | 522 | ...(l.phone === "" ? [] : ["c log a call"]), |
| 524 | 523 | ...(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"]), | |
| 527 | 526 | ...(l.replied_at === null || CLOSED.includes(l.state) ? [] : [l.back_on === null ? "a put away until a date" : "a move the date"]), |
| 528 | 527 | ...(l.back_on === null ? [] : ["A bring back now"]), |
| 529 | 528 | ...(l.state === "qualified" || l.state === "lost" |
| @@ -1045,8 +1044,8 @@ export function terminal( | ||
| 1045 | 1044 | } else if (input === "*" && mayStar(l)) { |
| 1046 | 1045 | const starred = setStarred(db, me, { id, starred: !l.starred }); |
| 1047 | 1046 | 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 }); | |
| 1050 | 1049 | said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message; |
| 1051 | 1050 | } else if (input === "w") |
| 1052 | 1051 | view = { name: "wrote", id, text: "", channel: "email" }; |
static/app.css +14
| @@ -860,3 +860,17 @@ label.check input { | ||
| 860 | 860 | #lead.printing .brief { |
| 861 | 861 | display: block; |
| 862 | 862 | } |
| 863 | ||
| 864 | .showings-booked { | |
| 865 | list-style: none; | |
| 866 | margin: 0 0 var(, 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(, 8px); | |
| 875 | padding: var(, 8px) 0; | |
| 876 | } |
new above
offline