Public: anyone can read this; the crew can change it.
A lead who came by referral names who sent them, and a thank-you to that person waits on the desk for the agent to approve #95
Check · Review · Land · Live done — Landed and live in production.
mason/speed-to-lead:mason/86-a-lead-who-came-by-referral-names-who-se → main 2 commits fork
21 files
changed +1136
−23
AGENTS.md +6
| @@ -140,6 +140,12 @@ Speed to Lead is one realtor's desk. The concepts, one module each: | ||
| 140 | 140 | not touch the cadence. `starredFirst` lifts starred open leads to the top of |
| 141 | 141 | any view but leaves a first reply past the green clock ahead of them, and does |
| 142 | 142 | nothing while nobody is starred. `show=starred` is a view of its own. |
| 143 | - `src/thanks.ts` — the thank-you to whoever referred a lead (`referred_by`, | |
| 144 | `referrer_email`, `referrer_phone` on the lead; `referrer_thanks` table, one | |
| 145 | per lead). It is deliberately not a `message`: it goes to someone who is not | |
| 146 | the lead, so STOP, the response clock, the cadence and `readyFor` never see | |
| 147 | it. A draft until `sendThanks` (a person approves); a text outside quiet | |
| 148 | hours is `held` and `turn` sends it at 8:00. Same cell as any lead change. | |
| 143 | 149 | - `src/drafts.ts` — the words: templates filled from the inquiry and the |
| 144 | 150 | agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*` |
| 145 | 151 | defaults of `agent` in `src/env.ts`; its `openers` are the agent's own |
README.md +17 −1
| @@ -124,6 +124,17 @@ what you see right after a restart. Do step 1 first. | ||
| 124 | 124 | cannot; "Add" makes each visitor a lead with a thank-you for that address |
| 125 | 125 | drafted. Someone already on the desk lands on their lead. Nothing is sent |
| 126 | 126 | until you approve it. |
| 127 | 12. When a lead came by referral, say who sent them: pick the source | |
| 128 | "Referral" and fill "Referred by" with their name and an email or phone | |
| 129 | (James O'Neill in the samples came from Sarah Patel). A short thank-you to | |
| 130 | that person, naming only the lead's first name, waits on the lead's page | |
| 131 | (and as a "Thank Sarah (referrer)" tag on the desk), labelled as going to | |
| 132 | the referrer, never to the lead. Press "Approve and send thank-you", | |
| 133 | edit it first, or "Don't thank". Nothing goes until you approve it; it | |
| 134 | goes by email when they gave one; with only a phone it goes as a text | |
| 135 | (to someone who has not agreed to be texted, so the card says so and the | |
| 136 | choice is yours), held until 8:00 a.m. if you approve it after hours. The referrer shows on the lead's page, in | |
| 137 | the spreadsheet and in Activity, and is never put in a message to the lead. | |
| 127 | 138 | |
| 128 | 139 | Nothing is really sent in this prototype: "send" records the message in the |
| 129 | 140 | lead's history and goes no further. To run the tour again, restart the |
| @@ -507,6 +518,11 @@ itself every five minutes. The whole API is described at `/openapi.json`, and th | ||
| 507 | 518 | actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`, |
| 508 | 519 | `send_reply`, `mark_lead`, `export_leads`). |
| 509 | 520 | |
| 521 | A referral may name who sent it the same way over the wire: `POST /leads` takes | |
| 522 | `referred_by` with `referrer_email` or `referrer_phone` (only with source | |
| 523 | `referral`), `add_lead` in MCP takes the same, and the thank-you is approved | |
| 524 | with `POST /leads/{id}/thanks` (`send_thanks` in MCP; `r` in the terminal). | |
| 525 | ||
| 510 | 526 | ## From a terminal |
| 511 | 527 | |
| 512 | 528 | When the forge gives the app a terminal, the command to reach it is shown |
| @@ -546,7 +562,7 @@ Every lead and its status, as a spreadsheet, for whoever may list leads, with no | ||
| 546 | 562 | - **Desk:** the "Download leads (CSV)" link under the list; it keeps the current view and search. **HTTP:** `GET /leads.csv[?show=needs|open|closed|all][&q=…]` (anon gets 401). The response is `no-store`. |
| 547 | 563 | - **MCP:** the `export_leads` tool (`show`, `q`) returns `{ name, csv, count }`. **Terminal:** `x` on the desk shows the CSV for the current view and search on screen (`esc` goes back); download the file from the web desk. |
| 548 | 564 | |
| 549 | Columns: name, email, phone, source, status, arrived at, first reply at, minutes to first reply, last message at (the later of a message sent and a reply from the lead), texts allowed. Times are ISO 8601. A field starting with `=`, `@`, `-`, `+`, tab or carriage return is prefixed with `'` so a spreadsheet never runs it as a formula; the one exception is a phone number written like `+1 206-555-0101` (a plus, then digits and the usual marks), which is kept as typed. | |
| 565 | Columns: name, email, phone, source, status, arrived at, first reply at, minutes to first reply, last message at (the later of a message sent and a reply from the lead), texts allowed, lost reason, starred, and who referred them (name, email, phone). Times are ISO 8601. A field starting with `=`, `@`, `-`, `+`, tab or carriage return is prefixed with `'` so a spreadsheet never runs it as a formula; the one exception is a phone number written like `+1 206-555-0101` (a plus, then digits and the usual marks), which is kept as typed. | |
| 550 | 566 | |
| 551 | 567 | ## Running it |
| 552 | 568 |
contract/openapi.json +292 −2
| @@ -113,6 +113,20 @@ | ||
| 113 | 113 | "consent": { |
| 114 | 114 | "type": "boolean", |
| 115 | 115 | "description": "Prior written consent to be texted. Without it, only email." |
| 116 | }, | |
| 117 | "referred_by": { | |
| 118 | "type": "string", | |
| 119 | "maxLength": 120, | |
| 120 | "description": "Only with source referral: who sent them. Needs referrer_email or referrer_phone; a thank-you to them is drafted for you to approve." | |
| 121 | }, | |
| 122 | "referrer_email": { | |
| 123 | "type": "string", | |
| 124 | "format": "email", | |
| 125 | "description": "The referrer's email; empty when none." | |
| 126 | }, | |
| 127 | "referrer_phone": { | |
| 128 | "type": "string", | |
| 129 | "description": "The referrer's phone (7 to 20 digits); a thank-you text only when no email is given." | |
| 116 | 130 | } |
| 117 | 131 | }, |
| 118 | 132 | "required": [ |
| @@ -816,6 +830,20 @@ | ||
| 816 | 830 | "type": "boolean", |
| 817 | 831 | "description": "The agent keeps this lead close: starred open leads lead the desk." |
| 818 | 832 | }, |
| 833 | "referred_by": { | |
| 834 | "type": "string", | |
| 835 | "maxLength": 120, | |
| 836 | "description": "For a referral: the name of who sent them; empty when nobody is named. Never part of a message to the lead." | |
| 837 | }, | |
| 838 | "referrer_email": { | |
| 839 | "type": "string", | |
| 840 | "format": "email", | |
| 841 | "description": "The referrer's email; empty when none." | |
| 842 | }, | |
| 843 | "referrer_phone": { | |
| 844 | "type": "string", | |
| 845 | "description": "The referrer's phone; empty when none." | |
| 846 | }, | |
| 819 | 847 | "created_at": { |
| 820 | 848 | "type": "string", |
| 821 | 849 | "format": "date-time" |
| @@ -947,6 +975,62 @@ | ||
| 947 | 975 | "booked_at" |
| 948 | 976 | ] |
| 949 | 977 | }, |
| 978 | "thanks": { | |
| 979 | "type": [ | |
| 980 | "object", | |
| 981 | "null" | |
| 982 | ], | |
| 983 | "description": "The thank-you drafted to the lead's referrer (it goes to the referrer, never the lead); null when nobody referred them.", | |
| 984 | "properties": { | |
| 985 | "lead_id": { | |
| 986 | "type": "integer" | |
| 987 | }, | |
| 988 | "channel": { | |
| 989 | "enum": [ | |
| 990 | "text", | |
| 991 | "email" | |
| 992 | ] | |
| 993 | }, | |
| 994 | "body": { | |
| 995 | "type": "string" | |
| 996 | }, | |
| 997 | "signature": { | |
| 998 | "type": "string" | |
| 999 | }, | |
| 1000 | "status": { | |
| 1001 | "enum": [ | |
| 1002 | "draft", | |
| 1003 | "held", | |
| 1004 | "sent", | |
| 1005 | "skipped" | |
| 1006 | ] | |
| 1007 | }, | |
| 1008 | "created_at": { | |
| 1009 | "type": "string", | |
| 1010 | "format": "date-time" | |
| 1011 | }, | |
| 1012 | "goes_at": { | |
| 1013 | "type": [ | |
| 1014 | "string", | |
| 1015 | "null" | |
| 1016 | ], | |
| 1017 | "format": "date-time" | |
| 1018 | }, | |
| 1019 | "sent_at": { | |
| 1020 | "type": [ | |
| 1021 | "string", | |
| 1022 | "null" | |
| 1023 | ], | |
| 1024 | "format": "date-time" | |
| 1025 | }, | |
| 1026 | "sent_by": { | |
| 1027 | "type": [ | |
| 1028 | "string", | |
| 1029 | "null" | |
| 1030 | ] | |
| 1031 | } | |
| 1032 | } | |
| 1033 | }, | |
| 950 | 1034 | "next": { |
| 951 | 1035 | "type": [ |
| 952 | 1036 | "object", |
| @@ -988,6 +1072,9 @@ | ||
| 988 | 1072 | "lostAt", |
| 989 | 1073 | "back_on", |
| 990 | 1074 | "starred", |
| 1075 | "referred_by", | |
| 1076 | "referrer_email", | |
| 1077 | "referrer_phone", | |
| 991 | 1078 | "created_at", |
| 992 | 1079 | "replied_at", |
| 993 | 1080 | "updated_at", |
| @@ -995,6 +1082,7 @@ | ||
| 995 | 1082 | "replies", |
| 996 | 1083 | "calls", |
| 997 | 1084 | "showing", |
| 1085 | "thanks", | |
| 998 | 1086 | "next" |
| 999 | 1087 | ] |
| 1000 | 1088 | } |
| @@ -1014,6 +1102,100 @@ | ||
| 1014 | 1102 | } |
| 1015 | 1103 | } |
| 1016 | 1104 | }, |
| 1105 | "/leads/{id}/thanks": { | |
| 1106 | "post": { | |
| 1107 | "summary": "Approve the thank-you drafted to the person who referred this lead — as drafted, or with `body` as edited. It goes to the referrer, never to the lead. A text outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 (thanks.status is `held`); an email goes now. A lead nobody referred is 422; a thank-you already dealt with is 409.", | |
| 1108 | "operationId": "postLeadsIdThanks", | |
| 1109 | "parameters": [ | |
| 1110 | { | |
| 1111 | "name": "id", | |
| 1112 | "in": "path", | |
| 1113 | "required": true, | |
| 1114 | "schema": { | |
| 1115 | "type": "integer" | |
| 1116 | } | |
| 1117 | } | |
| 1118 | ], | |
| 1119 | "requestBody": { | |
| 1120 | "required": true, | |
| 1121 | "content": { | |
| 1122 | "application/json": { | |
| 1123 | "schema": { | |
| 1124 | "type": "object", | |
| 1125 | "properties": { | |
| 1126 | "body": { | |
| 1127 | "type": "string", | |
| 1128 | "minLength": 1, | |
| 1129 | "maxLength": 4000, | |
| 1130 | "description": "The words, edited; the draft when left out. A text is at most 480 characters. The signature is added." | |
| 1131 | } | |
| 1132 | } | |
| 1133 | } | |
| 1134 | } | |
| 1135 | } | |
| 1136 | }, | |
| 1137 | "responses": { | |
| 1138 | "200": { | |
| 1139 | "description": "Approve the thank-you drafted to the person who referred this lead — as drafted, or with `body` as edited. It goes to the referrer, never to the lead. A text outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 (thanks.status is `held`); an email goes now. A lead nobody referred is 422; a thank-you already dealt with is 409.", | |
| 1140 | "content": { | |
| 1141 | "application/json": { | |
| 1142 | "schema": { | |
| 1143 | "$ref": "#/components/schemas/Lead" | |
| 1144 | } | |
| 1145 | } | |
| 1146 | } | |
| 1147 | }, | |
| 1148 | "default": { | |
| 1149 | "description": "{ error, message }: why not", | |
| 1150 | "content": { | |
| 1151 | "application/json": { | |
| 1152 | "schema": { | |
| 1153 | "$ref": "#/components/schemas/Error" | |
| 1154 | } | |
| 1155 | } | |
| 1156 | } | |
| 1157 | } | |
| 1158 | } | |
| 1159 | } | |
| 1160 | }, | |
| 1161 | "/leads/{id}/thanks/skip": { | |
| 1162 | "post": { | |
| 1163 | "summary": "Set the drafted thank-you to the lead's referrer aside; nothing is sent. No body needed.", | |
| 1164 | "operationId": "postLeadsIdThanksSkip", | |
| 1165 | "parameters": [ | |
| 1166 | { | |
| 1167 | "name": "id", | |
| 1168 | "in": "path", | |
| 1169 | "required": true, | |
| 1170 | "schema": { | |
| 1171 | "type": "integer" | |
| 1172 | } | |
| 1173 | } | |
| 1174 | ], | |
| 1175 | "responses": { | |
| 1176 | "200": { | |
| 1177 | "description": "Set the drafted thank-you to the lead's referrer aside; nothing is sent. No body needed.", | |
| 1178 | "content": { | |
| 1179 | "application/json": { | |
| 1180 | "schema": { | |
| 1181 | "$ref": "#/components/schemas/Lead" | |
| 1182 | } | |
| 1183 | } | |
| 1184 | } | |
| 1185 | }, | |
| 1186 | "default": { | |
| 1187 | "description": "{ error, message }: why not", | |
| 1188 | "content": { | |
| 1189 | "application/json": { | |
| 1190 | "schema": { | |
| 1191 | "$ref": "#/components/schemas/Error" | |
| 1192 | } | |
| 1193 | } | |
| 1194 | } | |
| 1195 | } | |
| 1196 | } | |
| 1197 | } | |
| 1198 | }, | |
| 1017 | 1199 | "/leads/{id}/insert": { |
| 1018 | 1200 | "post": { |
| 1019 | 1201 | "summary": "Add one of the agent's saved replies to the end of the draft that is ready for this lead and answer with the words, unsent and unsaved. `{first_name}` becomes the lead's first name. A text or email that would be too long is refused with 422. Send the result with POST /leads/{id}/reply.", |
| @@ -2482,6 +2664,20 @@ | ||
| 2482 | 2664 | "type": "boolean", |
| 2483 | 2665 | "description": "The agent keeps this lead close: starred open leads lead the desk." |
| 2484 | 2666 | }, |
| 2667 | "referred_by": { | |
| 2668 | "type": "string", | |
| 2669 | "maxLength": 120, | |
| 2670 | "description": "For a referral: the name of who sent them; empty when nobody is named. Never part of a message to the lead." | |
| 2671 | }, | |
| 2672 | "referrer_email": { | |
| 2673 | "type": "string", | |
| 2674 | "format": "email", | |
| 2675 | "description": "The referrer's email; empty when none." | |
| 2676 | }, | |
| 2677 | "referrer_phone": { | |
| 2678 | "type": "string", | |
| 2679 | "description": "The referrer's phone; empty when none." | |
| 2680 | }, | |
| 2485 | 2681 | "created_at": { |
| 2486 | 2682 | "type": "string", |
| 2487 | 2683 | "format": "date-time" |
| @@ -2612,6 +2808,62 @@ | ||
| 2612 | 2808 | "hold_until", |
| 2613 | 2809 | "booked_at" |
| 2614 | 2810 | ] |
| 2811 | }, | |
| 2812 | "thanks": { | |
| 2813 | "type": [ | |
| 2814 | "object", | |
| 2815 | "null" | |
| 2816 | ], | |
| 2817 | "description": "The thank-you drafted to the lead's referrer (it goes to the referrer, never the lead); null when nobody referred them.", | |
| 2818 | "properties": { | |
| 2819 | "lead_id": { | |
| 2820 | "type": "integer" | |
| 2821 | }, | |
| 2822 | "channel": { | |
| 2823 | "enum": [ | |
| 2824 | "text", | |
| 2825 | "email" | |
| 2826 | ] | |
| 2827 | }, | |
| 2828 | "body": { | |
| 2829 | "type": "string" | |
| 2830 | }, | |
| 2831 | "signature": { | |
| 2832 | "type": "string" | |
| 2833 | }, | |
| 2834 | "status": { | |
| 2835 | "enum": [ | |
| 2836 | "draft", | |
| 2837 | "held", | |
| 2838 | "sent", | |
| 2839 | "skipped" | |
| 2840 | ] | |
| 2841 | }, | |
| 2842 | "created_at": { | |
| 2843 | "type": "string", | |
| 2844 | "format": "date-time" | |
| 2845 | }, | |
| 2846 | "goes_at": { | |
| 2847 | "type": [ | |
| 2848 | "string", | |
| 2849 | "null" | |
| 2850 | ], | |
| 2851 | "format": "date-time" | |
| 2852 | }, | |
| 2853 | "sent_at": { | |
| 2854 | "type": [ | |
| 2855 | "string", | |
| 2856 | "null" | |
| 2857 | ], | |
| 2858 | "format": "date-time" | |
| 2859 | }, | |
| 2860 | "sent_by": { | |
| 2861 | "type": [ | |
| 2862 | "string", | |
| 2863 | "null" | |
| 2864 | ] | |
| 2865 | } | |
| 2866 | } | |
| 2615 | 2867 | } |
| 2616 | 2868 | }, |
| 2617 | 2869 | "required": [ |
| @@ -2630,13 +2882,17 @@ | ||
| 2630 | 2882 | "lostAt", |
| 2631 | 2883 | "back_on", |
| 2632 | 2884 | "starred", |
| 2885 | "referred_by", | |
| 2886 | "referrer_email", | |
| 2887 | "referrer_phone", | |
| 2633 | 2888 | "created_at", |
| 2634 | 2889 | "replied_at", |
| 2635 | 2890 | "updated_at", |
| 2636 | 2891 | "messages", |
| 2637 | 2892 | "replies", |
| 2638 | 2893 | "calls", |
| 2639 | "showing" | |
| 2894 | "showing", | |
| 2895 | "thanks" | |
| 2640 | 2896 | ] |
| 2641 | 2897 | }, |
| 2642 | 2898 | "Desk": { |
| @@ -2894,6 +3150,20 @@ | ||
| 2894 | 3150 | "type": "boolean", |
| 2895 | 3151 | "description": "The agent keeps this lead close: starred open leads lead the desk." |
| 2896 | 3152 | }, |
| 3153 | "referred_by": { | |
| 3154 | "type": "string", | |
| 3155 | "maxLength": 120, | |
| 3156 | "description": "For a referral: the name of who sent them; empty when nobody is named. Never part of a message to the lead." | |
| 3157 | }, | |
| 3158 | "referrer_email": { | |
| 3159 | "type": "string", | |
| 3160 | "format": "email", | |
| 3161 | "description": "The referrer's email; empty when none." | |
| 3162 | }, | |
| 3163 | "referrer_phone": { | |
| 3164 | "type": "string", | |
| 3165 | "description": "The referrer's phone; empty when none." | |
| 3166 | }, | |
| 2897 | 3167 | "created_at": { |
| 2898 | 3168 | "type": "string", |
| 2899 | 3169 | "format": "date-time" |
| @@ -2944,6 +3214,22 @@ | ||
| 2944 | 3214 | "format": "date-time", |
| 2945 | 3215 | "description": "When a text you approved goes, if one is held for quiet hours." |
| 2946 | 3216 | }, |
| 3217 | "thanks": { | |
| 3218 | "anyOf": [ | |
| 3219 | { | |
| 3220 | "enum": [ | |
| 3221 | "draft", | |
| 3222 | "held", | |
| 3223 | "sent", | |
| 3224 | "skipped" | |
| 3225 | ] | |
| 3226 | }, | |
| 3227 | { | |
| 3228 | "type": "null" | |
| 3229 | } | |
| 3230 | ], | |
| 3231 | "description": "Where the thank-you to the lead's referrer stands; null when nobody referred them." | |
| 3232 | }, | |
| 2947 | 3233 | "showing": { |
| 2948 | 3234 | "type": [ |
| 2949 | 3235 | "object", |
| @@ -2983,13 +3269,17 @@ | ||
| 2983 | 3269 | "lostAt", |
| 2984 | 3270 | "back_on", |
| 2985 | 3271 | "starred", |
| 3272 | "referred_by", | |
| 3273 | "referrer_email", | |
| 3274 | "referrer_phone", | |
| 2986 | 3275 | "created_at", |
| 2987 | 3276 | "replied_at", |
| 2988 | 3277 | "updated_at", |
| 2989 | 3278 | "ready", |
| 2990 | 3279 | "next_at", |
| 2991 | 3280 | "goes_at", |
| 2992 | "showing" | |
| 3281 | "showing", | |
| 3282 | "thanks" | |
| 2993 | 3283 | ] |
| 2994 | 3284 | }, |
| 2995 | 3285 | "Message": { |
src/actions.ts +109 −1
| @@ -72,11 +72,13 @@ import { | ||
| 72 | 72 | viewOf, |
| 73 | 73 | type Contact, |
| 74 | 74 | type Desk, |
| 75 | type Lead, | |
| 75 | 76 | type LeadDetail, |
| 76 | 77 | type NewLead, |
| 77 | 78 | type NextLead, |
| 78 | 79 | } from "./leads.ts"; |
| 79 | 80 | import { emit } from "./live.ts"; |
| 81 | import { approveThanks, sendHeldThanks, skipThanks, thanksOf, type Thanks } from "./thanks.ts"; | |
| 80 | 82 | import { capture, keep, restore, whyNot } from "./undo.ts"; |
| 81 | 83 | import { currentAgent, storeAgent } from "./profile.ts"; |
| 82 | 84 | import { append, fill, REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLIES, type SavedReply } from "./replies.ts"; |
| @@ -290,6 +292,8 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> { | ||
| 290 | 292 | ); |
| 291 | 293 | if (message.length === 0 || message.length > 2000) |
| 292 | 294 | return fail("invalid", "What they asked is 1 to 2000 characters."); |
| 295 | const sender = readReferrer(input, source); | |
| 296 | if (!sender.ok) return sender; | |
| 293 | 297 | return ok({ |
| 294 | 298 | name, |
| 295 | 299 | email, |
| @@ -297,9 +301,36 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> { | ||
| 297 | 301 | source, |
| 298 | 302 | message, |
| 299 | 303 | consent: consentOf(input.consent), |
| 304 | ...sender.value, | |
| 300 | 305 | }); |
| 301 | 306 | } |
| 302 | 307 | |
| 308 | /** | |
| 309 | * Who sent a referral lead, checked like a lead's own details (same length and | |
| 310 | * format limits). All three blank is no referrer; a name needs an email or a | |
| 311 | * phone; a contact with no name, or any of it on a lead that is not a | |
| 312 | * referral, is refused. | |
| 313 | */ | |
| 314 | function readReferrer( | |
| 315 | input: Record<string, unknown>, | |
| 316 | source: Source | undefined, | |
| 317 | ): Result<Pick<NewLead, "referred_by" | "referrer_email" | "referrer_phone">> { | |
| 318 | const text = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); | |
| 319 | const name = text(input.referred_by); | |
| 320 | const email = text(input.referrer_email).toLowerCase(); | |
| 321 | const phone = text(input.referrer_phone); | |
| 322 | if (name === "" && email === "" && phone === "") return ok({}); | |
| 323 | if (source !== "referral") | |
| 324 | return fail("invalid", "Only a lead whose source is referral can name who referred them."); | |
| 325 | if ([name, email, phone].some((v) => hasControl(v, false))) | |
| 326 | return fail("invalid", "A referrer's details are plain text: no control characters or line breaks."); | |
| 327 | if (name === "") return fail("invalid", "Name who referred them, or leave the referrer blank."); | |
| 328 | const wrong = contactProblem({ name, email, phone }, true); | |
| 329 | if (wrong !== undefined) | |
| 330 | return fail("invalid", wrong.replace("A name is", "A referrer's name is").replace("A lead needs", "A referrer needs")); | |
| 331 | return ok({ referred_by: name, referrer_email: email, referrer_phone: phone }); | |
| 332 | } | |
| 333 | ||
| 303 | 334 | /** A lead added; `again` when it was someone already on the desk who wrote in again. */ |
| 304 | 335 | export type Added = LeadDetail & { readonly again?: true }; |
| 305 | 336 | |
| @@ -315,6 +346,8 @@ export const addLead = ( | ||
| 315 | 346 | at?: Date, |
| 316 | 347 | ): Result<Added> => { |
| 317 | 348 | const result = add(db, who, input, at); |
| 349 | if (result.ok && result.value.again !== true && result.value.referred_by !== "") | |
| 350 | return audited(db, who, "lead", "create", undefined, result, "referred", JSON.stringify({ referrer: result.value.referred_by })); | |
| 318 | 351 | if (!result.ok || result.value.again !== true) |
| 319 | 352 | return audited(db, who, "lead", "create", undefined, result); |
| 320 | 353 | const detail = mergeDetail({ source: sourceOf(input.source)!, lead: result.value.id }); |
| @@ -332,6 +365,11 @@ function add( | ||
| 332 | 365 | const read = readNewLead(input); |
| 333 | 366 | if (!read.ok) return read; |
| 334 | 367 | const known = findMatch(db, read.value); |
| 368 | if (known !== null && read.value.referred_by !== undefined) | |
| 369 | return fail( | |
| 370 | "invalid", | |
| 371 | `${known.name} is already on the desk, so this would not be a new lead and the referrer would be lost. Add them without a referrer, or note who referred them in their private note.`, | |
| 372 | ); | |
| 335 | 373 | if (known !== null) { |
| 336 | 374 | writeInAgain(db, known, read.value.message, stamp(at), currentAgent(db)); |
| 337 | 375 | emit("lead.changed", { id: known.id }); |
| @@ -1212,6 +1250,76 @@ function remove( | ||
| 1212 | 1250 | return ok({ id: found.value.id }); |
| 1213 | 1251 | } |
| 1214 | 1252 | |
| 1253 | /** The thank-you to a lead's referrer as it can be approved: the lead, and the draft still waiting. */ | |
| 1254 | function waitingThanks( | |
| 1255 | db: Database, | |
| 1256 | who: Who, | |
| 1257 | id: number, | |
| 1258 | words: { signIn: string; no: string }, | |
| 1259 | ): Result<{ lead: Lead; thanks: Thanks }> { | |
| 1260 | const found = leadFor(db, who, "update", id, words); | |
| 1261 | if (!found.ok) return found; | |
| 1262 | const thanks = thanksOf(db, found.value.id); | |
| 1263 | if (thanks === null) return fail("invalid", "Nobody is named as having referred this lead."); | |
| 1264 | if (thanks.status !== "draft") return fail("conflict", "The thank-you to the referrer is already dealt with."); | |
| 1265 | return ok({ lead: found.value, thanks }); | |
| 1266 | } | |
| 1267 | ||
| 1268 | /** | |
| 1269 | * Approve the thank-you to the person who referred a lead, as drafted or as | |
| 1270 | * the agent edited it. It goes to the referrer, never to the lead. Nothing | |
| 1271 | * goes out until this is called; a text outside quiet hours is held for 8:00. | |
| 1272 | */ | |
| 1273 | export const sendThanks = ( | |
| 1274 | db: Database, | |
| 1275 | who: Who, | |
| 1276 | input: { id: number; body?: string | undefined }, | |
| 1277 | at?: Date, | |
| 1278 | ): Result<LeadDetail> => { | |
| 1279 | const waiting = waitingThanks(db, who, input.id, { | |
| 1280 | signIn: "Sign in to thank a referrer.", | |
| 1281 | no: "You may not thank this lead's referrer.", | |
| 1282 | }); | |
| 1283 | let result: Result<LeadDetail>; | |
| 1284 | let held = false; | |
| 1285 | if (!waiting.ok) result = waiting; | |
| 1286 | else { | |
| 1287 | const { lead, thanks } = waiting.value; | |
| 1288 | const body = lines(input.body ?? thanks.body).trim(); | |
| 1289 | const max = MAX_BODY[thanks.channel]; | |
| 1290 | if (hasControl(body, true)) result = fail("invalid", "A message is plain text: no control characters."); | |
| 1291 | else if (body.length === 0 || body.length > max) | |
| 1292 | result = fail("invalid", `A${thanks.channel === "text" ? " text" : "n email"} is 1 to ${max} characters.`); | |
| 1293 | else { | |
| 1294 | const by = who.role === "anon" ? "" : who.name; | |
| 1295 | held = db.transaction(() => approveThanks(db, thanks, body, by, stamp(at), currentAgent(db)))() !== null; | |
| 1296 | emit("lead.changed", { id: lead.id }); | |
| 1297 | result = ok(detail(db, lead.id)!); | |
| 1298 | } | |
| 1299 | } | |
| 1300 | return audited(db, who, "lead", "update", input.id, result, held ? "thanks_held" : "thanked"); | |
| 1301 | }; | |
| 1302 | ||
| 1303 | /** Set the thank-you to a referrer aside: nobody is thanked and the draft stops waiting. */ | |
| 1304 | export const skipThanksFor = ( | |
| 1305 | db: Database, | |
| 1306 | who: Who, | |
| 1307 | input: { id: number }, | |
| 1308 | ): Result<LeadDetail> => { | |
| 1309 | const waiting = waitingThanks(db, who, input.id, { | |
| 1310 | signIn: "Sign in to set a thank-you aside.", | |
| 1311 | no: "You may not set aside this thank-you.", | |
| 1312 | }); | |
| 1313 | let result: Result<LeadDetail>; | |
| 1314 | if (!waiting.ok) result = waiting; | |
| 1315 | else { | |
| 1316 | skipThanks(db, waiting.value.lead.id); | |
| 1317 | emit("lead.changed", { id: waiting.value.lead.id }); | |
| 1318 | result = ok(detail(db, waiting.value.lead.id)!); | |
| 1319 | } | |
| 1320 | return audited(db, who, "lead", "update", input.id, result, "thanks_skipped"); | |
| 1321 | }; | |
| 1322 | ||
| 1215 | 1323 | /** |
| 1216 | 1324 | * 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. |
| 1217 | 1325 | * The forge may call it daily (`POST /tick`); the server also runs it on |
| @@ -1240,7 +1348,7 @@ export function tick( | ||
| 1240 | 1348 | /** The clock's own turn, asked of no one: time passing is not a person. */ |
| 1241 | 1349 | export function turn(db: Database, at?: Date): number[] { |
| 1242 | 1350 | const now = stamp(at); |
| 1243 | const sent = sendHeld(db, now, currentAgent(db)); | |
| 1351 | const sent = [...sendHeld(db, now, currentAgent(db)), ...sendHeldThanks(db, now, currentAgent(db))]; | |
| 1244 | 1352 | const leads = [...new Set([...advance(db, now), ...sent])]; |
| 1245 | 1353 | for (const id of leads) emit("lead.changed", { id }); |
| 1246 | 1354 | return leads; |
src/audit.ts +2 −2
| @@ -34,8 +34,8 @@ export interface AuditRow { | ||
| 34 | 34 | readonly detail: string | null; |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go; `unsent` takes back a send within its minute. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred", "unsent"] as const; | |
| 37 | /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go; `unsent` takes back a send within its minute; `referred` is a lead added with the person who sent them (the detail holds `{"referrer":"name"}`); `thanked` approves the thank-you to a referrer, `thanks_held` approves it as a text held for quiet hours, `thanks_skipped` sets it aside. */ | |
| 38 | export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred", "unsent", "referred", "thanked", "thanks_held", "thanks_skipped"] as const; | |
| 39 | 39 | export type Act = (typeof ACTS)[number]; |
| 40 | 40 | |
| 41 | 41 | /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */ |
src/contract.test.ts +21
| @@ -34,6 +34,8 @@ import { | ||
| 34 | 34 | setNote, |
| 35 | 35 | setState, |
| 36 | 36 | setStarred, |
| 37 | sendThanks, | |
| 38 | skipThanksFor, | |
| 37 | 39 | } from "./actions.ts"; |
| 38 | 40 | import { record } from "./audit.ts"; |
| 39 | 41 | import { actingAs, identities, table, type Verb } from "./can.ts"; |
| @@ -55,6 +57,7 @@ function whoIs(identity: string): Who { | ||
| 55 | 57 | import { agent } from "./env.ts"; |
| 56 | 58 | import { findLead, hold, insertLead, type Message } from "./leads.ts"; |
| 57 | 59 | import { tools } from "./mcp.ts"; |
| 60 | import { insertThanks } from "./thanks.ts"; | |
| 58 | 61 | |
| 59 | 62 | // Leads name no one: they are the desk's, not a person's. `authorId` goes unused. |
| 60 | 63 | const aLead = (_authorId: string): number => |
| @@ -71,6 +74,13 @@ const aLead = (_authorId: string): number => | ||
| 71 | 74 | new Date().toISOString(), |
| 72 | 75 | agent, |
| 73 | 76 | ); |
| 77 | /** A referral lead with a thank-you to its referrer waiting. */ | |
| 78 | const referredLead = (_authorId: string): number => { | |
| 79 | const id = aLead(_authorId); | |
| 80 | db.query("UPDATE lead SET source = 'referral', referred_by = 'Sam Ray', referrer_email = '[email protected]' WHERE id = ?1").run(id); | |
| 81 | insertThanks(db, id, { referred_by: "Sam Ray", referrer_email: "[email protected]", referrer_phone: "" }, "Lead", new Date().toISOString()); | |
| 82 | return id; | |
| 83 | }; | |
| 74 | 84 | /** A lead with a text held for 8:00, as quiet hours leave it. */ |
| 75 | 85 | const heldLead = (authorId: string): number => { |
| 76 | 86 | const id = aLead(authorId); |
| @@ -184,7 +194,18 @@ const doors: Record< | ||
| 184 | 194 | // POST /leads/:id/star, the MCP tool star_lead). |
| 185 | 195 | const starred = setStarred(db, who, { id: replied, starred: true }).ok; |
| 186 | 196 | const starredViaTool = (tools.find((t) => t.name === "star_lead")!.run(db, who, { id: replied, starred: false }) as { ok: boolean }).ok; |
| 197 | // And so is thanking a lead's referrer, or setting the thank-you aside | |
| 198 | // (POST /leads/:id/thanks and /thanks/skip, the MCP tools send_thanks and | |
| 199 | // skip_thanks, `r` and `R` in the terminal): lead update. | |
| 200 | const thanked = sendThanks(db, who, { id: referredLead(authorId) }).ok; | |
| 201 | const thankedViaTool = (tools.find((t) => t.name === "send_thanks")!.run(db, who, { id: referredLead(authorId) }) as { ok: boolean }).ok; | |
| 202 | const thanksSkipped = skipThanksFor(db, who, { id: referredLead(authorId) }).ok; | |
| 203 | const skippedViaTool = (tools.find((t) => t.name === "skip_thanks")!.run(db, who, { id: referredLead(authorId) }) as { ok: boolean }).ok; | |
| 187 | 204 | const changed = setState(db, who, { id: aLead(authorId), state: "lost", reason: "other" }).ok; |
| 205 | expect(thanked).toBe(changed); | |
| 206 | expect(thankedViaTool).toBe(changed); | |
| 207 | expect(thanksSkipped).toBe(changed); | |
| 208 | expect(skippedViaTool).toBe(changed); | |
| 188 | 209 | expect(starred).toBe(changed); |
| 189 | 210 | expect(starredViaTool).toBe(changed); |
| 190 | 211 | expect(skipped).toBe(changed); |
src/db.ts +18
| @@ -276,6 +276,24 @@ export const migrations: string[] = [ | ||
| 276 | 276 | after_updated_at TEXT NOT NULL, |
| 277 | 277 | snapshot TEXT NOT NULL |
| 278 | 278 | )`, |
| 279 | // Who sent a referral lead: a name with an email and/or a phone. Empty on every lead that exists today. | |
| 280 | `ALTER TABLE lead ADD COLUMN referred_by TEXT NOT NULL DEFAULT ''`, | |
| 281 | `ALTER TABLE lead ADD COLUMN referrer_email TEXT NOT NULL DEFAULT ''`, | |
| 282 | `ALTER TABLE lead ADD COLUMN referrer_phone TEXT NOT NULL DEFAULT ''`, | |
| 283 | // The thank-you to a referrer, one per lead. It is not a message: it goes to someone who is not the lead, so the | |
| 284 | // lead's STOP, response clock and cadence never see it. A draft until the agent approves it; a text outside quiet | |
| 285 | // hours is 'held' until goes_at. | |
| 286 | `CREATE TABLE IF NOT EXISTS referrer_thanks ( | |
| 287 | lead_id INTEGER PRIMARY KEY REFERENCES lead (id) ON DELETE CASCADE, | |
| 288 | channel TEXT NOT NULL CHECK (channel IN ('text', 'email')), | |
| 289 | body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 4000), | |
| 290 | signature TEXT NOT NULL, | |
| 291 | status TEXT NOT NULL CHECK (status IN ('draft', 'held', 'sent', 'skipped')), | |
| 292 | created_at TEXT NOT NULL, | |
| 293 | goes_at TEXT, | |
| 294 | sent_at TEXT, | |
| 295 | sent_by TEXT | |
| 296 | )`, | |
| 279 | 297 | ]; |
| 280 | 298 | |
| 281 | 299 | /** |
src/drafts.ts +13
| @@ -400,3 +400,16 @@ export function answerDraft(lead: Asker, wrote: string): string { | ||
| 400 | 400 | return `Hi ${first}, thanks for getting back to me! ${next}`; |
| 401 | 401 | return `Hi ${first},\n\nThanks for getting back to me. ${next}\n\nTalk soon,`; |
| 402 | 402 | } |
| 403 | ||
| 404 | /** | |
| 405 | * The thank-you to whoever sent a referral lead: it goes to the referrer, not | |
| 406 | * the lead, and names only the lead's first name (nothing they asked or the | |
| 407 | * agent noted). A text when the referrer can only be reached by phone. | |
| 408 | */ | |
| 409 | export function thanksDraft(referrerName: string, leadName: string, channel: Channel): string { | |
| 410 | const first = firstName(referrerName); | |
| 411 | const lead = firstName(leadName); | |
| 412 | const thanks = `thank you for sending ${lead} my way. I'm looking after them now, and I'm grateful you thought of me.`; | |
| 413 | if (channel === "text") return `Hi ${first}, ${thanks}`; | |
| 414 | return `Hi ${first},\n\nThank you for sending ${lead} my way. I'm looking after them now, and I'm grateful you thought of me.\n\nWith thanks,`; | |
| 415 | } |
src/export.test.ts +4 −1
| @@ -171,9 +171,12 @@ test("minutes to first reply, texts allowed, and last message", () => { | ||
| 171 | 171 | "yes", |
| 172 | 172 | "", |
| 173 | 173 | "no", |
| 174 | "", | |
| 175 | "", | |
| 176 | "", | |
| 174 | 177 | ]); |
| 175 | 178 | const waiting = parse(leadsCsv([{ ...lead, replied_at: null, consent: false }], new Map()))[1]!; |
| 176 | expect(waiting.slice(6)).toEqual(["", "", "", "no", "", "no"]); | |
| 179 | expect(waiting.slice(6)).toEqual(["", "", "", "no", "", "no", "", "", ""]); | |
| 177 | 180 | expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv"); |
| 178 | 181 | }); |
| 179 | 182 |
src/export.ts +7 −1
| @@ -19,6 +19,9 @@ export const COLUMNS = [ | ||
| 19 | 19 | "texts allowed", |
| 20 | 20 | "lost_reason", |
| 21 | 21 | "starred", |
| 22 | "referred by", | |
| 23 | "referrer email", | |
| 24 | "referrer phone", | |
| 22 | 25 | ] as const; |
| 23 | 26 | |
| 24 | 27 | /** An international number, "+1 206-555-0101": a plus and then only digits and the marks people type. */ |
| @@ -61,8 +64,11 @@ export function leadsCsv( | ||
| 61 | 64 | lead.consent ? "yes" : "no", |
| 62 | 65 | lead.state === "lost" ? (lead.lostReason ?? "no reason given") : "", |
| 63 | 66 | lead.starred ? "yes" : "no", |
| 67 | lead.referred_by, | |
| 68 | lead.referrer_email, | |
| 69 | lead.referrer_phone, | |
| 64 | 70 | ]); |
| 65 | return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone")).join(",")).join("\r\n") + "\r\n"; | |
| 71 | return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone" || COLUMNS[i] === "referrer phone")).join(",")).join("\r\n") + "\r\n"; | |
| 66 | 72 | } |
| 67 | 73 | |
| 68 | 74 | /** The file's name for a day: leads-2026-11-02.csv. */ |
src/leads.ts +32 −4
| @@ -37,6 +37,7 @@ import { answers, type Call, type Outcome } from "./calls.ts"; | ||
| 37 | 37 | import { between, GREEN_MS } from "./clock.ts"; |
| 38 | 38 | import type { Agent } from "./env.ts"; |
| 39 | 39 | import { isQuiet, nextOpening } from "./quiet.ts"; |
| 40 | import { insertThanks, thanksOf, type Thanks } from "./thanks.ts"; | |
| 40 | 41 | import { type LostReason } from "./lost.ts"; |
| 41 | 42 | import { followUpsFinished } from "./finished.ts"; |
| 42 | 43 | import { morningOn } from "./putaway.ts"; |
| @@ -73,6 +74,10 @@ export interface Lead { | ||
| 73 | 74 | readonly back_on: string | null; |
| 74 | 75 | /** The agent keeps this lead close: starred open leads lead the desk. */ |
| 75 | 76 | readonly starred: boolean; |
| 77 | /** For a referral: who sent them. Empty when nobody is named. Never part of a message to the lead. */ | |
| 78 | readonly referred_by: string; | |
| 79 | readonly referrer_email: string; | |
| 80 | readonly referrer_phone: string; | |
| 76 | 81 | } |
| 77 | 82 | |
| 78 | 83 | export interface Message { |
| @@ -117,6 +122,8 @@ export interface LeadDetail extends Lead { | ||
| 117 | 122 | readonly showing: Showing | null; |
| 118 | 123 | /** Every follow-up has gone out or been set aside and no one answered: the agent may close it out. */ |
| 119 | 124 | readonly finished: boolean; |
| 125 | /** The thank-you drafted to the referrer (not the lead); null when nobody referred them. */ | |
| 126 | readonly thanks: Thanks | null; | |
| 120 | 127 | } |
| 121 | 128 | |
| 122 | 129 | /** When the lead began to wait on our answer to what they wrote back; null when no answer is owed. */ |
| @@ -135,6 +142,8 @@ export interface DeskLead extends Lead { | ||
| 135 | 142 | readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null; |
| 136 | 143 | /** Every follow-up has gone out or been set aside and no one answered. */ |
| 137 | 144 | readonly finished: boolean; |
| 145 | /** Where the thank-you to the lead's referrer stands (it goes to them, not the lead); null when nobody referred this lead. */ | |
| 146 | readonly thanks: Thanks["status"] | null; | |
| 138 | 147 | } |
| 139 | 148 | |
| 140 | 149 | /** |
| @@ -214,6 +223,10 @@ export type NewLead = { | ||
| 214 | 223 | readonly source: Source; |
| 215 | 224 | readonly message: string; |
| 216 | 225 | readonly consent: boolean; |
| 226 | /** For a referral: who sent them, with an email and/or a phone. */ | |
| 227 | readonly referred_by?: string; | |
| 228 | readonly referrer_email?: string; | |
| 229 | readonly referrer_phone?: string; | |
| 217 | 230 | }; |
| 218 | 231 | |
| 219 | 232 | type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt" | "starred"> & { |
| @@ -304,6 +317,7 @@ export function detail(db: Database, id: number): LeadDetail | null { | ||
| 304 | 317 | replies, |
| 305 | 318 | calls, |
| 306 | 319 | showing, |
| 320 | thanks: thanksOf(db, id), | |
| 307 | 321 | finished: followUpsFinished(found, messages, replies.length + calls.length > 0, showing !== null), |
| 308 | 322 | }; |
| 309 | 323 | } |
| @@ -363,6 +377,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 363 | 377 | show_at: string | null; |
| 364 | 378 | show_address: string | null; |
| 365 | 379 | show_hold: string | null; |
| 380 | thanks_status: Thanks["status"] | null; | |
| 366 | 381 | }, |
| 367 | 382 | [number, string, string] |
| 368 | 383 | >( |
| @@ -374,7 +389,8 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 374 | 389 | (SELECT min(goes_at) FROM message WHERE lead_id = lead.id AND status = 'held') AS goes_at, |
| 375 | 390 | (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at, |
| 376 | 391 | (SELECT address FROM showing WHERE lead_id = lead.id) AS show_address, |
| 377 | (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold | |
| 392 | (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold, | |
| 393 | (SELECT status FROM referrer_thanks WHERE lead_id = lead.id) AS thanks_status | |
| 378 | 394 | FROM lead |
| 379 | 395 | WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\' |
| 380 | 396 | OR lead.note LIKE ?2 ESCAPE '\\' |
| @@ -382,8 +398,9 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] { | ||
| 382 | 398 | ORDER BY max(created_at, coalesce((SELECT max(at) FROM inbound WHERE lead_id = lead.id), '')) DESC, id DESC LIMIT ?1`, |
| 383 | 399 | ) |
| 384 | 400 | .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`) |
| 385 | .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, ...row }) => ({ | |
| 401 | .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, thanks_status, ...row }) => ({ | |
| 386 | 402 | ...lead(row), |
| 403 | thanks: thanks_status, | |
| 387 | 404 | finished: finishedIds.has(row.id), |
| 388 | 405 | ready: |
| 389 | 406 | ready_id === null || ready_day === null || ready_since === null |
| @@ -566,9 +583,9 @@ export function insertLead( | ||
| 566 | 583 | const { id } = db |
| 567 | 584 | .query< |
| 568 | 585 | { id: number }, |
| 569 | [string, string, string, string, string, number, string] | |
| 586 | [string, string, string, string, string, number, string, string, string, string] | |
| 570 | 587 | >( |
| 571 | "INSERT INTO lead (name, email, phone, source, message, consent, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7) RETURNING id", | |
| 588 | "INSERT INTO lead (name, email, phone, source, message, consent, created_at, updated_at, referred_by, referrer_email, referrer_phone) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?8, ?9, ?10) RETURNING id", | |
| 572 | 589 | ) |
| 573 | 590 | .get( |
| 574 | 591 | input.name, |
| @@ -578,7 +595,18 @@ export function insertLead( | ||
| 578 | 595 | input.message, |
| 579 | 596 | input.consent ? 1 : 0, |
| 580 | 597 | at, |
| 598 | input.referred_by ?? "", | |
| 599 | input.referrer_email ?? "", | |
| 600 | input.referrer_phone ?? "", | |
| 581 | 601 | )!; |
| 602 | if (input.referred_by) | |
| 603 | insertThanks( | |
| 604 | db, | |
| 605 | id, | |
| 606 | { referred_by: input.referred_by, referrer_email: input.referrer_email ?? "", referrer_phone: input.referrer_phone ?? "" }, | |
| 607 | input.name, | |
| 608 | at, | |
| 609 | ); | |
| 582 | 610 | const channel = channelFor(input); |
| 583 | 611 | db.query( |
| 584 | 612 | "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, 0, ?2, ?3, ?4, 'draft', ?5)", |
src/mcp.ts +19 −1
| @@ -9,6 +9,8 @@ | ||
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | 10 | import { |
| 11 | 11 | addLead, |
| 12 | sendThanks, | |
| 13 | skipThanksFor, | |
| 12 | 14 | addSampleInquiry, |
| 13 | 15 | exportLeads, |
| 14 | 16 | getLead, |
| @@ -120,7 +122,7 @@ export const tools: readonly Tool[] = [ | ||
| 120 | 122 | { |
| 121 | 123 | name: "add_lead", |
| 122 | 124 | description: |
| 123 | "A new lead arrives, with its first reply drafted. consent is prior written consent to be texted.", | |
| 125 | "A new lead arrives, with its first reply drafted. consent is prior written consent to be texted. A referral may name who sent them (referred_by with referrer_email or referrer_phone): a thank-you to that person is drafted, to approve with send_thanks. It is never sent to the lead.", | |
| 124 | 126 | inputSchema: { |
| 125 | 127 | type: "object", |
| 126 | 128 | properties: { |
| @@ -130,11 +132,27 @@ export const tools: readonly Tool[] = [ | ||
| 130 | 132 | source: { enum: SOURCES }, |
| 131 | 133 | message: { type: "string" }, |
| 132 | 134 | consent: { type: "boolean" }, |
| 135 | referred_by: { type: "string", description: "Only with source referral: the name of who sent them. Needs referrer_email or referrer_phone." }, | |
| 136 | referrer_email: { type: "string" }, | |
| 137 | referrer_phone: { type: "string" }, | |
| 133 | 138 | }, |
| 134 | 139 | required: ["name", "email", "source", "message"], |
| 135 | 140 | }, |
| 136 | 141 | run: (db, who, args) => addLead(db, who, args), |
| 137 | 142 | }, |
| 143 | { | |
| 144 | name: "send_thanks", | |
| 145 | description: | |
| 146 | "Approve the thank-you drafted to the person who referred a lead (as drafted, or with body as edited). It goes to the referrer, never to the lead. A text outside 8:00 a.m. to 9:00 p.m. is held for the next 8:00; an email goes now. Sends only what a person approved by calling this.", | |
| 147 | inputSchema: { type: "object", properties: { id: { type: "integer" }, body: { type: "string" } }, required: ["id"] }, | |
| 148 | run: (db, who, args) => sendThanks(db, who, { id: Number(args.id), body: typeof args.body === "string" ? args.body : undefined }), | |
| 149 | }, | |
| 150 | { | |
| 151 | name: "skip_thanks", | |
| 152 | description: "Set the drafted thank-you to a lead's referrer aside; nothing is sent.", | |
| 153 | inputSchema: ONE, | |
| 154 | run: (db, who, args) => skipThanksFor(db, who, { id: Number(args.id) }), | |
| 155 | }, | |
| 138 | 156 | { |
| 139 | 157 | name: "parse_lead_email", |
| 140 | 158 | description: |
src/pages/desk.ts +15 −2
| @@ -7,7 +7,7 @@ import { day, clock, consent, source, starForm, STATE_LABEL } from "./parts.ts"; | ||
| 7 | 7 | import { deskTitle, layout } from "./layout.ts"; |
| 8 | 8 | import { escape } from "../http.ts"; |
| 9 | 9 | import { recordLine, sourceLine, trendLine } from "../clock.ts"; |
| 10 | import { isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts"; | |
| 10 | import { firstName, isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts"; | |
| 11 | 11 | import { FINISHED_ACTION, FINISHED_LABEL } from "../finished.ts"; |
| 12 | 12 | import { dateName } from "../putaway.ts"; |
| 13 | 13 | import { goesLabel, RECORD_NOTE } from "../quiet.ts"; |
| @@ -230,7 +230,7 @@ const row = (lead: DeskLead, now: number, zone: string, back?: string): string = | ||
| 230 | 230 | <span class="lead-main"> |
| 231 | 231 | <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : ` |
| 232 | 232 | <span class="note-line">${escape(noteLine(lead.note))}</span>`} |
| 233 | <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}${backBadge(lead)}</span> | |
| 233 | <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}${backBadge(lead)}${thanksBadge(lead)}</span> | |
| 234 | 234 | <span class="ask">${escape(lead.message)}</span> |
| 235 | 235 | ${status(lead, now, zone)} |
| 236 | 236 | </span> |
| @@ -280,6 +280,12 @@ const signInForm = (sheet?: { preview?: SignInPreview | undefined; address: stri | ||
| 280 | 280 | </details>`; |
| 281 | 281 | }; |
| 282 | 282 | |
| 283 | /** A thank-you to the referrer is waiting to be approved: a chip that says it is not for the lead. */ | |
| 284 | const thanksBadge = (lead: DeskLead): string => | |
| 285 | lead.thanks === "draft" | |
| 286 | ? `<a class="chip" data-thanks="draft" href="/leads/${lead.id}#thanks" title="A thank-you to the person who referred them waits for your approval">Thank ${escape(firstName(lead.referred_by))} (referrer)</a>` | |
| 287 | : ""; | |
| 288 | ||
| 283 | 289 | const addForm = (prefill?: Partial<NewLead>): string => `<details class="card add"${prefill === undefined ? "" : " open"}> |
| 284 | 290 | <summary>Log a lead by hand</summary> |
| 285 | 291 | ${prefill === undefined ? "" : `<p class="muted" role="status">${escape(missingLine(prefill))} Text OK is never taken from an email: tick it only with written consent.</p>`} |
| @@ -294,6 +300,13 @@ const addForm = (prefill?: Partial<NewLead>): string => `<details class="card ad | ||
| 294 | 300 | </label> |
| 295 | 301 | <label>What they asked <textarea class="input" name="message" required maxlength="2000" rows="3">${escape(prefill?.message ?? "")}</textarea></label> |
| 296 | 302 | <label class="check"><input type="checkbox" name="consent" value="yes"> They gave written consent to be texted</label> |
| 303 | <fieldset class="stack"> | |
| 304 | <legend>If it's a referral: who sent them (optional)</legend> | |
| 305 | <label>Referred by <input class="input" name="referred_by" maxlength="120" autocomplete="off"></label> | |
| 306 | <label>Their email <input class="input" name="referrer_email" type="email" maxlength="254" autocomplete="off"></label> | |
| 307 | <label>Their phone <input class="input" name="referrer_phone" type="tel" maxlength="20" autocomplete="off"></label> | |
| 308 | <p class="hint">A thank-you to them waits for you to approve. It is never sent to the lead.</p> | |
| 309 | </fieldset> | |
| 297 | 310 | <button class="button">Add to the desk</button> |
| 298 | 311 | </form> |
| 299 | 312 | </details>`; |
src/pages/lead.ts +42
| @@ -8,6 +8,7 @@ import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts"; | ||
| 8 | 8 | import { channelFor, dayLabel, isAnswer, planLabel, MAX_BODY } from "../drafts.ts"; |
| 9 | 9 | import { fill, joiner, SAMPLE_REPLIES } from "../replies.ts"; |
| 10 | 10 | import { escape } from "../http.ts"; |
| 11 | import { referrerAddress } from "../thanks.ts"; | |
| 11 | 12 | import { handoff } from "../handoff.ts"; |
| 12 | 13 | import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts"; |
| 13 | 14 | import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen } from "../showings.ts"; |
| @@ -326,6 +327,7 @@ export function leadPage(input: { | ||
| 326 | 327 | <h1>${escape(lead.name)}</h1>${mayUpdate ? ` |
| 327 | 328 | ${starForm(lead, path)}` : ""} |
| 328 | 329 | <p class="tags">${source(lead)}${consent(lead, agent.timeZone)}<span class="chip" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span></p> |
| 330 | ${lead.referred_by === "" ? "" : `<p class="muted" data-referrer>Referred by ${escape(lead.referred_by)} · ${escape(referrerAddress(lead))}</p>`} | |
| 329 | 331 | <p class="contact">${contact}${ |
| 330 | 332 | mayUpdate && lead.phone !== "" |
| 331 | 333 | ? ` · <a href="#log-call">Log a call</a>` |
| @@ -335,6 +337,7 @@ export function leadPage(input: { | ||
| 335 | 337 | ${clock(lead, now, owed)} |
| 336 | 338 | </header> |
| 337 | 339 | ${noteCard(lead, path, mayUpdate, agent.timeZone)} |
| 340 | ${thanksCard(lead, path, mayUpdate, agent, now)} | |
| 338 | 341 | <div class="split"> |
| 339 | 342 | <div class="pane theirs"> |
| 340 | 343 | <h2>They asked <span class="muted">· <time datetime="${escape(lead.created_at)}">${escape(when(lead.created_at, agent.timeZone))}</time></span></h2> |
| @@ -355,6 +358,45 @@ export function leadPage(input: { | ||
| 355 | 358 | }); |
| 356 | 359 | } |
| 357 | 360 | |
| 361 | /** | |
| 362 | * The thank-you to whoever referred the lead: labelled as going to the | |
| 363 | * referrer, not the lead, and approved on its own button like any message. | |
| 364 | */ | |
| 365 | function thanksCard(lead: LeadDetail, path: string, may: boolean, agent: Agent, now: number): string { | |
| 366 | const t = lead.thanks; | |
| 367 | if (t === null) return ""; | |
| 368 | const to = `${escape(lead.referred_by)} (${escape(referrerAddress(lead))})`; | |
| 369 | const head = `<h2>Thank-you to ${escape(lead.referred_by)} <span class="muted">· goes to the person who referred ${escape(lead.name)}, not to ${escape(lead.name)} · by ${CHANNEL[t.channel]}</span></h2>`; | |
| 370 | if (t.status === "sent") | |
| 371 | return `<section class="card" id="thanks" data-thanks="sent">${head}<p class="muted">Sent to ${to}${t.sent_at === null ? "" : ` ${escape(when(t.sent_at, agent.timeZone))}`}.</p><div class="draft-view">${escape(t.body)}</div></section>`; | |
| 372 | if (t.status === "skipped") | |
| 373 | return `<section class="card" id="thanks" data-thanks="skipped">${head}<p class="muted">Set aside: nobody was thanked.</p></section>`; | |
| 374 | if (t.status === "held") | |
| 375 | return `<section class="card" id="thanks" data-thanks="held">${head}<p class="muted">Approved for ${to}. ${escape(t.goes_at === null ? "" : goesLabel(t.goes_at, now, agent.timeZone))}.</p><div class="draft-view">${escape(t.body)}</div></section>`; | |
| 376 | return `<section class="card stack" id="thanks" data-thanks="draft">${head} | |
| 377 | <p class="muted">To ${to}. Nothing is sent until you approve it.</p> | |
| 378 | ${t.channel === "text" ? `<p class="hint">${escape(lead.referred_by)} gave only a phone number and has not agreed to be texted: this goes as a text to someone who never opted in. Add their email to the lead, or call them, if you would rather not.</p>` : ""} | |
| 379 | <div class="draft-view">${escape(t.body)}</div> | |
| 380 | ${ | |
| 381 | may | |
| 382 | ? `<div class="actions"> | |
| 383 | <form method="post" action="${path}/thanks"><button class="button">Approve and send thank-you</button></form> | |
| 384 | <details class="edit"> | |
| 385 | <summary class="button button-quiet">Edit</summary> | |
| 386 | <form class="stack" method="post" action="${path}/thanks"> | |
| 387 | <label class="sr" for="thanks-body">Your thank-you to ${escape(lead.referred_by)}</label> | |
| 388 | <textarea class="input" id="thanks-body" name="body" rows="${t.channel === "text" ? 4 : 7}" maxlength="${MAX_BODY[t.channel]}" required>${escape(t.body)}</textarea> | |
| 389 | <button class="button">Approve and send thank-you</button> | |
| 390 | </form> | |
| 391 | </details> | |
| 392 | <form method="post" action="${path}/thanks/skip"><button class="button button-quiet">Don't thank</button></form> | |
| 393 | </div> | |
| 394 | ${t.channel === "text" && isQuiet(now, agent.timeZone) ? `<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>` : ""}` | |
| 395 | : "" | |
| 396 | } | |
| 397 | </section>`; | |
| 398 | } | |
| 399 | ||
| 358 | 400 | /** "Your note": the agent's own, private; the form only for whoever may update the lead. */ |
| 359 | 401 | function noteCard(lead: LeadDetail, path: string, may: boolean, zone: string): string { |
| 360 | 402 | if (lead.note === "" && !may) return ""; |
src/referral.test.ts added +297
| @@ -0,0 +1,297 @@ | ||
| 1 | /** | |
| 2 | * A referral lead names who sent them. A thank-you to that person waits for | |
| 3 | * the agent to approve: it goes to the referrer and never to the lead, it is | |
| 4 | * kept out of the lead's messages (STOP, the clock and the cadence), and it | |
| 5 | * shows in the lead's page, JSON, the CSV and the Activity log. | |
| 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 | activity, | |
| 13 | addLead, | |
| 14 | exportLeads, | |
| 15 | getLead, | |
| 16 | listLeads, | |
| 17 | optOutTexts, | |
| 18 | sendReply, | |
| 19 | sendThanks, | |
| 20 | skipThanksFor, | |
| 21 | saveProfile, | |
| 22 | turn, | |
| 23 | } from "./actions.ts"; | |
| 24 | import { agent } from "./env.ts"; | |
| 25 | import { openDb } from "./db.ts"; | |
| 26 | import { activityPage } from "./pages/activity.ts"; | |
| 27 | import { deskPage } from "./pages/desk.ts"; | |
| 28 | import { leadPage } from "./pages/lead.ts"; | |
| 29 | import { serve } from "./server.ts"; | |
| 30 | import { plain, terminal } from "./terminal.ts"; | |
| 31 | import { SAMPLES } from "./sample.ts"; | |
| 32 | import { sign } from "./who.ts"; | |
| 33 | import type { Who } from "./who.ts"; | |
| 34 | ||
| 35 | const alice: Who = { role: "user", id: "u1", name: "alice" }; | |
| 36 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 37 | const anon: Who = { role: "anon" }; | |
| 38 | const ZONE = "America/Chicago"; | |
| 39 | const at = (hhmm: string, date = "2026-06-10") => new Date(`${date}T${hhmm}:00-05:00`); | |
| 40 | ||
| 41 | const fresh = () => { | |
| 42 | const db = openDb(mkdtempSync(join(tmpdir(), "app-referral-"))); | |
| 43 | const saved = saveProfile(db, root, { ...agent, timeZone: ZONE }); | |
| 44 | if (!saved.ok) throw new Error(saved.message); | |
| 45 | return db; | |
| 46 | }; | |
| 47 | const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => { | |
| 48 | if (!r.ok) throw new Error(r.message); | |
| 49 | return r.value as T; | |
| 50 | }; | |
| 51 | const referral = { | |
| 52 | name: "Kenji Watanabe", | |
| 53 | email: "[email protected]", | |
| 54 | phone: "", | |
| 55 | source: "referral", | |
| 56 | message: "Priya recommended you.", | |
| 57 | consent: false, | |
| 58 | referred_by: "Priya Raman", | |
| 59 | referrer_email: "[email protected]", | |
| 60 | }; | |
| 61 | const arrive = (db: ReturnType<typeof fresh>, extra: Record<string, unknown> = {}, when = at("10:00")) => | |
| 62 | value(addLead(db, alice, { ...referral, ...extra }, when)); | |
| 63 | ||
| 64 | // The suite turns quiet hours off; the held-text tests need them. | |
| 65 | let was: string | undefined; | |
| 66 | beforeAll(() => { | |
| 67 | was = process.env.QUIET_HOURS; | |
| 68 | delete process.env.QUIET_HOURS; | |
| 69 | }); | |
| 70 | afterAll(() => { | |
| 71 | if (was !== undefined) process.env.QUIET_HOURS = was; | |
| 72 | }); | |
| 73 | ||
| 74 | test("the referrer is checked at the boundary like a lead's own details", () => { | |
| 75 | const db = fresh(); | |
| 76 | const bad = (extra: Record<string, unknown>) => addLead(db, alice, { ...referral, ...extra }); | |
| 77 | expect(bad({ referrer_email: "", referrer_phone: "" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 78 | expect(bad({ referred_by: "x".repeat(121) })).toMatchObject({ ok: false, error: "invalid" }); | |
| 79 | expect(bad({ referrer_email: `${"x".repeat(250)}@e.com` })).toMatchObject({ ok: false, error: "invalid" }); | |
| 80 | expect(bad({ referrer_email: "not an email" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 81 | expect(bad({ referrer_email: "", referrer_phone: "12" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 82 | expect(bad({ referred_by: "", referrer_email: "[email protected]" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 83 | expect(bad({ referred_by: "Priya\u001b[2J" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 84 | expect(bad({ referred_by: "Priya\nRaman" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 85 | // Only a referral names a referrer. | |
| 86 | expect(bad({ source: "zillow" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 87 | expect(value(listLeads(db, alice)).leads).toHaveLength(0); | |
| 88 | // Nobody named is a lead like any other, with no thank-you. | |
| 89 | const plain = value(addLead(db, alice, { ...referral, referred_by: "", referrer_email: "" })); | |
| 90 | expect(plain.thanks).toBeNull(); | |
| 91 | }); | |
| 92 | ||
| 93 | test("a thank-you to the referrer is drafted, addressed to them, and names only the lead's first name", () => { | |
| 94 | const db = fresh(); | |
| 95 | const lead = arrive(db); | |
| 96 | expect(lead.referred_by).toBe("Priya Raman"); | |
| 97 | expect(lead.referrer_email).toBe("[email protected]"); | |
| 98 | expect(lead.thanks).toMatchObject({ status: "draft", channel: "email", sent_at: null }); | |
| 99 | expect(lead.thanks!.body).toContain("Hi Priya"); | |
| 100 | expect(lead.thanks!.body).toContain("Kenji"); | |
| 101 | expect(lead.thanks!.body).not.toContain("Watanabe"); | |
| 102 | expect(lead.thanks!.body).not.toContain("recommended"); | |
| 103 | // A phone-only referrer is thanked by text. | |
| 104 | const byText = arrive(db, { email: "[email protected]", referrer_email: "", referrer_phone: "(206) 555-0142" }); | |
| 105 | expect(byText.thanks).toMatchObject({ channel: "text" }); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the thank-you is kept out of the lead's own messages: STOP, clock and cadence never see it", () => { | |
| 109 | const db = fresh(); | |
| 110 | const lead = arrive(db); | |
| 111 | expect(lead.messages).toHaveLength(1); | |
| 112 | expect(lead.messages[0]!.body).not.toContain("Priya"); | |
| 113 | expect(lead.messages[0]!.body).not.toContain("thank you for sending"); | |
| 114 | // Approving the thank-you does not answer the lead. | |
| 115 | const thanked = value(sendThanks(db, alice, { id: lead.id }, at("10:05"))); | |
| 116 | expect(thanked.replied_at).toBeNull(); | |
| 117 | expect(thanked.state).toBe("new"); | |
| 118 | expect(thanked.messages.map((m) => m.status)).toEqual(["draft"]); | |
| 119 | // Sending the lead's first reply does not send the thank-you. | |
| 120 | const other = arrive(db, { email: "[email protected]", phone: "(206) 555-0177", consent: true }); | |
| 121 | value(sendReply(db, alice, { id: other.id }, at("10:01"))); | |
| 122 | expect(value(getLead(db, alice, { id: other.id })).thanks!.status).toBe("draft"); | |
| 123 | // The lead asking to stop texts leaves the referrer's thank-you alone. | |
| 124 | value(optOutTexts(db, alice, { id: other.id })); | |
| 125 | expect(value(getLead(db, alice, { id: other.id })).thanks!.status).toBe("draft"); | |
| 126 | }); | |
| 127 | ||
| 128 | test("nothing goes to the referrer until the agent approves; then once, as drafted or edited", () => { | |
| 129 | const db = fresh(); | |
| 130 | const lead = arrive(db); | |
| 131 | turn(db, at("12:00")); | |
| 132 | expect(value(getLead(db, alice, { id: lead.id })).thanks).toMatchObject({ status: "draft", sent_at: null }); | |
| 133 | const sent = value(sendThanks(db, alice, { id: lead.id, body: "Priya, thank you so much!" }, at("12:01"))); | |
| 134 | expect(sent.thanks).toMatchObject({ status: "sent", body: "Priya, thank you so much!", sent_by: "alice" }); | |
| 135 | expect(sent.thanks!.signature).toContain(agent.name); | |
| 136 | expect(sendThanks(db, alice, { id: lead.id }, at("12:02"))).toMatchObject({ ok: false, error: "conflict" }); | |
| 137 | expect(skipThanksFor(db, alice, { id: lead.id })).toMatchObject({ ok: false, error: "conflict" }); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a bad edit, a stranger and a lead nobody referred are refused", () => { | |
| 141 | const db = fresh(); | |
| 142 | const lead = arrive(db); | |
| 143 | expect(sendThanks(db, alice, { id: lead.id, body: "" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 144 | expect(sendThanks(db, alice, { id: lead.id, body: "x".repeat(4001) })).toMatchObject({ ok: false, error: "invalid" }); | |
| 145 | expect(sendThanks(db, alice, { id: lead.id, body: "hi\u001b[2J" })).toMatchObject({ ok: false, error: "invalid" }); | |
| 146 | expect(sendThanks(db, anon, { id: lead.id })).toMatchObject({ ok: false, error: "signin_required" }); | |
| 147 | expect(skipThanksFor(db, anon, { id: lead.id })).toMatchObject({ ok: false, error: "signin_required" }); | |
| 148 | const plain = value(addLead(db, alice, { ...referral, email: "[email protected]", referred_by: "", referrer_email: "" })); | |
| 149 | expect(sendThanks(db, alice, { id: plain.id })).toMatchObject({ ok: false, error: "invalid" }); | |
| 150 | expect(sendThanks(db, alice, { id: 9999 })).toMatchObject({ ok: false, error: "not_found" }); | |
| 151 | expect(value(getLead(db, alice, { id: lead.id })).thanks!.status).toBe("draft"); | |
| 152 | }); | |
| 153 | ||
| 154 | test("setting the thank-you aside sends nothing", () => { | |
| 155 | const db = fresh(); | |
| 156 | const lead = arrive(db); | |
| 157 | const skipped = value(skipThanksFor(db, alice, { id: lead.id })); | |
| 158 | expect(skipped.thanks).toMatchObject({ status: "skipped", sent_at: null }); | |
| 159 | expect(sendThanks(db, alice, { id: lead.id })).toMatchObject({ ok: false, error: "conflict" }); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a thank-you text outside quiet hours is held until 8:00, then goes", () => { | |
| 163 | const db = fresh(); | |
| 164 | const lead = arrive(db, { referrer_email: "", referrer_phone: "(206) 555-0142" }, at("22:00")); | |
| 165 | const held = value(sendThanks(db, alice, { id: lead.id }, at("22:30"))); | |
| 166 | expect(held.thanks).toMatchObject({ status: "held", sent_at: null }); | |
| 167 | expect(held.thanks!.goes_at).not.toBeNull(); | |
| 168 | turn(db, at("23:30")); | |
| 169 | expect(value(getLead(db, alice, { id: lead.id })).thanks!.status).toBe("held"); | |
| 170 | turn(db, at("08:05", "2026-06-11")); | |
| 171 | expect(value(getLead(db, alice, { id: lead.id })).thanks).toMatchObject({ status: "sent" }); | |
| 172 | // The lead was never answered by it. | |
| 173 | expect(value(getLead(db, alice, { id: lead.id })).replied_at).toBeNull(); | |
| 174 | }); | |
| 175 | ||
| 176 | test("the referrer is in the lead's JSON, the CSV, and the Activity log", () => { | |
| 177 | const db = fresh(); | |
| 178 | const lead = arrive(db); | |
| 179 | value(sendThanks(db, alice, { id: lead.id }, at("12:00"))); | |
| 180 | const csv = value(exportLeads(db, alice)).csv.split("\r\n"); | |
| 181 | expect(csv[0]).toContain("referred by,referrer email,referrer phone"); | |
| 182 | expect(csv[1]).toContain("Priya Raman,[email protected]"); | |
| 183 | const listed = value(listLeads(db, alice)).leads[0]!; | |
| 184 | expect(listed).toMatchObject({ referred_by: "Priya Raman", thanks: "sent" }); | |
| 185 | const log = value(activity(db, root, {})); | |
| 186 | const html = activityPage({ who: root, agent, rows: log.rows, names: log.names, older: undefined, lost: [], sentOnly: false }); | |
| 187 | expect(html).toContain("referred by Priya Raman"); | |
| 188 | expect(html).toContain("approved the thank-you to the person who referred"); | |
| 189 | const surprise = value(addLead(db, alice, { ...referral, email: "[email protected]", referred_by: "<b>Eve</b>" })); | |
| 190 | const again = value(activity(db, root, {})); | |
| 191 | const escaped = activityPage({ who: root, agent, rows: again.rows, names: again.names, older: undefined, lost: [], sentOnly: false }); | |
| 192 | expect(escaped).toContain("<b>Eve</b>"); | |
| 193 | expect(escaped).not.toContain("<b>Eve</b>"); | |
| 194 | expect(surprise.referred_by).toBe("<b>Eve</b>"); | |
| 195 | }); | |
| 196 | ||
| 197 | test("the lead's page and the desk label the thank-you as going to the referrer, escaped", () => { | |
| 198 | const db = fresh(); | |
| 199 | const lead = arrive(db, { referred_by: "Priya <script>" }); | |
| 200 | const detail = value(getLead(db, alice, { id: lead.id })); | |
| 201 | const page = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: detail, mayUpdate: true, next: null, now: at("12:00").getTime() }); | |
| 202 | expect(page).toContain("not to Kenji Watanabe"); | |
| 203 | expect(page).toContain(`action="/leads/${lead.id}/thanks"`); | |
| 204 | expect(page).toContain("Nothing is sent until you approve it"); | |
| 205 | expect(page).toContain("Referred by Priya <script>"); | |
| 206 | expect(page).not.toContain("<script>"); | |
| 207 | const readOnly = leadPage({ who: anon, agent: { ...agent, timeZone: ZONE }, lead: detail, mayUpdate: false, next: null, now: at("12:00").getTime() }); | |
| 208 | expect(readOnly).not.toContain(`action="/leads/${lead.id}/thanks"`); | |
| 209 | const listed = value(listLeads(db, alice)); | |
| 210 | const deskHtml = deskPage({ who: alice, agent, leads: listed.leads, record: listed.record, mayAdd: true, mayReset: false }); | |
| 211 | expect(deskHtml).toContain("(referrer)"); | |
| 212 | expect(deskHtml).toContain('name="referred_by"'); | |
| 213 | expect(deskHtml).not.toContain("<script>"); | |
| 214 | }); | |
| 215 | ||
| 216 | test("a sample referral carries a referrer", () => { | |
| 217 | const sample = SAMPLES.find((s) => s.source === "referral" && s.referred_by !== undefined); | |
| 218 | expect(sample?.referred_by).toBe("Sarah Patel"); | |
| 219 | expect(sample?.referrer_email).toContain("@"); | |
| 220 | }); | |
| 221 | ||
| 222 | test("the terminal shows the thank-you before it sends, and r approves it", () => { | |
| 223 | const db = fresh(); | |
| 224 | const lead = arrive(db); | |
| 225 | const t = terminal(db, alice, () => at("12:00").getTime()); | |
| 226 | t.key("\r"); | |
| 227 | const screen = () => t.screen(100).map(plain).join("\n"); | |
| 228 | expect(screen()).toContain("Thank-you to Priya Raman"); | |
| 229 | expect(screen()).toContain("not to the lead"); | |
| 230 | expect(screen()).toContain("Nothing is sent until you press r"); | |
| 231 | t.key("r"); | |
| 232 | expect(value(getLead(db, alice, { id: lead.id })).thanks!.status).toBe("sent"); | |
| 233 | }); | |
| 234 | ||
| 235 | const KEY = "referral-test-identity-key"; | |
| 236 | const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-referral-srv-")), identityKey: KEY, sample: false }); | |
| 237 | afterAll(() => server.stop(true)); | |
| 238 | const base = `http://${server.hostname}:${server.port}`; | |
| 239 | let grants = 0; | |
| 240 | const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => { | |
| 241 | const identity = `ref-${++grants}|alice|user|${Date.now() + 60_000}`; | |
| 242 | return fetch(base + path, { | |
| 243 | redirect: "manual", | |
| 244 | ...init, | |
| 245 | headers: { ...(init.headers as Record<string, string>), ...headers, "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }, | |
| 246 | }); | |
| 247 | }; | |
| 248 | const send = (method: string, path: string, body?: unknown) => | |
| 249 | api(path, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); | |
| 250 | ||
| 251 | test("POST /leads and MCP take a referrer; /thanks approves it; the spec describes both", async () => { | |
| 252 | const made = await send("POST", "/leads", { ...referral }); | |
| 253 | expect(made.status).toBe(201); | |
| 254 | const lead = (await made.json()) as { id: number; thanks: { status: string } | null; referred_by: string }; | |
| 255 | expect(lead.referred_by).toBe("Priya Raman"); | |
| 256 | expect(lead.thanks?.status).toBe("draft"); | |
| 257 | const bad = await send("POST", "/leads", { ...referral, email: "[email protected]", referrer_email: "", referrer_phone: "" }); | |
| 258 | expect(bad.status).toBe(422); | |
| 259 | const sent = await send("POST", `/leads/${lead.id}/thanks`, { body: "Thank you, Priya." }); | |
| 260 | expect(sent.status).toBe(200); | |
| 261 | expect(((await sent.json()) as { thanks: { status: string } }).thanks.status).toBe("sent"); | |
| 262 | expect((await send("POST", `/leads/${lead.id}/thanks`, {})).status).toBe(409); | |
| 263 | const mcp = await send("POST", "/mcp", { | |
| 264 | jsonrpc: "2.0", | |
| 265 | id: 1, | |
| 266 | method: "tools/call", | |
| 267 | params: { name: "add_lead", arguments: { ...referral, email: "[email protected]", referrer_email: "[email protected]" } }, | |
| 268 | }); | |
| 269 | const text = ((await mcp.json()) as { result: { content: { text: string }[] } }).result.content[0]!.text; | |
| 270 | expect(JSON.parse(text).thanks.status).toBe("draft"); | |
| 271 | const spec = JSON.stringify(await (await send("GET", "/openapi.json")).json()); | |
| 272 | expect(spec).toContain("referrer_email"); | |
| 273 | expect(spec).toContain("/leads/{id}/thanks"); | |
| 274 | // A form from another site is refused. | |
| 275 | const evil = await api(`/leads/${lead.id}/thanks/skip`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "" }, { origin: "https://evil.example", "sec-fetch-site": "cross-site" }); | |
| 276 | expect(evil.status).toBe(403); | |
| 277 | }); | |
| 278 | ||
| 279 | test("a repeat arrival that names a referrer is refused, not silently stripped of it", () => { | |
| 280 | const db = fresh(); | |
| 281 | arrive(db); | |
| 282 | const again = addLead(db, alice, { ...referral, name: "Kenji W", referred_by: "Someone Else" }); | |
| 283 | expect(again).toMatchObject({ ok: false, error: "invalid" }); | |
| 284 | expect(again.ok ? "" : again.message).toContain("referrer would be lost"); | |
| 285 | // Without a referrer it merges as before. | |
| 286 | expect(value(addLead(db, alice, { ...referral, referred_by: "", referrer_email: "" })).again).toBe(true); | |
| 287 | }); | |
| 288 | ||
| 289 | test("a thank-you text says it goes to someone who has not agreed to be texted", () => { | |
| 290 | const db = fresh(); | |
| 291 | const lead = arrive(db, { referrer_email: "", referrer_phone: "(206) 555-0142" }); | |
| 292 | const page = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: value(getLead(db, alice, { id: lead.id })), mayUpdate: true, next: null, now: at("12:00").getTime() }); | |
| 293 | expect(page).toContain("has not agreed to be texted"); | |
| 294 | const emailed = arrive(db, { email: "[email protected]" }); | |
| 295 | const emailPage = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: value(getLead(db, alice, { id: emailed.id })), mayUpdate: true, next: null, now: at("12:00").getTime() }); | |
| 296 | expect(emailPage).not.toContain("has not agreed to be texted"); | |
| 297 | }); |
src/routes.ts +62 −2
| @@ -35,6 +35,8 @@ import { | ||
| 35 | 35 | saveProfile, |
| 36 | 36 | optOutTexts, |
| 37 | 37 | approveReply, |
| 38 | sendThanks, | |
| 39 | skipThanksFor, | |
| 38 | 40 | insertReply, |
| 39 | 41 | cancelHeld, |
| 40 | 42 | undoSend, |
| @@ -191,6 +193,9 @@ const LEAD_FIELDS = { | ||
| 191 | 193 | description: "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away.", |
| 192 | 194 | }, |
| 193 | 195 | starred: { type: "boolean", description: "The agent keeps this lead close: starred open leads lead the desk." }, |
| 196 | referred_by: { type: "string", maxLength: 120, description: "For a referral: the name of who sent them; empty when nobody is named. Never part of a message to the lead." }, | |
| 197 | referrer_email: { type: "string", format: "email", description: "The referrer's email; empty when none." }, | |
| 198 | referrer_phone: { type: "string", description: "The referrer's phone; empty when none." }, | |
| 194 | 199 | created_at: STAMP, |
| 195 | 200 | replied_at: { type: ["string", "null"], format: "date-time" }, |
| 196 | 201 | updated_at: STAMP, |
| @@ -246,8 +251,23 @@ export const LEAD: Schema = { | ||
| 246 | 251 | items: CALL, |
| 247 | 252 | }, |
| 248 | 253 | showing: SHOWING, |
| 254 | thanks: { | |
| 255 | type: ["object", "null"], | |
| 256 | description: "The thank-you drafted to the lead's referrer (it goes to the referrer, never the lead); null when nobody referred them.", | |
| 257 | properties: { | |
| 258 | lead_id: { type: "integer" }, | |
| 259 | channel: { enum: ["text", "email"] }, | |
| 260 | body: { type: "string" }, | |
| 261 | signature: { type: "string" }, | |
| 262 | status: { enum: ["draft", "held", "sent", "skipped"] }, | |
| 263 | created_at: STAMP, | |
| 264 | goes_at: { type: ["string", "null"], format: "date-time" }, | |
| 265 | sent_at: { type: ["string", "null"], format: "date-time" }, | |
| 266 | sent_by: { type: ["string", "null"] }, | |
| 267 | }, | |
| 268 | }, | |
| 249 | 269 | }, |
| 250 | required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing"], | |
| 270 | required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing", "thanks"], | |
| 251 | 271 | }; |
| 252 | 272 | export const APPROVED: Schema = { |
| 253 | 273 | type: "object", |
| @@ -283,6 +303,7 @@ export const DESK_LEAD: Schema = { | ||
| 283 | 303 | }, |
| 284 | 304 | next_at: { type: ["string", "null"], format: "date-time" }, |
| 285 | 305 | goes_at: { type: ["string", "null"], format: "date-time", description: "When a text you approved goes, if one is held for quiet hours." }, |
| 306 | thanks: { anyOf: [{ enum: ["draft", "held", "sent", "skipped"] }, { type: "null" }], description: "Where the thank-you to the lead's referrer stands; null when nobody referred them." }, | |
| 286 | 307 | showing: { |
| 287 | 308 | type: ["object", "null"], |
| 288 | 309 | description: "The showing booked on this lead, if one is.", |
| @@ -293,7 +314,7 @@ export const DESK_LEAD: Schema = { | ||
| 293 | 314 | }, |
| 294 | 315 | }, |
| 295 | 316 | }, |
| 296 | required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing"], | |
| 317 | required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing", "thanks"], | |
| 297 | 318 | }; |
| 298 | 319 | const SHOW: Schema = { |
| 299 | 320 | enum: [...VIEWS], |
| @@ -374,6 +395,9 @@ const NEW_LEAD: Schema = { | ||
| 374 | 395 | source: LEAD_FIELDS.source, |
| 375 | 396 | message: LEAD_FIELDS.message, |
| 376 | 397 | consent: LEAD_FIELDS.consent, |
| 398 | referred_by: { ...LEAD_FIELDS.referred_by, description: "Only with source referral: who sent them. Needs referrer_email or referrer_phone; a thank-you to them is drafted for you to approve." }, | |
| 399 | referrer_email: LEAD_FIELDS.referrer_email, | |
| 400 | referrer_phone: { ...LEAD_FIELDS.referrer_phone, description: "The referrer's phone (7 to 20 digits); a thank-you text only when no email is given." }, | |
| 377 | 401 | }, |
| 378 | 402 | required: ["name", "email", "source", "message"], |
| 379 | 403 | }; |
| @@ -972,6 +996,42 @@ export const routes: readonly Route[] = [ | ||
| 972 | 996 | answer: APPROVED, |
| 973 | 997 | }, |
| 974 | 998 | }, |
| 999 | { | |
| 1000 | method: "POST", | |
| 1001 | path: "/leads/:id/thanks", | |
| 1002 | handle: (c) => | |
| 1003 | posted( | |
| 1004 | c, | |
| 1005 | (input) => | |
| 1006 | sendThanks(c.db, c.who, { id: ID(c), body: typeof input.body === "string" ? input.body : undefined }), | |
| 1007 | () => ({ to: `/leads/${ID(c)}`, said: "Thank-you sent to the referrer." }), | |
| 1008 | ), | |
| 1009 | api: { | |
| 1010 | summary: | |
| 1011 | "Approve the thank-you drafted to the person who referred this lead — as drafted, or with `body` as edited. It goes to the referrer, never to the lead. A text outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 (thanks.status is `held`); an email goes now. A lead nobody referred is 422; a thank-you already dealt with is 409.", | |
| 1012 | body: { | |
| 1013 | type: "object", | |
| 1014 | properties: { | |
| 1015 | body: { type: "string", minLength: 1, maxLength: MAX_BODY.email, description: `The words, edited; the draft when left out. A text is at most ${MAX_BODY.text} characters. The signature is added.` }, | |
| 1016 | }, | |
| 1017 | }, | |
| 1018 | answer: LEAD, | |
| 1019 | }, | |
| 1020 | }, | |
| 1021 | { | |
| 1022 | method: "POST", | |
| 1023 | path: "/leads/:id/thanks/skip", | |
| 1024 | handle: (c) => | |
| 1025 | posted( | |
| 1026 | c, | |
| 1027 | () => skipThanksFor(c.db, c.who, { id: ID(c) }), | |
| 1028 | () => ({ to: `/leads/${ID(c)}`, said: "Thank-you set aside." }), | |
| 1029 | ), | |
| 1030 | api: { | |
| 1031 | summary: "Set the drafted thank-you to the lead's referrer aside; nothing is sent. No body needed.", | |
| 1032 | answer: LEAD, | |
| 1033 | }, | |
| 1034 | }, | |
| 975 | 1035 | // Insert saved reply: the draft with the reply at its end, unsent. A script |
| 976 | 1036 | // gets the words; a browser gets the lead's page with the edit box open. |
| 977 | 1037 | { |
src/sample.ts +11 −2
| @@ -74,7 +74,12 @@ export const SAMPLES: readonly Sample[] = [ | ||
| 74 | 74 | person("Maria Gonzalez", "zillow", true, "Is 418 Juniper Ln still available? We'd love to see it this weekend if possible.", { ago: 40 * S }), |
| 75 | 75 | person("David Chen", "website", false, "We're thinking about selling our townhouse in the spring. Any idea what it might be worth in today's market?", { ago: 3 * M + 10 * S }), |
| 76 | 76 | person("Priya Raman", "open_house", true, "Loved the kitchen at Sunday's open house on Alder Ct. Are the sellers flexible on price at all?", { ago: 18 * M }), |
| 77 | person("James O'Neill", "referral", false, "Sarah Patel said you helped her family relocate last year. We're moving from Denver in August and don't know the area.", { ago: 47 * M }), | |
| 77 | { | |
| 78 | ...person("James O'Neill", "referral", false, "Sarah Patel said you helped her family relocate last year. We're moving from Denver in August and don't know the area.", { ago: 47 * M }), | |
| 79 | // The person who sent him: a thank-you to her waits on the desk beside his first reply. | |
| 80 | referred_by: "Sarah Patel", | |
| 81 | referrer_email: "[email protected]", | |
| 82 | }, | |
| 78 | 83 | person("Aisha Bello", "zillow", false, "Pre-approved up to $550k. Looking for 3 bedrooms with a yard, ideally near good schools.", { ago: 2 * H + 12 * M, showingInDays: 2, note: "Pre-approved to $550k. Wants 3 bed with a yard near Lincoln Elementary. Lease ends in June, so moving by then." }), |
| 79 | 84 | person("Tom Becker", "website", true, "Do you work with first-time buyers? We have no idea where to start.", { ago: 5 * H + 30 * M }), |
| 80 | 85 | person("Lena Novak", "open_house", false, "Signed in at the open house on Birch St. Could you send me the disclosures and HOA details?", { ago: 26 * H }), |
| @@ -181,7 +186,11 @@ export const INQUIRIES: readonly NewLead[] = [ | ||
| 181 | 186 | inquiry("Hugo Lindqvist", "(206) 555-0208", "realtor_com", true, "Found 9 Ridge Rd on Realtor.com. Is the seller open to offers before the weekend?"), |
| 182 | 187 | inquiry("Oliver Grant", "(206) 555-0202", "website", false, "Thinking of selling our duplex on Pine St this summer. Could you tell us what it might fetch?"), |
| 183 | 188 | inquiry("Sofia Marin", "(206) 555-0203", "open_house", true, "We toured the Willow Ct open house today and loved it. What would an offer need to look like?"), |
| 184 | inquiry("Kenji Watanabe", "(206) 555-0204", "referral", false, "Our neighbour Priya recommended you. We're relocating for work in September and need a 4-bedroom."), | |
| 189 | { | |
| 190 | ...inquiry("Kenji Watanabe", "(206) 555-0204", "referral", false, "Our neighbour Priya recommended you. We're relocating for work in September and need a 4-bedroom."), | |
| 191 | referred_by: "Priya Raman", | |
| 192 | referrer_email: "[email protected]", | |
| 193 | }, | |
| 185 | 194 | inquiry("Bridget Doyle", "(206) 555-0205", "zillow", true, "Does 310 Orchard Ln allow a home office addition? We're pre-approved to $620k."), |
| 186 | 195 | inquiry("Samuel Osei", "(206) 555-0206", "website", true, "First-time buyer here. Can we book a call this week to talk about the process?"), |
| 187 | 196 | inquiry("Ingrid Larsen", "(206) 555-0207", "open_house", false, "Signed in at the Elm St open house. Could you send the school zone and tax details?"), |
src/sentences.ts +25
| @@ -43,6 +43,16 @@ function awayWords(detail: string | null, esc: (text: string) => string): string | ||
| 43 | 43 | } |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | /** A referral's sender: " (referred by Sarah Patel)"; "" when the row names none. */ | |
| 47 | function referrerWords(detail: string | null, esc: (text: string) => string): string { | |
| 48 | try { | |
| 49 | const { referrer } = JSON.parse(detail ?? "") as { referrer?: unknown }; | |
| 50 | return typeof referrer === "string" && referrer !== "" ? ` (referred by ${esc(referrer)})` : ""; | |
| 51 | } catch { | |
| 52 | return ""; | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 46 | 56 | export function deed( |
| 47 | 57 | row: AuditRow, |
| 48 | 58 | lead: string, |
| @@ -112,6 +122,21 @@ export function deed( | ||
| 112 | 122 | tried: star ? `star ${lead}` : `take the star off ${lead}`, |
| 113 | 123 | }; |
| 114 | 124 | } |
| 125 | if (row.act === "referred") | |
| 126 | return { | |
| 127 | done: `added ${lead}${referrerWords(row.detail, esc)}`, | |
| 128 | tried: "add a lead", | |
| 129 | }; | |
| 130 | if (row.act === "thanked" || row.act === "thanks_held") | |
| 131 | return { | |
| 132 | done: `approved the thank-you to the person who referred ${lead}${row.act === "thanks_held" ? ", held until 8:00 a.m." : ""}`, | |
| 133 | tried: `approve the thank-you to the person who referred ${lead}`, | |
| 134 | }; | |
| 135 | if (row.act === "thanks_skipped") | |
| 136 | return { | |
| 137 | done: `set aside the thank-you to the person who referred ${lead}`, | |
| 138 | tried: `set aside the thank-you to the person who referred ${lead}`, | |
| 139 | }; | |
| 115 | 140 | if (row.act === "brought_back") |
| 116 | 141 | return { |
| 117 | 142 | done: `brought ${lead} back`, |
src/server.test.ts +2
| @@ -319,6 +319,8 @@ test("the MCP server lists the tools and calls them as the caller", async () => | ||
| 319 | 319 | "export_leads", |
| 320 | 320 | "get_lead", |
| 321 | 321 | "add_lead", |
| 322 | "send_thanks", | |
| 323 | "skip_thanks", | |
| 322 | 324 | "parse_lead_email", |
| 323 | 325 | "preview_sign_ins", |
| 324 | 326 | "add_sign_ins", |
src/terminal.ts +48 −4
| @@ -43,6 +43,8 @@ import { | ||
| 43 | 43 | resetSample, |
| 44 | 44 | saveProfile, |
| 45 | 45 | approveReply, |
| 46 | sendThanks, | |
| 47 | skipThanksFor, | |
| 46 | 48 | cancelHeld, |
| 47 | 49 | undoSend, |
| 48 | 50 | restoreFollowUp, |
| @@ -61,6 +63,7 @@ import { | ||
| 61 | 63 | type SignInPreview, |
| 62 | 64 | } from "./actions.ts"; |
| 63 | 65 | import { missingLine } from "./intake.ts"; |
| 66 | import { referrerAddress } from "./thanks.ts"; | |
| 64 | 67 | import { MAX_SIGNIN_LINES } from "./signins.ts"; |
| 65 | 68 | import { dateName, MAX_AWAY_DAYS } from "./putaway.ts"; |
| 66 | 69 | import { showingLine, showingWhen } from "./showings.ts"; |
| @@ -127,7 +130,19 @@ const ADD_FIELDS = [ | ||
| 127 | 130 | }, |
| 128 | 131 | { key: "message", label: "What they asked" }, |
| 129 | 132 | { key: "consent", label: "Written consent to be texted? y/n" }, |
| 130 | ] as const; | |
| 133 | // Asked only of a referral. | |
| 134 | { key: "referred_by", label: "Referred by (name, blank for nobody)", referral: true }, | |
| 135 | { key: "referrer_email", label: "Their email (blank for none)", referral: true }, | |
| 136 | { key: "referrer_phone", label: "Their phone (blank for none)", referral: true }, | |
| 137 | ] as const satisfies readonly { key: string; label: string; referral?: true }[]; | |
| 138 | ||
| 139 | /** The next question of the add screen after `step`: the referrer's are asked only of a referral, and only when one is named. */ | |
| 140 | function nextAddStep(step: number, fields: Record<string, string>): number { | |
| 141 | const referral = (SOURCES[Number(fields.source) - 1] ?? fields.source) === "referral"; | |
| 142 | let next = step + 1; | |
| 143 | while (next < ADD_FIELDS.length && "referral" in ADD_FIELDS[next]! && (!referral || (next > 6 && (fields.referred_by ?? "") === ""))) next++; | |
| 144 | return next; | |
| 145 | } | |
| 131 | 146 | |
| 132 | 147 | const PROFILE_FIELDS = [ |
| 133 | 148 | { key: "name", label: "Name" }, |
| @@ -375,6 +390,23 @@ export function terminal( | ||
| 375 | 390 | "", |
| 376 | 391 | ]), |
| 377 | 392 | ]; |
| 393 | if (l.thanks !== null) { | |
| 394 | const t = l.thanks; | |
| 395 | lines.push( | |
| 396 | bold(`Thank-you to ${clean(l.referred_by)}, who referred ${clean(l.name)} — by ${t.channel}, goes to ${clean(referrerAddress(l))}, not to the lead`), | |
| 397 | ...(t.status === "draft" ? wrap(t.body, width).map((s) => ` ${s}`) : []), | |
| 398 | dim( | |
| 399 | t.status === "draft" | |
| 400 | ? " Nothing is sent until you press r." | |
| 401 | : t.status === "held" && t.goes_at !== null | |
| 402 | ? ` Approved. ${goesLabel(t.goes_at, now(), zone)}.` | |
| 403 | : t.status === "sent" | |
| 404 | ? " Sent." | |
| 405 | : " Set aside.", | |
| 406 | ), | |
| 407 | "", | |
| 408 | ); | |
| 409 | } | |
| 378 | 410 | const held = l.messages.find((m) => m.status === "held"); |
| 379 | 411 | if (held !== undefined && held.goes_at !== null) |
| 380 | 412 | lines.push( |
| @@ -448,6 +480,7 @@ export function terminal( | ||
| 448 | 480 | ...(r === undefined ? [] : ["s approve and send", "e edit"]), |
| 449 | 481 | ...(undoable(db, l.id, now()) === null ? [] : ["z undo send (for a minute)"]), |
| 450 | 482 | ...(held === undefined ? [] : ["h take back the held text"]), |
| 483 | ...(l.thanks?.status === "draft" ? ["r send the thank-you to the referrer", "R don't thank them"] : []), | |
| 451 | 484 | ...(skippable(l) === undefined ? [] : ["k skip the next follow-up"]), |
| 452 | 485 | ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]), |
| 453 | 486 | ...(l.phone === "" ? [] : ["c log a call"]), |
| @@ -900,6 +933,16 @@ export function terminal( | ||
| 900 | 933 | else if (input === "o" && CLOSED.includes(l.state)) { |
| 901 | 934 | const back = setState(db, me, { id, state: "open" }); |
| 902 | 935 | said = back.ok ? `${l.name}: back in follow-ups.` : back.message; |
| 936 | } else if (input === "r" && l.thanks?.status === "draft") { | |
| 937 | const thanked = sendThanks(db, me, { id }, new Date(now())); | |
| 938 | said = thanked.ok | |
| 939 | ? thanked.value.thanks?.status === "held" | |
| 940 | ? `Thank-you to ${thanked.value.referred_by} held for quiet hours.` | |
| 941 | : `Thank-you sent to ${thanked.value.referred_by}.` | |
| 942 | : thanked.message; | |
| 943 | } else if (input === "R" && l.thanks?.status === "draft") { | |
| 944 | const skipped = skipThanksFor(db, me, { id }); | |
| 945 | said = skipped.ok ? "Thank-you set aside." : skipped.message; | |
| 903 | 946 | } else if (input === "t" && l.consent) |
| 904 | 947 | view = { name: "confirm", what: "opt-out", id, back: view }; |
| 905 | 948 | else if (input === "D") |
| @@ -1118,11 +1161,12 @@ export function terminal( | ||
| 1118 | 1161 | } else if (input === "\r") { |
| 1119 | 1162 | const field = ADD_FIELDS[view.step]!; |
| 1120 | 1163 | const fields = { ...view.fields, [field.key]: view.typed.trim() }; |
| 1121 | if (view.step + 1 < ADD_FIELDS.length) | |
| 1164 | const next = nextAddStep(view.step, fields); | |
| 1165 | if (next < ADD_FIELDS.length) | |
| 1122 | 1166 | view = { |
| 1123 | 1167 | ...view, |
| 1124 | step: view.step + 1, | |
| 1125 | typed: view.found?.[ADD_FIELDS[view.step + 1]!.key] ?? "", | |
| 1168 | step: next, | |
| 1169 | typed: view.found?.[ADD_FIELDS[next]!.key] ?? "", | |
| 1126 | 1170 | fields, |
| 1127 | 1171 | }; |
| 1128 | 1172 | else finishAdd(fields); |
src/thanks.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * The thank-you to the person who sent a referral lead: one per lead, kept | |
| 3 | * apart from the lead's own `message` rows on purpose. It goes to someone | |
| 4 | * who is not the lead, so the lead's STOP, response clock and cadence never | |
| 5 | * see it. A draft until the agent approves it; a text approved outside quiet | |
| 6 | * hours is held until the next 8:00 a.m. No permission is asked here. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { signature, thanksDraft, type Channel } from "./drafts.ts"; | |
| 11 | import type { Agent } from "./env.ts"; | |
| 12 | import { goesAt, isQuiet, nextOpening } from "./quiet.ts"; | |
| 13 | ||
| 14 | export interface Thanks { | |
| 15 | readonly lead_id: number; | |
| 16 | /** How it reaches the referrer: email when they gave one, else a text to their phone. */ | |
| 17 | readonly channel: Channel; | |
| 18 | readonly body: string; | |
| 19 | readonly signature: string; | |
| 20 | readonly status: "draft" | "held" | "sent" | "skipped"; | |
| 21 | readonly created_at: string; | |
| 22 | /** For a held text, the moment it goes. */ | |
| 23 | readonly goes_at: string | null; | |
| 24 | readonly sent_at: string | null; | |
| 25 | readonly sent_by: string | null; | |
| 26 | } | |
| 27 | ||
| 28 | /** Who sent the lead, as the lead row holds them. */ | |
| 29 | export interface Referrer { | |
| 30 | readonly referred_by: string; | |
| 31 | readonly referrer_email: string; | |
| 32 | readonly referrer_phone: string; | |
| 33 | } | |
| 34 | ||
| 35 | export const referrerChannel = (r: Pick<Referrer, "referrer_email">): Channel => | |
| 36 | r.referrer_email !== "" ? "email" : "text"; | |
| 37 | ||
| 38 | /** The address a thank-you goes to: the referrer's email, else their phone. */ | |
| 39 | export const referrerAddress = (r: Pick<Referrer, "referrer_email" | "referrer_phone">): string => | |
| 40 | r.referrer_email !== "" ? r.referrer_email : r.referrer_phone; | |
| 41 | ||
| 42 | export const thanksOf = (db: Database, leadId: number): Thanks | null => | |
| 43 | db.query<Thanks, [number]>("SELECT * FROM referrer_thanks WHERE lead_id = ?1").get(leadId); | |
| 44 | ||
| 45 | /** Draft the thank-you for a new referral lead; nothing is sent. */ | |
| 46 | export function insertThanks(db: Database, leadId: number, referrer: Referrer, leadName: string, at: string): void { | |
| 47 | const channel = referrerChannel(referrer); | |
| 48 | db.query( | |
| 49 | "INSERT INTO referrer_thanks (lead_id, channel, body, signature, status, created_at) VALUES (?1, ?2, ?3, '', 'draft', ?4)", | |
| 50 | ).run(leadId, channel, thanksDraft(referrer.referred_by, leadName, channel), at); | |
| 51 | } | |
| 52 | ||
| 53 | /** | |
| 54 | * Approve the draft as `body`: it goes now, or, for a text outside quiet hours, | |
| 55 | * is held for the next 8:00. Returns the moment it goes when held. | |
| 56 | */ | |
| 57 | export function approveThanks(db: Database, found: Thanks, body: string, by: string, at: string, agent: Agent): string | null { | |
| 58 | const goes = goesAt(found.channel, at, agent.timeZone); | |
| 59 | if (goes === null) | |
| 60 | db.query( | |
| 61 | "UPDATE referrer_thanks SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4, goes_at = NULL WHERE lead_id = ?5", | |
| 62 | ).run(body, signature(found.channel, agent), at, by, found.lead_id); | |
| 63 | else | |
| 64 | db.query("UPDATE referrer_thanks SET body = ?1, status = 'held', goes_at = ?2, sent_by = ?3 WHERE lead_id = ?4").run( | |
| 65 | body, | |
| 66 | goes, | |
| 67 | by, | |
| 68 | found.lead_id, | |
| 69 | ); | |
| 70 | return goes; | |
| 71 | } | |
| 72 | ||
| 73 | export const skipThanks = (db: Database, leadId: number): void => { | |
| 74 | db.query("UPDATE referrer_thanks SET status = 'skipped' WHERE lead_id = ?1").run(leadId); | |
| 75 | }; | |
| 76 | ||
| 77 | /** Held thank-you texts whose time has come go out, signed as the agent is now. Returns the lead ids. */ | |
| 78 | export function sendHeldThanks(db: Database, at: string, agent: Agent): number[] { | |
| 79 | const due = db | |
| 80 | .query<Thanks, [string]>("SELECT * FROM referrer_thanks WHERE status = 'held' AND goes_at <= ?1") | |
| 81 | .all(at); | |
| 82 | const sent: number[] = []; | |
| 83 | for (const t of due) { | |
| 84 | if (isQuiet(at, agent.timeZone)) { | |
| 85 | db.query("UPDATE referrer_thanks SET goes_at = ?1 WHERE lead_id = ?2").run(nextOpening(at, agent.timeZone), t.lead_id); | |
| 86 | continue; | |
| 87 | } | |
| 88 | db.query( | |
| 89 | "UPDATE referrer_thanks SET status = 'sent', signature = ?1, sent_at = ?2, goes_at = NULL WHERE lead_id = ?3", | |
| 90 | ).run(signature(t.channel, agent), at, t.lead_id); | |
| 91 | sent.push(t.lead_id); | |
| 92 | } | |
| 93 | return sent; | |
| 94 | } |
new above
offline