Public: anyone can read this; the crew can change it.

The agent chooses the days their follow-ups go out (default 1, 3, 7, 14, 30) from their profile, and new leads follow it #75

Merged opened this

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

Merged

mason/speed-to-lead:mason/58-the-agent-chooses-the-days-their-follow → main 2 commits fork

  • Merged. mason/58-the-agent-chooses-the-days-their-follow was merged into main as 83f4956.

Review

Sign in to review this change.
17 files changed +421 −41
README.md +2
@@ -350,6 +350,8 @@ messages already sent keep the signature they went out with.
350350
351351 Under **How your first reply opens**, an admin can write the opening line for each source (Zillow, Realtor.com, website, open house, referral), up to 160 characters on one line; leave one empty to keep the built-in wording. **Preview** shows the first reply to a sample lead in your words without saving; new first replies use them, drafts already on the desk keep theirs, and an opener too long to leave a text under its limit falls back to the built-in line for that text.
352352
353 Under **Follow-up days** an admin chooses when follow-ups go out after the first reply: 1 to 8 whole days, each 1 to 90 and each later than the one before, typed as `1, 3, 7, 14, 30` (the default). A lead you answer after saving gets its follow-ups on the new days; leads already in their follow-ups keep the touches already scheduled, and messages already sent are never touched. A list that breaks those rules is refused with a plain-English message and nothing changes (`422` from the API, where `cadence` is a list of numbers, e.g. `{"cadence": [2, 5, 10]}`; MCP's `set_profile` takes the same). Activity shows the change. A day with no wording of its own borrows the nearest standard wording. In the terminal, `p` shows the days and an admin's `e` ends with a "Follow-up days" line (after the openers) that takes the same list and shows the same refusal.
354
353355 Until you save one, the app uses these environment variables (forge
354356 Settings → App → Environment) or, failing those, a sample agent, Jordan
355357 Avery of Harbor & Pine Realty. Once a profile is saved it wins.
contract/openapi.json +37 −2
@@ -1514,6 +1514,17 @@
15141514 }
15151515 },
15161516 "additionalProperties": false
1517 },
1518 "cadence": {
1519 "type": "array",
1520 "minItems": 1,
1521 "maxItems": 8,
1522 "items": {
1523 "type": "integer",
1524 "minimum": 1,
1525 "maximum": 90
1526 },
1527 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
15171528 }
15181529 },
15191530 "required": [
@@ -1524,7 +1535,8 @@
15241535 "phone",
15251536 "email",
15261537 "timeZone",
1527 "openers"
1538 "openers",
1539 "cadence"
15281540 ]
15291541 }
15301542 }
@@ -1607,6 +1619,17 @@
16071619 }
16081620 },
16091621 "additionalProperties": false
1622 },
1623 "cadence": {
1624 "type": "array",
1625 "minItems": 1,
1626 "maxItems": 8,
1627 "items": {
1628 "type": "integer",
1629 "minimum": 1,
1630 "maximum": 90
1631 },
1632 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
16101633 }
16111634 },
16121635 "required": [
@@ -1686,6 +1709,17 @@
16861709 }
16871710 },
16881711 "additionalProperties": false
1712 },
1713 "cadence": {
1714 "type": "array",
1715 "minItems": 1,
1716 "maxItems": 8,
1717 "items": {
1718 "type": "integer",
1719 "minimum": 1,
1720 "maximum": 90
1721 },
1722 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
16891723 }
16901724 },
16911725 "required": [
@@ -1696,7 +1730,8 @@
16961730 "phone",
16971731 "email",
16981732 "timeZone",
1699 "openers"
1733 "openers",
1734 "cadence"
17001735 ]
17011736 }
17021737 }
src/actions.ts +72 −7
@@ -14,6 +14,7 @@ import { MAX_NOTE, outcomeOf } from "./calls.ts";
1414 import { permit } from "./contract.ts";
1515 import {
1616 BUILT_IN_OPENER,
17 CADENCE,
1718 channelFor,
1819 MAX_BODY,
1920 OPENER_MAX,
@@ -1007,6 +1008,8 @@ export function resetSample(
10071008 export type Profile = Agent & {
10081009 readonly id: 1;
10091010 readonly openers: Readonly<Record<Source, string>>;
1011 /** The days after the first reply that each get a follow-up, for leads answered from now on. */
1012 readonly cadence: readonly number[];
10101013 };
10111014
10121015 /** Every source's opening words: the agent's own, else the built-in line. */
@@ -1017,7 +1020,7 @@ const wording = (own: Openers | undefined): Record<Source, string> =>
10171020
10181021 const profileOf = (db: Database): Profile => {
10191022 const now = currentAgent(db);
1020 return { id: 1, ...now, openers: wording(now.openers) };
1023 return { id: 1, ...now, openers: wording(now.openers), cadence: now.cadence ?? CADENCE };
10211024 };
10221025
10231026 export function getProfile(db: Database, who: Who): Result<Profile> {
@@ -1063,6 +1066,43 @@ export function readOpeners(
10631066 return ok(own);
10641067 }
10651068
1069 /** The most follow-ups a cadence holds, and the furthest day any may fall on. */
1070 export const CADENCE_MAX_TOUCHES = 8;
1071 export const CADENCE_MAX_DAY = 90;
1072
1073 /**
1074 * The follow-up days that arrived — a list of numbers, or text like
1075 * "1, 3, 7" — checked: 1 to 8 whole days, each 1 to 90, strictly increasing.
1076 * Left out, the days stay as they were.
1077 */
1078 export function parseCadence(
1079 input: unknown,
1080 kept: readonly number[],
1081 ): Result<readonly number[]> {
1082 if (input === undefined) return ok(kept);
1083 const parts: unknown[] | undefined = Array.isArray(input)
1084 ? input
1085 : typeof input === "string"
1086 ? input.trim() === ""
1087 ? []
1088 : input.split(/[\s,]+/).filter((p) => p !== "")
1089 : undefined;
1090 if (parts === undefined)
1091 return fail("invalid", "Follow-up days are a list of numbers, like 1, 3, 7, 14, 30.");
1092 if (parts.length === 0 || parts.length > CADENCE_MAX_TOUCHES)
1093 return fail("invalid", `Choose 1 to ${CADENCE_MAX_TOUCHES} follow-up days.`);
1094 const days = parts.map((p) =>
1095 typeof p === "number" ? p : typeof p === "string" && /^\d{1,3}$/.test(p) ? Number(p) : NaN,
1096 );
1097 if (days.some((d) => !Number.isInteger(d)))
1098 return fail("invalid", "Follow-up days are whole numbers, like 1, 3, 7, 14, 30.");
1099 if (days.some((d) => d < 1 || d > CADENCE_MAX_DAY))
1100 return fail("invalid", `Each follow-up day is between 1 and ${CADENCE_MAX_DAY}.`);
1101 if (days.some((d, i) => i > 0 && d <= days[i - 1]!))
1102 return fail("invalid", "Follow-up days must go up, each later than the one before (no repeats).");
1103 return ok(days);
1104 }
1105
10661106 /** What arrived for the profile, checked field by field: the agent to keep, or what is wrong. */
10671107 export function readAgent(
10681108 input: Record<string, unknown>,
@@ -1106,17 +1146,37 @@ export function saveProfile(
11061146 ): Result<Profile> {
11071147 const changes: Record<string, { from: string; to: string }> = {};
11081148 const result = change(db, who, input, changes, at);
1109 const changed = result.ok && Object.keys(changes).length > 0;
1110 return audited(
1149 // One audit row per kind of change, each under its own act.
1150 const kinds = [
1151 { act: "cadence" as const, on: (k: string) => k === "follow-up days" },
1152 { act: "openers" as const, on: (k: string) => k !== "follow-up days" },
1153 ].map(({ act, on }) => ({
1154 act,
1155 detail: Object.fromEntries(Object.entries(changes).filter(([k]) => on(k))),
1156 }));
1157 const made = result.ok ? kinds.filter((k) => Object.keys(k.detail).length > 0) : [];
1158 const [first, ...more] = made;
1159 const out = audited(
11111160 db,
11121161 who,
11131162 "profile",
11141163 "update",
11151164 1,
11161165 result,
1117 changed ? "openers" : undefined,
1118 changed ? JSON.stringify(changes) : undefined,
1166 first?.act,
1167 first === undefined ? undefined : JSON.stringify(first.detail),
11191168 );
1169 for (const k of more)
1170 record(db, {
1171 act: k.act,
1172 detail: JSON.stringify(k.detail),
1173 who,
1174 resource: "profile",
1175 verb: "update",
1176 target: 1,
1177 outcome: "ok",
1178 });
1179 return out;
11201180 }
11211181
11221182 function change(
@@ -1137,6 +1197,11 @@ function change(
11371197 const before = currentAgent(db).openers ?? {};
11381198 const openers = readOpeners(input.openers, before);
11391199 if (!openers.ok) return openers;
1200 const cadence = parseCadence(input.cadence, currentAgent(db).cadence ?? CADENCE);
1201 if (!cadence.ok) return cadence;
1202 const days = currentAgent(db).cadence ?? CADENCE;
1203 if (cadence.value.join(", ") !== days.join(", "))
1204 changes["follow-up days"] = { from: days.join(", "), to: cadence.value.join(", ") };
11401205 const was = wording(before);
11411206 const now = wording(openers.value);
11421207 for (const source of SOURCES)
@@ -1145,12 +1210,12 @@ function change(
11451210 db.transaction(() => {
11461211 storeAgent(
11471212 db,
1148 { ...read.value, openers: openers.value },
1213 { ...read.value, openers: openers.value, cadence: cadence.value },
11491214 who.role === "anon" ? "" : who.name,
11501215 stamp(at),
11511216 );
11521217 // Drafts on the desk keep the opening they were written with.
1153 redraftUnsent(db, { ...read.value, openers: before });
1218 redraftUnsent(db, { ...read.value, openers: before, cadence: cadence.value });
11541219 })();
11551220 emit("lead.changed", {});
11561221 return ok(profileOf(db));
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); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "noted", "merged", "skipped", "unskipped"] as const;
37 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped"] as const;
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/cadence.test.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * The agent's own follow-up days: kept with the profile, used by leads
3 * answered after the change, and never applied to leads already in their
4 * follow-ups.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { activity, addLead, getProfile, listAudit, saveProfile, sendReply, type Result } from "./actions.ts";
11 import { openDb } from "./db.ts";
12 import { CADENCE, draft, wordingDay } from "./drafts.ts";
13 import { rpc } from "./mcp.ts";
14 import { deed } from "./sentences.ts";
15 import type { Who } from "./who.ts";
16
17 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-cadence-")));
18 const alice: Who = { role: "user", id: "u1", name: "alice" };
19 const root: Who = { role: "admin", id: "u0", name: "root" };
20 const must = <T>(r: Result<T>): T => {
21 if (!r.ok) throw new Error(`${r.error}: ${r.message}`);
22 return r.value;
23 };
24 const mine = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
25 const lead = (n: number) => ({
26 name: "Maria Gonzalez",
27 email: `maria${n}@example.com`,
28 phone: "",
29 source: "website",
30 message: "Could we see 418 Juniper Ln?",
31 consent: false,
32 });
33 const when = new Date("2026-03-02T15:00:00Z");
34 const answered = (db: ReturnType<typeof fresh>, n: number) => {
35 const l = must(addLead(db, alice, lead(n), when));
36 return must(sendReply(db, alice, { id: l.id }, when));
37 };
38 const days = (d: { messages: { day: number }[] }) => d.messages.map((m) => m.day).filter((x) => x > 0).sort((a, b) => a - b);
39
40 test("the days are the default until the agent chooses", () => {
41 const db = fresh();
42 expect(must(getProfile(db, alice)).cadence).toEqual(CADENCE);
43 expect(days(answered(db, 1))).toEqual([1, 3, 7, 14, 30]);
44 });
45
46 test("a lead answered after the change gets its touches on the new days; one already in the cadence keeps its own", () => {
47 const db = fresh();
48 const before = answered(db, 1);
49 const saved = must(saveProfile(db, root, { ...mine, cadence: "2, 5, 10" }));
50 expect(saved.cadence).toEqual([2, 5, 10]);
51 expect(days(answered(db, 2))).toEqual([2, 5, 10]);
52 expect(must(listAudit(db, root)).some((a) => a.act === "cadence")).toBe(true);
53 const lead1 = db.query("SELECT day FROM message WHERE lead_id = ?1 AND day > 0 ORDER BY day").all(before.id);
54 expect(lead1.map((r) => (r as { day: number }).day)).toEqual([1, 3, 7, 14, 30]);
55 });
56
57 test("the days survive a restart, and a list works as well as text", () => {
58 const dir = mkdtempSync(join(tmpdir(), "app-cadence-"));
59 must(saveProfile(openDb(dir), root, { ...mine, cadence: [1, 4, 90] }));
60 expect(must(getProfile(openDb(dir), alice)).cadence).toEqual([1, 4, 90]);
61 });
62
63 test("saving without days leaves them as they were", () => {
64 const db = fresh();
65 must(saveProfile(db, root, { ...mine, cadence: "2, 5" }));
66 must(saveProfile(db, root, { ...mine, name: "Sam R." }));
67 expect(must(getProfile(db, alice)).cadence).toEqual([2, 5]);
68 });
69
70 test("each invalid list is refused in plain English and changes nothing", () => {
71 const db = fresh();
72 const bad: unknown[] = [
73 "", " ", [], "1, 2, 3, 4, 5, 6, 7, 8, 9", "0, 3", "1, 91", "-1, 3", "1.5, 3", "a, b",
74 "3, 3", "7, 3", [1, "x"], [1, null], [1, 2.5], 5, { a: 1 }, "1; 3", "1e1",
75 ];
76 for (const cadence of bad) {
77 const r = saveProfile(db, root, { ...mine, name: "Changed", cadence });
78 expect(r.ok).toBe(false);
79 if (!r.ok) {
80 expect(r.error).toBe("invalid");
81 expect(r.message).toMatch(/follow-up|Choose/i);
82 }
83 }
84 const now = must(getProfile(db, alice));
85 expect(now.cadence).toEqual(CADENCE);
86 expect(now.name).not.toBe("Changed");
87 expect(must(listAudit(db, root)).filter((a) => a.act === "cadence")).toHaveLength(0);
88 });
89
90 test("only an admin may set them", () => {
91 const db = fresh();
92 const r = saveProfile(db, alice, { ...mine, cadence: "2, 5" });
93 expect(r.ok).toBe(false);
94 expect(must(getProfile(db, alice)).cadence).toEqual(CADENCE);
95 });
96
97 test("the change reads in Activity", () => {
98 const db = fresh();
99 must(saveProfile(db, root, { ...mine, cadence: "2, 5" }));
100 const row = must(listAudit(db, root)).find((a) => a.act === "cadence")!;
101 const words = deed(row, "", (t) => t).done;
102 expect(words).toContain("changed the follow-up days");
103 expect(words).toContain("1, 3, 7, 14, 30");
104 expect(words).toContain("2, 5");
105 expect(JSON.stringify(must(activity(db, root, {})))).toContain("cadence");
106 });
107
108 test("a day with no wording of its own borrows a fitting one and the draft says nothing false", () => {
109 expect(wordingDay(1)).toBe(1);
110 expect(wordingDay(2)).toBe(3);
111 expect(wordingDay(30)).toBe(30);
112 expect(wordingDay(90)).toBe(14);
113 const asker = { ...lead(1), source: "website" as const };
114 expect(draft(asker, 2, { ...mine, timeZone: "UTC" })).not.toContain("yesterday");
115 expect(draft(asker, 60, { ...mine, timeZone: "UTC" })).not.toContain("month");
116 });
117
118 test("MCP set_profile takes the days", () => {
119 const db = fresh();
120 const out = rpc(db, root, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_profile", arguments: { ...mine, cadence: [3, 6] } } }) as unknown;
121 expect(JSON.stringify(out)).not.toContain("isError\":true");
122 expect(must(getProfile(db, alice)).cadence).toEqual([3, 6]);
123 });
124
125 test("one save that changes the days and an opening is audited as two rows, each under its own act", () => {
126 const db = fresh();
127 must(saveProfile(db, root, { ...mine, cadence: "2, 5", openers: { zillow: "Glad you wrote." } }));
128 const acts = must(listAudit(db, root)).map((a) => a.act).sort();
129 expect(acts).toEqual(["cadence", "openers"]);
130 const rows = must(listAudit(db, root));
131 expect(rows.find((a) => a.act === "cadence")!.detail).not.toContain("opening");
132 expect(rows.find((a) => a.act === "openers")!.detail).not.toContain("follow-up");
133 });
src/db.ts +2
@@ -260,6 +260,8 @@ export const migrations: string[] = [
260260 `ALTER TABLE lead ADD COLUMN lost_reason TEXT`,
261261 `ALTER TABLE lead ADD COLUMN lost_at TEXT`,
262262 `UPDATE lead SET lost_at = updated_at WHERE state = 'lost'`,
263 // The agent's follow-up days as JSON, e.g. [1,3,7]. Null means the default (CADENCE).
264 `ALTER TABLE profile ADD COLUMN cadence TEXT`,
263265 ];
264266
265267 /**
src/drafts.ts +11 −2
@@ -27,7 +27,7 @@ export const SOURCE_LABEL: Readonly<Record<Source, string>> = {
2727 referral: "Referral",
2828 };
2929
30 /** The cadence: the days after the first reply that each get a touch. */
30 /** The default cadence: the days after the first reply that each get a touch, until the agent chooses their own (`profile.cadence`). */
3131 export const CADENCE: readonly number[] = [1, 3, 7, 14, 30];
3232
3333 /** How much a message may say, before the signature. */
@@ -256,6 +256,15 @@ const TOUCH: Readonly<Record<number, Readonly<Record<Topic, Touch>>>> = {
256256 },
257257 };
258258
259 /**
260 * Which day's wording a follow-up uses. The agent may choose any days, so a
261 * day without wording of its own borrows the nearest that fits: "yesterday"
262 * only for day 1, "about a month" only for 28 to 45, and the open-ended
263 * "still here" for anything later.
264 */
265 export const wordingDay = (day: number): 1 | 3 | 7 | 14 | 30 =>
266 day <= 1 ? 1 : day <= 5 ? 3 : day <= 10 ? 7 : day <= 27 ? 14 : day <= 45 ? 30 : 14;
267
259268 /**
260269 * The words for one message to `lead`: day 0 is the first reply, any other
261270 * day a touch of the cadence. The signature is not in here; it is added,
@@ -279,7 +288,7 @@ export function draft(lead: Asker, day: number, agent: Writer): string {
279288 }
280289 return `Hi ${first},\n\n${own === "" ? BUILT_IN_OPENER[lead.source] : own}. ${ask(topic, address, false)}\n\nTalk soon,`;
281290 }
282 const words = TOUCH[day] ?? TOUCH[30]!;
291 const words = TOUCH[wordingDay(day)]!;
283292 const touch = words[topic](first, addressIn(lead.message));
284293 return channel === "text" ? touch : `${touch}\n\nBest,`;
285294 }
src/env.ts +2 −1
@@ -49,4 +49,5 @@ export const agent = {
4949 /** Where the agent's clock is: quiet hours for texts are kept in it. */
5050 timeZone: [process.env.AGENT_TIMEZONE, process.env.TZ].find(isZone) ?? "America/New_York",
5151 } as const;
52 export type Agent = typeof agent;
52 /** The agent as the app uses them: the profile's fields, and the follow-up days they chose (the default when left out). */
53 export type Agent = typeof agent & { readonly cadence?: readonly number[] };
src/leads.ts +1 −1
@@ -646,7 +646,7 @@ function startCadence(
646646 ).run(repliedAt, at, found.id);
647647 const channel = channelFor(found);
648648 const open = !CLOSED.includes(found.state);
649 for (const day of CADENCE)
649 for (const day of agent.cadence ?? CADENCE)
650650 db.query(
651651 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
652652 ).run(
src/mcp.ts +3
@@ -29,6 +29,8 @@ import {
2929 logLeadReply,
3030 parseLeadEmail,
3131 type Result,
32 CADENCE_MAX_DAY,
33 CADENCE_MAX_TOUCHES,
3234 } from "./actions.ts";
3335 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
3436 import { MAX_EMAIL_TEXT } from "./intake.ts";
@@ -320,6 +322,7 @@ export const tools: readonly Tool[] = [
320322 SOURCES.map((s) => [s, { type: "string", maxLength: OPENER_MAX }]),
321323 ),
322324 },
325 cadence: { type: "array", items: { type: "integer", minimum: 1, maximum: CADENCE_MAX_DAY }, minItems: 1, maxItems: CADENCE_MAX_TOUCHES, description: `The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to ${CADENCE_MAX_TOUCHES} whole days, each 1 to ${CADENCE_MAX_DAY}, strictly increasing. Leads already in their follow-ups keep the days scheduled. Left out, unchanged.` },
323326 timeZone: { type: "string", description: "An IANA name like America/Chicago: texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, unchanged." },
324327 },
325328 required: ["name", "brokerage", "license", "phone", "email"],
src/pages/profile.ts +9 −1
@@ -56,8 +56,11 @@ export function profilePage(input: {
5656 fields?: Readonly<Record<Source, string>> | undefined;
5757 /** Whether to preview `fields` rather than what is saved. */
5858 preview?: boolean | undefined;
59 /** What the form fields held when a save was refused, to show again instead of what is saved. */
60 typed?: Readonly<Record<string, string>> | undefined;
5961 }): string {
6062 const { who, profile, mayUpdate, notice } = input;
63 const typed = input.typed ?? {};
6164 const fields = input.fields ?? profile.openers;
6265 const opening = mayUpdate
6366 ? `${SOURCES.map(
@@ -74,14 +77,19 @@ export function profilePage(input: {
7477 ? `<form class="card stack" method="post" action="/profile">
7578 ${FIELDS.map(
7679 (f) =>
77 `<label>${f.label} <input class="input" name="${f.name}" type="${f.type}" value="${escape(profile[f.name])}" required maxlength="${f.max}" autocomplete="${f.auto}"></label>`,
80 `<label>${f.label} <input class="input" name="${f.name}" type="${f.type}" value="${escape(typed[f.name] ?? profile[f.name])}" required maxlength="${f.max}" autocomplete="${f.auto}"></label>`,
7881 ).join("\n ")}
82 <h2>Follow-up days</h2>
83 <label>Days after the first reply <input class="input" name="cadence" type="text" value="${escape(typed.cadence ?? profile.cadence.join(", "))}" required maxlength="40" autocomplete="off" inputmode="numeric"></label>
84 <p class="muted">1 to 8 whole days, each 1 to 90, each later than the one before (the default is 1, 3, 7, 14, 30). Leads you answer from now on get their follow-ups on these days; leads already in their follow-ups keep the days already scheduled.</p>
7985 <h2>How your first reply opens</h2>
8086 ${opening}
8187 </form>
8288 ${previews(profile, shown)}`
8389 : `<div class="card stack">
8490 ${FIELDS.map((f) => `<p><span class="muted">${f.label}</span><br>${escape(profile[f.name])}</p>`).join("\n ")}
91 <h2>Follow-up days</h2>
92 <p>${escape(profile.cadence.join(", "))}</p>
8593 <h2>How your first reply opens</h2>
8694 ${opening}
8795 <p class="muted">Only an admin can change this.</p>
src/profile.ts +19 −8
@@ -6,7 +6,7 @@
66 */
77
88 import type { Database } from "bun:sqlite";
9 import { SOURCES, type Openers, type Writer } from "./drafts.ts";
9 import { CADENCE, SOURCES, type Openers, type Writer } from "./drafts.ts";
1010 import { agent as fromEnvironment } from "./env.ts";
1111
1212 /** The openers kept as JSON: only the strings, only for known sources. */
@@ -26,16 +26,26 @@ function readOpeners(json: string): Openers {
2626 );
2727 }
2828
29 /** The follow-up days kept as JSON: whole days, strictly increasing, or the default. */
30 function keptCadence(json: string | null): readonly number[] {
31 try {
32 const kept: unknown = JSON.parse(json ?? "");
33 if (Array.isArray(kept) && kept.length > 0 && kept.every((d) => Number.isInteger(d) && d > 0))
34 return kept as number[];
35 } catch {}
36 return CADENCE;
37 }
38
2939 /** The saved profile, or the environment's until there is one. */
3040 export function currentAgent(db: Database): Writer {
3141 const saved = db
32 .query<Omit<Writer, "timeZone" | "openers"> & { time_zone: string | null; openers: string }, []>(
33 "SELECT name, brokerage, license, phone, email, time_zone, openers FROM profile WHERE id = 1",
42 .query<Omit<Writer, "timeZone" | "openers"> & { time_zone: string | null; openers: string; cadence: string | null }, []>(
43 "SELECT name, brokerage, license, phone, email, time_zone, openers, cadence FROM profile WHERE id = 1",
3444 )
3545 .get();
3646 if (saved === null) return fromEnvironment;
37 const { time_zone, openers, ...rest } = saved;
38 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone, openers: readOpeners(openers) };
47 const { time_zone, openers, cadence, ...rest } = saved;
48 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone, openers: readOpeners(openers), cadence: keptCadence(cadence) };
3949 }
4050
4151 /** Save `agent` as the profile, whoever it replaces. */
@@ -46,10 +56,10 @@ export function storeAgent(
4656 at: string,
4757 ): void {
4858 db.query(
49 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, openers, updated_at, updated_by)
50 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?9, ?6, ?7)
59 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, openers, cadence, updated_at, updated_by)
60 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?9, ?10, ?6, ?7)
5161 ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3,
52 phone = ?4, email = ?5, time_zone = ?8, openers = ?9, updated_at = ?6, updated_by = ?7`,
62 phone = ?4, email = ?5, time_zone = ?8, openers = ?9, cadence = ?10, updated_at = ?6, updated_by = ?7`,
5363 ).run(
5464 agent.name,
5565 agent.brokerage,
@@ -60,5 +70,6 @@ export function storeAgent(
6070 by,
6171 agent.timeZone,
6272 JSON.stringify(agent.openers ?? {}),
73 JSON.stringify(agent.cadence ?? CADENCE),
6374 );
6475 }
src/routes.ts +41 −9
@@ -44,6 +44,8 @@ import {
4444 tick,
4545 type Failure,
4646 type Result,
47 CADENCE_MAX_DAY,
48 CADENCE_MAX_TOUCHES,
4749 } from "./actions.ts";
4850 import { permit } from "./contract.ts";
4951 import { CADENCE, MAX_BODY, OPENER_MAX, SOURCES, type Source } from "./drafts.ts";
@@ -386,6 +388,14 @@ const PROFILE_FIELDS = {
386388 description: "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is.",
387389 },
388390 } as const;
391 const CADENCE_FIELD: Schema = {
392 type: "array",
393 minItems: 1,
394 maxItems: CADENCE_MAX_TOUCHES,
395 items: { type: "integer", minimum: 1, maximum: CADENCE_MAX_DAY },
396 description:
397 `The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to ${CADENCE_MAX_TOUCHES} whole days, each 1 to ${CADENCE_MAX_DAY}, strictly increasing. A form may send it as text, "1, 3, 7". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422.`,
398 };
389399 const OPENERS: Schema = {
390400 type: "object",
391401 description:
@@ -397,8 +407,8 @@ const OPENERS: Schema = {
397407 };
398408 export const PROFILE: Schema = {
399409 type: "object",
400 properties: { id: { const: 1 }, ...PROFILE_FIELDS, openers: OPENERS },
401 required: ["id", ...Object.keys(PROFILE_FIELDS), "openers"],
410 properties: { id: { const: 1 }, ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD },
411 required: ["id", ...Object.keys(PROFILE_FIELDS), "openers", "cadence"],
402412 };
403413 export const ERROR: Schema = {
404414 type: "object",
@@ -1088,18 +1098,40 @@ export const routes: readonly Route[] = [
10881098 {
10891099 method: "POST",
10901100 path: "/profile",
1091 handle: (c) =>
1092 posted(
1093 c,
1094 (input) => saveProfile(c.db, c.who, withOpeners(input)),
1095 () => ({ to: "/profile", said: "Saved. Drafts now carry this profile." }),
1096 ),
1101 handle: async (c) => {
1102 if (scripted(c.request))
1103 return posted(c, (input) => saveProfile(c.db, c.who, withOpeners(input)), () => ({ to: "/profile" }));
1104 const input = await readFields(c.request);
1105 if (input === undefined) return text("too large", 413);
1106 const saved = saveProfile(c.db, c.who, withOpeners(input));
1107 if (saved.ok || saved.error !== "invalid")
1108 return done(saved, "/profile", "Saved. Drafts now carry this profile.");
1109 // A refused save shows the form again with what was typed and why.
1110 const profile = getProfile(c.db, c.who);
1111 if (!profile.ok) return done(saved, "/profile");
1112 const typed = withOpeners(input).openers as Record<string, unknown> | undefined;
1113 return html(
1114 profilePage({
1115 who: c.who,
1116 profile: profile.value,
1117 mayUpdate: true,
1118 notice: saved.message,
1119 typed: Object.fromEntries(
1120 Object.entries(input).map(([k, v]) => [k, typeof v === "string" ? v : ""]),
1121 ),
1122 fields: Object.fromEntries(
1123 SOURCES.map((s) => [s, typeof typed?.[s] === "string" ? typed[s].trim() : profile.value.openers[s]]),
1124 ) as Record<Source, string>,
1125 }),
1126 422,
1127 );
1128 },
10971129 api: {
10981130 summary:
10991131 "Change the profile (admin only). Drafts not yet sent take it at once; messages already sent keep the signature they went out with. The license may not be blank.",
11001132 body: {
11011133 type: "object",
1102 properties: { ...PROFILE_FIELDS, openers: OPENERS },
1134 properties: { ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD },
11031135 required: Object.keys(PROFILE_FIELDS).filter((f) => f !== "timeZone"),
11041136 },
11051137 answer: PROFILE,
src/sentences.ts +5
@@ -37,6 +37,11 @@ export function deed(
3737 lead: string,
3838 esc: (text: string) => string,
3939 ): { done: string; tried: string } {
40 if (row.resource === "profile" && row.act === "cadence")
41 return {
42 done: `changed the follow-up days${changeWords(row.detail, esc)}`,
43 tried: "change the follow-up days",
44 };
4045 if (row.resource === "profile" && row.act === "openers")
4146 return {
4247 done: `changed how first replies open${changeWords(row.detail, esc)}`,
src/server.test.ts +18 −3
@@ -541,10 +541,11 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
541541
542542 test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => {
543543 const seen = await (await api("/profile", { headers: asJson }, alice)).json();
544 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "openers", "phone", "timeZone"]);
544 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "cadence", "email", "id", "license", "name", "openers", "phone", "timeZone"]);
545545 const page = await (await api("/profile", {}, alice)).text();
546546 expect(page).toContain("Your profile");
547547 expect(page).not.toContain('action="/profile"');
548 expect(page).toContain("Follow-up days");
548549 expect((await api("/profile", { redirect: "manual" })).status).toBe(401);
549550
550551 const sam = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
@@ -554,9 +555,23 @@ test("the profile is a page and a JSON twin: everyone in reads, only an admin sa
554555 expect(blank.status).toBe(422);
555556 const saved = await api("/profile", { method: "POST", ...jsonBody(sam) }, root);
556557 expect(saved.status).toBe(200);
557 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toMatchObject({ id: 1, ...sam, timeZone: "America/New_York" });
558 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toMatchObject({ id: 1, ...sam, timeZone: "America/New_York", cadence: [1, 3, 7, 14, 30] });
558559 const form_ = await api("/profile", {}, root);
559 expect(await form_.text()).toContain('action="/profile"');
560 const formPage = await form_.text();
561 expect(formPage).toContain('action="/profile"');
562 expect(formPage).toContain('name="cadence" type="text" value="1, 3, 7, 14, 30"');
563 // Bad days: 422 on the API, nothing changes; good days from the form are kept.
564 expect((await api("/profile", { method: "POST", ...jsonBody({ ...sam, cadence: [3, 3] }) }, root)).status).toBe(422);
565 expect((await api("/profile", { method: "POST", ...jsonBody({ ...sam, cadence: [1, 91] }) }, root)).status).toBe(422);
566 const viaForm = await api("/profile", { method: "POST", body: form({ ...sam, cadence: "2, 4, 9" }) }, root);
567 expect(viaForm.status).toBeLessThan(400);
568 expect(((await (await api("/profile", { headers: asJson }, bob)).json()) as { cadence: number[] }).cadence).toEqual([2, 4, 9]);
569 const badForm = await api("/profile", { method: "POST", body: form({ ...sam, cadence: "9, 4" }) }, root);
570 expect(badForm.status).toBe(422);
571 const badPage = await badForm.text();
572 expect(badPage).toContain("must go up");
573 expect(badPage).toContain('name="cadence" type="text" value="9, 4"');
574 expect(((await (await api("/profile", { headers: asJson }, bob)).json()) as { cadence: number[] }).cadence).toEqual([2, 4, 9]);
560575 const home = await (await api("/", {}, bob)).text();
561576 expect(home).toContain("Sam Realtor");
562577 expect(home).toContain("WA 99887");
src/terminal.test.ts +48 −3
@@ -247,7 +247,7 @@ test("an admin edits the profile one field at a time; it is saved, audited and r
247247 next(agent.phone, "(555) 010-0000");
248248 next(agent.email, "[email protected]");
249249 next(agent.timeZone, "America/Chicago");
250 for (let i = 0; i < 5; i++) t.key("\r"); // the openers stay built-in
250 for (let i = 0; i < 6; i++) t.key("\r"); // the openers and the follow-up days stay as they are
251251 expect(read(t)).toContain("Saved.");
252252 expect(db.query<{ time_zone: string }, []>("SELECT time_zone FROM profile").get()?.time_zone).toBe("America/Chicago");
253253 expect(read(t)).toContain("WA 99887");
@@ -279,7 +279,8 @@ test("the profile shows each source's opening; an admin words them in the termin
279279 clear(t, "x".repeat(300));
280280 type(t, "Hi from the open house!");
281281 t.key("\r");
282 t.key("\r"); // Referral stays; the last one saves
282 t.key("\r"); // Referral stays
283 t.key("\r"); // the follow-up days stay; the last one saves
283284 expect(read(t)).toContain("Saved.");
284285 expect(read(t)).toContain("Hi from the open house!");
285286 const saved = db.query<{ openers: string }, []>("SELECT openers FROM profile").get();
@@ -295,7 +296,7 @@ test("a blank license typed in the terminal is refused and nothing is saved", ()
295296 for (const current of [agent.name, agent.brokerage]) t.key("\r"), void current;
296297 clear(t, agent.license);
297298 t.key("\r");
298 for (let i = 0; i < 8; i++) t.key("\r");
299 for (let i = 0; i < 9; i++) t.key("\r");
299300 expect(read(t)).toContain("license number is required");
300301 expect(db.query("SELECT * FROM profile").all()).toHaveLength(0);
301302 });
@@ -499,3 +500,47 @@ test("adding someone already on the desk says they wrote in again, and adds no l
499500 const after = listLeads(db, alice);
500501 expect(before.ok && after.ok && after.value.leads.length === before.value.leads.length).toBe(true);
501502 });
503
504 test("the terminal shows the follow-up days, an admin edits them, a bad list changes nothing, and a user cannot save", () => {
505 const db = fresh();
506 const user = terminal(db, alice);
507 user.key("p");
508 expect(read(user)).toContain("Follow-up days");
509 expect(read(user)).toContain("1, 3, 7, 14, 30");
510
511 const edit = (days: string) => {
512 const t = terminal(db, root);
513 t.key("p");
514 t.key("e");
515 for (let i = 0; i < 11; i++) t.key("\r"); // name … the openers stay
516 clear(t, "1, 3, 7, 14, 30");
517 type(t, days);
518 t.key("\r");
519 return t;
520 };
521 const days = () => db.query<{ cadence: string | null }, []>("SELECT cadence FROM profile").get()?.cadence;
522
523 const bad = edit("7, 3");
524 expect(read(bad)).toContain("Follow-up days must go up");
525 expect(days()).toBeUndefined();
526
527 const good = edit("2, 5, 10");
528 expect(read(good)).toContain("Saved.");
529 expect(read(good)).toContain("2, 5, 10");
530 expect(days()).toBe("[2,5,10]");
531 const later = terminal(db, alice);
532 later.key("p");
533 expect(read(later)).toContain("2, 5, 10");
534
535 // Saving something else from the terminal leaves the days alone.
536 const again = terminal(db, root);
537 again.key("p");
538 again.key("e");
539 for (let i = 0; i < 12; i++) again.key("\r");
540 expect(days()).toBe("[2,5,10]");
541
542 user.key("e");
543 expect(read(user)).toContain("Only an admin can change the profile.");
544 expect(read(user)).not.toContain("editing");
545 expect(days()).toBe("[2,5,10]");
546 });
src/terminal.ts +16 −2
@@ -49,6 +49,8 @@ import {
4949 nextLead,
5050 parseLeadEmail,
5151 setState,
52 CADENCE_MAX_DAY,
53 CADENCE_MAX_TOUCHES,
5254 } from "./actions.ts";
5355 import { missingLine } from "./intake.ts";
5456 import { showingLine, showingWhen } from "./showings.ts";
@@ -131,14 +133,23 @@ const OPENER_FIELDS = SOURCES.map((s) => ({
131133 source: s,
132134 label: `Opening for ${SOURCE_LABEL[s]} (empty: built-in)`,
133135 }));
134 const EDIT_FIELDS = [...PROFILE_FIELDS, ...OPENER_FIELDS];
136 /** The follow-up days, typed as "1, 3, 7"; the last thing the editor asks. */
137 const CADENCE_FIELD = {
138 key: "cadence",
139 label: `Follow-up days (1 to ${CADENCE_MAX_TOUCHES} days, each 1 to ${CADENCE_MAX_DAY}, rising: e.g. 1, 3, 7, 14, 30)`,
140 } as const;
141 const EDIT_FIELDS = [...PROFILE_FIELDS, ...OPENER_FIELDS, CADENCE_FIELD];
135142
136143 /** What a field holds now, in the profile the editor starts from. */
137144 const held = (p: Profile, key: string): string =>
138 key.startsWith("opener_")
145 key === "cadence"
146 ? p.cadence.join(", ")
147 : key.startsWith("opener_")
139148 ? (p.openers[key.slice("opener_".length) as Source] ?? "")
140149 : p[key as (typeof PROFILE_FIELDS)[number]["key"]];
141150
151 const daysOf = (p: Profile): string => p.cadence.join(", ");
152
142153 type View =
143154 | { name: "desk" }
144155 | { name: "profile" }
@@ -450,6 +461,9 @@ export function terminal(
450461 bold("How your first reply opens"),
451462 ...OPENER_FIELDS.map((f) => `${SOURCE_LABEL[f.source].padEnd(15)} ${clean(found.value.openers[f.source])}`),
452463 "",
464 bold("Follow-up days"),
465 daysOf(found.value),
466 "",
453467 dim(`Every message is signed with this.${mayEditProfile() ? " e edit ·" : " Only an admin can change it ·"} esc back`),
454468 ];
455469 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs