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

Merged opened this

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

Merged

mason/speed-to-lead:mason/86-a-lead-who-came-by-referral-names-who-se → main 2 commits fork

  • Merged. mason/86-a-lead-who-came-by-referral-names-who-se was merged into main as 07b85e0.

Review

Sign in to review this change.
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:
140140 not touch the cadence. `starredFirst` lifts starred open leads to the top of
141141 any view but leaves a first reply past the green clock ahead of them, and does
142142 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.
143149 - `src/drafts.ts` — the words: templates filled from the inquiry and the
144150 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
145151 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.
124124 cannot; "Add" makes each visitor a lead with a thank-you for that address
125125 drafted. Someone already on the desk lands on their lead. Nothing is sent
126126 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.
127138
128139 Nothing is really sent in this prototype: "send" records the message in the
129140 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
507518 actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`,
508519 `send_reply`, `mark_lead`, `export_leads`).
509520
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
510526 ## From a terminal
511527
512528 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
546562 - **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`.
547563 - **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.
548564
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.
550566
551567 ## Running it
552568
contract/openapi.json +292 −2
@@ -113,6 +113,20 @@
113113 "consent": {
114114 "type": "boolean",
115115 "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."
116130 }
117131 },
118132 "required": [
@@ -816,6 +830,20 @@
816830 "type": "boolean",
817831 "description": "The agent keeps this lead close: starred open leads lead the desk."
818832 },
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 },
819847 "created_at": {
820848 "type": "string",
821849 "format": "date-time"
@@ -947,6 +975,62 @@
947975 "booked_at"
948976 ]
949977 },
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 },
9501034 "next": {
9511035 "type": [
9521036 "object",
@@ -988,6 +1072,9 @@
9881072 "lostAt",
9891073 "back_on",
9901074 "starred",
1075 "referred_by",
1076 "referrer_email",
1077 "referrer_phone",
9911078 "created_at",
9921079 "replied_at",
9931080 "updated_at",
@@ -995,6 +1082,7 @@
9951082 "replies",
9961083 "calls",
9971084 "showing",
1085 "thanks",
9981086 "next"
9991087 ]
10001088 }
@@ -1014,6 +1102,100 @@
10141102 }
10151103 }
10161104 },
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 },
10171199 "/leads/{id}/insert": {
10181200 "post": {
10191201 "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 @@
24822664 "type": "boolean",
24832665 "description": "The agent keeps this lead close: starred open leads lead the desk."
24842666 },
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 },
24852681 "created_at": {
24862682 "type": "string",
24872683 "format": "date-time"
@@ -2612,6 +2808,62 @@
26122808 "hold_until",
26132809 "booked_at"
26142810 ]
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 }
26152867 }
26162868 },
26172869 "required": [
@@ -2630,13 +2882,17 @@
26302882 "lostAt",
26312883 "back_on",
26322884 "starred",
2885 "referred_by",
2886 "referrer_email",
2887 "referrer_phone",
26332888 "created_at",
26342889 "replied_at",
26352890 "updated_at",
26362891 "messages",
26372892 "replies",
26382893 "calls",
2639 "showing"
2894 "showing",
2895 "thanks"
26402896 ]
26412897 },
26422898 "Desk": {
@@ -2894,6 +3150,20 @@
28943150 "type": "boolean",
28953151 "description": "The agent keeps this lead close: starred open leads lead the desk."
28963152 },
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 },
28973167 "created_at": {
28983168 "type": "string",
28993169 "format": "date-time"
@@ -2944,6 +3214,22 @@
29443214 "format": "date-time",
29453215 "description": "When a text you approved goes, if one is held for quiet hours."
29463216 },
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 },
29473233 "showing": {
29483234 "type": [
29493235 "object",
@@ -2983,13 +3269,17 @@
29833269 "lostAt",
29843270 "back_on",
29853271 "starred",
3272 "referred_by",
3273 "referrer_email",
3274 "referrer_phone",
29863275 "created_at",
29873276 "replied_at",
29883277 "updated_at",
29893278 "ready",
29903279 "next_at",
29913280 "goes_at",
2992 "showing"
3281 "showing",
3282 "thanks"
29933283 ]
29943284 },
29953285 "Message": {
src/actions.ts +109 −1
@@ -72,11 +72,13 @@ import {
7272 viewOf,
7373 type Contact,
7474 type Desk,
75 type Lead,
7576 type LeadDetail,
7677 type NewLead,
7778 type NextLead,
7879 } from "./leads.ts";
7980 import { emit } from "./live.ts";
81 import { approveThanks, sendHeldThanks, skipThanks, thanksOf, type Thanks } from "./thanks.ts";
8082 import { capture, keep, restore, whyNot } from "./undo.ts";
8183 import { currentAgent, storeAgent } from "./profile.ts";
8284 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> {
290292 );
291293 if (message.length === 0 || message.length > 2000)
292294 return fail("invalid", "What they asked is 1 to 2000 characters.");
295 const sender = readReferrer(input, source);
296 if (!sender.ok) return sender;
293297 return ok({
294298 name,
295299 email,
@@ -297,9 +301,36 @@ export function readNewLead(input: Record<string, unknown>): Result<NewLead> {
297301 source,
298302 message,
299303 consent: consentOf(input.consent),
304 ...sender.value,
300305 });
301306 }
302307
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
303334 /** A lead added; `again` when it was someone already on the desk who wrote in again. */
304335 export type Added = LeadDetail & { readonly again?: true };
305336
@@ -315,6 +346,8 @@ export const addLead = (
315346 at?: Date,
316347 ): Result<Added> => {
317348 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 }));
318351 if (!result.ok || result.value.again !== true)
319352 return audited(db, who, "lead", "create", undefined, result);
320353 const detail = mergeDetail({ source: sourceOf(input.source)!, lead: result.value.id });
@@ -332,6 +365,11 @@ function add(
332365 const read = readNewLead(input);
333366 if (!read.ok) return read;
334367 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 );
335373 if (known !== null) {
336374 writeInAgain(db, known, read.value.message, stamp(at), currentAgent(db));
337375 emit("lead.changed", { id: known.id });
@@ -1212,6 +1250,76 @@ function remove(
12121250 return ok({ id: found.value.id });
12131251 }
12141252
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
12151323 /**
12161324 * 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.
12171325 * The forge may call it daily (`POST /tick`); the server also runs it on
@@ -1240,7 +1348,7 @@ export function tick(
12401348 /** The clock's own turn, asked of no one: time passing is not a person. */
12411349 export function turn(db: Database, at?: Date): number[] {
12421350 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))];
12441352 const leads = [...new Set([...advance(db, now), ...sent])];
12451353 for (const id of leads) emit("lead.changed", { id });
12461354 return leads;
src/audit.ts +2 −2
@@ -34,8 +34,8 @@ export interface AuditRow {
3434 readonly detail: string | null;
3535 }
3636
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;
3939 export type Act = (typeof ACTS)[number];
4040
4141 /** 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 {
3434 setNote,
3535 setState,
3636 setStarred,
37 sendThanks,
38 skipThanksFor,
3739 } from "./actions.ts";
3840 import { record } from "./audit.ts";
3941 import { actingAs, identities, table, type Verb } from "./can.ts";
@@ -55,6 +57,7 @@ function whoIs(identity: string): Who {
5557 import { agent } from "./env.ts";
5658 import { findLead, hold, insertLead, type Message } from "./leads.ts";
5759 import { tools } from "./mcp.ts";
60 import { insertThanks } from "./thanks.ts";
5861
5962 // Leads name no one: they are the desk's, not a person's. `authorId` goes unused.
6063 const aLead = (_authorId: string): number =>
@@ -71,6 +74,13 @@ const aLead = (_authorId: string): number =>
7174 new Date().toISOString(),
7275 agent,
7376 );
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 };
7484 /** A lead with a text held for 8:00, as quiet hours leave it. */
7585 const heldLead = (authorId: string): number => {
7686 const id = aLead(authorId);
@@ -184,7 +194,18 @@ const doors: Record<
184194 // POST /leads/:id/star, the MCP tool star_lead).
185195 const starred = setStarred(db, who, { id: replied, starred: true }).ok;
186196 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;
187204 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);
188209 expect(starred).toBe(changed);
189210 expect(starredViaTool).toBe(changed);
190211 expect(skipped).toBe(changed);
src/db.ts +18
@@ -276,6 +276,24 @@ export const migrations: string[] = [
276276 after_updated_at TEXT NOT NULL,
277277 snapshot TEXT NOT NULL
278278 )`,
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 )`,
279297 ];
280298
281299 /**
src/drafts.ts +13
@@ -400,3 +400,16 @@ export function answerDraft(lead: Asker, wrote: string): string {
400400 return `Hi ${first}, thanks for getting back to me! ${next}`;
401401 return `Hi ${first},\n\nThanks for getting back to me. ${next}\n\nTalk soon,`;
402402 }
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", () => {
171171 "yes",
172172 "",
173173 "no",
174 "",
175 "",
176 "",
174177 ]);
175178 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", "", "", ""]);
177180 expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv");
178181 });
179182
src/export.ts +7 −1
@@ -19,6 +19,9 @@ export const COLUMNS = [
1919 "texts allowed",
2020 "lost_reason",
2121 "starred",
22 "referred by",
23 "referrer email",
24 "referrer phone",
2225 ] as const;
2326
2427 /** 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(
6164 lead.consent ? "yes" : "no",
6265 lead.state === "lost" ? (lead.lostReason ?? "no reason given") : "",
6366 lead.starred ? "yes" : "no",
67 lead.referred_by,
68 lead.referrer_email,
69 lead.referrer_phone,
6470 ]);
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";
6672 }
6773
6874 /** 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";
3737 import { between, GREEN_MS } from "./clock.ts";
3838 import type { Agent } from "./env.ts";
3939 import { isQuiet, nextOpening } from "./quiet.ts";
40 import { insertThanks, thanksOf, type Thanks } from "./thanks.ts";
4041 import { type LostReason } from "./lost.ts";
4142 import { followUpsFinished } from "./finished.ts";
4243 import { morningOn } from "./putaway.ts";
@@ -73,6 +74,10 @@ export interface Lead {
7374 readonly back_on: string | null;
7475 /** The agent keeps this lead close: starred open leads lead the desk. */
7576 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;
7681 }
7782
7883 export interface Message {
@@ -117,6 +122,8 @@ export interface LeadDetail extends Lead {
117122 readonly showing: Showing | null;
118123 /** Every follow-up has gone out or been set aside and no one answered: the agent may close it out. */
119124 readonly finished: boolean;
125 /** The thank-you drafted to the referrer (not the lead); null when nobody referred them. */
126 readonly thanks: Thanks | null;
120127 }
121128
122129 /** 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 {
135142 readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null;
136143 /** Every follow-up has gone out or been set aside and no one answered. */
137144 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;
138147 }
139148
140149 /**
@@ -214,6 +223,10 @@ export type NewLead = {
214223 readonly source: Source;
215224 readonly message: string;
216225 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;
217230 };
218231
219232 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt" | "starred"> & {
@@ -304,6 +317,7 @@ export function detail(db: Database, id: number): LeadDetail | null {
304317 replies,
305318 calls,
306319 showing,
320 thanks: thanksOf(db, id),
307321 finished: followUpsFinished(found, messages, replies.length + calls.length > 0, showing !== null),
308322 };
309323 }
@@ -363,6 +377,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
363377 show_at: string | null;
364378 show_address: string | null;
365379 show_hold: string | null;
380 thanks_status: Thanks["status"] | null;
366381 },
367382 [number, string, string]
368383 >(
@@ -374,7 +389,8 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
374389 (SELECT min(goes_at) FROM message WHERE lead_id = lead.id AND status = 'held') AS goes_at,
375390 (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at,
376391 (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
378394 FROM lead
379395 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
380396 OR lead.note LIKE ?2 ESCAPE '\\'
@@ -382,8 +398,9 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
382398 ORDER BY max(created_at, coalesce((SELECT max(at) FROM inbound WHERE lead_id = lead.id), '')) DESC, id DESC LIMIT ?1`,
383399 )
384400 .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 }) => ({
386402 ...lead(row),
403 thanks: thanks_status,
387404 finished: finishedIds.has(row.id),
388405 ready:
389406 ready_id === null || ready_day === null || ready_since === null
@@ -566,9 +583,9 @@ export function insertLead(
566583 const { id } = db
567584 .query<
568585 { id: number },
569 [string, string, string, string, string, number, string]
586 [string, string, string, string, string, number, string, string, string, string]
570587 >(
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",
572589 )
573590 .get(
574591 input.name,
@@ -578,7 +595,18 @@ export function insertLead(
578595 input.message,
579596 input.consent ? 1 : 0,
580597 at,
598 input.referred_by ?? "",
599 input.referrer_email ?? "",
600 input.referrer_phone ?? "",
581601 )!;
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 );
582610 const channel = channelFor(input);
583611 db.query(
584612 "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 @@
99 import type { Database } from "bun:sqlite";
1010 import {
1111 addLead,
12 sendThanks,
13 skipThanksFor,
1214 addSampleInquiry,
1315 exportLeads,
1416 getLead,
@@ -120,7 +122,7 @@ export const tools: readonly Tool[] = [
120122 {
121123 name: "add_lead",
122124 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.",
124126 inputSchema: {
125127 type: "object",
126128 properties: {
@@ -130,11 +132,27 @@ export const tools: readonly Tool[] = [
130132 source: { enum: SOURCES },
131133 message: { type: "string" },
132134 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" },
133138 },
134139 required: ["name", "email", "source", "message"],
135140 },
136141 run: (db, who, args) => addLead(db, who, args),
137142 },
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 },
138156 {
139157 name: "parse_lead_email",
140158 description:
src/pages/desk.ts +15 −2
@@ -7,7 +7,7 @@ import { day, clock, consent, source, starForm, STATE_LABEL } from "./parts.ts";
77 import { deskTitle, layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 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";
1111 import { FINISHED_ACTION, FINISHED_LABEL } from "../finished.ts";
1212 import { dateName } from "../putaway.ts";
1313 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
@@ -230,7 +230,7 @@ const row = (lead: DeskLead, now: number, zone: string, back?: string): string =
230230 <span class="lead-main">
231231 <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : `
232232 <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>
234234 <span class="ask">${escape(lead.message)}</span>
235235 ${status(lead, now, zone)}
236236 </span>
@@ -280,6 +280,12 @@ const signInForm = (sheet?: { preview?: SignInPreview | undefined; address: stri
280280 </details>`;
281281 };
282282
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
283289 const addForm = (prefill?: Partial<NewLead>): string => `<details class="card add"${prefill === undefined ? "" : " open"}>
284290 <summary>Log a lead by hand</summary>
285291 ${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
294300 </label>
295301 <label>What they asked <textarea class="input" name="message" required maxlength="2000" rows="3">${escape(prefill?.message ?? "")}</textarea></label>
296302 <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>
297310 <button class="button">Add to the desk</button>
298311 </form>
299312 </details>`;
src/pages/lead.ts +42
@@ -8,6 +8,7 @@ import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts";
88 import { channelFor, dayLabel, isAnswer, planLabel, MAX_BODY } from "../drafts.ts";
99 import { fill, joiner, SAMPLE_REPLIES } from "../replies.ts";
1010 import { escape } from "../http.ts";
11 import { referrerAddress } from "../thanks.ts";
1112 import { handoff } from "../handoff.ts";
1213 import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts";
1314 import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen } from "../showings.ts";
@@ -326,6 +327,7 @@ export function leadPage(input: {
326327 <h1>${escape(lead.name)}</h1>${mayUpdate ? `
327328 ${starForm(lead, path)}` : ""}
328329 <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>`}
329331 <p class="contact">${contact}${
330332 mayUpdate && lead.phone !== ""
331333 ? ` · <a href="#log-call">Log a call</a>`
@@ -335,6 +337,7 @@ export function leadPage(input: {
335337 ${clock(lead, now, owed)}
336338 </header>
337339 ${noteCard(lead, path, mayUpdate, agent.timeZone)}
340 ${thanksCard(lead, path, mayUpdate, agent, now)}
338341 <div class="split">
339342 <div class="pane theirs">
340343 <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: {
355358 });
356359 }
357360
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
358400 /** "Your note": the agent's own, private; the form only for whoever may update the lead. */
359401 function noteCard(lead: LeadDetail, path: string, may: boolean, zone: string): string {
360402 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("&lt;b&gt;Eve&lt;/b&gt;");
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 &lt;script&gt;");
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 {
3535 saveProfile,
3636 optOutTexts,
3737 approveReply,
38 sendThanks,
39 skipThanksFor,
3840 insertReply,
3941 cancelHeld,
4042 undoSend,
@@ -191,6 +193,9 @@ const LEAD_FIELDS = {
191193 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.",
192194 },
193195 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." },
194199 created_at: STAMP,
195200 replied_at: { type: ["string", "null"], format: "date-time" },
196201 updated_at: STAMP,
@@ -246,8 +251,23 @@ export const LEAD: Schema = {
246251 items: CALL,
247252 },
248253 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 },
249269 },
250 required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing"],
270 required: [...LEAD_REQUIRED, "messages", "replies", "calls", "showing", "thanks"],
251271 };
252272 export const APPROVED: Schema = {
253273 type: "object",
@@ -283,6 +303,7 @@ export const DESK_LEAD: Schema = {
283303 },
284304 next_at: { type: ["string", "null"], format: "date-time" },
285305 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." },
286307 showing: {
287308 type: ["object", "null"],
288309 description: "The showing booked on this lead, if one is.",
@@ -293,7 +314,7 @@ export const DESK_LEAD: Schema = {
293314 },
294315 },
295316 },
296 required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing"],
317 required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing", "thanks"],
297318 };
298319 const SHOW: Schema = {
299320 enum: [...VIEWS],
@@ -374,6 +395,9 @@ const NEW_LEAD: Schema = {
374395 source: LEAD_FIELDS.source,
375396 message: LEAD_FIELDS.message,
376397 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." },
377401 },
378402 required: ["name", "email", "source", "message"],
379403 };
@@ -972,6 +996,42 @@ export const routes: readonly Route[] = [
972996 answer: APPROVED,
973997 },
974998 },
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 },
9751035 // Insert saved reply: the draft with the reply at its end, unsent. A script
9761036 // gets the words; a browser gets the lead's page with the edit box open.
9771037 {
src/sample.ts +11 −2
@@ -74,7 +74,12 @@ export const SAMPLES: readonly Sample[] = [
7474 person("Maria Gonzalez", "zillow", true, "Is 418 Juniper Ln still available? We'd love to see it this weekend if possible.", { ago: 40 * S }),
7575 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 }),
7676 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 },
7883 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." }),
7984 person("Tom Becker", "website", true, "Do you work with first-time buyers? We have no idea where to start.", { ago: 5 * H + 30 * M }),
8085 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[] = [
181186 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?"),
182187 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?"),
183188 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 },
185194 inquiry("Bridget Doyle", "(206) 555-0205", "zillow", true, "Does 310 Orchard Ln allow a home office addition? We're pre-approved to $620k."),
186195 inquiry("Samuel Osei", "(206) 555-0206", "website", true, "First-time buyer here. Can we book a call this week to talk about the process?"),
187196 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
4343 }
4444 }
4545
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
4656 export function deed(
4757 row: AuditRow,
4858 lead: string,
@@ -112,6 +122,21 @@ export function deed(
112122 tried: star ? `star ${lead}` : `take the star off ${lead}`,
113123 };
114124 }
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 };
115140 if (row.act === "brought_back")
116141 return {
117142 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 () =>
319319 "export_leads",
320320 "get_lead",
321321 "add_lead",
322 "send_thanks",
323 "skip_thanks",
322324 "parse_lead_email",
323325 "preview_sign_ins",
324326 "add_sign_ins",
src/terminal.ts +48 −4
@@ -43,6 +43,8 @@ import {
4343 resetSample,
4444 saveProfile,
4545 approveReply,
46 sendThanks,
47 skipThanksFor,
4648 cancelHeld,
4749 undoSend,
4850 restoreFollowUp,
@@ -61,6 +63,7 @@ import {
6163 type SignInPreview,
6264 } from "./actions.ts";
6365 import { missingLine } from "./intake.ts";
66 import { referrerAddress } from "./thanks.ts";
6467 import { MAX_SIGNIN_LINES } from "./signins.ts";
6568 import { dateName, MAX_AWAY_DAYS } from "./putaway.ts";
6669 import { showingLine, showingWhen } from "./showings.ts";
@@ -127,7 +130,19 @@ const ADD_FIELDS = [
127130 },
128131 { key: "message", label: "What they asked" },
129132 { 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 }
131146
132147 const PROFILE_FIELDS = [
133148 { key: "name", label: "Name" },
@@ -375,6 +390,23 @@ export function terminal(
375390 "",
376391 ]),
377392 ];
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 }
378410 const held = l.messages.find((m) => m.status === "held");
379411 if (held !== undefined && held.goes_at !== null)
380412 lines.push(
@@ -448,6 +480,7 @@ export function terminal(
448480 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
449481 ...(undoable(db, l.id, now()) === null ? [] : ["z undo send (for a minute)"]),
450482 ...(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"] : []),
451484 ...(skippable(l) === undefined ? [] : ["k skip the next follow-up"]),
452485 ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]),
453486 ...(l.phone === "" ? [] : ["c log a call"]),
@@ -900,6 +933,16 @@ export function terminal(
900933 else if (input === "o" && CLOSED.includes(l.state)) {
901934 const back = setState(db, me, { id, state: "open" });
902935 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;
903946 } else if (input === "t" && l.consent)
904947 view = { name: "confirm", what: "opt-out", id, back: view };
905948 else if (input === "D")
@@ -1118,11 +1161,12 @@ export function terminal(
11181161 } else if (input === "\r") {
11191162 const field = ADD_FIELDS[view.step]!;
11201163 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)
11221166 view = {
11231167 ...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] ?? "",
11261170 fields,
11271171 };
11281172 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 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs