Public: anyone can read this; the crew can change it.
A lead who says "not until spring" can be put away until a date: follow-ups stop, and that morning a check-in draft waits on the desk #80
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/77-a-lead-who-says-not-until-spring-can-be → main 2 commits fork 1 thread · 1 unresolved
20 files
changed +726
−32
AGENTS.md +7
| @@ -128,6 +128,13 @@ Speed to Lead is one realtor's desk. The concepts, one module each: | ||
| 128 | 128 | `AFTER_SHOWING_DAY` + n, one per showing, between the cadence and |
| 129 | 129 | `ANSWER_DAY`); `advance` does not hold it, rebooking before it goes moves it, |
| 130 | 130 | cancelling deletes it, closing skips it. |
| 131 | - Put away: a lead told to come back later (`putAway`/`bringBack` in | |
| 132 | `src/leads.ts`, dates in `src/putaway.ts`). It is the lead's `back_on` field, | |
| 133 | not a state, so lost/qualified are untouched. Unsent cadence touches are | |
| 134 | skipped (not by hand, so `bringBack` schedules them again from now); one | |
| 135 | check-in message numbered `CHECK_IN_DAY` + n (300…399) comes due at 8:00 on | |
| 136 | the date in the agent's zone. Writing back, closing and sending the check-in | |
| 137 | clear it. `inView` keeps a put-away lead out of `needs` and `open`. | |
| 131 | 138 | - `src/drafts.ts` — the words: templates filled from the inquiry and the |
| 132 | 139 | agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*` |
| 133 | 140 | defaults of `agent` in `src/env.ts`; its `openers` are the agent's own |
README.md +24
| @@ -73,6 +73,12 @@ what you see right after a restart. Do step 1 first. | ||
| 73 | 73 | with the showing. The sample **Ethan Brooks** has a showing tomorrow, so |
| 74 | 74 | his confirmation is on a fresh desk. |
| 75 | 75 | A fresh desk also lists upcoming showings above the leads (soonest first, at most five, each linked to its lead): **Aisha Bello** has one in two days. |
| 76 | A lead who says "not until spring" can be put away: on an open lead press | |
| 77 | "Come back on…" and pick a day. Their follow-ups stop, they leave *Needs | |
| 78 | you* and *In follow-up*, and their row (under *All*) says *Back on* that | |
| 79 | day; at 8:00 that morning in your time zone a check-in draft waits for you | |
| 80 | to approve. **Hannah Wright** is already put away for sixty days. "Bring | |
| 81 | back now" clears the day, and so does a lead writing back. | |
| 76 | 82 | 8. Set your profile (admin to save). Press "Your profile" at the top, fill |
| 77 | 83 | in your name, brokerage, license number, phone and email, and save. Every |
| 78 | 84 | draft not yet sent takes it at once. |
| @@ -293,6 +299,24 @@ past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP | ||
| 293 | 299 | tools `book_showing` and `cancel_showing`. It needs the same permission as any |
| 294 | 300 | change to a lead, and shows on the Activity page. |
| 295 | 301 | |
| 302 | **When a lead says "not until spring".** On an open lead whose first reply | |
| 303 | has gone, **Come back on…** takes a day (a calendar day in your profile's time | |
| 304 | zone, from tomorrow to 365 days out). The lead gets a `back_on` date, not a new | |
| 305 | state, so qualified and lost are untouched: follow-ups not yet sent are set | |
| 306 | aside, the lead is in neither *Needs you* nor *In follow-up* (it shows under | |
| 307 | *All* with a *Back on* badge), and at 8:00 that morning in your zone one | |
| 308 | check-in draft ("you said to get back in touch around now…", by the lead's | |
| 309 | channel, signed with your profile, never your private note) comes due for you | |
| 310 | to approve. Nothing is sent without approval. **Bring back now** clears the | |
| 311 | date, removes an unsent check-in and schedules the set-aside follow-ups again | |
| 312 | from today; logging that the lead wrote back, marking them qualified or lost, | |
| 313 | and sending the check-in do the same. The same is `PATCH /leads/:id` with | |
| 314 | `{"back_on": "2027-03-01"}` (`null` brings them back; `422` naming `back_on` | |
| 315 | for a bad date), the MCP tool `put_lead_away`, and `a` (put away) and `A` | |
| 316 | (bring back) on a lead's terminal screen. It needs the same permission as any | |
| 317 | change to a lead, and the Activity page says "put … away until …" and "brought | |
| 318 | … back". | |
| 319 | ||
| 296 | 320 | **Quiet hours.** Texts go out only between 8:00 a.m. and 9:00 p.m. in your |
| 297 | 321 | time zone, the window realtors are told to keep. Approve a text at 11 p.m. |
| 298 | 322 | and the app does not send it: it is approved, held, and the lead's page and |
contract/openapi.json +38 −4
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | "closed", |
| 32 | 32 | "all" |
| 33 | 33 | ], |
| 34 | "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)." | |
| 34 | "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)." | |
| 35 | 35 | } |
| 36 | 36 | }, |
| 37 | 37 | { |
| @@ -168,7 +168,7 @@ | ||
| 168 | 168 | "closed", |
| 169 | 169 | "all" |
| 170 | 170 | ], |
| 171 | "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)." | |
| 171 | "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)." | |
| 172 | 172 | } |
| 173 | 173 | }, |
| 174 | 174 | { |
| @@ -325,7 +325,7 @@ | ||
| 325 | 325 | } |
| 326 | 326 | }, |
| 327 | 327 | "patch": { |
| 328 | "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.", | |
| 328 | "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.", | |
| 329 | 329 | "operationId": "patchLeadsId", |
| 330 | 330 | "parameters": [ |
| 331 | 331 | { |
| @@ -379,6 +379,13 @@ | ||
| 379 | 379 | "type": "string", |
| 380 | 380 | "maxLength": 2000, |
| 381 | 381 | "description": "Empty clears it." |
| 382 | }, | |
| 383 | "back_on": { | |
| 384 | "type": [ | |
| 385 | "string", | |
| 386 | "null" | |
| 387 | ], | |
| 388 | "description": "YYYY-MM-DD: put the lead away until then; null brings it back now." | |
| 382 | 389 | } |
| 383 | 390 | } |
| 384 | 391 | } |
| @@ -387,7 +394,7 @@ | ||
| 387 | 394 | }, |
| 388 | 395 | "responses": { |
| 389 | 396 | "200": { |
| 390 | "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.", | |
| 397 | "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.", | |
| 391 | 398 | "content": { |
| 392 | 399 | "application/json": { |
| 393 | 400 | "schema": { |
| @@ -590,6 +597,14 @@ | ||
| 590 | 597 | "format": "date-time", |
| 591 | 598 | "description": "When the lead was marked lost; null unless it is lost." |
| 592 | 599 | }, |
| 600 | "back_on": { | |
| 601 | "type": [ | |
| 602 | "string", | |
| 603 | "null" | |
| 604 | ], | |
| 605 | "pattern": "^\\d{4}-\\d{2}-\\d{2}$", | |
| 606 | "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away." | |
| 607 | }, | |
| 593 | 608 | "created_at": { |
| 594 | 609 | "type": "string", |
| 595 | 610 | "format": "date-time" |
| @@ -760,6 +775,7 @@ | ||
| 760 | 775 | "state", |
| 761 | 776 | "lostReason", |
| 762 | 777 | "lostAt", |
| 778 | "back_on", | |
| 763 | 779 | "created_at", |
| 764 | 780 | "replied_at", |
| 765 | 781 | "updated_at", |
| @@ -2045,6 +2061,14 @@ | ||
| 2045 | 2061 | "format": "date-time", |
| 2046 | 2062 | "description": "When the lead was marked lost; null unless it is lost." |
| 2047 | 2063 | }, |
| 2064 | "back_on": { | |
| 2065 | "type": [ | |
| 2066 | "string", | |
| 2067 | "null" | |
| 2068 | ], | |
| 2069 | "pattern": "^\\d{4}-\\d{2}-\\d{2}$", | |
| 2070 | "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away." | |
| 2071 | }, | |
| 2048 | 2072 | "created_at": { |
| 2049 | 2073 | "type": "string", |
| 2050 | 2074 | "format": "date-time" |
| @@ -2191,6 +2215,7 @@ | ||
| 2191 | 2215 | "state", |
| 2192 | 2216 | "lostReason", |
| 2193 | 2217 | "lostAt", |
| 2218 | "back_on", | |
| 2194 | 2219 | "created_at", |
| 2195 | 2220 | "replied_at", |
| 2196 | 2221 | "updated_at", |
| @@ -2415,6 +2440,14 @@ | ||
| 2415 | 2440 | "format": "date-time", |
| 2416 | 2441 | "description": "When the lead was marked lost; null unless it is lost." |
| 2417 | 2442 | }, |
| 2443 | "back_on": { | |
| 2444 | "type": [ | |
| 2445 | "string", | |
| 2446 | "null" | |
| 2447 | ], | |
| 2448 | "pattern": "^\\d{4}-\\d{2}-\\d{2}$", | |
| 2449 | "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away." | |
| 2450 | }, | |
| 2418 | 2451 | "created_at": { |
| 2419 | 2452 | "type": "string", |
| 2420 | 2453 | "format": "date-time" |
| @@ -2502,6 +2535,7 @@ | ||
| 2502 | 2535 | "state", |
| 2503 | 2536 | "lostReason", |
| 2504 | 2537 | "lostAt", |
| 2538 | "back_on", | |
| 2505 | 2539 | "created_at", |
| 2506 | 2540 | "replied_at", |
| 2507 | 2541 | "updated_at", |
src/actions.test.ts +4 −1
| @@ -266,7 +266,10 @@ test("the desk's views: each lists exactly its leads, counts add up, a bad value | ||
| 266 | 266 | expect(needs.leads.length).toBeGreaterThan(0); |
| 267 | 267 | expect(open.leads.length).toBeGreaterThan(0); |
| 268 | 268 | expect(closed.leads.length).toBeGreaterThan(0); |
| 269 | expect([...ids(needs), ...ids(open), ...ids(closed)].sort()).toEqual(ids({ leads: everyone }).sort()); | |
| 269 | // A lead put away until a date is in none of the three, only in all. | |
| 270 | const away = everyone.filter((l) => l.back_on !== null); | |
| 271 | expect(away.length).toBe(1); | |
| 272 | expect([...ids(needs), ...ids(open), ...ids(closed), ...ids({ leads: away })].sort()).toEqual(ids({ leads: everyone }).sort()); | |
| 270 | 273 | expect(needs.counts).toEqual({ |
| 271 | 274 | needs: needs.leads.length, |
| 272 | 275 | open: open.leads.length, |
src/actions.ts +55
| @@ -59,6 +59,8 @@ import { | ||
| 59 | 59 | readyFor, |
| 60 | 60 | recordCall, |
| 61 | 61 | bookShowing as bookShowingFor, |
| 62 | bringBack, | |
| 63 | putAway, | |
| 62 | 64 | cancelShowing as cancelShowingFor, |
| 63 | 65 | recordInbound, |
| 64 | 66 | redraftUnsent, |
| @@ -78,6 +80,7 @@ import { nextInquiry, seed } from "./sample.ts"; | ||
| 78 | 80 | import { goesAt, isZone } from "./quiet.ts"; |
| 79 | 81 | import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts"; |
| 80 | 82 | import { MAX_ADDRESS, timeOf } from "./showings.ts"; |
| 83 | import { dateOf } from "./putaway.ts"; | |
| 81 | 84 | import type { Who } from "./who.ts"; |
| 82 | 85 | |
| 83 | 86 | export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid" | "conflict"; |
| @@ -737,6 +740,58 @@ function booked( | ||
| 737 | 740 | return ok(detail(db, lead.id)!); |
| 738 | 741 | } |
| 739 | 742 | |
| 743 | /** | |
| 744 | * Put an open lead away until a day (`back_on`, `YYYY-MM-DD` on the agent's | |
| 745 | * calendar, from tomorrow to 365 days out), or bring it back now (`null`). | |
| 746 | * Follow-ups not yet sent are set aside; that morning at 8:00 a check-in | |
| 747 | * draft waits for the agent to approve. Nothing is sent. | |
| 748 | */ | |
| 749 | export const setBackOn = ( | |
| 750 | db: Database, | |
| 751 | who: Who, | |
| 752 | input: { id: number; back_on: unknown }, | |
| 753 | at?: Date, | |
| 754 | ): Result<LeadDetail> => | |
| 755 | audited( | |
| 756 | db, | |
| 757 | who, | |
| 758 | "lead", | |
| 759 | "update", | |
| 760 | input.id, | |
| 761 | comeBack(db, who, input, at), | |
| 762 | input.back_on === null ? "brought_back" : "put_away", | |
| 763 | typeof input.back_on === "string" ? JSON.stringify({ on: input.back_on.trim() }) : undefined, | |
| 764 | ); | |
| 765 | ||
| 766 | function comeBack( | |
| 767 | db: Database, | |
| 768 | who: Who, | |
| 769 | input: { id: number; back_on: unknown }, | |
| 770 | at?: Date, | |
| 771 | ): Result<LeadDetail> { | |
| 772 | const found = leadFor(db, who, "update", input.id, { | |
| 773 | signIn: "Sign in to put this lead away.", | |
| 774 | no: "You may not put this lead away.", | |
| 775 | }); | |
| 776 | if (!found.ok) return found; | |
| 777 | const lead = found.value; | |
| 778 | const now = stamp(at); | |
| 779 | const agent = currentAgent(db); | |
| 780 | if (input.back_on === null) { | |
| 781 | bringBack(db, lead, now); | |
| 782 | } else { | |
| 783 | const day = dateOf(input.back_on, Date.parse(now), agent.timeZone); | |
| 784 | if ("error" in day) return fail("invalid", `back_on: ${day.error}`); | |
| 785 | if (CLOSED.includes(lead.state)) | |
| 786 | return fail("invalid", "A qualified or lost lead is already out of follow-ups: put it back first."); | |
| 787 | if (lead.replied_at === null) | |
| 788 | return fail("invalid", "Send the first reply before putting a lead away."); | |
| 789 | putAway(db, lead, day.on, now, agent); | |
| 790 | } | |
| 791 | emit("lead.changed", { id: lead.id }); | |
| 792 | return ok(detail(db, lead.id)!); | |
| 793 | } | |
| 794 | ||
| 740 | 795 | /** Take the showing off a lead; the follow-ups held for it return to their usual place. */ |
| 741 | 796 | export const cancelShowing = ( |
| 742 | 797 | db: Database, |
src/audit.ts +2 −2
| @@ -34,8 +34,8 @@ export interface AuditRow { | ||
| 34 | 34 | readonly detail: string | null; |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped"] as const; | |
| 37 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back"] as const; | |
| 39 | 39 | export type Act = (typeof ACTS)[number]; |
| 40 | 40 | |
| 41 | 41 | /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */ |
src/contract.test.ts +10
| @@ -21,6 +21,7 @@ import { | ||
| 21 | 21 | listLeads, |
| 22 | 22 | logCall, |
| 23 | 23 | bookShowing, |
| 24 | setBackOn, | |
| 24 | 25 | cancelHeld, |
| 25 | 26 | restoreFollowUp, |
| 26 | 27 | skipFollowUp, |
| @@ -145,6 +146,12 @@ const doors: Record< | ||
| 145 | 146 | const week = new Date(Date.now() + 7 * 86_400_000).toISOString(); |
| 146 | 147 | const showing = bookShowing(db, who, { id: replied, when: week }).ok; |
| 147 | 148 | const off = cancelShowing(db, who, { id: replied }).ok; |
| 149 | // And so is putting a lead away until a date, and bringing it back (PATCH /leads/:id | |
| 150 | // with back_on, POST /leads/:id/back-on and /bring-back, the MCP tool put_lead_away). | |
| 151 | const away = new Date(Date.now() + 30 * 86_400_000).toISOString().slice(0, 10); | |
| 152 | const putAway = setBackOn(db, who, { id: replied, back_on: away }).ok; | |
| 153 | const awayViaTool = (tools.find((t) => t.name === "put_lead_away")!.run(db, who, { id: replied, back_on: away }) as { ok: boolean }).ok; | |
| 154 | const broughtBack = setBackOn(db, who, { id: replied, back_on: null }).ok; | |
| 148 | 155 | // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id |
| 149 | 156 | // with a name, email or phone, and the MCP tool edit_lead). |
| 150 | 157 | const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok; |
| @@ -173,6 +180,9 @@ const doors: Record< | ||
| 173 | 180 | expect(viaTool).toBe(changed); |
| 174 | 181 | expect(showing).toBe(changed); |
| 175 | 182 | expect(off).toBe(changed); |
| 183 | expect(putAway).toBe(changed); | |
| 184 | expect(awayViaTool).toBe(changed); | |
| 185 | expect(broughtBack).toBe(changed); | |
| 176 | 186 | expect(edited).toBe(changed); |
| 177 | 187 | expect(noted).toBe(changed); |
| 178 | 188 | expect(notedViaTool).toBe(changed); |
src/db.ts +2
| @@ -262,6 +262,8 @@ export const migrations: string[] = [ | ||
| 262 | 262 | `UPDATE lead SET lost_at = updated_at WHERE state = 'lost'`, |
| 263 | 263 | // The agent's follow-up days as JSON, e.g. [1,3,7]. Null means the default (CADENCE). |
| 264 | 264 | `ALTER TABLE profile ADD COLUMN cadence TEXT`, |
| 265 | // The day (YYYY-MM-DD, the agent's calendar) a lead put away is due back; null when it is not put away. | |
| 266 | `ALTER TABLE lead ADD COLUMN back_on TEXT`, | |
| 265 | 267 | ]; |
| 266 | 268 | |
| 267 | 269 | /** |
src/drafts.ts +26 −6
| @@ -55,6 +55,13 @@ export const AFTER_SHOWING_DAY = 500; | ||
| 55 | 55 | * `AFTER_SHOWING_DAY`, so it meets neither. |
| 56 | 56 | */ |
| 57 | 57 | export const BEFORE_SHOWING_DAY = 400; |
| 58 | /** | |
| 59 | * The check-in for a lead put away until a date is numbered from here (300, | |
| 60 | * 301, …, one per time it is put away), above every cadence day and below | |
| 61 | * `BEFORE_SHOWING_DAY`, so it meets neither. | |
| 62 | */ | |
| 63 | export const CHECK_IN_DAY = 300; | |
| 64 | export const isCheckIn = (day: number): boolean => day >= CHECK_IN_DAY && day < BEFORE_SHOWING_DAY; | |
| 58 | 65 | export const isBeforeShowing = (day: number): boolean => |
| 59 | 66 | day >= BEFORE_SHOWING_DAY && day < AFTER_SHOWING_DAY; |
| 60 | 67 | export const isAfterShowing = (day: number): boolean => |
| @@ -66,15 +73,17 @@ export const dayLabel = (day: number): string => | ||
| 66 | 73 | ? "First reply" |
| 67 | 74 | : isAnswer(day) |
| 68 | 75 | ? "Answer to their reply" |
| 69 | : isAfterShowing(day) | |
| 70 | ? "After the showing" | |
| 71 | : isBeforeShowing(day) | |
| 72 | ? "Before the showing" | |
| 73 | : `Day ${day} follow-up`; | |
| 76 | : isCheckIn(day) | |
| 77 | ? "Check-in" | |
| 78 | : isAfterShowing(day) | |
| 79 | ? "After the showing" | |
| 80 | : isBeforeShowing(day) | |
| 81 | ? "Before the showing" | |
| 82 | : `Day ${day} follow-up`; | |
| 74 | 83 | |
| 75 | 84 | /** A message's short name in the follow-up plan: "Day 7", "Before the showing". */ |
| 76 | 85 | export const planLabel = (day: number): string => |
| 77 | isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`; | |
| 86 | isCheckIn(day) ? "Check-in" : isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`; | |
| 78 | 87 | |
| 79 | 88 | export interface Asker { |
| 80 | 89 | readonly name: string; |
| @@ -348,6 +357,17 @@ export function confirmationDraft( | ||
| 348 | 357 | return `Hi ${first},\n\nA quick note before your showing: ${line(address)}\n\nBest,`; |
| 349 | 358 | } |
| 350 | 359 | |
| 360 | /** | |
| 361 | * The morning a lead put away comes back: they said to get in touch around | |
| 362 | * now. Short enough to text; it says nothing of the agent's private note. | |
| 363 | */ | |
| 364 | export function checkInDraft(lead: Asker): string { | |
| 365 | const first = firstName(lead.name); | |
| 366 | const ask = "you said to get back in touch around now, so here I am. Is it still a good time to talk about your search? Just say the word and we'll pick it up."; | |
| 367 | if (channelFor(lead) === "text") return `Hi ${first}, ${ask}`; | |
| 368 | return `Hi ${first},\n\nA quick note: ${ask}\n\nBest,`; | |
| 369 | } | |
| 370 | ||
| 351 | 371 | const AGREES = /\b(yes|yeah|yep|sure|sounds good|works for me|that works|perfect|great)\b/i; |
| 352 | 372 | |
| 353 | 373 | /** |
src/leads.ts +64 −8
| @@ -16,6 +16,9 @@ import { | ||
| 16 | 16 | AFTER_SHOWING_DAY, |
| 17 | 17 | afterShowingDraft, |
| 18 | 18 | BEFORE_SHOWING_DAY, |
| 19 | CHECK_IN_DAY, | |
| 20 | checkInDraft, | |
| 21 | isCheckIn, | |
| 19 | 22 | confirmationDraft, |
| 20 | 23 | isBeforeShowing, |
| 21 | 24 | ANSWER_DAY, |
| @@ -34,6 +37,7 @@ import { GREEN_MS } from "./clock.ts"; | ||
| 34 | 37 | import type { Agent } from "./env.ts"; |
| 35 | 38 | import { isQuiet, nextOpening } from "./quiet.ts"; |
| 36 | 39 | import { type LostReason } from "./lost.ts"; |
| 40 | import { morningOn } from "./putaway.ts"; | |
| 37 | 41 | import { clockTime, dayName, holdUntil, morningAfter, morningBefore, type Showing } from "./showings.ts"; |
| 38 | 42 | |
| 39 | 43 | export type State = "new" | "contacted" | "qualified" | "lost"; |
| @@ -63,6 +67,8 @@ export interface Lead { | ||
| 63 | 67 | readonly lostReason: LostReason | null; |
| 64 | 68 | /** When the lead was marked lost; null unless it is lost. */ |
| 65 | 69 | readonly lostAt: string | null; |
| 70 | /** The day (`YYYY-MM-DD`, the agent's calendar) a lead put away comes back; null when it is not put away. */ | |
| 71 | readonly back_on: string | null; | |
| 66 | 72 | } |
| 67 | 73 | |
| 68 | 74 | export interface Message { |
| @@ -126,14 +132,15 @@ export interface DeskLead extends Lead { | ||
| 126 | 132 | /** |
| 127 | 133 | * Ways to look at the desk. `needs`: a first reply or a follow-up is waiting |
| 128 | 134 | * on the agent. `open`: still in the cadence, nothing waiting. `closed`: |
| 129 | * qualified or lost. `all`: everyone. The first three never overlap. | |
| 135 | * qualified or lost. `all`: everyone. The first three never overlap, and a | |
| 136 | * lead put away until a date is in none of them until its check-in is ready. | |
| 130 | 137 | */ |
| 131 | 138 | export const VIEWS = ["needs", "open", "closed", "all"] as const; |
| 132 | 139 | export type View = (typeof VIEWS)[number]; |
| 133 | 140 | |
| 134 | 141 | /** What a door says about the views, in one place. */ |
| 135 | 142 | export const VIEW_HELP = |
| 136 | "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)."; | |
| 143 | "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)."; | |
| 137 | 144 | |
| 138 | 145 | /** A view from user text; anything unknown is `all`. */ |
| 139 | 146 | export const viewOf = (text: unknown): View => |
| @@ -145,7 +152,7 @@ export const inView = (lead: DeskLead, view: View): boolean => { | ||
| 145 | 152 | case "needs": |
| 146 | 153 | return !closed && lead.ready !== null; |
| 147 | 154 | case "open": |
| 148 | return !closed && lead.ready === null; | |
| 155 | return !closed && lead.ready === null && lead.back_on === null; | |
| 149 | 156 | case "closed": |
| 150 | 157 | return closed; |
| 151 | 158 | case "all": |
| @@ -568,6 +575,8 @@ export function send( | ||
| 568 | 575 | ); |
| 569 | 576 | // Their answer is out: the follow-ups paused for it start again from today. |
| 570 | 577 | if (isAnswer(message.day)) respace(db, found.id, at); |
| 578 | // The check-in is out: the lead is no longer put away, and the follow-ups start again from today. | |
| 579 | if (isCheckIn(message.day)) bringBack(db, found, at); | |
| 571 | 580 | } |
| 572 | 581 | })(); |
| 573 | 582 | } |
| @@ -720,7 +729,7 @@ function respace(db: Database, id: number, at: string): void { | ||
| 720 | 729 | .query<{ id: number; day: number }, [number, number]>( |
| 721 | 730 | "SELECT id, day FROM message WHERE lead_id = ?1 AND status = 'scheduled' AND day < ?2", |
| 722 | 731 | ) |
| 723 | .all(id, BEFORE_SHOWING_DAY); | |
| 732 | .all(id, CHECK_IN_DAY); | |
| 724 | 733 | for (const m of waiting) |
| 725 | 734 | db.query("UPDATE message SET due_at = ?1 WHERE id = ?2").run( |
| 726 | 735 | later(at, m.day), |
| @@ -749,6 +758,8 @@ export function recordInbound( | ||
| 749 | 758 | "INSERT INTO inbound (lead_id, channel, body, at) VALUES (?1, ?2, ?3, ?4) RETURNING id", |
| 750 | 759 | ) |
| 751 | 760 | .get(found.id, channel, body, at)!; |
| 761 | // Writing back is coming back: the lead is no longer put away. | |
| 762 | bringBack(db, found, at); | |
| 752 | 763 | if (answerSince(messagesOf(db, found.id)) === null) { |
| 753 | 764 | db.query( |
| 754 | 765 | "UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due'", |
| @@ -801,6 +812,7 @@ export function redraftUnsent(db: Database, agent: Agent): void { | ||
| 801 | 812 | |
| 802 | 813 | /** The words for an unsent touch or showing note: the cadence's, or the note for the lead's showing as it stands. */ |
| 803 | 814 | const wordsFor = (db: Database, found: Lead, day: number, agent: Agent): string => { |
| 815 | if (isCheckIn(day)) return checkInDraft(found); | |
| 804 | 816 | if (!isAfterShowing(day) && !isBeforeShowing(day)) return draft(found, day, agent); |
| 805 | 817 | const showing = showingOf(db, found.id); |
| 806 | 818 | if (isAfterShowing(day)) return afterShowingDraft(found, showing?.address ?? ""); |
| @@ -904,7 +916,7 @@ export type Closing = { readonly state: "qualified" } | { readonly state: "lost" | ||
| 904 | 916 | export function close(db: Database, id: number, closing: Closing, at: string): void { |
| 905 | 917 | db.transaction(() => { |
| 906 | 918 | db.query( |
| 907 | "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5 WHERE id = ?3", | |
| 919 | "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5, back_on = NULL WHERE id = ?3", | |
| 908 | 920 | ).run( |
| 909 | 921 | closing.state, |
| 910 | 922 | at, |
| @@ -937,7 +949,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi | ||
| 937 | 949 | const channel = channelFor(found); |
| 938 | 950 | const skipped = db |
| 939 | 951 | .query<{ id: number; day: number; due_at: string }, [number, number, number]>( |
| 940 | `SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND skipped_by_hand = 0 AND day < ?2 AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY}) AND NOT (day = 0 AND ?3 = 1)`, | |
| 952 | `SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND skipped_by_hand = 0 AND day < ?2 AND NOT (day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY}) AND NOT (day = 0 AND ?3 = 1)`, | |
| 941 | 953 | ) |
| 942 | 954 | .all(found.id, ANSWER_DAY, replied ? 1 : 0); |
| 943 | 955 | for (const m of skipped) |
| @@ -953,7 +965,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi | ||
| 953 | 965 | ); |
| 954 | 966 | respace(db, found.id, at); |
| 955 | 967 | db.query( |
| 956 | `DELETE FROM message WHERE lead_id = ?1 AND day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`, | |
| 968 | `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`, | |
| 957 | 969 | ).run(found.id); |
| 958 | 970 | const showing = showingOf(db, found.id); |
| 959 | 971 | if (showing !== null) |
| @@ -964,6 +976,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi | ||
| 964 | 976 | /** Why a follow-up cannot be skipped, or null when it can: only its lead's own scheduled or due cadence touches. */ |
| 965 | 977 | export function whyNotSkip(message: Message): string | null { |
| 966 | 978 | if (message.day === 0) return "The first reply is not a follow-up: send it, or close the lead."; |
| 979 | if (isCheckIn(message.day)) return "That is the check-in for a lead put away: bring the lead back instead."; | |
| 967 | 980 | if (message.day >= ANSWER_DAY) return "An answer to something the lead wrote is not a follow-up to skip."; |
| 968 | 981 | if (message.status === "sent") return "That follow-up has already been sent."; |
| 969 | 982 | if (message.status === "held") return "That text is approved and held for 8:00 a.m.: take it back first."; |
| @@ -1017,7 +1030,7 @@ export function advance(db: Database, at: string, only?: number): number[] { | ||
| 1017 | 1030 | `UPDATE message SET status = 'due' |
| 1018 | 1031 | WHERE status = 'scheduled' AND due_at <= ?1 AND (?2 = 0 OR id = ?2) |
| 1019 | 1032 | AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted') |
| 1020 | AND (day >= ${BEFORE_SHOWING_DAY} AND day < ${ANSWER_DAY} | |
| 1033 | AND (day >= ${CHECK_IN_DAY} AND day < ${ANSWER_DAY} | |
| 1021 | 1034 | OR lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1)) |
| 1022 | 1035 | AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY} |
| 1023 | 1036 | AND lead_id IN (SELECT lead_id FROM showing WHERE at <= ?1)) |
| @@ -1167,6 +1180,49 @@ function placeShowingMessage( | ||
| 1167 | 1180 | const reachable = (lead: Pick<Lead, "consent" | "phone" | "email">): boolean => |
| 1168 | 1181 | channelFor(lead) === "text" || lead.email !== ""; |
| 1169 | 1182 | |
| 1183 | /** | |
| 1184 | * The lead is put away until `on` (a `YYYY-MM-DD` on the agent's calendar): | |
| 1185 | * every follow-up not yet sent is set aside, and at 8:00 that morning in the | |
| 1186 | * agent's zone a check-in draft comes due for the agent to approve. Putting | |
| 1187 | * it away again moves the date (and the unsent check-in). | |
| 1188 | */ | |
| 1189 | export function putAway(db: Database, found: Lead, on: string, at: string, agent: Agent): void { | |
| 1190 | db.transaction(() => { | |
| 1191 | db.query("UPDATE lead SET back_on = ?1, updated_at = ?2 WHERE id = ?3").run(on, at, found.id); | |
| 1192 | db.query( | |
| 1193 | `UPDATE message SET status = 'skipped', goes_at = NULL WHERE lead_id = ?1 AND day > 0 AND day < ${CHECK_IN_DAY} AND status IN ('scheduled', 'due')`, | |
| 1194 | ).run(found.id); | |
| 1195 | placeShowingMessage( | |
| 1196 | db, | |
| 1197 | found, | |
| 1198 | CHECK_IN_DAY, | |
| 1199 | BEFORE_SHOWING_DAY, | |
| 1200 | () => checkInDraft(found), | |
| 1201 | morningOn(on, Date.parse(at), agent.timeZone), | |
| 1202 | agent, | |
| 1203 | ); | |
| 1204 | })(); | |
| 1205 | } | |
| 1206 | ||
| 1207 | /** | |
| 1208 | * The lead is no longer put away: its date is cleared, an unsent check-in | |
| 1209 | * goes, and the follow-ups put aside for it are scheduled again from `at` on | |
| 1210 | * the cadence's spacing. Nothing happens to a lead that is not put away. | |
| 1211 | */ | |
| 1212 | export function bringBack(db: Database, found: Lead, at: string): void { | |
| 1213 | if (found.back_on === null) return; | |
| 1214 | db.transaction(() => { | |
| 1215 | db.query("UPDATE lead SET back_on = NULL, updated_at = ?1 WHERE id = ?2").run(at, found.id); | |
| 1216 | db.query( | |
| 1217 | `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${BEFORE_SHOWING_DAY} AND status IN ${UNSENT_SQL}`, | |
| 1218 | ).run(found.id); | |
| 1219 | db.query( | |
| 1220 | `UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND day > 0 AND day < ${CHECK_IN_DAY} AND status = 'skipped' AND skipped_by_hand = 0`, | |
| 1221 | ).run(found.id); | |
| 1222 | respace(db, found.id, at); | |
| 1223 | })(); | |
| 1224 | } | |
| 1225 | ||
| 1170 | 1226 | /** The showing is off: follow-ups whose day has come are due again at once. */ |
| 1171 | 1227 | export function cancelShowing(db: Database, found: Lead, at: string): void { |
| 1172 | 1228 | db.transaction(() => { |
src/mcp.ts +16
| @@ -24,6 +24,7 @@ import { | ||
| 24 | 24 | logCall, |
| 25 | 25 | bookShowing, |
| 26 | 26 | cancelShowing, |
| 27 | setBackOn, | |
| 27 | 28 | restoreFollowUp, |
| 28 | 29 | skipFollowUp, |
| 29 | 30 | logLeadReply, |
| @@ -200,6 +201,21 @@ export const tools: readonly Tool[] = [ | ||
| 200 | 201 | run: (db, who, args) => |
| 201 | 202 | bookShowing(db, who, { id: Number(args.id), when: args.at, address: args.address }), |
| 202 | 203 | }, |
| 204 | { | |
| 205 | name: "put_lead_away", | |
| 206 | description: | |
| 207 | "A lead said 'not until spring': put an open lead away until a day (back_on, YYYY-MM-DD on the agent's calendar, from tomorrow to 365 days out), or bring it back now with back_on null. Unsent follow-ups are set aside, and at 8:00 that morning a check-in draft waits on the desk for approval. Nothing is sent.", | |
| 208 | inputSchema: { | |
| 209 | type: "object", | |
| 210 | properties: { | |
| 211 | id: { type: "integer" }, | |
| 212 | back_on: { type: ["string", "null"], description: "YYYY-MM-DD, or null to bring the lead back now." }, | |
| 213 | }, | |
| 214 | required: ["id", "back_on"], | |
| 215 | }, | |
| 216 | run: (db, who, args) => | |
| 217 | setBackOn(db, who, { id: Number(args.id), back_on: args.back_on === undefined ? "" : args.back_on }), | |
| 218 | }, | |
| 203 | 219 | { |
| 204 | 220 | name: "cancel_showing", |
| 205 | 221 | description: |
src/pages/desk.ts +12 −2
| @@ -7,7 +7,8 @@ import { day, clock, consent, source, STATE_LABEL } from "./parts.ts"; | ||
| 7 | 7 | import { deskTitle, layout } from "./layout.ts"; |
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import { recordLine, sourceLine } from "../clock.ts"; |
| 10 | import { isAfterShowing, isBeforeShowing, isAnswer } from "../drafts.ts"; | |
| 10 | import { isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts"; | |
| 11 | import { dateName } from "../putaway.ts"; | |
| 11 | 12 | import { goesLabel, RECORD_NOTE } from "../quiet.ts"; |
| 12 | 13 | import { MAX_LISTED, showingWhen } from "../showings.ts"; |
| 13 | 14 | import { MAX_EMAIL_TEXT, missingLine } from "../intake.ts"; |
| @@ -176,6 +177,11 @@ const showingBadge = (lead: DeskLead, now: number, zone: string): string => | ||
| 176 | 177 | ["Showing", showingWhen(lead.showing.at, now, zone), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "), |
| 177 | 178 | )}</span>`; |
| 178 | 179 | |
| 180 | const backBadge = (lead: DeskLead): string => | |
| 181 | lead.back_on === null || (lead.ready !== null && isCheckIn(lead.ready.day)) | |
| 182 | ? "" | |
| 183 | : `<span class="badge" data-back title="Put away: no follow-ups until then, when a check-in draft waits for you">${escape(`Back on ${dateName(lead.back_on)}`)}</span>`; | |
| 184 | ||
| 179 | 185 | function status(lead: DeskLead, now: number, zone: string): string { |
| 180 | 186 | if (lead.state === "qualified" || lead.state === "lost") |
| 181 | 187 | return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`; |
| @@ -185,8 +191,12 @@ function status(lead: DeskLead, now: number, zone: string): string { | ||
| 185 | 191 | return `<span class="status" data-ready>Reply drafted — approve and send</span>`; |
| 186 | 192 | if (lead.ready !== null && isAnswer(lead.ready.day)) |
| 187 | 193 | return `<span class="status" data-ready>They wrote back — answer drafted</span>`; |
| 194 | if (lead.ready !== null && isCheckIn(lead.ready.day)) | |
| 195 | return `<span class="status" data-ready>Check-in ready — they asked you to come back</span>`; | |
| 188 | 196 | if (lead.ready !== null) |
| 189 | 197 | return `<span class="status" data-ready>${isBeforeShowing(lead.ready.day) ? "Before the showing — confirmation ready" : isAfterShowing(lead.ready.day) ? "After the showing — note ready" : `Day ${lead.ready.day} follow-up ready`}</span>`; |
| 198 | if (lead.back_on !== null) | |
| 199 | return `<span class="status">Put away until ${escape(dateName(lead.back_on))}</span>`; | |
| 190 | 200 | if (lead.next_at !== null) |
| 191 | 201 | return `<span class="status">Next follow-up ${escape(day(held(lead, lead.next_at), zone))}</span>`; |
| 192 | 202 | return `<span class="status">Follow-ups done</span>`; |
| @@ -197,7 +207,7 @@ const row = (lead: DeskLead, now: number, zone: string): string => `<li> | ||
| 197 | 207 | <span class="lead-main"> |
| 198 | 208 | <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : ` |
| 199 | 209 | <span class="note-line">${escape(noteLine(lead.note))}</span>`} |
| 200 | <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}</span> | |
| 210 | <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}${backBadge(lead)}</span> | |
| 201 | 211 | <span class="ask">${escape(lead.message)}</span> |
| 202 | 212 | ${status(lead, now, zone)} |
| 203 | 213 | </span> |
src/pages/lead.ts +21
| @@ -8,6 +8,7 @@ import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts"; | ||
| 8 | 8 | import { channelFor, dayLabel, isAnswer, planLabel, MAX_BODY } from "../drafts.ts"; |
| 9 | 9 | import { escape } from "../http.ts"; |
| 10 | 10 | import { handoff } from "../handoff.ts"; |
| 11 | import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts"; | |
| 11 | 12 | import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen } from "../showings.ts"; |
| 12 | 13 | import { elapsed, between } from "../clock.ts"; |
| 13 | 14 | import { goesLabel, isQuiet, nextOpening } from "../quiet.ts"; |
| @@ -254,6 +255,25 @@ export function leadPage(input: { | ||
| 254 | 255 | </details>` |
| 255 | 256 | : ""; |
| 256 | 257 | |
| 258 | const tomorrow = today(now + 86_400_000, agent.timeZone); | |
| 259 | const furthest = today(now + MAX_AWAY_DAYS * 86_400_000, agent.timeZone); | |
| 260 | const away = | |
| 261 | mayUpdate && !closed && lead.replied_at !== null | |
| 262 | ? `<details class="card add record" id="come-back"${lead.back_on === null ? "" : " open"}> | |
| 263 | <summary>${lead.back_on === null ? "Come back on…" : `Back on ${escape(dateName(lead.back_on))}`}</summary> | |
| 264 | <form class="stack" method="post" action="${path}/back-on"> | |
| 265 | <label>Day (${escape(agent.timeZone)}) <input class="input" type="date" name="back_on" required min="${tomorrow}" max="${furthest}"${lead.back_on === null ? "" : ` value="${escape(lead.back_on)}"`}></label> | |
| 266 | <p class="hint">Unsent follow-ups are set aside. That morning at 8:00 a check-in draft waits on the desk for you to approve; nothing is sent until you do.</p> | |
| 267 | <button class="button">${lead.back_on === null ? "Put away until then" : "Move the date"}</button> | |
| 268 | </form>${ | |
| 269 | lead.back_on === null | |
| 270 | ? "" | |
| 271 | : ` | |
| 272 | <form method="post" action="${path}/bring-back"><button class="button button-quiet">Bring back now</button></form>` | |
| 273 | } | |
| 274 | </details>` | |
| 275 | : ""; | |
| 276 | ||
| 257 | 277 | const stop = |
| 258 | 278 | mayUpdate && lead.consent |
| 259 | 279 | ? `<section class="states"> |
| @@ -304,6 +324,7 @@ export function leadPage(input: { | ||
| 304 | 324 | ${thread} |
| 305 | 325 | ${call} |
| 306 | 326 | ${showing} |
| 327 | ${away} | |
| 307 | 328 | ${record} |
| 308 | 329 | ${details} |
| 309 | 330 | ${plan} |
src/put-away.test.ts added +246
| @@ -0,0 +1,246 @@ | ||
| 1 | /** | |
| 2 | * A lead who says "not until spring" is put away until a date: unsent | |
| 3 | * follow-ups are set aside, and at 8:00 that morning in the agent's zone a | |
| 4 | * check-in draft waits for approval. Writing back or "bring back now" ends it. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { addLead, getLead, listLeads, logLeadReply, sendReply, setBackOn, setNote, setState, skipFollowUp, turn } from "./actions.ts"; | |
| 11 | import { openDb } from "./db.ts"; | |
| 12 | import { CHECK_IN_DAY, BEFORE_SHOWING_DAY } from "./drafts.ts"; | |
| 13 | import { dateOf, morningOn } from "./putaway.ts"; | |
| 14 | import { activityPage } from "./pages/activity.ts"; | |
| 15 | import { deskPage } from "./pages/desk.ts"; | |
| 16 | import { currentAgent, storeAgent } from "./profile.ts"; | |
| 17 | import { seed } from "./sample.ts"; | |
| 18 | import { terminal, plain } from "./terminal.ts"; | |
| 19 | import type { Who } from "./who.ts"; | |
| 20 | ||
| 21 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 22 | const anon = { role: "anon" } as Who; | |
| 23 | const T0 = new Date("2026-03-01T10:00:00Z"); | |
| 24 | const DAY = 86_400_000; | |
| 25 | const at = (days: number) => new Date(T0.getTime() + days * DAY); | |
| 26 | ||
| 27 | const fresh = (zone = "UTC") => { | |
| 28 | const db = openDb(mkdtempSync(join(tmpdir(), "app-away-"))); | |
| 29 | storeAgent(db, { ...currentAgent(db), timeZone: zone }, "test", T0.toISOString()); | |
| 30 | return db; | |
| 31 | }; | |
| 32 | const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => { | |
| 33 | if (!r.ok) throw new Error(r.message); | |
| 34 | return r.value as T; | |
| 35 | }; | |
| 36 | const answered = (db: ReturnType<typeof fresh>, consent = false) => { | |
| 37 | const id = value( | |
| 38 | addLead(db, alice, { | |
| 39 | name: "Dana Reyes", | |
| 40 | email: "[email protected]", | |
| 41 | phone: "(206) 555-0111", | |
| 42 | source: "zillow", | |
| 43 | message: "Can I see 12 Oak Street?", | |
| 44 | consent, | |
| 45 | }, T0), | |
| 46 | ).id; | |
| 47 | value(sendReply(db, alice, { id }, T0)); | |
| 48 | return id; | |
| 49 | }; | |
| 50 | const lead = (db: ReturnType<typeof fresh>, id: number) => value(getLead(db, alice, { id })); | |
| 51 | const checkIns = (db: ReturnType<typeof fresh>, id: number) => | |
| 52 | lead(db, id).messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY); | |
| 53 | const view = (db: ReturnType<typeof fresh>, show: string) => | |
| 54 | value(listLeads(db, alice, { show })).leads.map((l) => l.name); | |
| 55 | ||
| 56 | test("the date is checked at the boundary, on the agent's calendar", () => { | |
| 57 | const now = T0.getTime(); | |
| 58 | expect(dateOf("2026-03-02", now, "UTC")).toEqual({ on: "2026-03-02" }); | |
| 59 | expect(dateOf("2027-03-01", now, "UTC")).toEqual({ on: "2027-03-01" }); | |
| 60 | for (const bad of ["2026-03-01", "2026-02-28", "2027-03-02", "2026-02-30", "2026-3-5", "tomorrow", "", 20260305, null, {}, "2026-03-05T10:00"]) | |
| 61 | expect("error" in dateOf(bad, now, "UTC")).toBe(true); | |
| 62 | // 02:00 UTC on Mar 2 is still Mar 1 in Los Angeles: Mar 2 is then tomorrow, not today. | |
| 63 | const late = Date.parse("2026-03-02T02:00:00Z"); | |
| 64 | expect("error" in dateOf("2026-03-02", late, "UTC")).toBe(true); | |
| 65 | expect(dateOf("2026-03-02", late, "America/Los_Angeles")).toEqual({ on: "2026-03-02" }); | |
| 66 | expect(morningOn("2026-03-05", now, "America/Los_Angeles")).toBe("2026-03-05T16:00:00.000Z"); | |
| 67 | }); | |
| 68 | ||
| 69 | test("putting a lead away sets the follow-ups aside and takes it out of Needs you and In follow-up", () => { | |
| 70 | const db = fresh(); | |
| 71 | const id = answered(db); | |
| 72 | expect(view(db, "open")).toEqual(["Dana Reyes"]); | |
| 73 | const away = value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 74 | expect(away.back_on).toBe("2026-05-01"); | |
| 75 | expect(away.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY).every((m) => m.status === "skipped")).toBe(true); | |
| 76 | expect(view(db, "needs")).toEqual([]); | |
| 77 | expect(view(db, "open")).toEqual([]); | |
| 78 | expect(view(db, "all")).toEqual(["Dana Reyes"]); | |
| 79 | // Nothing comes due, however long it is left. | |
| 80 | turn(db, at(30)); | |
| 81 | expect(lead(db, id).messages.some((m) => m.status === "due" && m.day < CHECK_IN_DAY)).toBe(false); | |
| 82 | expect(view(db, "needs")).toEqual([]); | |
| 83 | }); | |
| 84 | ||
| 85 | test("the desk row carries a Back on badge", () => { | |
| 86 | const db = fresh(); | |
| 87 | const id = answered(db); | |
| 88 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 89 | const desk = value(listLeads(db, alice, { show: "all" })); | |
| 90 | const html = deskPage({ who: alice, agent: currentAgent(db), leads: desk.leads, record: desk.record, show: "all", counts: desk.counts, mayAdd: true, mayReset: false }); | |
| 91 | expect(html).toContain("Back on May 1, 2026"); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a check-in draft waits at 8:00 that morning in the agent's zone, and not before", () => { | |
| 95 | const db = fresh("America/Los_Angeles"); | |
| 96 | const id = answered(db); | |
| 97 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 98 | const [check] = checkIns(db, id); | |
| 99 | expect(check!.due_at).toBe("2026-05-01T15:00:00.000Z"); | |
| 100 | expect(check!.status).toBe("scheduled"); | |
| 101 | turn(db, new Date("2026-05-01T14:59:00Z")); | |
| 102 | expect(checkIns(db, id)[0]!.status).toBe("scheduled"); | |
| 103 | expect(view(db, "needs")).toEqual([]); | |
| 104 | turn(db, new Date("2026-05-01T15:00:00Z")); | |
| 105 | expect(checkIns(db, id)[0]!.status).toBe("due"); | |
| 106 | expect(view(db, "needs")).toEqual(["Dana Reyes"]); | |
| 107 | expect(checkIns(db, id)).toHaveLength(1); | |
| 108 | }); | |
| 109 | ||
| 110 | test("the check-in speaks of coming back, is signed, goes by the lead's channel and never shows the private note", () => { | |
| 111 | const db = fresh(); | |
| 112 | const id = answered(db, true); | |
| 113 | value(setNote(db, alice, { id, note: "SECRET budget is tight" }, T0)); | |
| 114 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 115 | const [check] = checkIns(db, id); | |
| 116 | expect(check!.channel).toBe("text"); | |
| 117 | expect(check!.body).toContain("Hi Dana"); | |
| 118 | expect(check!.body).toContain("get back in touch around now"); | |
| 119 | expect(check!.body).not.toContain("SECRET"); | |
| 120 | expect(check!.signature).not.toBe(""); | |
| 121 | const plan = lead(db, id); | |
| 122 | expect(plan.messages.some((m) => m.day === 0 && m.status === "sent")).toBe(true); | |
| 123 | }); | |
| 124 | ||
| 125 | test("nothing is sent without approval; approving sends it and brings the lead back into follow-ups", () => { | |
| 126 | const db = fresh(); | |
| 127 | const id = answered(db); | |
| 128 | value(setBackOn(db, alice, { id, back_on: "2026-03-10" }, at(1))); | |
| 129 | turn(db, at(20)); | |
| 130 | expect(checkIns(db, id)[0]!.status).toBe("due"); | |
| 131 | value(sendReply(db, alice, { id }, at(20))); | |
| 132 | const after = lead(db, id); | |
| 133 | expect(checkIns(db, id)[0]!.status).toBe("sent"); | |
| 134 | expect(after.back_on).toBeNull(); | |
| 135 | const follow = after.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY); | |
| 136 | expect(follow.every((m) => m.status === "scheduled")).toBe(true); | |
| 137 | expect(Date.parse(follow[0]!.due_at)).toBe(at(20).getTime() + DAY); | |
| 138 | }); | |
| 139 | ||
| 140 | test("Bring back now clears the date, deletes the check-in and schedules the follow-ups again", () => { | |
| 141 | const db = fresh(); | |
| 142 | const id = answered(db); | |
| 143 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 144 | const back = value(setBackOn(db, alice, { id, back_on: null }, at(2))); | |
| 145 | expect(back.back_on).toBeNull(); | |
| 146 | expect(checkIns(db, id)).toHaveLength(0); | |
| 147 | expect(back.messages.filter((m) => m.day > 0).every((m) => m.status === "scheduled")).toBe(true); | |
| 148 | expect(view(db, "open")).toEqual(["Dana Reyes"]); | |
| 149 | }); | |
| 150 | ||
| 151 | test("a follow-up skipped by hand stays skipped through put away and bring back", () => { | |
| 152 | const db = fresh(); | |
| 153 | const id = answered(db); | |
| 154 | const three = lead(db, id).messages.find((m) => m.day === 3)!; | |
| 155 | value(skipFollowUp(db, alice, { id, messageId: three.id }, at(0.5))); | |
| 156 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 157 | const back = value(setBackOn(db, alice, { id, back_on: null }, at(2))); | |
| 158 | expect(back.messages.find((m) => m.day === 3)!.status).toBe("skipped"); | |
| 159 | expect(back.messages.find((m) => m.day === 7)!.status).toBe("scheduled"); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a lead writing back clears the date", () => { | |
| 163 | const db = fresh(); | |
| 164 | const id = answered(db); | |
| 165 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 166 | const wrote = value(logLeadReply(db, alice, { id, body: "Actually, we're ready now.", channel: "email" }, at(2))); | |
| 167 | expect(wrote.back_on).toBeNull(); | |
| 168 | expect(wrote.messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY)).toHaveLength(0); | |
| 169 | expect(wrote.messages.some((m) => m.day >= 1000 && m.status === "draft")).toBe(true); | |
| 170 | expect(view(db, "open")).toEqual([]); | |
| 171 | expect(view(db, "needs")).toEqual(["Dana Reyes"]); | |
| 172 | }); | |
| 173 | ||
| 174 | test("putting away again moves the date and the one check-in; closing clears it for good", () => { | |
| 175 | const db = fresh(); | |
| 176 | const id = answered(db); | |
| 177 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 178 | value(setBackOn(db, alice, { id, back_on: "2026-06-01" }, at(2))); | |
| 179 | expect(checkIns(db, id)).toHaveLength(1); | |
| 180 | expect(checkIns(db, id)[0]!.due_at.slice(0, 10)).toBe("2026-06-01"); | |
| 181 | const lost = value(setState(db, alice, { id, state: "lost", reason: "not_ready" }, at(3))); | |
| 182 | expect(lost.back_on).toBeNull(); | |
| 183 | const reopened = value(setState(db, alice, { id, state: "open" }, at(4))); | |
| 184 | expect(reopened.messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY)).toHaveLength(0); | |
| 185 | expect(reopened.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY).every((m) => m.status === "scheduled")).toBe(true); | |
| 186 | }); | |
| 187 | ||
| 188 | test("a bad date is refused naming the field; a lead not yet answered or closed cannot be put away", () => { | |
| 189 | const db = fresh(); | |
| 190 | const id = answered(db); | |
| 191 | const bad = setBackOn(db, alice, { id, back_on: "2026-03-01" }, at(0)); | |
| 192 | expect(!bad.ok && bad.error === "invalid" && bad.message.startsWith("back_on:")).toBe(true); | |
| 193 | const fresher = value(addLead(db, alice, { name: "New Person", email: "[email protected]", phone: "", source: "website", message: "Hi", consent: false }, T0)).id; | |
| 194 | expect(setBackOn(db, alice, { id: fresher, back_on: "2026-05-01" }, at(1)).ok).toBe(false); | |
| 195 | value(setState(db, alice, { id, state: "qualified" }, at(1))); | |
| 196 | expect(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)).ok).toBe(false); | |
| 197 | }); | |
| 198 | ||
| 199 | test("it is a lead update: a visitor is refused", () => { | |
| 200 | const db = fresh(); | |
| 201 | const id = answered(db); | |
| 202 | const refused = setBackOn(db, anon, { id, back_on: "2026-05-01" }, at(1)); | |
| 203 | expect(!refused.ok && refused.error).toBe("signin_required"); | |
| 204 | expect(lead(db, id).back_on).toBeNull(); | |
| 205 | }); | |
| 206 | ||
| 207 | test("the Activity page says who put a lead away until when, and who brought it back", () => { | |
| 208 | const db = fresh(); | |
| 209 | const id = answered(db); | |
| 210 | value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1))); | |
| 211 | value(setBackOn(db, alice, { id, back_on: null }, at(2))); | |
| 212 | const rows = db.query("SELECT * FROM audit ORDER BY id").all() as never[]; | |
| 213 | const html = activityPage({ who: alice, agent: currentAgent(db), rows, names: new Map([[id, "Dana Reyes"]]), older: undefined, lost: [], sentOnly: false }); | |
| 214 | expect(html).toContain("put <a href=\"/leads/" + id + "\">Dana Reyes</a> away until May 1, 2026"); | |
| 215 | expect(html).toContain("brought <a href=\"/leads/" + id + "\">Dana Reyes</a> back"); | |
| 216 | }); | |
| 217 | ||
| 218 | test("one sample lead is already put away", () => { | |
| 219 | const db = fresh(); | |
| 220 | seed(db, T0); | |
| 221 | const away = value(listLeads(db, alice, { show: "all" })).leads.filter((l) => l.back_on !== null); | |
| 222 | expect(away.map((l) => l.name)).toEqual(["Hannah Wright"]); | |
| 223 | expect(away[0]!.back_on! > "2026-03-01").toBe(true); | |
| 224 | }); | |
| 225 | ||
| 226 | test("the terminal's lead screen puts a lead away with a, and brings it back with A", () => { | |
| 227 | const db = fresh(); | |
| 228 | const id = answered(db); | |
| 229 | const t = terminal(db, alice); | |
| 230 | t.key("\r"); | |
| 231 | expect(t.screen(100).map(plain).join("\n")).toContain("a put away until a date"); | |
| 232 | t.key("a"); | |
| 233 | for (const ch of "2020-01-01") t.key(ch); | |
| 234 | t.key("\r"); | |
| 235 | expect(t.screen(100).map(plain).join("\n")).toContain("Pick a day from tomorrow on."); | |
| 236 | const on = new Date(Date.now() + 30 * DAY).toISOString().slice(0, 10); | |
| 237 | for (let i = 0; i < 10; i++) t.key("\x7f"); | |
| 238 | for (const ch of on) t.key(ch); | |
| 239 | t.key("\r"); | |
| 240 | const shown = t.screen(100).map(plain).join("\n"); | |
| 241 | expect(shown).toContain("Put away until"); | |
| 242 | expect(lead(db, id).back_on).toBe(on); | |
| 243 | expect(shown).toContain("A bring back now"); | |
| 244 | t.key("A"); | |
| 245 | expect(lead(db, id).back_on).toBeNull(); | |
| 246 | }); |
src/putaway.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | /** | |
| 2 | * Putting a lead away until a date: "call me in March". The date is a | |
| 3 | * calendar day on the agent's wall clock (their profile's time zone, never | |
| 4 | * the server's); that morning at 8:00 a check-in draft waits on the desk. | |
| 5 | * Nothing here is sent anywhere. | |
| 6 | */ | |
| 7 | ||
| 8 | import { localInput, wallAt } from "./showings.ts"; | |
| 9 | ||
| 10 | /** How far ahead a lead may be put away. */ | |
| 11 | export const MAX_AWAY_DAYS = 365; | |
| 12 | ||
| 13 | const DAY_MS = 86_400_000; | |
| 14 | const DATE = /^(\d{4})-(\d{2})-(\d{2})$/; | |
| 15 | ||
| 16 | /** The calendar day of `ms` on the wall clock of `zone`: `YYYY-MM-DD`. */ | |
| 17 | export const today = (ms: number, zone: string): string => localInput(ms, zone).slice(0, 10); | |
| 18 | ||
| 19 | /** Whole days from the calendar day `from` to `to`, both `YYYY-MM-DD`. */ | |
| 20 | const daysBetween = (from: string, to: string): number => | |
| 21 | Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS); | |
| 22 | ||
| 23 | /** | |
| 24 | * A come-back date from user text: a real `YYYY-MM-DD`, at least tomorrow | |
| 25 | * and at most 365 days out, counted on the agent's calendar in `zone`. | |
| 26 | */ | |
| 27 | export function dateOf( | |
| 28 | text: unknown, | |
| 29 | now: number, | |
| 30 | zone: string, | |
| 31 | ): { on: string } | { error: string } { | |
| 32 | const bad = { error: "A come-back date is a day, like 2027-03-01." }; | |
| 33 | if (typeof text !== "string") return bad; | |
| 34 | const m = DATE.exec(text.trim()); | |
| 35 | if (m === null) return bad; | |
| 36 | const [y, mo, d] = [+m[1]!, +m[2]!, +m[3]!]; | |
| 37 | // Date.parse rolls 02-30 over to March; a real date reads back as itself. | |
| 38 | const real = new Date(Date.UTC(y, mo - 1, d)); | |
| 39 | if (real.getUTCFullYear() !== y || real.getUTCMonth() !== mo - 1 || real.getUTCDate() !== d) return bad; | |
| 40 | const on = text.trim(); | |
| 41 | const away = daysBetween(today(now, zone), on); | |
| 42 | if (away < 1) return { error: "Pick a day from tomorrow on." }; | |
| 43 | if (away > MAX_AWAY_DAYS) return { error: `Pick a day within ${MAX_AWAY_DAYS} days.` }; | |
| 44 | return { on }; | |
| 45 | } | |
| 46 | ||
| 47 | /** When the check-in on `on` comes due: 8:00 that morning in `zone`, the agent's. */ | |
| 48 | export function morningOn(on: string, now: number, zone: string): string { | |
| 49 | const days = daysBetween(today(now, zone), on); | |
| 50 | return new Date(wallAt(now, days, 8, zone) ?? Date.parse(`${on}T08:00:00Z`)).toISOString(); | |
| 51 | } | |
| 52 | ||
| 53 | /** "Mar 1, 2027": a come-back date said plainly. */ | |
| 54 | export const dateName = (on: string): string => | |
| 55 | new Date(`${on}T12:00:00Z`).toLocaleDateString("en-US", { | |
| 56 | month: "short", | |
| 57 | day: "numeric", | |
| 58 | year: "numeric", | |
| 59 | timeZone: "UTC", | |
| 60 | }); |
src/routes.ts +41 −4
| @@ -38,6 +38,7 @@ import { | ||
| 38 | 38 | logCall, |
| 39 | 39 | bookShowing, |
| 40 | 40 | cancelShowing, |
| 41 | setBackOn, | |
| 41 | 42 | restoreFollowUp, |
| 42 | 43 | skipFollowUp, |
| 43 | 44 | logLeadReply, |
| @@ -175,6 +176,11 @@ const LEAD_FIELDS = { | ||
| 175 | 176 | format: "date-time", |
| 176 | 177 | description: "When the lead was marked lost; null unless it is lost.", |
| 177 | 178 | }, |
| 179 | back_on: { | |
| 180 | type: ["string", "null"], | |
| 181 | pattern: "^\\d{4}-\\d{2}-\\d{2}$", | |
| 182 | description: "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away.", | |
| 183 | }, | |
| 178 | 184 | created_at: STAMP, |
| 179 | 185 | replied_at: { type: ["string", "null"], format: "date-time" }, |
| 180 | 186 | updated_at: STAMP, |
| @@ -501,6 +507,11 @@ const REASON_FIELD = { | ||
| 501 | 507 | description: "Why the lead is lost; required when state is lost.", |
| 502 | 508 | } as const; |
| 503 | 509 | |
| 510 | const BACK_ON_FIELD = { | |
| 511 | type: ["string", "null"], | |
| 512 | description: "YYYY-MM-DD: put the lead away until then; null brings it back now.", | |
| 513 | } as const; | |
| 514 | ||
| 504 | 515 | const NOTE_FIELD = { |
| 505 | 516 | type: "string", |
| 506 | 517 | maxLength: MAX_LEAD_NOTE, |
| @@ -726,11 +737,13 @@ export const routes: readonly Route[] = [ | ||
| 726 | 737 | // One change at a time: a mark, or a correction of the details. |
| 727 | 738 | const details = CONTACT.some((field) => input[field] !== undefined); |
| 728 | 739 | const noted = input.note !== undefined; |
| 729 | if ([details, noted, input.state !== undefined].filter(Boolean).length > 1) | |
| 740 | const away = input.back_on !== undefined; | |
| 741 | if ([details, noted, away, input.state !== undefined].filter(Boolean).length > 1) | |
| 730 | 742 | return json( |
| 731 | { error: "invalid", message: "Send one change at a time: a state, details to correct, or a note." }, | |
| 743 | { error: "invalid", message: "Send one change at a time: a state, details to correct, a note, or a come-back date." }, | |
| 732 | 744 | 422, |
| 733 | 745 | ); |
| 746 | if (away) return answer(setBackOn(c.db, c.who, { id: ID(c), back_on: input.back_on })); | |
| 734 | 747 | if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note })); |
| 735 | 748 | if (details) |
| 736 | 749 | return answer(editLead(c.db, c.who, { id: ID(c), ...contactOf(input) })); |
| @@ -738,10 +751,10 @@ export const routes: readonly Route[] = [ | ||
| 738 | 751 | }, |
| 739 | 752 | api: { |
| 740 | 753 | summary: |
| 741 | "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.", | |
| 754 | "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.", | |
| 742 | 755 | body: { |
| 743 | 756 | type: "object", |
| 744 | properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD }, | |
| 757 | properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD, back_on: BACK_ON_FIELD }, | |
| 745 | 758 | }, |
| 746 | 759 | answer: LEAD, |
| 747 | 760 | }, |
| @@ -884,6 +897,30 @@ export const routes: readonly Route[] = [ | ||
| 884 | 897 | answer: LEAD, |
| 885 | 898 | }, |
| 886 | 899 | }, |
| 900 | { | |
| 901 | // The page's forms for `back_on` on PATCH: a form can only post. | |
| 902 | method: "POST", | |
| 903 | path: "/leads/:id/back-on", | |
| 904 | handle: (c) => | |
| 905 | posted( | |
| 906 | c, | |
| 907 | (input) => setBackOn(c.db, c.who, { id: ID(c), back_on: input.back_on }), | |
| 908 | (lead) => ({ | |
| 909 | to: `/leads/${ID(c)}`, | |
| 910 | said: `Put away until ${lead?.back_on ?? "the day you chose"}. Nothing goes until then.`, | |
| 911 | }), | |
| 912 | ), | |
| 913 | }, | |
| 914 | { | |
| 915 | method: "POST", | |
| 916 | path: "/leads/:id/bring-back", | |
| 917 | handle: (c) => | |
| 918 | posted( | |
| 919 | c, | |
| 920 | () => setBackOn(c.db, c.who, { id: ID(c), back_on: null }), | |
| 921 | () => ({ to: `/leads/${ID(c)}`, said: "Brought back." }), | |
| 922 | ), | |
| 923 | }, | |
| 887 | 924 | { |
| 888 | 925 | method: "DELETE", |
| 889 | 926 | path: "/leads/:id/showing", |
src/sample.ts +9 −1
| @@ -11,9 +11,11 @@ import type { Database } from "bun:sqlite"; | ||
| 11 | 11 | import type { Source } from "./drafts.ts"; |
| 12 | 12 | import { morningAfter, wallAt } from "./showings.ts"; |
| 13 | 13 | import { currentAgent } from "./profile.ts"; |
| 14 | import { today } from "./putaway.ts"; | |
| 14 | 15 | import { |
| 15 | 16 | advance, |
| 16 | 17 | bookShowing, |
| 18 | putAway, | |
| 17 | 19 | close, |
| 18 | 20 | findLead, |
| 19 | 21 | insertLead, |
| @@ -36,6 +38,8 @@ interface Sample extends NewLead { | ||
| 36 | 38 | readonly showedAgo?: number; |
| 37 | 39 | /** A showing booked ahead: this many days from today at 10:00 in the agent's zone. */ |
| 38 | 40 | readonly showingInDays?: number; |
| 41 | /** Put away until this many days from today, on the agent's calendar: "call me in the spring". */ | |
| 42 | readonly awayInDays?: number; | |
| 39 | 43 | /** The agent's private note on the lead, as of the first reply or the inquiry. */ |
| 40 | 44 | readonly note?: string; |
| 41 | 45 | } |
| @@ -78,7 +82,7 @@ export const SAMPLES: readonly Sample[] = [ | ||
| 78 | 82 | person("Rosa Alvarez", "referral", false, "My cousin Elena recommended you. We need a bigger place before the baby comes in March.", { ago: 4 * D + 2 * H, answeredIn: 3 * M + 20 * S, touched: [1], showedAgo: D }), |
| 79 | 83 | person("Ethan Brooks", "realtor_com", true, "What would my 2-bed condo on Seaview Ave sell for? Considering upsizing next year.", { ago: 8 * D + 5 * H, answeredIn: 2 * M + 5 * S, touched: [1, 3], showingInDays: 1 }), |
| 80 | 84 | person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: { state: "qualified" } }), |
| 81 | person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14] }), | |
| 85 | person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14], awayInDays: 60 }), | |
| 82 | 86 | person("Owen Hart", "zillow", false, "Is 55 Cedar Ln still on the market? We'd like a second showing.", { ago: 9 * D, answeredIn: 2 * M + 40 * S, touched: [1, 3], closed: { state: "lost", reason: "bought_elsewhere" } }), |
| 83 | 87 | person("Nadia Petrov", "website", true, "We might sell, but not before our kids finish school in two years. What should we do now?", { ago: 12 * D, answeredIn: 3 * M + 5 * S, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }), |
| 84 | 88 | person("Carl Dunn", "referral", false, "A friend gave me your name. Call me about listing the duplex.", { ago: 20 * D, answeredIn: 5 * M, touched: [1, 3, 7], closed: { state: "lost", reason: "never_answered" } }), |
| @@ -113,6 +117,10 @@ export function seed(db: Database, now: Date): number { | ||
| 113 | 117 | const ahead = wallAt(t, sample.showingInDays, 10, agent.timeZone) ?? t + sample.showingInDays * D; |
| 114 | 118 | bookShowing(db, findLead(db, id)!, iso(ahead), "27 Alder Ct", iso(asked), agent); |
| 115 | 119 | } |
| 120 | if (sample.awayInDays !== undefined) { | |
| 121 | const agent = currentAgent(db); | |
| 122 | putAway(db, findLead(db, id)!, today(t + sample.awayInDays * D, agent.timeZone), iso(t), agent); | |
| 123 | } | |
| 116 | 124 | if (sample.note !== undefined) |
| 117 | 125 | writeNote(db, findLead(db, id)!, sample.note, iso(asked + 30 * M)); |
| 118 | 126 | if (sample.closed !== undefined) close(db, id, sample.closed, iso(t - 2 * D)); |
src/sentences.ts +23
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { readMergeDetail, type AuditRow } from "./audit.ts"; |
| 9 | import { dateName } from "./putaway.ts"; | |
| 9 | 10 | import { SOURCE_LABEL, type Source } from "./drafts.ts"; |
| 10 | 11 | |
| 11 | 12 | /** What a correction changed, as ": phone “a” → “b”, …"; "" when the row names nothing readable. */ |
| @@ -32,6 +33,16 @@ function mergeWords(detail: string | null, esc: (text: string) => string): strin | ||
| 32 | 33 | return label === undefined ? "" : ` (via ${esc(label)})`; |
| 33 | 34 | } |
| 34 | 35 | |
| 36 | /** A put-away's date: " until Mar 1, 2027"; "" when the row names none. */ | |
| 37 | function awayWords(detail: string | null, esc: (text: string) => string): string { | |
| 38 | try { | |
| 39 | const { on } = JSON.parse(detail ?? "") as { on?: unknown }; | |
| 40 | return typeof on === "string" && /^\d{4}-\d{2}-\d{2}$/.test(on) ? ` until ${esc(dateName(on))}` : ""; | |
| 41 | } catch { | |
| 42 | return ""; | |
| 43 | } | |
| 44 | } | |
| 45 | ||
| 35 | 46 | export function deed( |
| 36 | 47 | row: AuditRow, |
| 37 | 48 | lead: string, |
| @@ -77,6 +88,18 @@ export function deed( | ||
| 77 | 88 | tried: skip ? `skip a follow-up to ${lead}` : `bring back a skipped follow-up to ${lead}`, |
| 78 | 89 | }; |
| 79 | 90 | } |
| 91 | if (row.act === "put_away") { | |
| 92 | const on = awayWords(row.detail, esc); | |
| 93 | return { | |
| 94 | done: `put ${lead} away${on}`, | |
| 95 | tried: `put ${lead} away`, | |
| 96 | }; | |
| 97 | } | |
| 98 | if (row.act === "brought_back") | |
| 99 | return { | |
| 100 | done: `brought ${lead} back`, | |
| 101 | tried: `bring ${lead} back`, | |
| 102 | }; | |
| 80 | 103 | if (row.act === "qualified" || row.act === "lost") |
| 81 | 104 | return { |
| 82 | 105 | done: `marked ${lead} ${row.act}`, |
src/server.test.ts +27
| @@ -257,6 +257,32 @@ test("POST /leads/:id/state and PATCH /leads/:id: qualified or lost leaves the c | ||
| 257 | 257 | ).toBe(422); |
| 258 | 258 | }); |
| 259 | 259 | |
| 260 | test("PATCH /leads/:id with back_on puts a lead away (null brings it back); a bad date is a 422 naming the field", async () => { | |
| 261 | const one = await created({ ...NEW, name: "Not Until Spring" }); | |
| 262 | await api(`/leads/${one.id}/reply`, { method: "POST", ...jsonBody({}) }, alice); | |
| 263 | const tomorrow = new Date(Date.now() + 2 * 86_400_000).toISOString().slice(0, 10); | |
| 264 | const away = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow }) }, alice); | |
| 265 | expect(away.status).toBe(200); | |
| 266 | const put = (await away.json()) as Lead & { back_on: string | null }; | |
| 267 | expect(put.back_on).toBe(tomorrow); | |
| 268 | expect(put.messages.some((m) => m.day === 300 && m.status === "scheduled")).toBe(true); | |
| 269 | const bad = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: "2020-01-01" }) }, alice); | |
| 270 | expect(bad.status).toBe(422); | |
| 271 | expect(((await bad.json()) as { message: string }).message).toContain("back_on"); | |
| 272 | expect((await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow, note: "x" }) }, alice)).status).toBe(422); | |
| 273 | expect((await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow }) })).status).toBe(401); | |
| 274 | const back = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: null }) }, alice); | |
| 275 | expect(((await back.json()) as { back_on: string | null }).back_on).toBeNull(); | |
| 276 | // The page's forms reach the same actions. | |
| 277 | const form1 = await api(`/leads/${one.id}/back-on`, { method: "POST", body: form({ back_on: tomorrow }), redirect: "manual" }, alice); | |
| 278 | expect(form1.status).toBe(303); | |
| 279 | expect((await lead(one.id) as Lead & { back_on: string | null }).back_on).toBe(tomorrow); | |
| 280 | const page = await (await api(`/leads/${one.id}`, {}, alice)).text(); | |
| 281 | expect(page).toContain("Bring back now"); | |
| 282 | expect((await api(`/leads/${one.id}/bring-back`, { method: "POST", body: form({}), redirect: "manual" }, alice)).status).toBe(303); | |
| 283 | expect((await lead(one.id) as Lead & { back_on: string | null }).back_on).toBeNull(); | |
| 284 | }); | |
| 285 | ||
| 260 | 286 | test("POST /tick: the day turns for whoever may update leads; a stranger may not", async () => { |
| 261 | 287 | const ticked = await api("/tick", { method: "POST", ...jsonBody({}) }, alice); |
| 262 | 288 | expect(ticked.status).toBe(200); |
| @@ -299,6 +325,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 299 | 325 | "log_lead_reply", |
| 300 | 326 | "log_call", |
| 301 | 327 | "book_showing", |
| 328 | "put_lead_away", | |
| 302 | 329 | "cancel_showing", |
| 303 | 330 | "mark_lead", |
| 304 | 331 | "edit_lead", |
src/terminal.ts +39 −4
| @@ -45,6 +45,7 @@ import { | ||
| 45 | 45 | logCall, |
| 46 | 46 | bookShowing, |
| 47 | 47 | cancelShowing, |
| 48 | setBackOn, | |
| 48 | 49 | logLeadReply, |
| 49 | 50 | nextLead, |
| 50 | 51 | parseLeadEmail, |
| @@ -53,13 +54,14 @@ import { | ||
| 53 | 54 | CADENCE_MAX_TOUCHES, |
| 54 | 55 | } from "./actions.ts"; |
| 55 | 56 | import { missingLine } from "./intake.ts"; |
| 57 | import { dateName, MAX_AWAY_DAYS } from "./putaway.ts"; | |
| 56 | 58 | import { showingLine, showingWhen } from "./showings.ts"; |
| 57 | 59 | import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts"; |
| 58 | 60 | import { between, elapsed, recordLine, sourceLine, tone } from "./clock.ts"; |
| 59 | 61 | import { permit } from "./contract.ts"; |
| 60 | 62 | import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts"; |
| 61 | 63 | import { said as saidOf } from "./sentences.ts"; |
| 62 | import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, planLabel, type Channel, type Source } from "./drafts.ts"; | |
| 64 | import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, planLabel, type Channel, type Source } from "./drafts.ts"; | |
| 63 | 65 | import { ssh, title, where } from "./env.ts"; |
| 64 | 66 | import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts"; |
| 65 | 67 | import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts"; |
| @@ -161,6 +163,7 @@ type View = | ||
| 161 | 163 | | { name: "edit"; id: number; text: string } |
| 162 | 164 | | { name: "call"; id: number; outcome: Outcome; text: string } |
| 163 | 165 | | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string } |
| 166 | | { name: "away"; id: number; typed: string } | |
| 164 | 167 | | { name: "wrote"; id: number; text: string; channel: Channel } |
| 165 | 168 | | { name: "note"; id: number; text: string } |
| 166 | 169 | | { name: "lost"; id: number } |
| @@ -276,12 +279,12 @@ export function terminal( | ||
| 276 | 279 | l.goes_at !== null |
| 277 | 280 | ? dim(goesLabel(l.goes_at, now(), zone)) |
| 278 | 281 | : l.ready === null |
| 279 | ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "") | |
| 282 | ? dim(l.state === "qualified" || l.state === "lost" ? l.state : l.back_on !== null ? `back on ${dateName(l.back_on)}` : "") | |
| 280 | 283 | : l.ready.day === 0 |
| 281 | 284 | ? "reply drafted" |
| 282 | 285 | : isAnswer(l.ready.day) |
| 283 | 286 | ? "wrote back · answer drafted" |
| 284 | : 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`; | |
| 287 | : 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`; | |
| 285 | 288 | const name = clean(l.name).padEnd(18).slice(0, 18); |
| 286 | 289 | const showing = |
| 287 | 290 | l.showing === null |
| @@ -407,6 +410,8 @@ export function terminal( | ||
| 407 | 410 | ? [dim(` Follow-ups due before it wait until ${showingWhen(l.showing.hold_until, now(), currentAgent(db).timeZone)}.`)] |
| 408 | 411 | : []), |
| 409 | 412 | ); |
| 413 | if (l.back_on !== null) | |
| 414 | lines.push(dim(`Put away until ${dateName(l.back_on)}: no follow-ups; a check-in draft waits that morning at 8:00.`)); | |
| 410 | 415 | const sent = l.messages.filter((m) => m.status === "sent").length; |
| 411 | 416 | for (const c of l.calls) |
| 412 | 417 | lines.push(dim(`${callLine(c.outcome)} — ${c.at.slice(0, 16).replace("T", " ")}${c.note === "" ? "" : `: ${clean(c.note)}`}`)); |
| @@ -431,6 +436,8 @@ export function terminal( | ||
| 431 | 436 | ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []), |
| 432 | 437 | ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]), |
| 433 | 438 | ...(l.showing === null || CLOSED.includes(l.state) ? [] : ["u cancel the showing"]), |
| 439 | ...(l.replied_at === null || CLOSED.includes(l.state) ? [] : [l.back_on === null ? "a put away until a date" : "a move the date"]), | |
| 440 | ...(l.back_on === null ? [] : ["A bring back now"]), | |
| 434 | 441 | ...(l.state === "qualified" || l.state === "lost" |
| 435 | 442 | ? ["o put back in follow-ups"] |
| 436 | 443 | : ["q qualified", "x lost"]), |
| @@ -616,6 +623,14 @@ export function terminal( | ||
| 616 | 623 | "", |
| 617 | 624 | dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"), |
| 618 | 625 | ] |
| 626 | : view.name === "away" | |
| 627 | ? [ | |
| 628 | bold(`Put ${clean(lead(view.id)?.name ?? "the lead")} away`), | |
| 629 | "", | |
| 630 | `Back on (YYYY-MM-DD, your calendar, from tomorrow to ${MAX_AWAY_DAYS} days out): ${clean(view.typed)}█`, | |
| 631 | "", | |
| 632 | dim("Unsent follow-ups are set aside; that morning at 8:00 a check-in draft waits for you. enter save · esc cancel"), | |
| 633 | ] | |
| 619 | 634 | : view.name === "showing" |
| 620 | 635 | ? [ |
| 621 | 636 | bold(`A showing with ${clean(lead(view.id)?.name ?? "the lead")}`), |
| @@ -811,7 +826,12 @@ export function terminal( | ||
| 811 | 826 | view = { name: "call", id, outcome: "talked", text: "" }; |
| 812 | 827 | else if (input === "b" && !CLOSED.includes(l.state)) |
| 813 | 828 | view = { name: "showing", id, step: 0, typed: "", when: "" }; |
| 814 | else if (input === "u" && l.showing !== null) { | |
| 829 | else if (input === "a" && l.replied_at !== null && !CLOSED.includes(l.state)) | |
| 830 | view = { name: "away", id, typed: l.back_on ?? "" }; | |
| 831 | else if (input === "A" && l.back_on !== null) { | |
| 832 | const back = setBackOn(db, me, { id, back_on: null }); | |
| 833 | said = back.ok ? `${l.name}: brought back. Follow-ups are scheduled again.` : back.message; | |
| 834 | } else if (input === "u" && l.showing !== null) { | |
| 815 | 835 | const off = cancelShowing(db, me, { id }); |
| 816 | 836 | said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message; |
| 817 | 837 | } else if (input === "w") |
| @@ -841,6 +861,21 @@ export function terminal( | ||
| 841 | 861 | } |
| 842 | 862 | return; |
| 843 | 863 | } |
| 864 | case "away": { | |
| 865 | if (input === "\x1b") { | |
| 866 | said = "Not put away."; | |
| 867 | view = { name: "lead", id: view.id }; | |
| 868 | } else if (input === "\r") { | |
| 869 | const away = setBackOn(db, me, { id: view.id, back_on: view.typed }); | |
| 870 | said = away.ok ? `Put away until ${dateName(view.typed.trim())}. A check-in draft waits that morning.` : away.message; | |
| 871 | // A refused date is typed again; anything else goes back to the lead. | |
| 872 | if (away.ok || away.error !== "invalid") view = { name: "lead", id: view.id }; | |
| 873 | } else { | |
| 874 | const next = typing(view.typed, input); | |
| 875 | if (next !== undefined) view = { ...view, typed: next }; | |
| 876 | } | |
| 877 | return; | |
| 878 | } | |
| 844 | 879 | case "showing": { |
| 845 | 880 | if (input === "\x1b") { |
| 846 | 881 | said = "No showing booked."; |
new above
offline
Add this door (setBackOn) to the role table in src/contract.test.ts, alongside bookShowing/cancelShowing.