Public: anyone can read this; the crew can change it.
A text approved late at night waits until 8 a.m. and the desk says when it will go #44
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/42-a-text-approved-late-at-night-waits-unti → main 3 commits fork
24 files
changed +942
−76
README.md +21 −2
| @@ -203,6 +203,24 @@ past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP | ||
| 203 | 203 | tools `book_showing` and `cancel_showing`. It needs the same permission as any |
| 204 | 204 | change to a lead, and shows on the Activity page. |
| 205 | 205 | |
| 206 | **Quiet hours.** Texts go out only between 8:00 a.m. and 9:00 p.m. in your | |
| 207 | time zone, the window realtors are told to keep. Approve a text at 11 p.m. | |
| 208 | and the app does not send it: it is approved, held, and the lead's page and | |
| 209 | the desk say "Goes at 8:00 a.m. tomorrow". It goes by itself soon after 8:00 | |
| 210 | (the app checks every five minutes), and until then **Cancel and keep as a | |
| 211 | draft** takes it back. If the lead replies STOP before it goes, it never goes | |
| 212 | as a text: it becomes an email draft. Emails are never held. A held text | |
| 213 | counts as your reply from the moment you approve it, not from when it goes, | |
| 214 | and the line under your response record says so. Set your time zone on | |
| 215 | **Your profile** (an IANA name such as `America/Chicago`; until you do it is | |
| 216 | `AGENT_TIMEZONE`, then `TZ`, then `America/New_York`). A script sees it as | |
| 217 | `scheduledFor` in the answer to `POST /leads/:id/reply` and takes the text | |
| 218 | back with `POST /leads/:id/unhold`; MCP has `send_reply` and | |
| 219 | `cancel_held_text`; in the terminal, `h` on the lead. `QUIET_HOURS=off` lets | |
| 220 | texts go at any hour (the test suite sets it). The 8:00 delivery is done by | |
| 221 | the clock, not by a person, so it is not audited: Activity shows the text as | |
| 222 | `held` (and the cancel), but never the send itself. | |
| 223 | ||
| 206 | 224 | **Sample leads.** The app starts with twelve sample leads so you can see it |
| 207 | 225 | work: two just in, two waiting a while, three gone red, and five already |
| 208 | 226 | answered and partway through their follow-ups. An admin can restart them |
| @@ -241,12 +259,13 @@ Avery of Harbor & Pine Realty. Once a profile is saved it wins. | ||
| 241 | 259 | | `AGENT_LICENSE` | your license number, as shown | |
| 242 | 260 | | `AGENT_PHONE` | the phone number in your emails | |
| 243 | 261 | | `AGENT_EMAIL` | the email address in your emails | |
| 262 | | `AGENT_TIMEZONE` | your time zone, for quiet hours (falls back to `TZ`) | | |
| 244 | 263 | |
| 245 | 264 | In the terminal, press `p` on the desk to read it; an admin presses `e` |
| 246 | 265 | and types each field in turn (enter moves on, the last one saves). |
| 247 | 266 | |
| 248 | 267 | A script reads it with `GET /profile` and an admin changes it with |
| 249 | `POST /profile` (JSON, all five fields); MCP has `get_profile` and | |
| 268 | `POST /profile` (JSON, the five fields and optionally `timeZone`); MCP has `get_profile` and | |
| 250 | 269 | `set_profile`. |
| 251 | 270 | |
| 252 | 271 | ## For whoever connects it to a website |
| @@ -274,7 +293,7 @@ emails, phones and messages are plain text: anything carrying control | ||
| 274 | 293 | characters is turned away. `POST /tick` is safe to call as often as you |
| 275 | 294 | like, but only as someone the forge has signed in — an unsigned scheduled |
| 276 | 295 | job gets "sign in first". Nothing depends on it: the app does the same |
| 277 | itself every hour. The whole API is described at `/openapi.json`, and the same | |
| 296 | itself every five minutes. The whole API is described at `/openapi.json`, and the same | |
| 278 | 297 | actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`, |
| 279 | 298 | `send_reply`, `mark_lead`, `export_leads`). |
| 280 | 299 |
bunfig.toml added +2
| @@ -0,0 +1,2 @@ | ||
| 1 | [test] | |
| 2 | preload = ["./src/test-setup.ts"] |
contract/openapi.json +94 −7
| @@ -373,7 +373,7 @@ | ||
| 373 | 373 | }, |
| 374 | 374 | "/leads/{id}/reply": { |
| 375 | 375 | "post": { |
| 376 | "summary": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 376 | "summary": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.", | |
| 377 | 377 | "operationId": "postLeadsIdReply", |
| 378 | 378 | "parameters": [ |
| 379 | 379 | { |
| @@ -405,7 +405,7 @@ | ||
| 405 | 405 | }, |
| 406 | 406 | "responses": { |
| 407 | 407 | "200": { |
| 408 | "description": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 408 | "description": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.", | |
| 409 | 409 | "content": { |
| 410 | 410 | "application/json": { |
| 411 | 411 | "schema": { |
| @@ -608,6 +608,11 @@ | ||
| 608 | 608 | "id", |
| 609 | 609 | "name" |
| 610 | 610 | ] |
| 611 | }, | |
| 612 | "scheduledFor": { | |
| 613 | "type": "string", | |
| 614 | "format": "date-time", | |
| 615 | "description": "Present only when the text was held for quiet hours: when it will go (the next 8:00 a.m. in your time zone). Absent when it went now." | |
| 611 | 616 | } |
| 612 | 617 | }, |
| 613 | 618 | "required": [ |
| @@ -1001,6 +1006,44 @@ | ||
| 1001 | 1006 | } |
| 1002 | 1007 | } |
| 1003 | 1008 | }, |
| 1009 | "/leads/{id}/unhold": { | |
| 1010 | "post": { | |
| 1011 | "summary": "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.", | |
| 1012 | "operationId": "postLeadsIdUnhold", | |
| 1013 | "parameters": [ | |
| 1014 | { | |
| 1015 | "name": "id", | |
| 1016 | "in": "path", | |
| 1017 | "required": true, | |
| 1018 | "schema": { | |
| 1019 | "type": "integer" | |
| 1020 | } | |
| 1021 | } | |
| 1022 | ], | |
| 1023 | "responses": { | |
| 1024 | "200": { | |
| 1025 | "description": "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.", | |
| 1026 | "content": { | |
| 1027 | "application/json": { | |
| 1028 | "schema": { | |
| 1029 | "$ref": "#/components/schemas/Lead" | |
| 1030 | } | |
| 1031 | } | |
| 1032 | } | |
| 1033 | }, | |
| 1034 | "default": { | |
| 1035 | "description": "{ error, message }: why not", | |
| 1036 | "content": { | |
| 1037 | "application/json": { | |
| 1038 | "schema": { | |
| 1039 | "$ref": "#/components/schemas/Error" | |
| 1040 | } | |
| 1041 | } | |
| 1042 | } | |
| 1043 | } | |
| 1044 | } | |
| 1045 | } | |
| 1046 | }, | |
| 1004 | 1047 | "/leads/{id}/opt-out": { |
| 1005 | 1048 | "post": { |
| 1006 | 1049 | "summary": "They replied STOP: no more texts to this lead, for good. Every unsent draft becomes an email; sent messages stay as they were. No body needed; asking twice changes nothing.", |
| @@ -1041,11 +1084,11 @@ | ||
| 1041 | 1084 | }, |
| 1042 | 1085 | "/tick": { |
| 1043 | 1086 | "post": { |
| 1044 | "summary": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 1087 | "summary": "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.", | |
| 1045 | 1088 | "operationId": "postTick", |
| 1046 | 1089 | "responses": { |
| 1047 | 1090 | "200": { |
| 1048 | "description": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 1091 | "description": "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.", | |
| 1049 | 1092 | "content": { |
| 1050 | 1093 | "application/json": { |
| 1051 | 1094 | "schema": { |
| @@ -1144,6 +1187,11 @@ | ||
| 1144 | 1187 | "email": { |
| 1145 | 1188 | "type": "string", |
| 1146 | 1189 | "format": "email" |
| 1190 | }, | |
| 1191 | "timeZone": { | |
| 1192 | "type": "string", | |
| 1193 | "maxLength": 60, | |
| 1194 | "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is." | |
| 1147 | 1195 | } |
| 1148 | 1196 | }, |
| 1149 | 1197 | "required": [ |
| @@ -1152,7 +1200,8 @@ | ||
| 1152 | 1200 | "brokerage", |
| 1153 | 1201 | "license", |
| 1154 | 1202 | "phone", |
| 1155 | "email" | |
| 1203 | "email", | |
| 1204 | "timeZone" | |
| 1156 | 1205 | ] |
| 1157 | 1206 | } |
| 1158 | 1207 | } |
| @@ -1203,6 +1252,11 @@ | ||
| 1203 | 1252 | "email": { |
| 1204 | 1253 | "type": "string", |
| 1205 | 1254 | "format": "email" |
| 1255 | }, | |
| 1256 | "timeZone": { | |
| 1257 | "type": "string", | |
| 1258 | "maxLength": 60, | |
| 1259 | "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is." | |
| 1206 | 1260 | } |
| 1207 | 1261 | }, |
| 1208 | 1262 | "required": [ |
| @@ -1250,6 +1304,11 @@ | ||
| 1250 | 1304 | "email": { |
| 1251 | 1305 | "type": "string", |
| 1252 | 1306 | "format": "email" |
| 1307 | }, | |
| 1308 | "timeZone": { | |
| 1309 | "type": "string", | |
| 1310 | "maxLength": 60, | |
| 1311 | "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is." | |
| 1253 | 1312 | } |
| 1254 | 1313 | }, |
| 1255 | 1314 | "required": [ |
| @@ -1258,7 +1317,8 @@ | ||
| 1258 | 1317 | "brokerage", |
| 1259 | 1318 | "license", |
| 1260 | 1319 | "phone", |
| 1261 | "email" | |
| 1320 | "email", | |
| 1321 | "timeZone" | |
| 1262 | 1322 | ] |
| 1263 | 1323 | } |
| 1264 | 1324 | } |
| @@ -1870,6 +1930,14 @@ | ||
| 1870 | 1930 | ], |
| 1871 | 1931 | "format": "date-time" |
| 1872 | 1932 | }, |
| 1933 | "goes_at": { | |
| 1934 | "type": [ | |
| 1935 | "string", | |
| 1936 | "null" | |
| 1937 | ], | |
| 1938 | "format": "date-time", | |
| 1939 | "description": "When a text you approved goes, if one is held for quiet hours." | |
| 1940 | }, | |
| 1873 | 1941 | "showing": { |
| 1874 | 1942 | "type": [ |
| 1875 | 1943 | "object", |
| @@ -1908,6 +1976,7 @@ | ||
| 1908 | 1976 | "updated_at", |
| 1909 | 1977 | "ready", |
| 1910 | 1978 | "next_at", |
| 1979 | "goes_at", | |
| 1911 | 1980 | "showing" |
| 1912 | 1981 | ] |
| 1913 | 1982 | }, |
| @@ -1944,9 +2013,11 @@ | ||
| 1944 | 2013 | "draft", |
| 1945 | 2014 | "scheduled", |
| 1946 | 2015 | "due", |
| 2016 | "held", | |
| 1947 | 2017 | "sent", |
| 1948 | 2018 | "skipped" |
| 1949 | ] | |
| 2019 | ], | |
| 2020 | "description": "held: a text you approved outside 8:00 a.m. to 9:00 p.m. in your time zone; it goes at goes_at." | |
| 1950 | 2021 | }, |
| 1951 | 2022 | "due_at": { |
| 1952 | 2023 | "type": "string", |
| @@ -1964,6 +2035,22 @@ | ||
| 1964 | 2035 | "string", |
| 1965 | 2036 | "null" |
| 1966 | 2037 | ] |
| 2038 | }, | |
| 2039 | "goes_at": { | |
| 2040 | "type": [ | |
| 2041 | "string", | |
| 2042 | "null" | |
| 2043 | ], | |
| 2044 | "format": "date-time", | |
| 2045 | "description": "For a held text, when it goes." | |
| 2046 | }, | |
| 2047 | "approved_at": { | |
| 2048 | "type": [ | |
| 2049 | "string", | |
| 2050 | "null" | |
| 2051 | ], | |
| 2052 | "format": "date-time", | |
| 2053 | "description": "For a held text, when you approved it: the moment that counts as the reply." | |
| 1967 | 2054 | } |
| 1968 | 2055 | }, |
| 1969 | 2056 | "required": [ |
src/actions.ts +65 −16
| @@ -25,6 +25,11 @@ import { | ||
| 25 | 25 | inView, |
| 26 | 26 | queryOf, |
| 27 | 27 | reopen, |
| 28 | heldFor, | |
| 29 | hold, | |
| 30 | release, | |
| 31 | sendHeld, | |
| 32 | messagesOf, | |
| 28 | 33 | MAX_INBOUND, |
| 29 | 34 | MAX_QUERY, |
| 30 | 35 | insertLead, |
| @@ -51,6 +56,7 @@ import { | ||
| 51 | 56 | import { emit } from "./live.ts"; |
| 52 | 57 | import { currentAgent, storeAgent } from "./profile.ts"; |
| 53 | 58 | import { nextInquiry, seed } from "./sample.ts"; |
| 59 | import { goesAt, isZone } from "./quiet.ts"; | |
| 54 | 60 | import { MAX_ADDRESS, timeOf } from "./showings.ts"; |
| 55 | 61 | import type { Who } from "./who.ts"; |
| 56 | 62 | |
| @@ -383,15 +389,10 @@ export const sendReply = ( | ||
| 383 | 389 | at?: Date, |
| 384 | 390 | ): Result<LeadDetail> => { |
| 385 | 391 | const first = findLead(db, input.id)?.replied_at === null; |
| 386 | return audited( | |
| 387 | db, | |
| 388 | who, | |
| 389 | "lead", | |
| 390 | "update", | |
| 391 | input.id, | |
| 392 | reply(db, who, input, at), | |
| 393 | first ? "first_reply" : "reply", | |
| 394 | ); | |
| 392 | const ready = readyFor(db, input.id)?.id; | |
| 393 | const result = reply(db, who, input, at); | |
| 394 | const held = result.ok && result.value.messages.some((m) => m.id === ready && m.status === "held"); | |
| 395 | return audited(db, who, "lead", "update", input.id, result, held ? "held" : first ? "first_reply" : "reply"); | |
| 395 | 396 | }; |
| 396 | 397 | |
| 397 | 398 | /** |
| @@ -409,6 +410,8 @@ export const nextLead = ( | ||
| 409 | 410 | /** A sent reply, and the lead to open next: the id and name, or null. */ |
| 410 | 411 | export type Approved = LeadDetail & { |
| 411 | 412 | readonly next: { readonly id: number; readonly name: string } | null; |
| 413 | /** When the text will go, if it was held for quiet hours; absent when it went now. */ | |
| 414 | readonly scheduledFor?: string; | |
| 412 | 415 | }; |
| 413 | 416 | |
| 414 | 417 | /** `sendReply`, and which lead needs the agent after it. */ |
| @@ -418,12 +421,15 @@ export const approveReply = ( | ||
| 418 | 421 | input: { id: number; body?: string | undefined }, |
| 419 | 422 | at?: Date, |
| 420 | 423 | ): Result<Approved> => { |
| 424 | const before = readyFor(db, input.id)?.id; | |
| 421 | 425 | const sent = sendReply(db, who, input, at); |
| 422 | 426 | if (!sent.ok) return sent; |
| 423 | 427 | const next = nextLead(db, who, { except: input.id }); |
| 428 | const held = sent.value.messages.find((m) => m.id === before && m.status === "held"); | |
| 424 | 429 | return ok({ |
| 425 | 430 | ...sent.value, |
| 426 | 431 | next: next === null ? null : { id: next.id, name: next.name }, |
| 432 | ...(held?.goes_at ? { scheduledFor: held.goes_at } : {}), | |
| 427 | 433 | }); |
| 428 | 434 | }; |
| 429 | 435 | |
| @@ -453,7 +459,42 @@ function reply( | ||
| 453 | 459 | if (ready.channel === "email" && found.value.email === "") |
| 454 | 460 | return fail("invalid", "This lead has no email address and has not agreed to be texted: add one, or call them."); |
| 455 | 461 | const by = who.role === "anon" ? "" : who.name; |
| 456 | send(db, found.value, ready, body, by, stamp(at), currentAgent(db)); | |
| 462 | const now = stamp(at); | |
| 463 | const agent = currentAgent(db); | |
| 464 | // A text outside quiet hours is approved now and goes at the next 8:00. | |
| 465 | const goes = goesAt(ready.channel, now, agent.timeZone); | |
| 466 | if (goes === null) send(db, found.value, ready, body, by, now, agent); | |
| 467 | else hold(db, found.value, ready, body, by, now, goes); | |
| 468 | emit("lead.changed", { id: found.value.id }); | |
| 469 | return ok(detail(db, found.value.id)!); | |
| 470 | } | |
| 471 | ||
| 472 | /** | |
| 473 | * Take back a text held for quiet hours: it returns to an unsent draft the | |
| 474 | * agent can edit and approve again, and the lead is as unanswered as before. | |
| 475 | */ | |
| 476 | export const cancelHeld = ( | |
| 477 | db: Database, | |
| 478 | who: Who, | |
| 479 | input: { id: number }, | |
| 480 | at?: Date, | |
| 481 | ): Result<LeadDetail> => | |
| 482 | audited(db, who, "lead", "update", input.id, unhold(db, who, input, at), "unhold"); | |
| 483 | ||
| 484 | function unhold( | |
| 485 | db: Database, | |
| 486 | who: Who, | |
| 487 | input: { id: number }, | |
| 488 | at?: Date, | |
| 489 | ): Result<LeadDetail> { | |
| 490 | const found = leadFor(db, who, "update", input.id, { | |
| 491 | signIn: "Sign in to cancel a text.", | |
| 492 | no: "You may not cancel a text for this lead.", | |
| 493 | }); | |
| 494 | if (!found.ok) return found; | |
| 495 | const held = heldFor(db, found.value.id); | |
| 496 | if (held === null) return fail("invalid", "No text is waiting for 8:00 a.m. on this lead."); | |
| 497 | release(db, held, stamp(at)); | |
| 457 | 498 | emit("lead.changed", { id: found.value.id }); |
| 458 | 499 | return ok(detail(db, found.value.id)!); |
| 459 | 500 | } |
| @@ -718,9 +759,9 @@ function remove( | ||
| 718 | 759 | } |
| 719 | 760 | |
| 720 | 761 | /** |
| 721 | * The day turns: every touch whose day has come is due, ready to approve. | |
| 762 | * The day turns: every touch whose day has come is due, ready to approve, and every text held for quiet hours whose time has come goes out. | |
| 722 | 763 | * The forge may call it daily (`POST /tick`); the server also runs it on |
| 723 | * its own every hour, so a missed call costs nothing. Running it twice | |
| 764 | * its own every five minutes (a held text goes within minutes of 8:00), so a missed call costs nothing. Running it twice | |
| 724 | 765 | * changes nothing the second time. |
| 725 | 766 | */ |
| 726 | 767 | export function tick( |
| @@ -744,7 +785,9 @@ export function tick( | ||
| 744 | 785 | |
| 745 | 786 | /** The clock's own turn, asked of no one: time passing is not a person. */ |
| 746 | 787 | export function turn(db: Database, at?: Date): number[] { |
| 747 | const leads = advance(db, stamp(at)); | |
| 788 | const now = stamp(at); | |
| 789 | const sent = sendHeld(db, now, currentAgent(db)); | |
| 790 | const leads = [...new Set([...advance(db, now), ...sent])]; | |
| 748 | 791 | for (const id of leads) emit("lead.changed", { id }); |
| 749 | 792 | return leads; |
| 750 | 793 | } |
| @@ -793,7 +836,10 @@ export function getProfile(db: Database, who: Who): Result<Profile> { | ||
| 793 | 836 | } |
| 794 | 837 | |
| 795 | 838 | /** What arrived for the profile, checked field by field: the agent to keep, or what is wrong. */ |
| 796 | export function readAgent(input: Record<string, unknown>): Result<Agent> { | |
| 839 | export function readAgent( | |
| 840 | input: Record<string, unknown>, | |
| 841 | keep: string, | |
| 842 | ): Result<Agent> { | |
| 797 | 843 | const text = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); |
| 798 | 844 | const name = text(input.name); |
| 799 | 845 | const brokerage = text(input.brokerage); |
| @@ -818,7 +864,10 @@ export function readAgent(input: Record<string, unknown>): Result<Agent> { | ||
| 818 | 864 | return fail("invalid", "A phone number is 7 to 20 digits."); |
| 819 | 865 | if (email.length > 254 || !EMAIL.test(email)) |
| 820 | 866 | return fail("invalid", "An email address looks like [email protected]."); |
| 821 | return ok({ name, brokerage, license, phone, email }); | |
| 867 | const timeZone = input.timeZone === undefined ? keep : text(input.timeZone); | |
| 868 | if (!isZone(timeZone)) | |
| 869 | return fail("invalid", "A time zone is a name like America/Chicago or Europe/London."); | |
| 870 | return ok({ name, brokerage, license, phone, email, timeZone }); | |
| 822 | 871 | } |
| 823 | 872 | |
| 824 | 873 | export const saveProfile = ( |
| @@ -841,7 +890,7 @@ function change( | ||
| 841 | 890 | "Sign in to change the profile.", |
| 842 | 891 | "Only an admin can change the profile.", |
| 843 | 892 | ); |
| 844 | const read = readAgent(input); | |
| 893 | const read = readAgent(input, currentAgent(db).timeZone); | |
| 845 | 894 | if (!read.ok) return read; |
| 846 | 895 | db.transaction(() => { |
| 847 | 896 | storeAgent(db, read.value, who.role === "anon" ? "" : who.name, stamp(at)); |
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. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited"] 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. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold"] as const; | |
| 39 | 39 | export type Act = (typeof ACTS)[number]; |
| 40 | 40 | |
| 41 | 41 | export interface Attempt { |
src/contract.test.ts +20 −1
| @@ -21,6 +21,7 @@ import { | ||
| 21 | 21 | listLeads, |
| 22 | 22 | logCall, |
| 23 | 23 | bookShowing, |
| 24 | cancelHeld, | |
| 24 | 25 | cancelShowing, |
| 25 | 26 | logLeadReply, |
| 26 | 27 | saveProfile, |
| @@ -44,7 +45,8 @@ function whoIs(identity: string): Who { | ||
| 44 | 45 | } |
| 45 | 46 | |
| 46 | 47 | import { agent } from "./env.ts"; |
| 47 | import { insertLead } from "./leads.ts"; | |
| 48 | import { findLead, hold, insertLead, type Message } from "./leads.ts"; | |
| 49 | import { tools } from "./mcp.ts"; | |
| 48 | 50 | |
| 49 | 51 | // Leads name no one: they are the desk's, not a person's. `authorId` goes unused. |
| 50 | 52 | const aLead = (_authorId: string): number => |
| @@ -61,6 +63,16 @@ const aLead = (_authorId: string): number => | ||
| 61 | 63 | new Date().toISOString(), |
| 62 | 64 | agent, |
| 63 | 65 | ); |
| 66 | /** A lead with a text held for 8:00, as quiet hours leave it. */ | |
| 67 | const heldLead = (authorId: string): number => { | |
| 68 | const id = aLead(authorId); | |
| 69 | const draft = db | |
| 70 | .query<Message, [number]>("SELECT * FROM message WHERE lead_id = ?1 AND day = 0") | |
| 71 | .get(id)!; | |
| 72 | const now = new Date().toISOString(); | |
| 73 | hold(db, findLead(db, id)!, draft, "Hello", "alice", now, new Date(Date.now() + 3_600_000).toISOString()); | |
| 74 | return id; | |
| 75 | }; | |
| 64 | 76 | const PROFILE = { |
| 65 | 77 | name: "Sam Realtor", |
| 66 | 78 | brokerage: "Sam & Co", |
| @@ -130,7 +142,14 @@ const doors: Record< | ||
| 130 | 142 | // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id |
| 131 | 143 | // with a name, email or phone, and the MCP tool edit_lead). |
| 132 | 144 | const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok; |
| 145 | // And so is taking back a text held for quiet hours (POST /leads/:id/unhold, | |
| 146 | // the MCP tool cancel_held_text). | |
| 147 | const untold = cancelHeld(db, who, { id: heldLead(authorId) }).ok; | |
| 148 | const cancelTool = tools.find((t) => t.name === "cancel_held_text")!; | |
| 149 | const viaTool = (cancelTool.run(db, who, { id: heldLead(authorId) }) as { ok: boolean }).ok; | |
| 133 | 150 | const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok; |
| 151 | expect(untold).toBe(changed); | |
| 152 | expect(viaTool).toBe(changed); | |
| 134 | 153 | expect(showing).toBe(changed); |
| 135 | 154 | expect(off).toBe(changed); |
| 136 | 155 | expect(edited).toBe(changed); |
src/db.ts +49
| @@ -165,6 +165,55 @@ export const migrations: string[] = [ | ||
| 165 | 165 | ALTER TABLE lead_new RENAME TO lead; |
| 166 | 166 | PRAGMA legacy_alter_table = OFF`, |
| 167 | 167 | `CREATE INDEX IF NOT EXISTS lead_created ON lead (created_at)`, |
| 168 | // Quiet hours. The agent's time zone (null until set: the environment's | |
| 169 | // speaks), and a text the agent approved outside 8:00-21:00 there: it is | |
| 170 | // `held` with the moment it goes (`goes_at`) and when it was approved | |
| 171 | // (`approved_at`, the moment that counts as the reply). SQLite cannot widen | |
| 172 | // a CHECK in place (nor add a column twice), so both tables are rebuilt with | |
| 173 | // their rows, index and triggers; safe to run again. | |
| 174 | `DROP TABLE IF EXISTS profile_new`, | |
| 175 | `CREATE TABLE profile_new ( | |
| 176 | id INTEGER PRIMARY KEY CHECK (id = 1), | |
| 177 | name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120), | |
| 178 | brokerage TEXT NOT NULL CHECK (length(brokerage) BETWEEN 1 AND 120), | |
| 179 | license TEXT NOT NULL CHECK (length(trim(license)) BETWEEN 1 AND 60), | |
| 180 | phone TEXT NOT NULL CHECK (length(phone) BETWEEN 1 AND 40), | |
| 181 | email TEXT NOT NULL CHECK (length(email) BETWEEN 3 AND 254), | |
| 182 | updated_at TEXT NOT NULL, | |
| 183 | updated_by TEXT NOT NULL, | |
| 184 | time_zone TEXT | |
| 185 | )`, | |
| 186 | `INSERT INTO profile_new (id, name, brokerage, license, phone, email, updated_at, updated_by) | |
| 187 | SELECT id, name, brokerage, license, phone, email, updated_at, updated_by FROM profile`, | |
| 188 | `DROP TABLE profile`, | |
| 189 | `ALTER TABLE profile_new RENAME TO profile`, | |
| 190 | `DROP TABLE IF EXISTS message_new`, | |
| 191 | `CREATE TABLE message_new ( | |
| 192 | id INTEGER PRIMARY KEY, | |
| 193 | lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE, | |
| 194 | day INTEGER NOT NULL CHECK (day >= 0), | |
| 195 | channel TEXT NOT NULL CHECK (channel IN ('text', 'email')), | |
| 196 | body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 4000), | |
| 197 | signature TEXT NOT NULL, | |
| 198 | status TEXT NOT NULL CHECK (status IN ('draft', 'scheduled', 'due', 'held', 'sent', 'skipped')), | |
| 199 | due_at TEXT NOT NULL, | |
| 200 | sent_at TEXT, | |
| 201 | sent_by TEXT, | |
| 202 | goes_at TEXT, | |
| 203 | approved_at TEXT, | |
| 204 | UNIQUE (lead_id, day) | |
| 205 | )`, | |
| 206 | `INSERT INTO message_new (id, lead_id, day, channel, body, signature, status, due_at, sent_at, sent_by) | |
| 207 | SELECT id, lead_id, day, channel, body, signature, status, due_at, sent_at, sent_by FROM message`, | |
| 208 | `DROP TABLE message`, | |
| 209 | `ALTER TABLE message_new RENAME TO message`, | |
| 210 | `CREATE INDEX IF NOT EXISTS message_due ON message (status, due_at)`, | |
| 211 | `CREATE TRIGGER IF NOT EXISTS message_text_needs_consent BEFORE INSERT ON message | |
| 212 | WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0 | |
| 213 | BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`, | |
| 214 | `CREATE TRIGGER IF NOT EXISTS message_text_needs_consent_update BEFORE UPDATE OF channel ON message | |
| 215 | WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0 | |
| 216 | BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`, | |
| 168 | 217 | ]; |
| 169 | 218 | |
| 170 | 219 | export function openDb(dir = dataDir): Database { |
src/env.ts +3
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import pkg from "../package.json"; |
| 8 | import { isZone } from "./quiet.ts"; | |
| 8 | 9 | |
| 9 | 10 | /** What a person sees the app called. */ |
| 10 | 11 | export const title = "Speed to Lead"; |
| @@ -45,5 +46,7 @@ export const agent = { | ||
| 45 | 46 | license: process.env.AGENT_LICENSE || "CA DRE 02145789", |
| 46 | 47 | phone: process.env.AGENT_PHONE || "(555) 214-0187", |
| 47 | 48 | email: process.env.AGENT_EMAIL || "[email protected]", |
| 49 | /** Where the agent's clock is: quiet hours for texts are kept in it. */ | |
| 50 | timeZone: [process.env.AGENT_TIMEZONE, process.env.TZ].find(isZone) ?? "America/New_York", | |
| 48 | 51 | } as const; |
| 49 | 52 | export type Agent = typeof agent; |
src/leads.ts +119 −14
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | import { answers, type Call, type Outcome } from "./calls.ts"; |
| 27 | 27 | import { GREEN_MS } from "./clock.ts"; |
| 28 | 28 | import type { Agent } from "./env.ts"; |
| 29 | import { isQuiet, nextOpening } from "./quiet.ts"; | |
| 29 | 30 | import { holdUntil, type Showing } from "./showings.ts"; |
| 30 | 31 | |
| 31 | 32 | export type State = "new" | "contacted" | "qualified" | "lost"; |
| @@ -57,10 +58,14 @@ export interface Message { | ||
| 57 | 58 | readonly channel: Channel; |
| 58 | 59 | readonly body: string; |
| 59 | 60 | readonly signature: string; |
| 60 | readonly status: "draft" | "scheduled" | "due" | "sent" | "skipped"; | |
| 61 | readonly status: "draft" | "scheduled" | "due" | "held" | "sent" | "skipped"; | |
| 61 | 62 | readonly due_at: string; |
| 62 | 63 | readonly sent_at: string | null; |
| 63 | 64 | readonly sent_by: string | null; |
| 65 | /** For a held text: the moment it goes (the next 8:00 a.m.); null otherwise. */ | |
| 66 | readonly goes_at: string | null; | |
| 67 | /** For a held text: when the agent approved it, which is when the lead counts as answered. */ | |
| 68 | readonly approved_at: string | null; | |
| 64 | 69 | } |
| 65 | 70 | |
| 66 | 71 | /** The most a lead's reply may hold. */ |
| @@ -95,6 +100,8 @@ export interface DeskLead extends Lead { | ||
| 95 | 100 | readonly ready: { readonly id: number; readonly day: number; readonly since: string } | null; |
| 96 | 101 | /** When the next scheduled touch comes due, if one is. */ |
| 97 | 102 | readonly next_at: string | null; |
| 103 | /** When a text the agent approved goes, if one is held for quiet hours. */ | |
| 104 | readonly goes_at: string | null; | |
| 98 | 105 | /** The showing booked on this lead, if one is. */ |
| 99 | 106 | readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null; |
| 100 | 107 | } |
| @@ -253,6 +260,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 253 | 260 | ready_day: number | null; |
| 254 | 261 | ready_since: string | null; |
| 255 | 262 | next_at: string | null; |
| 263 | goes_at: string | null; | |
| 256 | 264 | show_at: string | null; |
| 257 | 265 | show_address: string | null; |
| 258 | 266 | show_hold: string | null; |
| @@ -264,6 +272,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 264 | 272 | (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day, |
| 265 | 273 | (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since, |
| 266 | 274 | (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at, |
| 275 | (SELECT min(goes_at) FROM message WHERE lead_id = lead.id AND status = 'held') AS goes_at, | |
| 267 | 276 | (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at, |
| 268 | 277 | (SELECT address FROM showing WHERE lead_id = lead.id) AS show_address, |
| 269 | 278 | (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold |
| @@ -273,13 +282,14 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 273 | 282 | ORDER BY created_at DESC, id DESC LIMIT ?1`, |
| 274 | 283 | ) |
| 275 | 284 | .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`) |
| 276 | .map(({ ready_id, ready_day, ready_since, next_at, show_at, show_address, show_hold, ...row }) => ({ | |
| 285 | .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, ...row }) => ({ | |
| 277 | 286 | ...lead(row), |
| 278 | 287 | ready: |
| 279 | 288 | ready_id === null || ready_day === null || ready_since === null |
| 280 | 289 | ? null |
| 281 | 290 | : { id: ready_id, day: ready_day, since: ready_since }, |
| 282 | 291 | next_at, |
| 292 | goes_at, | |
| 283 | 293 | showing: |
| 284 | 294 | show_at === null || show_address === null || show_hold === null |
| 285 | 295 | ? null |
| @@ -420,13 +430,14 @@ export function send( | ||
| 420 | 430 | by: string, |
| 421 | 431 | at: string, |
| 422 | 432 | agent: Agent, |
| 433 | repliedAt = at, | |
| 423 | 434 | ): void { |
| 424 | 435 | db.transaction(() => { |
| 425 | 436 | db.query( |
| 426 | "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4 WHERE id = ?5", | |
| 437 | "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4, goes_at = NULL WHERE id = ?5", | |
| 427 | 438 | ).run(body, signature(message.channel, agent), at, by, message.id); |
| 428 | 439 | if (message.day === 0) { |
| 429 | startCadence(db, found, at, agent); | |
| 440 | startCadence(db, found, at, agent, repliedAt); | |
| 430 | 441 | } else { |
| 431 | 442 | db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run( |
| 432 | 443 | at, |
| @@ -438,11 +449,99 @@ export function send( | ||
| 438 | 449 | })(); |
| 439 | 450 | } |
| 440 | 451 | |
| 441 | /** The first answer is out at `at`: the clock stops and the follow-ups are drafted and scheduled from it. */ | |
| 442 | function startCadence(db: Database, found: Lead, at: string, agent: Agent): void { | |
| 452 | /** | |
| 453 | * The agent approved a text outside quiet hours: it is kept, signed when it | |
| 454 | * goes, and goes at `goesAt`. The lead counts as answered now, at approval | |
| 455 | * (the clock stops, the state is `contacted`), but the follow-ups start only | |
| 456 | * when the text is out. Cancelling puts it all back (`release`). | |
| 457 | */ | |
| 458 | export function hold( | |
| 459 | db: Database, | |
| 460 | found: Lead, | |
| 461 | message: Message, | |
| 462 | body: string, | |
| 463 | by: string, | |
| 464 | at: string, | |
| 465 | goesAt: string, | |
| 466 | ): void { | |
| 467 | db.transaction(() => { | |
| 468 | db.query( | |
| 469 | "UPDATE message SET body = ?1, status = 'held', goes_at = ?2, approved_at = ?3, sent_by = ?4 WHERE id = ?5", | |
| 470 | ).run(body, goesAt, at, by, message.id); | |
| 471 | if (message.day === 0) | |
| 472 | db.query( | |
| 473 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 474 | ).run(at, found.id); | |
| 475 | else db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id); | |
| 476 | })(); | |
| 477 | } | |
| 478 | ||
| 479 | /** The held text of `lead`, if one is. */ | |
| 480 | export const heldFor = (db: Database, id: number): Message | null => | |
| 481 | db | |
| 482 | .query<Message, [number]>("SELECT * FROM message WHERE lead_id = ?1 AND status = 'held' LIMIT 1") | |
| 483 | .get(id); | |
| 484 | ||
| 485 | /** | |
| 486 | * A held text goes back to an unsent draft the agent can approve again: a | |
| 487 | * draft for the first reply or an answer, due for a follow-up. A first reply | |
| 488 | * un-answers the lead; they wait from when they asked. | |
| 489 | */ | |
| 490 | export function release(db: Database, message: Message, at: string): void { | |
| 491 | db.transaction(() => { | |
| 492 | const first = message.day === 0; | |
| 493 | db.query( | |
| 494 | "UPDATE message SET status = ?1, goes_at = NULL, approved_at = NULL, sent_by = NULL WHERE id = ?2", | |
| 495 | ).run(first || isAnswer(message.day) ? "draft" : "due", message.id); | |
| 496 | if (first) | |
| 497 | db.query( | |
| 498 | "UPDATE lead SET replied_at = NULL, state = CASE state WHEN 'contacted' THEN 'new' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 499 | ).run(at, message.lead_id); | |
| 500 | else db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, message.lead_id); | |
| 501 | })(); | |
| 502 | } | |
| 503 | ||
| 504 | /** | |
| 505 | * Held texts whose time has come go out as approved, signed as the agent is | |
| 506 | * now. One whose lead has since stopped texts goes back as an email draft | |
| 507 | * instead, never as a text; one that fell due after 9 p.m. (the clock was | |
| 508 | * not turned) waits for the next 8:00. Returns the ids of the leads touched. | |
| 509 | */ | |
| 510 | export function sendHeld(db: Database, at: string, agent: Agent): number[] { | |
| 511 | const due = db | |
| 512 | .query<Message, [string]>( | |
| 513 | "SELECT * FROM message WHERE status = 'held' AND goes_at <= ?1 ORDER BY goes_at, id", | |
| 514 | ) | |
| 515 | .all(at); | |
| 516 | const touched: number[] = []; | |
| 517 | for (const m of due) { | |
| 518 | const found = findLead(db, m.lead_id)!; | |
| 519 | if (channelFor(found) !== "text") { | |
| 520 | release(db, m, at); | |
| 521 | redraftFor(db, found, agent, false); | |
| 522 | } else if (isQuiet(at, agent.timeZone)) { | |
| 523 | db.query("UPDATE message SET goes_at = ?1 WHERE id = ?2").run( | |
| 524 | nextOpening(at, agent.timeZone), | |
| 525 | m.id, | |
| 526 | ); | |
| 527 | continue; | |
| 528 | } else send(db, found, m, m.body, m.sent_by ?? "", at, agent, m.approved_at ?? at); | |
| 529 | touched.push(m.lead_id); | |
| 530 | } | |
| 531 | return touched.filter((id, i, all) => all.indexOf(id) === i); | |
| 532 | } | |
| 533 | ||
| 534 | /** The first answer is out at `at` (approved at `repliedAt`, when the clock stopped): the clock stops and the follow-ups are drafted and scheduled from it. */ | |
| 535 | function startCadence( | |
| 536 | db: Database, | |
| 537 | found: Lead, | |
| 538 | at: string, | |
| 539 | agent: Agent, | |
| 540 | repliedAt = at, | |
| 541 | ): void { | |
| 443 | 542 | db.query( |
| 444 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2", | |
| 445 | ).run(at, found.id); | |
| 543 | "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?2 WHERE id = ?3", | |
| 544 | ).run(repliedAt, at, found.id); | |
| 446 | 545 | const channel = channelFor(found); |
| 447 | 546 | const open = !CLOSED.includes(found.state); |
| 448 | 547 | for (const day of CADENCE) |
| @@ -631,13 +730,18 @@ export function updateContact(db: Database, found: Lead, to: Contact, at: string | ||
| 631 | 730 | function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): void { |
| 632 | 731 | const channel = channelFor(lead); |
| 633 | 732 | const unsent = db |
| 634 | .query<{ id: number; day: number }, [number]>( | |
| 733 | .query<Message, [number]>( | |
| 635 | 734 | aside |
| 636 | ? "SELECT id, day FROM message WHERE lead_id = ?1 AND status <> 'sent'" | |
| 637 | : "SELECT id, day FROM message WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')", | |
| 735 | ? "SELECT * FROM message WHERE lead_id = ?1 AND status <> 'sent'" | |
| 736 | : "SELECT * FROM message WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due', 'held')", | |
| 638 | 737 | ) |
| 639 | 738 | .all(lead.id); |
| 640 | for (const m of unsent) | |
| 739 | for (const m of unsent) { | |
| 740 | // A held text the lead can still be texted keeps the words the agent approved. | |
| 741 | if (m.status === "held") { | |
| 742 | if (channel === "text") continue; | |
| 743 | release(db, m, m.approved_at ?? m.due_at); | |
| 744 | } | |
| 641 | 745 | db.query( |
| 642 | 746 | "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4", |
| 643 | 747 | ).run( |
| @@ -646,6 +750,7 @@ function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): voi | ||
| 646 | 750 | signature(channel, agent), |
| 647 | 751 | m.id, |
| 648 | 752 | ); |
| 753 | } | |
| 649 | 754 | } |
| 650 | 755 | |
| 651 | 756 | /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */ |
| @@ -662,7 +767,7 @@ export function close( | ||
| 662 | 767 | id, |
| 663 | 768 | ); |
| 664 | 769 | db.query( |
| 665 | "UPDATE message SET status = 'skipped' WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')", | |
| 770 | "UPDATE message SET status = 'skipped', goes_at = NULL WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due', 'held')", | |
| 666 | 771 | ).run(id); |
| 667 | 772 | })(); |
| 668 | 773 | } |
| @@ -710,7 +815,7 @@ export function advance(db: Database, at: string): number[] { | ||
| 710 | 815 | WHERE status = 'scheduled' AND due_at <= ?1 |
| 711 | 816 | AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted') |
| 712 | 817 | AND lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1) |
| 713 | AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status = 'draft') | |
| 818 | AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status IN ('draft', 'held')) | |
| 714 | 819 | RETURNING lead_id`, |
| 715 | 820 | ) |
| 716 | 821 | .all(at) |
src/mcp.ts +12 −3
| @@ -18,6 +18,7 @@ import { | ||
| 18 | 18 | editLead, |
| 19 | 19 | optOutTexts, |
| 20 | 20 | approveReply, |
| 21 | cancelHeld, | |
| 21 | 22 | setState, |
| 22 | 23 | logCall, |
| 23 | 24 | bookShowing, |
| @@ -120,7 +121,7 @@ export const tools: readonly Tool[] = [ | ||
| 120 | 121 | { |
| 121 | 122 | name: "send_reply", |
| 122 | 123 | description: |
| 123 | "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. The answer says which lead is next (`next`: id and name, or null): the one that has waited longest among those that need the person now. Only call this when the person has approved the words.", | |
| 124 | "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. The answer says which lead is next (`next`: id and name, or null): the one that has waited longest among those that need the person now. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now. Only call this when the person has approved the words.", | |
| 124 | 125 | inputSchema: { |
| 125 | 126 | type: "object", |
| 126 | 127 | properties: { id: { type: "integer" }, body: { type: "string" } }, |
| @@ -222,6 +223,13 @@ export const tools: readonly Tool[] = [ | ||
| 222 | 223 | run: (db, who, args) => |
| 223 | 224 | editLead(db, who, { id: Number(args.id), name: args.name, email: args.email, phone: args.phone }), |
| 224 | 225 | }, |
| 226 | { | |
| 227 | name: "cancel_held_text", | |
| 228 | description: | |
| 229 | "Take back a text held for quiet hours (send_reply answered `scheduledFor`): it returns to an unsent draft, to edit and approve again.", | |
| 230 | inputSchema: ONE, | |
| 231 | run: (db, who, args) => cancelHeld(db, who, { id: Number(args.id) }), | |
| 232 | }, | |
| 225 | 233 | { |
| 226 | 234 | name: "opt_out_texts", |
| 227 | 235 | description: |
| @@ -232,14 +240,14 @@ export const tools: readonly Tool[] = [ | ||
| 232 | 240 | { |
| 233 | 241 | name: "get_profile", |
| 234 | 242 | description: |
| 235 | "The agent whose desk this is: name, brokerage, license, phone and email, as every message is signed.", | |
| 243 | "The agent whose desk this is: name, brokerage, license, phone, email and time zone, as every message is signed.", | |
| 236 | 244 | inputSchema: { type: "object", properties: {} }, |
| 237 | 245 | run: (db, who) => getProfile(db, who), |
| 238 | 246 | }, |
| 239 | 247 | { |
| 240 | 248 | name: "set_profile", |
| 241 | 249 | description: |
| 242 | "Change the agent's name, brokerage, license, phone and email (admin only). Unsent drafts take it at once; sent messages keep theirs.", | |
| 250 | "Change the agent's name, brokerage, license, phone, email and time zone (admin only). Unsent drafts take it at once; sent messages keep theirs.", | |
| 243 | 251 | inputSchema: { |
| 244 | 252 | type: "object", |
| 245 | 253 | properties: { |
| @@ -248,6 +256,7 @@ export const tools: readonly Tool[] = [ | ||
| 248 | 256 | license: { type: "string" }, |
| 249 | 257 | phone: { type: "string" }, |
| 250 | 258 | email: { type: "string" }, |
| 259 | timeZone: { type: "string", description: "An IANA name like America/Chicago: texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, unchanged." }, | |
| 251 | 260 | }, |
| 252 | 261 | required: ["name", "brokerage", "license", "phone", "email"], |
| 253 | 262 | }, |
src/pages/desk.ts +8 −5
| @@ -8,6 +8,7 @@ import { layout } from "./layout.ts"; | ||
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import { recordLine } from "../clock.ts"; |
| 10 | 10 | import { isAnswer } from "../drafts.ts"; |
| 11 | import { goesLabel, RECORD_NOTE } from "../quiet.ts"; | |
| 11 | 12 | import { showingWhen } from "../showings.ts"; |
| 12 | 13 | import type { DeskLead, ResponseRecord, View } from "../leads.ts"; |
| 13 | 14 | import type { Agent } from "../env.ts"; |
| @@ -51,7 +52,7 @@ export function deskPage(input: { | ||
| 51 | 52 | const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length; |
| 52 | 53 | const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length; |
| 53 | 54 | const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today${answers === 0 ? "" : ` <span aria-hidden="true">·</span> <b>${answers}</b> wrote back`}</p>`; |
| 54 | const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>`; | |
| 55 | const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p><p class="muted">${RECORD_NOTE}</p>`; | |
| 55 | 56 | const q = input.q ?? ""; |
| 56 | 57 | const views = |
| 57 | 58 | counts === undefined |
| @@ -69,7 +70,7 @@ export function deskPage(input: { | ||
| 69 | 70 | const list = |
| 70 | 71 | leads.length === 0 |
| 71 | 72 | ? `<p class="empty">${q === "" ? EMPTY[show] : `No lead matches '${escape(q)}'${show === "all" ? "" : " in this view"}.`}</p>` |
| 72 | : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`; | |
| 73 | : `<ul class="desk">${leads.map((lead) => row(lead, now, agent.timeZone)).join("")}</ul>`; | |
| 73 | 74 | return layout({ |
| 74 | 75 | who, |
| 75 | 76 | agent, |
| @@ -151,9 +152,11 @@ const showingBadge = (lead: DeskLead, now: number): string => | ||
| 151 | 152 | ["Showing", showingWhen(lead.showing.at, now), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "), |
| 152 | 153 | )}</span>`; |
| 153 | 154 | |
| 154 | function status(lead: DeskLead): string { | |
| 155 | function status(lead: DeskLead, now: number, zone: string): string { | |
| 155 | 156 | if (lead.state === "qualified" || lead.state === "lost") |
| 156 | 157 | return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`; |
| 158 | if (lead.goes_at !== null) | |
| 159 | return `<span class="status">${escape(goesLabel(lead.goes_at, now, zone))}</span>`; | |
| 157 | 160 | if (lead.ready?.day === 0) |
| 158 | 161 | return `<span class="status" data-ready>Reply drafted — approve and send</span>`; |
| 159 | 162 | if (lead.ready !== null && isAnswer(lead.ready.day)) |
| @@ -165,13 +168,13 @@ function status(lead: DeskLead): string { | ||
| 165 | 168 | return `<span class="status">Follow-ups done</span>`; |
| 166 | 169 | } |
| 167 | 170 | |
| 168 | const row = (lead: DeskLead, now: number): string => `<li> | |
| 171 | const row = (lead: DeskLead, now: number, zone: string): string => `<li> | |
| 169 | 172 | <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}> |
| 170 | 173 | <span class="lead-main"> |
| 171 | 174 | <span class="lead-name">${escape(lead.name)}</span> |
| 172 | 175 | <span class="tags">${source(lead)}${consent(lead)}${showingBadge(lead, now)}</span> |
| 173 | 176 | <span class="ask">${escape(lead.message)}</span> |
| 174 | ${status(lead)} | |
| 177 | ${status(lead, now, zone)} | |
| 175 | 178 | </span> |
| 176 | 179 | ${clock(lead, now, lead.ready !== null && isAnswer(lead.ready.day) ? lead.ready.since : null)} |
| 177 | 180 | </a> |
src/pages/lead.ts +25 −2
| @@ -9,6 +9,7 @@ import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts"; | ||
| 9 | 9 | import { escape } from "../http.ts"; |
| 10 | 10 | import { MAX_ADDRESS, MAX_AHEAD_DAYS, showingLine, showingWhen } from "../showings.ts"; |
| 11 | 11 | import { elapsed, between } from "../clock.ts"; |
| 12 | import { goesLabel, isQuiet, nextOpening } from "../quiet.ts"; | |
| 12 | 13 | import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts"; |
| 13 | 14 | import type { Agent } from "../env.ts"; |
| 14 | 15 | import type { Who } from "../who.ts"; |
| @@ -63,8 +64,24 @@ export function leadPage(input: { | ||
| 63 | 64 | : [`<a href="tel:${escape(lead.phone.replace(/[^\d+]/g, ""))}">${escape(lead.phone)}</a>`]), |
| 64 | 65 | ].join(" · "); |
| 65 | 66 | |
| 67 | const held = lead.messages.find((m) => m.status === "held"); | |
| 68 | const holdPane = | |
| 69 | held === undefined || held.goes_at === null | |
| 70 | ? "" | |
| 71 | : `<div class="pane ours held"> | |
| 72 | <h2>${titleOf(held)} <span class="muted">· by ${CHANNEL[held.channel]}</span></h2> | |
| 73 | <p class="hint" data-held>${escape(goesLabel(held.goes_at, now, agent.timeZone))}. Texts go out between 8:00 a.m. and 9:00 p.m. (${escape(agent.timeZone)}); you approved this one, and it waits.</p> | |
| 74 | <div class="draft-view">${words({ body: held.body, signature: held.signature })}</div> | |
| 75 | ${ | |
| 76 | mayUpdate | |
| 77 | ? `<form method="post" action="${path}/unhold"><button class="button button-quiet">Cancel and keep as a draft</button></form>` | |
| 78 | : "" | |
| 79 | } | |
| 80 | </div>`; | |
| 66 | 81 | const draft = |
| 67 | ready === undefined | |
| 82 | ready === undefined && held !== undefined | |
| 83 | ? holdPane | |
| 84 | : ready === undefined | |
| 68 | 85 | ? `<div class="pane ours"><h2>Nothing to send right now</h2><p class="muted">${ |
| 69 | 86 | closed |
| 70 | 87 | ? `Marked ${STATE_LABEL[lead.state].toLowerCase()}: out of the follow-up plan.` |
| @@ -91,6 +108,11 @@ export function leadPage(input: { | ||
| 91 | 108 | </div>` |
| 92 | 109 | : "" |
| 93 | 110 | } |
| 111 | ${ | |
| 112 | ready.channel === "text" && isQuiet(now, agent.timeZone) | |
| 113 | ? `<p class="hint">It is outside texting hours (8:00 a.m. to 9:00 p.m.): approving holds this text. ${escape(goesLabel(nextOpening(now, agent.timeZone), now, agent.timeZone))}.</p>` | |
| 114 | : "" | |
| 115 | } | |
| 94 | 116 | ${ |
| 95 | 117 | ready.channel === "email" && lead.email === "" |
| 96 | 118 | ? `<p class="hint">No email address on file, and they have not agreed to be texted: this waits until you add an address or call them.</p>` |
| @@ -98,7 +120,7 @@ export function leadPage(input: { | ||
| 98 | 120 | ? `<p class="hint">Email only: ${lead.consent ? "no phone number to text." : lead.opted_out_at !== null ? "they asked to stop texts." : "they have not given written consent to be texted."}</p>` |
| 99 | 121 | : "" |
| 100 | 122 | } |
| 101 | </div>`; | |
| 123 | </div>${holdPane}`; | |
| 102 | 124 | |
| 103 | 125 | const history: HistoryEntry[] = [ |
| 104 | 126 | ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })), |
| @@ -297,6 +319,7 @@ const PLAN: Readonly<Record<Message["status"], string>> = { | ||
| 297 | 319 | draft: "Drafted", |
| 298 | 320 | scheduled: "Upcoming", |
| 299 | 321 | due: "Ready to send", |
| 322 | held: "Held for 8:00 a.m.", | |
| 300 | 323 | sent: "Sent", |
| 301 | 324 | skipped: "Skipped", |
| 302 | 325 | }; |
src/pages/profile.ts +1
| @@ -14,6 +14,7 @@ const FIELDS = [ | ||
| 14 | 14 | { name: "license", label: "License number", type: "text", max: 60, auto: "off" }, |
| 15 | 15 | { name: "phone", label: "Phone", type: "tel", max: 20, auto: "tel" }, |
| 16 | 16 | { name: "email", label: "Email", type: "email", max: 254, auto: "email" }, |
| 17 | { name: "timeZone", label: "Time zone (texts wait for 8:00 a.m. there, e.g. America/Chicago)", type: "text", max: 60, auto: "off" }, | |
| 17 | 18 | ] as const; |
| 18 | 19 | |
| 19 | 20 | export function profilePage(input: { |
src/profile.test.ts +2 −2
| @@ -62,8 +62,8 @@ test("saving changes the next draft's signature and the unsent ones, never a sen | ||
| 62 | 62 | expect(oldSignature).toContain(agent.license); |
| 63 | 63 | const b = must(addLead(db, alice, { ...lead, email: "[email protected]" })); |
| 64 | 64 | |
| 65 | expect(must(saveProfile(db, root, sam))).toEqual({ id: 1, ...sam }); | |
| 66 | expect(currentAgent(db)).toEqual(sam); | |
| 65 | expect(must(saveProfile(db, root, sam))).toEqual({ id: 1, ...sam, timeZone: agent.timeZone }); | |
| 66 | expect(currentAgent(db)).toEqual({ ...sam, timeZone: agent.timeZone }); | |
| 67 | 67 | |
| 68 | 68 | const next = must(addLead(db, alice, { ...lead, email: "[email protected]" })); |
| 69 | 69 | expect(next.messages[0]!.signature).toContain("WA 99887"); |
src/profile.ts +9 −7
| @@ -11,11 +11,13 @@ import { agent as fromEnvironment, type Agent } from "./env.ts"; | ||
| 11 | 11 | /** The saved profile, or the environment's until there is one. */ |
| 12 | 12 | export function currentAgent(db: Database): Agent { |
| 13 | 13 | const saved = db |
| 14 | .query<Agent, []>( | |
| 15 | "SELECT name, brokerage, license, phone, email FROM profile WHERE id = 1", | |
| 14 | .query<Omit<Agent, "timeZone"> & { time_zone: string | null }, []>( | |
| 15 | "SELECT name, brokerage, license, phone, email, time_zone FROM profile WHERE id = 1", | |
| 16 | 16 | ) |
| 17 | 17 | .get(); |
| 18 | return saved ?? fromEnvironment; | |
| 18 | if (saved === null) return fromEnvironment; | |
| 19 | const { time_zone, ...rest } = saved; | |
| 20 | return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone }; | |
| 19 | 21 | } |
| 20 | 22 | |
| 21 | 23 | /** Save `agent` as the profile, whoever it replaces. */ |
| @@ -26,9 +28,9 @@ export function storeAgent( | ||
| 26 | 28 | at: string, |
| 27 | 29 | ): void { |
| 28 | 30 | db.query( |
| 29 | `INSERT INTO profile (id, name, brokerage, license, phone, email, updated_at, updated_by) | |
| 30 | VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7) | |
| 31 | `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, updated_at, updated_by) | |
| 32 | VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?6, ?7) | |
| 31 | 33 | ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3, |
| 32 | phone = ?4, email = ?5, updated_at = ?6, updated_by = ?7`, | |
| 33 | ).run(agent.name, agent.brokerage, agent.license, agent.phone, agent.email, at, by); | |
| 34 | phone = ?4, email = ?5, time_zone = ?8, updated_at = ?6, updated_by = ?7`, | |
| 35 | ).run(agent.name, agent.brokerage, agent.license, agent.phone, agent.email, at, by, agent.timeZone); | |
| 34 | 36 | } |
src/quiet.test.ts added +316
| @@ -0,0 +1,316 @@ | ||
| 1 | /** | |
| 2 | * Quiet hours: a text approved outside 8:00 a.m. to 9:00 p.m. in the agent's | |
| 3 | * time zone waits for the next 8:00 and goes with the tick; an email never | |
| 4 | * waits; the agent can take a held text back; a lead who opts out before it | |
| 5 | * goes is never texted. At every door. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, 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 { | |
| 12 | addLead, | |
| 13 | approveReply, | |
| 14 | cancelHeld, | |
| 15 | getLead, | |
| 16 | listLeads, | |
| 17 | optOutTexts, | |
| 18 | saveProfile, | |
| 19 | setState, | |
| 20 | tick, | |
| 21 | turn, | |
| 22 | } from "./actions.ts"; | |
| 23 | import { openDb } from "./db.ts"; | |
| 24 | import { deskPage } from "./pages/desk.ts"; | |
| 25 | import { leadPage } from "./pages/lead.ts"; | |
| 26 | import { agent } from "./env.ts"; | |
| 27 | import { goesAt, goesLabel, isQuiet, isZone, nextOpening } from "./quiet.ts"; | |
| 28 | import { serve } from "./server.ts"; | |
| 29 | import { plain, terminal } from "./terminal.ts"; | |
| 30 | import { sign } from "./who.ts"; | |
| 31 | import type { Who } from "./who.ts"; | |
| 32 | ||
| 33 | // The suite turns quiet hours off for everyone else; these tests need them. | |
| 34 | let was: string | undefined; | |
| 35 | beforeAll(() => { | |
| 36 | was = process.env.QUIET_HOURS; | |
| 37 | delete process.env.QUIET_HOURS; | |
| 38 | }); | |
| 39 | afterAll(() => { | |
| 40 | if (was !== undefined) process.env.QUIET_HOURS = was; | |
| 41 | }); | |
| 42 | ||
| 43 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 44 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 45 | const ZONE = "America/Chicago"; | |
| 46 | // June: Chicago is on daylight time, five hours behind UTC. | |
| 47 | const at = (hhmm: string, date = "2026-06-10") => new Date(`${date}T${hhmm}:00-05:00`); | |
| 48 | ||
| 49 | const fresh = (zone = ZONE) => { | |
| 50 | const db = openDb(mkdtempSync(join(tmpdir(), "app-quiet-"))); | |
| 51 | const saved = saveProfile(db, root, { ...agent, timeZone: zone }); | |
| 52 | if (!saved.ok) throw new Error(saved.message); | |
| 53 | return db; | |
| 54 | }; | |
| 55 | const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => { | |
| 56 | if (!r.ok) throw new Error(r.message); | |
| 57 | return r.value as T; | |
| 58 | }; | |
| 59 | const arrive = (db: ReturnType<typeof fresh>, consent = true, when = at("20:00")) => | |
| 60 | value( | |
| 61 | addLead( | |
| 62 | db, | |
| 63 | alice, | |
| 64 | { | |
| 65 | name: "Dana Reyes", | |
| 66 | email: "[email protected]", | |
| 67 | phone: "(206) 555-0199", | |
| 68 | source: "zillow", | |
| 69 | message: "Can I see 12 Oak Street this week?", | |
| 70 | consent, | |
| 71 | }, | |
| 72 | when, | |
| 73 | ), | |
| 74 | ).id; | |
| 75 | ||
| 76 | test("the window is 8:00 to 21:00 on the agent's wall clock", () => { | |
| 77 | expect(isQuiet(at("07:59"), ZONE)).toBe(true); | |
| 78 | expect(isQuiet(at("08:00"), ZONE)).toBe(false); | |
| 79 | expect(isQuiet(at("20:59"), ZONE)).toBe(false); | |
| 80 | expect(isQuiet(at("21:00"), ZONE)).toBe(true); | |
| 81 | expect(isQuiet(at("22:30"), "UTC")).toBe(true); // 03:30 UTC, the same instant | |
| 82 | expect(isQuiet("2026-06-10T12:00:00Z", "UTC")).toBe(false); | |
| 83 | }); | |
| 84 | ||
| 85 | test("the next opening is the coming 8:00, today before it and tomorrow after it", () => { | |
| 86 | expect(nextOpening(at("22:30"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 87 | expect(nextOpening(at("03:00"), ZONE)).toBe(at("08:00").toISOString()); | |
| 88 | expect(nextOpening(at("21:00"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 89 | }); | |
| 90 | ||
| 91 | test("the arithmetic holds across a daylight-saving change", () => { | |
| 92 | // New York springs forward on 2026-03-08: 22:30 EST on the 7th, 8:00 EDT on the 8th. | |
| 93 | const evening = new Date("2026-03-08T03:30:00Z"); | |
| 94 | expect(nextOpening(evening, "America/New_York")).toBe("2026-03-08T12:00:00.000Z"); | |
| 95 | // And falls back on 2026-11-01: 22:30 EDT on the 31st, 8:00 EST on the 1st. | |
| 96 | expect(nextOpening(new Date("2026-11-01T02:30:00Z"), "America/New_York")).toBe("2026-11-01T13:00:00.000Z"); | |
| 97 | // 21:00 EST the night before a spring change still lands on 8:00 local. | |
| 98 | expect(nextOpening(new Date("2026-03-08T02:00:00Z"), "America/New_York")).toBe("2026-03-08T12:00:00.000Z"); | |
| 99 | }); | |
| 100 | ||
| 101 | test("emails are never held; a text is held only in quiet hours", () => { | |
| 102 | expect(goesAt("email", at("23:00"), ZONE)).toBeNull(); | |
| 103 | expect(goesAt("text", at("12:00"), ZONE)).toBeNull(); | |
| 104 | expect(goesAt("text", at("22:30"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 105 | }); | |
| 106 | ||
| 107 | test("zones are IANA names the runtime knows", () => { | |
| 108 | expect(isZone("America/Chicago")).toBe(true); | |
| 109 | expect(isZone("Mars/Olympus")).toBe(false); | |
| 110 | expect(isZone("")).toBe(false); | |
| 111 | expect(isZone(5)).toBe(false); | |
| 112 | }); | |
| 113 | ||
| 114 | test("the label says today, tomorrow or the date", () => { | |
| 115 | const goes = at("08:00", "2026-06-11").toISOString(); | |
| 116 | expect(goesLabel(goes, at("22:30"), ZONE)).toBe("Goes at 8:00 a.m. tomorrow"); | |
| 117 | expect(goesLabel(goes, at("05:00", "2026-06-11"), ZONE)).toBe("Goes at 8:00 a.m. today"); | |
| 118 | expect(goesLabel(goes, at("22:30", "2026-06-08"), ZONE)).toBe("Goes at 8:00 a.m. on Jun 11"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("a text approved at 22:30 is held until 8:00 next day; the record counts the approval", () => { | |
| 122 | const db = fresh(); | |
| 123 | const id = arrive(db); | |
| 124 | const approved = value(approveReply(db, alice, { id }, at("22:30"))); | |
| 125 | expect(approved.scheduledFor).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 126 | const first = approved.messages.find((m) => m.day === 0)!; | |
| 127 | expect(first.status).toBe("held"); | |
| 128 | expect(first.sent_at).toBeNull(); | |
| 129 | expect(approved.replied_at).toBe(at("22:30").toISOString()); | |
| 130 | expect(approved.state).toBe("contacted"); | |
| 131 | expect(approved.messages.filter((m) => m.day > 0)).toHaveLength(0); | |
| 132 | const desk = value(listLeads(db, alice)).leads[0]!; | |
| 133 | expect(desk.goes_at).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 134 | expect(desk.ready).toBeNull(); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a text approved at 12:00 goes now", () => { | |
| 138 | const db = fresh(); | |
| 139 | const id = arrive(db); | |
| 140 | const approved = value(approveReply(db, alice, { id }, at("12:00"))); | |
| 141 | expect(approved.scheduledFor).toBeUndefined(); | |
| 142 | expect(approved.messages[0]!.status).toBe("sent"); | |
| 143 | }); | |
| 144 | ||
| 145 | test("an email at 23:00 goes now", () => { | |
| 146 | const db = fresh(); | |
| 147 | const id = arrive(db, false); | |
| 148 | const approved = value(approveReply(db, alice, { id }, at("23:00"))); | |
| 149 | expect(approved.scheduledFor).toBeUndefined(); | |
| 150 | expect(approved.messages[0]!.channel).toBe("email"); | |
| 151 | expect(approved.messages[0]!.status).toBe("sent"); | |
| 152 | }); | |
| 153 | ||
| 154 | test("the tick at 8:00 sends the held text and starts the follow-ups; before 8:00 it waits", () => { | |
| 155 | const db = fresh(); | |
| 156 | const id = arrive(db); | |
| 157 | value(approveReply(db, alice, { id }, at("22:30"))); | |
| 158 | turn(db, at("07:59", "2026-06-11")); | |
| 159 | expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("held"); | |
| 160 | expect(value(tick(db, alice, at("08:00", "2026-06-11"))).leads).toEqual([id]); | |
| 161 | const lead = value(getLead(db, alice, { id })); | |
| 162 | expect(lead.messages[0]!.status).toBe("sent"); | |
| 163 | expect(lead.messages[0]!.sent_at).toBe(at("08:00", "2026-06-11").toISOString()); | |
| 164 | expect(lead.messages[0]!.sent_by).toBe("alice"); | |
| 165 | expect(lead.replied_at).toBe(at("22:30").toISOString()); | |
| 166 | expect(lead.messages.filter((m) => m.day > 0 && m.status === "scheduled")).toHaveLength(5); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a tick that comes late, after 21:00, waits for the next 8:00 instead", () => { | |
| 170 | const db = fresh(); | |
| 171 | const id = arrive(db); | |
| 172 | value(approveReply(db, alice, { id }, at("22:30"))); | |
| 173 | turn(db, at("22:00", "2026-06-11")); | |
| 174 | const lead = value(getLead(db, alice, { id })); | |
| 175 | expect(lead.messages[0]!.status).toBe("held"); | |
| 176 | expect(lead.messages[0]!.goes_at).toBe(at("08:00", "2026-06-12").toISOString()); | |
| 177 | }); | |
| 178 | ||
| 179 | test("cancelling returns a held text to an unsent draft, and the lead is unanswered again", () => { | |
| 180 | const db = fresh(); | |
| 181 | const id = arrive(db); | |
| 182 | value(approveReply(db, alice, { id }, at("22:30"))); | |
| 183 | const back = value(cancelHeld(db, alice, { id }, at("22:40"))); | |
| 184 | const first = back.messages[0]!; | |
| 185 | expect(first.status).toBe("draft"); | |
| 186 | expect(first.goes_at).toBeNull(); | |
| 187 | expect(back.replied_at).toBeNull(); | |
| 188 | expect(back.state).toBe("new"); | |
| 189 | expect(value(listLeads(db, alice)).leads[0]!.ready?.day).toBe(0); | |
| 190 | turn(db, at("09:00", "2026-06-11")); | |
| 191 | expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("draft"); | |
| 192 | expect(cancelHeld(db, alice, { id })).toMatchObject({ ok: false, error: "invalid" }); | |
| 193 | }); | |
| 194 | ||
| 195 | test("a lead who opts out before 8:00 gets an email draft, never the text", () => { | |
| 196 | const db = fresh(); | |
| 197 | const id = arrive(db); | |
| 198 | value(approveReply(db, alice, { id }, at("22:30"))); | |
| 199 | value(optOutTexts(db, alice, { id })); | |
| 200 | turn(db, at("08:00", "2026-06-11")); | |
| 201 | const lead = value(getLead(db, alice, { id })); | |
| 202 | expect(lead.messages.every((m) => m.status !== "sent")).toBe(true); | |
| 203 | const first = lead.messages[0]!; | |
| 204 | expect(first.channel).toBe("email"); | |
| 205 | expect(first.status).toBe("draft"); | |
| 206 | expect(lead.replied_at).toBeNull(); | |
| 207 | }); | |
| 208 | ||
| 209 | test("a held text of a lead since marked lost is set aside and never goes", () => { | |
| 210 | const db = fresh(); | |
| 211 | const id = arrive(db); | |
| 212 | value(approveReply(db, alice, { id }, at("22:30"))); | |
| 213 | value(setState(db, alice, { id, state: "lost" })); | |
| 214 | turn(db, at("08:00", "2026-06-11")); | |
| 215 | expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("skipped"); | |
| 216 | }); | |
| 217 | ||
| 218 | test("an invalid time zone on the profile is a 422 and nothing is saved", async () => { | |
| 219 | const db = fresh(); | |
| 220 | const bad = saveProfile(db, root, { ...agent, timeZone: "Mars/Olympus" }); | |
| 221 | expect(bad).toMatchObject({ ok: false, error: "invalid" }); | |
| 222 | expect(value(listLeads(db, alice)).record).toBeDefined(); | |
| 223 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-quiet-srv-")), identityKey: "k", sample: false }); | |
| 224 | try { | |
| 225 | const identity = `u0|root|admin|${Date.now() + 60_000}`; | |
| 226 | const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json" }; | |
| 227 | const post = (body: unknown) => | |
| 228 | fetch(`http://${server.hostname}:${server.port}/profile`, { method: "POST", headers, body: JSON.stringify(body) }); | |
| 229 | expect((await post({ ...agent, timeZone: "Mars/Olympus" })).status).toBe(422); | |
| 230 | expect((await post({ ...agent, timeZone: "Europe/London" })).status).toBe(200); | |
| 231 | // Left out, it stays as it was. | |
| 232 | const { timeZone: _, ...rest } = agent; | |
| 233 | const kept = await post(rest); | |
| 234 | expect(((await kept.json()) as { timeZone: string }).timeZone).toBe("Europe/London"); | |
| 235 | } finally { | |
| 236 | server.stop(true); | |
| 237 | } | |
| 238 | }); | |
| 239 | ||
| 240 | test("the same hold at the JSON door, the MCP and the terminal", async () => { | |
| 241 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-quiet-doors-")), identityKey: "k", sample: false }); | |
| 242 | try { | |
| 243 | const identity = `u1|alice|user|${Date.now() + 60_000}`; | |
| 244 | const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json", accept: "application/json" }; | |
| 245 | const admin = `u0|root|admin|${Date.now() + 60_000}`; | |
| 246 | const adminHeaders = { ...headers, "x-forge-identity": admin, "x-forge-signature": sign(admin, "k") }; | |
| 247 | const url = `http://${server.hostname}:${server.port}`; | |
| 248 | // The doors read the real clock, so choose a zone in which it is quiet right now. | |
| 249 | const quietZone = Array.from({ length: 25 }, (_, i) => `Etc/GMT${i - 12 < 0 ? "" : "+"}${i - 12}`).find((z) => | |
| 250 | isQuiet(new Date(), z), | |
| 251 | )!; | |
| 252 | await fetch(`${url}/profile`, { method: "POST", headers: adminHeaders, body: JSON.stringify({ ...agent, timeZone: quietZone }) }); | |
| 253 | const made = async () => | |
| 254 | ((await (await fetch(`${url}/leads`, { | |
| 255 | method: "POST", | |
| 256 | headers, | |
| 257 | body: JSON.stringify({ name: "Nina Park", email: "[email protected]", phone: "(206) 555-0177", source: "website", message: "Could we see 12 Cedar Ln?", consent: true }), | |
| 258 | })).json()) as { id: number }).id; | |
| 259 | const json = await made(); | |
| 260 | const answered = (await (await fetch(`${url}/leads/${json}/reply`, { method: "POST", headers, body: "{}" })).json()) as { scheduledFor?: string }; | |
| 261 | expect(answered.scheduledFor).toBeDefined(); | |
| 262 | const back = await fetch(`${url}/leads/${json}/unhold`, { method: "POST", headers, body: "{}" }); | |
| 263 | expect(back.status).toBe(200); | |
| 264 | const spec = (await (await fetch(`${url}/openapi.json`, { headers })).json()) as { components?: unknown }; | |
| 265 | expect(JSON.stringify(spec)).toContain("scheduledFor"); | |
| 266 | ||
| 267 | const viaMcp = await made(); | |
| 268 | const call = (name: string, args: unknown) => | |
| 269 | fetch(`${url}/mcp`, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }).then((r) => r.json() as Promise<any>); | |
| 270 | const sent = await call("send_reply", { id: viaMcp }); | |
| 271 | expect(JSON.parse(sent.result.content[0].text).scheduledFor).toBeDefined(); | |
| 272 | const taken = await call("cancel_held_text", { id: viaMcp }); | |
| 273 | expect(JSON.parse(taken.result.content[0].text).messages[0].status).toBe("draft"); | |
| 274 | } finally { | |
| 275 | server.stop(true); | |
| 276 | } | |
| 277 | }); | |
| 278 | ||
| 279 | test("the terminal says when a held text goes and lets the agent take it back", () => { | |
| 280 | const db = fresh(); | |
| 281 | const id = arrive(db); | |
| 282 | const clock = at("22:30").getTime(); | |
| 283 | const t = terminal(db, alice, () => clock); | |
| 284 | const screen = () => t.screen(100).map(plain).join("\n"); | |
| 285 | expect(screen()).toContain("No replies yet"); | |
| 286 | expect(screen()).toContain("counts as answered when you approve it"); | |
| 287 | value(approveReply(db, alice, { id }, new Date(clock))); | |
| 288 | expect(screen()).toContain("Goes at 8:00 a.m. tomorrow"); | |
| 289 | t.key("\r"); | |
| 290 | expect(screen()).toContain("Goes at 8:00 a.m. tomorrow"); | |
| 291 | t.key("h"); | |
| 292 | expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("draft"); | |
| 293 | }); | |
| 294 | ||
| 295 | test("the lead's page and the desk say when a held text goes, and offer to take it back", () => { | |
| 296 | const db = fresh(); | |
| 297 | const id = arrive(db); | |
| 298 | const now = at("22:30"); | |
| 299 | value(approveReply(db, alice, { id }, now)); | |
| 300 | const profile = { ...agent, timeZone: ZONE }; | |
| 301 | const page = leadPage({ who: alice, agent: profile, lead: value(getLead(db, alice, { id })), mayUpdate: true, next: null, now: now.getTime() }); | |
| 302 | expect(page).toContain("Goes at 8:00 a.m. tomorrow"); | |
| 303 | expect(page).toContain(`action="/leads/${id}/unhold"`); | |
| 304 | const listed = value(listLeads(db, alice)); | |
| 305 | const desk = deskPage({ who: alice, agent: profile, leads: listed.leads, record: listed.record, mayAdd: false, mayReset: false }); | |
| 306 | expect(desk).toContain("counts as answered when you approve it"); | |
| 307 | expect(desk).toMatch(/Goes at 8:00 a\.m\. (today|tomorrow|on )/); | |
| 308 | }); | |
| 309 | ||
| 310 | test("an unsent text opened in quiet hours says approving will hold it", () => { | |
| 311 | const db = fresh(); | |
| 312 | const id = arrive(db); | |
| 313 | const now = at("22:30"); | |
| 314 | const page = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: value(getLead(db, alice, { id })), mayUpdate: true, next: null, now: now.getTime() }); | |
| 315 | expect(page).toContain("approving holds this text"); | |
| 316 | }); |
src/quiet.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** | |
| 2 | * Quiet hours: when a text may go. Texts leave between 8:00 a.m. and 9:00 | |
| 3 | * p.m. in the agent's time zone, the window realtors are told to keep; an | |
| 4 | * email goes any time. Pure functions of an instant and a zone name — no | |
| 5 | * database, no clock of their own. | |
| 6 | */ | |
| 7 | ||
| 8 | export const OPENS = 8; | |
| 9 | export const CLOSES = 21; | |
| 10 | ||
| 11 | /** Whether `zone` is an IANA time zone name the runtime knows. */ | |
| 12 | export function isZone(zone: unknown): zone is string { | |
| 13 | if (typeof zone !== "string" || zone === "" || zone.length > 60) return false; | |
| 14 | try { | |
| 15 | new Intl.DateTimeFormat("en-US", { timeZone: zone }); | |
| 16 | return true; | |
| 17 | } catch { | |
| 18 | return false; | |
| 19 | } | |
| 20 | } | |
| 21 | ||
| 22 | interface Wall { | |
| 23 | readonly y: number; | |
| 24 | readonly m: number; | |
| 25 | readonly d: number; | |
| 26 | readonly h: number; | |
| 27 | } | |
| 28 | ||
| 29 | /** The clock on the wall in `zone` at the instant `ms`. */ | |
| 30 | function wall(ms: number, zone: string): Wall { | |
| 31 | const parts = new Intl.DateTimeFormat("en-US", { | |
| 32 | timeZone: zone, | |
| 33 | year: "numeric", | |
| 34 | month: "numeric", | |
| 35 | day: "numeric", | |
| 36 | hour: "numeric", | |
| 37 | hourCycle: "h23", | |
| 38 | }).formatToParts(ms); | |
| 39 | const n = (type: string): number => | |
| 40 | Number(parts.find((p) => p.type === type)?.value); | |
| 41 | return { y: n("year"), m: n("month"), d: n("day"), h: n("hour") }; | |
| 42 | } | |
| 43 | ||
| 44 | /** The instant at which the wall in `zone` reads `h`:00 on that date (months from 1; days may overflow). */ | |
| 45 | function instant(y: number, m: number, d: number, h: number, zone: string): number { | |
| 46 | const asUtc = Date.UTC(y, m - 1, d, h); | |
| 47 | // The zone's offset at the answer, found by closing in from the guess: two | |
| 48 | // passes settle it on either side of a daylight-saving change. | |
| 49 | let guess = asUtc; | |
| 50 | for (let i = 0; i < 2; i++) { | |
| 51 | const w = wall(guess, zone); | |
| 52 | guess += asUtc - Date.UTC(w.y, w.m - 1, w.d, w.h); | |
| 53 | } | |
| 54 | return guess; | |
| 55 | } | |
| 56 | ||
| 57 | /** | |
| 58 | * Whether a text sent at `at` would land in quiet hours in `zone`. The one | |
| 59 | * switch is the operator's: `QUIET_HOURS=off` lets texts go at any hour (the | |
| 60 | * test suite sets it, so its fixed and real clocks do not matter). | |
| 61 | */ | |
| 62 | export const isQuiet = (at: Date | string | number, zone: string): boolean => { | |
| 63 | if (process.env.QUIET_HOURS === "off") return false; | |
| 64 | const h = wall(new Date(at).getTime(), zone).h; | |
| 65 | return h < OPENS || h >= CLOSES; | |
| 66 | }; | |
| 67 | ||
| 68 | /** The next 8:00 a.m. in `zone` strictly after `at`, as an ISO stamp. */ | |
| 69 | export function nextOpening(at: Date | string | number, zone: string): string { | |
| 70 | const ms = new Date(at).getTime(); | |
| 71 | const w = wall(ms, zone); | |
| 72 | const today = instant(w.y, w.m, w.d, OPENS, zone); | |
| 73 | const opens = today > ms ? today : instant(w.y, w.m, w.d + 1, OPENS, zone); | |
| 74 | return new Date(opens).toISOString(); | |
| 75 | } | |
| 76 | ||
| 77 | /** | |
| 78 | * When a text approved at `at` goes: null when it may go now, else the next | |
| 79 | * 8:00 a.m. Emails never wait. | |
| 80 | */ | |
| 81 | export const goesAt = ( | |
| 82 | channel: "text" | "email", | |
| 83 | at: Date | string | number, | |
| 84 | zone: string, | |
| 85 | ): string | null => | |
| 86 | channel === "text" && isQuiet(at, zone) ? nextOpening(at, zone) : null; | |
| 87 | ||
| 88 | const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; | |
| 89 | ||
| 90 | /** "Goes at 8:00 a.m. tomorrow", or on its date when it is further off. */ | |
| 91 | export function goesLabel(goes: string, now: Date | string | number, zone: string): string { | |
| 92 | const then = wall(Date.parse(goes), zone); | |
| 93 | const here = wall(new Date(now).getTime(), zone); | |
| 94 | const days = | |
| 95 | (Date.UTC(then.y, then.m - 1, then.d) - Date.UTC(here.y, here.m - 1, here.d)) / 86_400_000; | |
| 96 | const time = `${then.h % 12 === 0 ? 12 : then.h % 12}:00 ${then.h < 12 ? "a.m." : "p.m."}`; | |
| 97 | const when = | |
| 98 | days <= 0 ? "today" : days === 1 ? "tomorrow" : `on ${MONTHS[then.m - 1]} ${then.d}`; | |
| 99 | return `Goes at ${time} ${when}`; | |
| 100 | } | |
| 101 | ||
| 102 | /** The sentence under the response record: what counts as the reply. */ | |
| 103 | export const RECORD_NOTE = | |
| 104 | "A text held for quiet hours counts as answered when you approve it, not when it goes."; |
src/routes.ts +37 −5
| @@ -29,6 +29,7 @@ import { | ||
| 29 | 29 | saveProfile, |
| 30 | 30 | optOutTexts, |
| 31 | 31 | approveReply, |
| 32 | cancelHeld, | |
| 32 | 33 | nextLead, |
| 33 | 34 | setState, |
| 34 | 35 | logCall, |
| @@ -117,10 +118,15 @@ export const MESSAGE: Schema = { | ||
| 117 | 118 | channel: { enum: ["text", "email"] }, |
| 118 | 119 | body: { type: "string", minLength: 1, maxLength: MAX_BODY.email }, |
| 119 | 120 | signature: { type: "string" }, |
| 120 | status: { enum: ["draft", "scheduled", "due", "sent", "skipped"] }, | |
| 121 | status: { | |
| 122 | enum: ["draft", "scheduled", "due", "held", "sent", "skipped"], | |
| 123 | description: "held: a text you approved outside 8:00 a.m. to 9:00 p.m. in your time zone; it goes at goes_at.", | |
| 124 | }, | |
| 121 | 125 | due_at: STAMP, |
| 122 | 126 | sent_at: { type: ["string", "null"], format: "date-time" }, |
| 123 | 127 | sent_by: { type: ["string", "null"] }, |
| 128 | goes_at: { type: ["string", "null"], format: "date-time", description: "For a held text, when it goes." }, | |
| 129 | approved_at: { type: ["string", "null"], format: "date-time", description: "For a held text, when you approved it: the moment that counts as the reply." }, | |
| 124 | 130 | }, |
| 125 | 131 | required: ["id", "lead_id", "day", "channel", "body", "signature", "status", "due_at"], |
| 126 | 132 | }; |
| @@ -210,6 +216,11 @@ export const APPROVED: Schema = { | ||
| 210 | 216 | properties: { id: { type: "integer" }, name: { type: "string" } }, |
| 211 | 217 | required: ["id", "name"], |
| 212 | 218 | }, |
| 219 | scheduledFor: { | |
| 220 | ...STAMP, | |
| 221 | description: | |
| 222 | "Present only when the text was held for quiet hours: when it will go (the next 8:00 a.m. in your time zone). Absent when it went now.", | |
| 223 | }, | |
| 213 | 224 | }, |
| 214 | 225 | required: [...(LEAD.required ?? []), "next"], |
| 215 | 226 | }; |
| @@ -227,6 +238,7 @@ export const DESK_LEAD: Schema = { | ||
| 227 | 238 | }, |
| 228 | 239 | }, |
| 229 | 240 | next_at: { type: ["string", "null"], format: "date-time" }, |
| 241 | goes_at: { type: ["string", "null"], format: "date-time", description: "When a text you approved goes, if one is held for quiet hours." }, | |
| 230 | 242 | showing: { |
| 231 | 243 | type: ["object", "null"], |
| 232 | 244 | description: "The showing booked on this lead, if one is.", |
| @@ -237,7 +249,7 @@ export const DESK_LEAD: Schema = { | ||
| 237 | 249 | }, |
| 238 | 250 | }, |
| 239 | 251 | }, |
| 240 | required: [...LEAD_REQUIRED, "ready", "next_at", "showing"], | |
| 252 | required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing"], | |
| 241 | 253 | }; |
| 242 | 254 | const SHOW: Schema = { |
| 243 | 255 | enum: [...VIEWS], |
| @@ -327,6 +339,11 @@ const PROFILE_FIELDS = { | ||
| 327 | 339 | }, |
| 328 | 340 | phone: { type: "string", description: "7 to 20 digits." }, |
| 329 | 341 | email: { type: "string", format: "email" }, |
| 342 | timeZone: { | |
| 343 | type: "string", | |
| 344 | maxLength: 60, | |
| 345 | description: "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is.", | |
| 346 | }, | |
| 330 | 347 | } as const; |
| 331 | 348 | export const PROFILE: Schema = { |
| 332 | 349 | type: "object", |
| @@ -626,7 +643,7 @@ export const routes: readonly Route[] = [ | ||
| 626 | 643 | ), |
| 627 | 644 | api: { |
| 628 | 645 | summary: |
| 629 | "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.", | |
| 646 | "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.", | |
| 630 | 647 | body: { |
| 631 | 648 | type: "object", |
| 632 | 649 | properties: { |
| @@ -795,6 +812,21 @@ export const routes: readonly Route[] = [ | ||
| 795 | 812 | answer: LEAD, |
| 796 | 813 | }, |
| 797 | 814 | }, |
| 815 | { | |
| 816 | method: "POST", | |
| 817 | path: "/leads/:id/unhold", | |
| 818 | handle: (c) => | |
| 819 | posted( | |
| 820 | c, | |
| 821 | () => cancelHeld(c.db, c.who, { id: ID(c) }), | |
| 822 | () => ({ to: `/leads/${ID(c)}`, said: "Taken back. It is a draft again." }), | |
| 823 | ), | |
| 824 | api: { | |
| 825 | summary: | |
| 826 | "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.", | |
| 827 | answer: LEAD, | |
| 828 | }, | |
| 829 | }, | |
| 798 | 830 | { |
| 799 | 831 | method: "POST", |
| 800 | 832 | path: "/leads/:id/opt-out", |
| @@ -816,7 +848,7 @@ export const routes: readonly Route[] = [ | ||
| 816 | 848 | handle: (c) => answer(tick(c.db, c.who)), |
| 817 | 849 | api: { |
| 818 | 850 | summary: |
| 819 | "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.", | |
| 851 | "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.", | |
| 820 | 852 | answer: { |
| 821 | 853 | type: "object", |
| 822 | 854 | properties: { leads: list({ type: "integer" }) }, |
| @@ -902,7 +934,7 @@ export const routes: readonly Route[] = [ | ||
| 902 | 934 | body: { |
| 903 | 935 | type: "object", |
| 904 | 936 | properties: PROFILE_FIELDS, |
| 905 | required: Object.keys(PROFILE_FIELDS), | |
| 937 | required: Object.keys(PROFILE_FIELDS).filter((f) => f !== "timeZone"), | |
| 906 | 938 | }, |
| 907 | 939 | answer: PROFILE, |
| 908 | 940 | }, |
src/sentences.ts +10
| @@ -42,6 +42,16 @@ export function deed( | ||
| 42 | 42 | tried: `send ${kind} to ${lead}`, |
| 43 | 43 | }; |
| 44 | 44 | } |
| 45 | if (row.act === "held") | |
| 46 | return { | |
| 47 | done: `approved a text to ${lead}, held until 8:00 a.m.`, | |
| 48 | tried: `approve a text to ${lead}`, | |
| 49 | }; | |
| 50 | if (row.act === "unhold") | |
| 51 | return { | |
| 52 | done: `took back the held text to ${lead}`, | |
| 53 | tried: `take back the held text to ${lead}`, | |
| 54 | }; | |
| 45 | 55 | if (row.act === "qualified" || row.act === "lost") |
| 46 | 56 | return { |
| 47 | 57 | done: `marked ${lead} ${row.act}`, |
src/server.test.ts +6 −4
| @@ -294,6 +294,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 294 | 294 | "cancel_showing", |
| 295 | 295 | "mark_lead", |
| 296 | 296 | "edit_lead", |
| 297 | "cancel_held_text", | |
| 297 | 298 | "opt_out_texts", |
| 298 | 299 | "get_profile", |
| 299 | 300 | "set_profile", |
| @@ -317,7 +318,7 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 317 | 318 | expect(userSet.result.content[0].text).toContain("forbidden"); |
| 318 | 319 | expect((await call("set_profile", { ...mine, license: "" }, root)).result.isError).toBe(true); |
| 319 | 320 | expect((await call("set_profile", mine, root)).result.isError).toBeUndefined(); |
| 320 | expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine }); | |
| 321 | expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine, timeZone: "America/New_York" }); | |
| 321 | 322 | // The desk over MCP carries the response record beside the leads. |
| 322 | 323 | const deskText = (await call("list_leads", {}, bob)).result.content[0].text; |
| 323 | 324 | const mcpDesk = JSON.parse(deskText) as { record: { days: number; leads: number }; leads: unknown[] }; |
| @@ -343,7 +344,8 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 343 | 344 | }); |
| 344 | 345 | |
| 345 | 346 | test("a change is on the event stream, and a late client hears what it missed", async () => { |
| 346 | const stream = await fetch(base + "/events"); | |
| 347 | // Start past every event any earlier test emitted: only live ones follow. | |
| 348 | const stream = await fetch(base + "/events?since=999999999"); | |
| 347 | 349 | expect(stream.headers.get("content-type")).toBe("text/event-stream"); |
| 348 | 350 | const reader = stream.body!.getReader(); |
| 349 | 351 | const next = async (): Promise<{ id: string; type: string }> => { |
| @@ -528,7 +530,7 @@ test("what the web expects: robots.txt, and security.txt from the forge that run | ||
| 528 | 530 | |
| 529 | 531 | test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => { |
| 530 | 532 | const seen = await (await api("/profile", { headers: asJson }, alice)).json(); |
| 531 | expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone"]); | |
| 533 | expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone", "timeZone"]); | |
| 532 | 534 | const page = await (await api("/profile", {}, alice)).text(); |
| 533 | 535 | expect(page).toContain("Your profile"); |
| 534 | 536 | expect(page).not.toContain('action="/profile"'); |
| @@ -541,7 +543,7 @@ test("the profile is a page and a JSON twin: everyone in reads, only an admin sa | ||
| 541 | 543 | expect(blank.status).toBe(422); |
| 542 | 544 | const saved = await api("/profile", { method: "POST", ...jsonBody(sam) }, root); |
| 543 | 545 | expect(saved.status).toBe(200); |
| 544 | expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam }); | |
| 546 | expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam, timeZone: "America/New_York" }); | |
| 545 | 547 | const form_ = await api("/profile", {}, root); |
| 546 | 548 | expect(await form_.text()).toContain('action="/profile"'); |
| 547 | 549 | const home = await (await api("/", {}, bob)).text(); |
src/server.ts +1 −1
| @@ -27,7 +27,7 @@ export interface ServeOptions { | ||
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 29 | /** How often the server turns the cadence on its own, whether or not anyone calls `POST /tick`. */ |
| 30 | const TURN_MS = 60 * 60_000; | |
| 30 | const TURN_MS = 5 * 60_000; | |
| 31 | 31 | |
| 32 | 32 | export function serve(options: ServeOptions) { |
| 33 | 33 | const db = openDb(options.dataDir); |
src/terminal.test.ts +3 −1
| @@ -243,7 +243,9 @@ test("an admin edits the profile one field at a time; it is saved, audited and r | ||
| 243 | 243 | next(agent.license, "WA 99887"); |
| 244 | 244 | next(agent.phone, "(555) 010-0000"); |
| 245 | 245 | next(agent.email, "[email protected]"); |
| 246 | next(agent.timeZone, "America/Chicago"); | |
| 246 | 247 | expect(read(t)).toContain("Saved."); |
| 248 | expect(db.query<{ time_zone: string }, []>("SELECT time_zone FROM profile").get()?.time_zone).toBe("America/Chicago"); | |
| 247 | 249 | expect(read(t)).toContain("WA 99887"); |
| 248 | 250 | const saved = db.query<{ license: string }, []>("SELECT license FROM profile").get(); |
| 249 | 251 | expect(saved?.license).toBe("WA 99887"); |
| @@ -264,7 +266,7 @@ test("a blank license typed in the terminal is refused and nothing is saved", () | ||
| 264 | 266 | for (const current of [agent.name, agent.brokerage]) t.key("\r"), void current; |
| 265 | 267 | clear(t, agent.license); |
| 266 | 268 | t.key("\r"); |
| 267 | for (let i = 0; i < 2; i++) t.key("\r"); | |
| 269 | for (let i = 0; i < 3; i++) t.key("\r"); | |
| 268 | 270 | expect(read(t)).toContain("license number is required"); |
| 269 | 271 | expect(db.query("SELECT * FROM profile").all()).toHaveLength(0); |
| 270 | 272 | }); |
src/terminal.ts +27 −4
| @@ -36,6 +36,7 @@ import { | ||
| 36 | 36 | resetSample, |
| 37 | 37 | saveProfile, |
| 38 | 38 | approveReply, |
| 39 | cancelHeld, | |
| 39 | 40 | logCall, |
| 40 | 41 | bookShowing, |
| 41 | 42 | cancelShowing, |
| @@ -47,6 +48,7 @@ import { showingLine, showingWhen } from "./showings.ts"; | ||
| 47 | 48 | import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts"; |
| 48 | 49 | import { between, elapsed, recordLine, tone } from "./clock.ts"; |
| 49 | 50 | import { permit } from "./contract.ts"; |
| 51 | import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts"; | |
| 50 | 52 | import { said as saidOf } from "./sentences.ts"; |
| 51 | 53 | import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel } from "./drafts.ts"; |
| 52 | 54 | import { ssh, title, where } from "./env.ts"; |
| @@ -111,6 +113,7 @@ const PROFILE_FIELDS = [ | ||
| 111 | 113 | { key: "license", label: "License number (required: every message shows it)" }, |
| 112 | 114 | { key: "phone", label: "Phone" }, |
| 113 | 115 | { key: "email", label: "Email" }, |
| 116 | { key: "timeZone", label: "Time zone (e.g. America/Chicago: texts go 8:00 a.m. to 9:00 p.m. there)" }, | |
| 114 | 117 | ] as const; |
| 115 | 118 | |
| 116 | 119 | type View = |
| @@ -222,8 +225,10 @@ export function terminal( | ||
| 222 | 225 | const rows = listed.value.leads; |
| 223 | 226 | cursor = Math.min(cursor, Math.max(0, rows.length - 1)); |
| 224 | 227 | const counts = listed.value.counts; |
| 228 | const zone = currentAgent(db).timeZone; | |
| 225 | 229 | const lines: string[] = [ |
| 226 | 230 | dim(recordLine(listed.value.record)), |
| 231 | dim(RECORD_NOTE), | |
| 227 | 232 | VIEWS.map((v) => { |
| 228 | 233 | const tab = `${VIEW_LABEL[v]} ${counts[v]}`; |
| 229 | 234 | return v === show ? bold(`[${tab}]`) : dim(tab); |
| @@ -235,7 +240,9 @@ export function terminal( | ||
| 235 | 240 | lines.push(dim(q === "" ? EMPTY[show] : `No lead matches '${clean(q)}'.`)); |
| 236 | 241 | rows.forEach((l, i) => { |
| 237 | 242 | const next = |
| 238 | l.ready === null | |
| 243 | l.goes_at !== null | |
| 244 | ? dim(goesLabel(l.goes_at, now(), zone)) | |
| 245 | : l.ready === null | |
| 239 | 246 | ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "") |
| 240 | 247 | : l.ready.day === 0 |
| 241 | 248 | ? "reply drafted" |
| @@ -284,6 +291,7 @@ export function terminal( | ||
| 284 | 291 | return deskScreen(); |
| 285 | 292 | } |
| 286 | 293 | const r = ready(l); |
| 294 | const zone = currentAgent(db).timeZone; | |
| 287 | 295 | const channel = channelFor(l); |
| 288 | 296 | const lines = [ |
| 289 | 297 | `${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`, |
| @@ -298,6 +306,14 @@ export function terminal( | ||
| 298 | 306 | "", |
| 299 | 307 | ]), |
| 300 | 308 | ]; |
| 309 | const held = l.messages.find((m) => m.status === "held"); | |
| 310 | if (held !== undefined && held.goes_at !== null) | |
| 311 | lines.push( | |
| 312 | bold(`${titleOf(held)} — by ${held.channel}, approved`), | |
| 313 | dim(` ${goesLabel(held.goes_at, now(), zone)} (texts go 8:00 a.m. to 9:00 p.m., ${zone})`), | |
| 314 | ...wrap(held.body, width).map((s) => ` ${s}`), | |
| 315 | "", | |
| 316 | ); | |
| 301 | 317 | if (r === undefined) { |
| 302 | 318 | const next = l.messages.find((m) => m.status === "scheduled"); |
| 303 | 319 | lines.push( |
| @@ -315,6 +331,8 @@ export function terminal( | ||
| 315 | 331 | `${titleOf(r)} — by ${r.channel}${editing === undefined ? ", as it will go" : ", editing"}`, |
| 316 | 332 | ), |
| 317 | 333 | ); |
| 334 | if (r.channel === "text" && isQuiet(now(), zone)) | |
| 335 | lines.push(dim(` Outside texting hours: approving holds it. ${goesLabel(nextOpening(now(), zone), now(), zone)}.`)); | |
| 318 | 336 | if (r.channel === "email") |
| 319 | 337 | lines.push( |
| 320 | 338 | dim( |
| @@ -355,6 +373,7 @@ export function terminal( | ||
| 355 | 373 | : dim( |
| 356 | 374 | [ |
| 357 | 375 | ...(r === undefined ? [] : ["s approve and send", "e edit"]), |
| 376 | ...(held === undefined ? [] : ["h take back the held text"]), | |
| 358 | 377 | ...(l.phone === "" ? [] : ["c log a call"]), |
| 359 | 378 | ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []), |
| 360 | 379 | ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]), |
| @@ -454,9 +473,10 @@ export function terminal( | ||
| 454 | 473 | } |
| 455 | 474 | |
| 456 | 475 | function send(id: number, body?: string): void { |
| 457 | const sent = approveReply(db, me, { id, body }); | |
| 476 | const zone = currentAgent(db).timeZone; | |
| 477 | const sent = approveReply(db, me, { id, body }, new Date(now())); | |
| 458 | 478 | said = sent.ok |
| 459 | ? `Sent to ${sent.value.name}.${sent.value.next === null ? " Nothing else needs you right now." : ` Next: ${sent.value.next.name} (])`}` | |
| 479 | ? `${sent.value.scheduledFor === undefined ? "Sent to" : `Held for quiet hours; ${goesLabel(sent.value.scheduledFor, now(), zone).toLowerCase()}:`} ${sent.value.name}.${sent.value.next === null ? " Nothing else needs you right now." : ` Next: ${sent.value.next.name} (])`}` | |
| 460 | 480 | : sent.message; |
| 461 | 481 | view = { name: "lead", id }; |
| 462 | 482 | } |
| @@ -664,7 +684,10 @@ export function terminal( | ||
| 664 | 684 | if (next === null) said = "Nothing else needs you right now."; |
| 665 | 685 | else view = { name: "lead", id: next.id }; |
| 666 | 686 | } |
| 667 | else if (input === "e") { | |
| 687 | else if (input === "h" && l.messages.some((m) => m.status === "held")) { | |
| 688 | const back = cancelHeld(db, me, { id }); | |
| 689 | said = back.ok ? "Taken back. It is a draft again." : back.message; | |
| 690 | } else if (input === "e") { | |
| 668 | 691 | const r = ready(l); |
| 669 | 692 | if (r === undefined) said = "Nothing is waiting to go to this lead right now."; |
| 670 | 693 | else view = { name: "edit", id, text: r.body }; |
src/test-setup.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | /** | |
| 2 | * Runs before every test file. Most tests approve texts at whatever hour the | |
| 3 | * machine's clock (or their fixed stamp) says, so quiet hours are off for | |
| 4 | * them; the tests about quiet hours turn them back on (`quiet.test.ts`). | |
| 5 | */ | |
| 6 | process.env.QUIET_HOURS = "off"; |
new above
offline