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

A lead who says "not until spring" can be put away until a date: follow-ups stop, and that morning a check-in draft waits on the desk #80

Merged opened this

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

Merged

mason/speed-to-lead:mason/77-a-lead-who-says-not-until-spring-can-be → main 2 commits fork 1 thread · 1 unresolved

  • Merged. mason/77-a-lead-who-says-not-until-spring-can-be was merged into main as 910bc7b.

Review

Sign in to review this change.
20 files changed +726 −32
AGENTS.md +7
@@ -128,6 +128,13 @@ Speed to Lead is one realtor's desk. The concepts, one module each:
128128 `AFTER_SHOWING_DAY` + n, one per showing, between the cadence and
129129 `ANSWER_DAY`); `advance` does not hold it, rebooking before it goes moves it,
130130 cancelling deletes it, closing skips it.
131 - Put away: a lead told to come back later (`putAway`/`bringBack` in
132 `src/leads.ts`, dates in `src/putaway.ts`). It is the lead's `back_on` field,
133 not a state, so lost/qualified are untouched. Unsent cadence touches are
134 skipped (not by hand, so `bringBack` schedules them again from now); one
135 check-in message numbered `CHECK_IN_DAY` + n (300…399) comes due at 8:00 on
136 the date in the agent's zone. Writing back, closing and sending the check-in
137 clear it. `inView` keeps a put-away lead out of `needs` and `open`.
131138 - `src/drafts.ts` — the words: templates filled from the inquiry and the
132139 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
133140 defaults of `agent` in `src/env.ts`; its `openers` are the agent's own
README.md +24
@@ -73,6 +73,12 @@ what you see right after a restart. Do step 1 first.
7373 with the showing. The sample **Ethan Brooks** has a showing tomorrow, so
7474 his confirmation is on a fresh desk.
7575 A fresh desk also lists upcoming showings above the leads (soonest first, at most five, each linked to its lead): **Aisha Bello** has one in two days.
76 A lead who says "not until spring" can be put away: on an open lead press
77 "Come back on…" and pick a day. Their follow-ups stop, they leave *Needs
78 you* and *In follow-up*, and their row (under *All*) says *Back on* that
79 day; at 8:00 that morning in your time zone a check-in draft waits for you
80 to approve. **Hannah Wright** is already put away for sixty days. "Bring
81 back now" clears the day, and so does a lead writing back.
7682 8. Set your profile (admin to save). Press "Your profile" at the top, fill
7783 in your name, brokerage, license number, phone and email, and save. Every
7884 draft not yet sent takes it at once.
@@ -293,6 +299,24 @@ past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP
293299 tools `book_showing` and `cancel_showing`. It needs the same permission as any
294300 change to a lead, and shows on the Activity page.
295301
302 **When a lead says "not until spring".** On an open lead whose first reply
303 has gone, **Come back on…** takes a day (a calendar day in your profile's time
304 zone, from tomorrow to 365 days out). The lead gets a `back_on` date, not a new
305 state, so qualified and lost are untouched: follow-ups not yet sent are set
306 aside, the lead is in neither *Needs you* nor *In follow-up* (it shows under
307 *All* with a *Back on* badge), and at 8:00 that morning in your zone one
308 check-in draft ("you said to get back in touch around now…", by the lead's
309 channel, signed with your profile, never your private note) comes due for you
310 to approve. Nothing is sent without approval. **Bring back now** clears the
311 date, removes an unsent check-in and schedules the set-aside follow-ups again
312 from today; logging that the lead wrote back, marking them qualified or lost,
313 and sending the check-in do the same. The same is `PATCH /leads/:id` with
314 `{"back_on": "2027-03-01"}` (`null` brings them back; `422` naming `back_on`
315 for a bad date), the MCP tool `put_lead_away`, and `a` (put away) and `A`
316 (bring back) on a lead's terminal screen. It needs the same permission as any
317 change to a lead, and the Activity page says "put … away until …" and "brought
318 … back".
319
296320 **Quiet hours.** Texts go out only between 8:00 a.m. and 9:00 p.m. in your
297321 time zone, the window realtors are told to keep. Approve a text at 11 p.m.
298322 and the app does not send it: it is approved, held, and the lead's page and
contract/openapi.json +38 −4
@@ -31,7 +31,7 @@
3131 "closed",
3232 "all"
3333 ],
34 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)."
34 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)."
3535 }
3636 },
3737 {
@@ -168,7 +168,7 @@
168168 "closed",
169169 "all"
170170 ],
171 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value)."
171 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)."
172172 }
173173 },
174174 {
@@ -325,7 +325,7 @@
325325 }
326326 },
327327 "patch": {
328 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
328 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
329329 "operationId": "patchLeadsId",
330330 "parameters": [
331331 {
@@ -379,6 +379,13 @@
379379 "type": "string",
380380 "maxLength": 2000,
381381 "description": "Empty clears it."
382 },
383 "back_on": {
384 "type": [
385 "string",
386 "null"
387 ],
388 "description": "YYYY-MM-DD: put the lead away until then; null brings it back now."
382389 }
383390 }
384391 }
@@ -387,7 +394,7 @@
387394 },
388395 "responses": {
389396 "200": {
390 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
397 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
391398 "content": {
392399 "application/json": {
393400 "schema": {
@@ -590,6 +597,14 @@
590597 "format": "date-time",
591598 "description": "When the lead was marked lost; null unless it is lost."
592599 },
600 "back_on": {
601 "type": [
602 "string",
603 "null"
604 ],
605 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
606 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
607 },
593608 "created_at": {
594609 "type": "string",
595610 "format": "date-time"
@@ -760,6 +775,7 @@
760775 "state",
761776 "lostReason",
762777 "lostAt",
778 "back_on",
763779 "created_at",
764780 "replied_at",
765781 "updated_at",
@@ -2045,6 +2061,14 @@
20452061 "format": "date-time",
20462062 "description": "When the lead was marked lost; null unless it is lost."
20472063 },
2064 "back_on": {
2065 "type": [
2066 "string",
2067 "null"
2068 ],
2069 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
2070 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
2071 },
20482072 "created_at": {
20492073 "type": "string",
20502074 "format": "date-time"
@@ -2191,6 +2215,7 @@
21912215 "state",
21922216 "lostReason",
21932217 "lostAt",
2218 "back_on",
21942219 "created_at",
21952220 "replied_at",
21962221 "updated_at",
@@ -2415,6 +2440,14 @@
24152440 "format": "date-time",
24162441 "description": "When the lead was marked lost; null unless it is lost."
24172442 },
2443 "back_on": {
2444 "type": [
2445 "string",
2446 "null"
2447 ],
2448 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
2449 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
2450 },
24182451 "created_at": {
24192452 "type": "string",
24202453 "format": "date-time"
@@ -2502,6 +2535,7 @@
25022535 "state",
25032536 "lostReason",
25042537 "lostAt",
2538 "back_on",
25052539 "created_at",
25062540 "replied_at",
25072541 "updated_at",
src/actions.test.ts +4 −1
@@ -266,7 +266,10 @@ test("the desk's views: each lists exactly its leads, counts add up, a bad value
266266 expect(needs.leads.length).toBeGreaterThan(0);
267267 expect(open.leads.length).toBeGreaterThan(0);
268268 expect(closed.leads.length).toBeGreaterThan(0);
269 expect([...ids(needs), ...ids(open), ...ids(closed)].sort()).toEqual(ids({ leads: everyone }).sort());
269 // A lead put away until a date is in none of the three, only in all.
270 const away = everyone.filter((l) => l.back_on !== null);
271 expect(away.length).toBe(1);
272 expect([...ids(needs), ...ids(open), ...ids(closed), ...ids({ leads: away })].sort()).toEqual(ids({ leads: everyone }).sort());
270273 expect(needs.counts).toEqual({
271274 needs: needs.leads.length,
272275 open: open.leads.length,
src/actions.ts +55
@@ -59,6 +59,8 @@ import {
5959 readyFor,
6060 recordCall,
6161 bookShowing as bookShowingFor,
62 bringBack,
63 putAway,
6264 cancelShowing as cancelShowingFor,
6365 recordInbound,
6466 redraftUnsent,
@@ -78,6 +80,7 @@ import { nextInquiry, seed } from "./sample.ts";
7880 import { goesAt, isZone } from "./quiet.ts";
7981 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
8082 import { MAX_ADDRESS, timeOf } from "./showings.ts";
83 import { dateOf } from "./putaway.ts";
8184 import type { Who } from "./who.ts";
8285
8386 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid" | "conflict";
@@ -737,6 +740,58 @@ function booked(
737740 return ok(detail(db, lead.id)!);
738741 }
739742
743 /**
744 * Put an open lead away until a day (`back_on`, `YYYY-MM-DD` on the agent's
745 * calendar, from tomorrow to 365 days out), or bring it back now (`null`).
746 * Follow-ups not yet sent are set aside; that morning at 8:00 a check-in
747 * draft waits for the agent to approve. Nothing is sent.
748 */
749 export const setBackOn = (
750 db: Database,
751 who: Who,
752 input: { id: number; back_on: unknown },
753 at?: Date,
754 ): Result<LeadDetail> =>
755 audited(
756 db,
757 who,
758 "lead",
759 "update",
760 input.id,
761 comeBack(db, who, input, at),
762 input.back_on === null ? "brought_back" : "put_away",
763 typeof input.back_on === "string" ? JSON.stringify({ on: input.back_on.trim() }) : undefined,
764 );
765
766 function comeBack(
767 db: Database,
768 who: Who,
769 input: { id: number; back_on: unknown },
770 at?: Date,
771 ): Result<LeadDetail> {
772 const found = leadFor(db, who, "update", input.id, {

Add this door (setBackOn) to the role table in src/contract.test.ts, alongside bookShowing/cancelShowing.

773 signIn: "Sign in to put this lead away.",
774 no: "You may not put this lead away.",
775 });
776 if (!found.ok) return found;
777 const lead = found.value;
778 const now = stamp(at);
779 const agent = currentAgent(db);
780 if (input.back_on === null) {
781 bringBack(db, lead, now);
782 } else {
783 const day = dateOf(input.back_on, Date.parse(now), agent.timeZone);
784 if ("error" in day) return fail("invalid", `back_on: ${day.error}`);
785 if (CLOSED.includes(lead.state))
786 return fail("invalid", "A qualified or lost lead is already out of follow-ups: put it back first.");
787 if (lead.replied_at === null)
788 return fail("invalid", "Send the first reply before putting a lead away.");
789 putAway(db, lead, day.on, now, agent);
790 }
791 emit("lead.changed", { id: lead.id });
792 return ok(detail(db, lead.id)!);
793 }
794
740795 /** Take the showing off a lead; the follow-ups held for it return to their usual place. */
741796 export const cancelShowing = (
742797 db: Database,
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. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped"] as const;
37 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back"] as const;
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 +10
@@ -21,6 +21,7 @@ import {
2121 listLeads,
2222 logCall,
2323 bookShowing,
24 setBackOn,
2425 cancelHeld,
2526 restoreFollowUp,
2627 skipFollowUp,
@@ -145,6 +146,12 @@ const doors: Record<
145146 const week = new Date(Date.now() + 7 * 86_400_000).toISOString();
146147 const showing = bookShowing(db, who, { id: replied, when: week }).ok;
147148 const off = cancelShowing(db, who, { id: replied }).ok;
149 // And so is putting a lead away until a date, and bringing it back (PATCH /leads/:id
150 // with back_on, POST /leads/:id/back-on and /bring-back, the MCP tool put_lead_away).
151 const away = new Date(Date.now() + 30 * 86_400_000).toISOString().slice(0, 10);
152 const putAway = setBackOn(db, who, { id: replied, back_on: away }).ok;
153 const awayViaTool = (tools.find((t) => t.name === "put_lead_away")!.run(db, who, { id: replied, back_on: away }) as { ok: boolean }).ok;
154 const broughtBack = setBackOn(db, who, { id: replied, back_on: null }).ok;
148155 // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id
149156 // with a name, email or phone, and the MCP tool edit_lead).
150157 const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok;
@@ -173,6 +180,9 @@ const doors: Record<
173180 expect(viaTool).toBe(changed);
174181 expect(showing).toBe(changed);
175182 expect(off).toBe(changed);
183 expect(putAway).toBe(changed);
184 expect(awayViaTool).toBe(changed);
185 expect(broughtBack).toBe(changed);
176186 expect(edited).toBe(changed);
177187 expect(noted).toBe(changed);
178188 expect(notedViaTool).toBe(changed);
src/db.ts +2
@@ -262,6 +262,8 @@ export const migrations: string[] = [
262262 `UPDATE lead SET lost_at = updated_at WHERE state = 'lost'`,
263263 // The agent's follow-up days as JSON, e.g. [1,3,7]. Null means the default (CADENCE).
264264 `ALTER TABLE profile ADD COLUMN cadence TEXT`,
265 // The day (YYYY-MM-DD, the agent's calendar) a lead put away is due back; null when it is not put away.
266 `ALTER TABLE lead ADD COLUMN back_on TEXT`,
265267 ];
266268
267269 /**
src/drafts.ts +26 −6
@@ -55,6 +55,13 @@ export const AFTER_SHOWING_DAY = 500;
5555 * `AFTER_SHOWING_DAY`, so it meets neither.
5656 */
5757 export const BEFORE_SHOWING_DAY = 400;
58 /**
59 * The check-in for a lead put away until a date is numbered from here (300,
60 * 301, …, one per time it is put away), above every cadence day and below
61 * `BEFORE_SHOWING_DAY`, so it meets neither.
62 */
63 export const CHECK_IN_DAY = 300;
64 export const isCheckIn = (day: number): boolean => day >= CHECK_IN_DAY && day < BEFORE_SHOWING_DAY;
5865 export const isBeforeShowing = (day: number): boolean =>
5966 day >= BEFORE_SHOWING_DAY && day < AFTER_SHOWING_DAY;
6067 export const isAfterShowing = (day: number): boolean =>
@@ -66,15 +73,17 @@ export const dayLabel = (day: number): string =>
6673 ? "First reply"
6774 : isAnswer(day)
6875 ? "Answer to their reply"
69 : isAfterShowing(day)
70 ? "After the showing"
71 : isBeforeShowing(day)
72 ? "Before the showing"
73 : `Day ${day} follow-up`;
76 : isCheckIn(day)
77 ? "Check-in"
78 : isAfterShowing(day)
79 ? "After the showing"
80 : isBeforeShowing(day)
81 ? "Before the showing"
82 : `Day ${day} follow-up`;
7483
7584 /** A message's short name in the follow-up plan: "Day 7", "Before the showing". */
7685 export const planLabel = (day: number): string =>
77 isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`;
86 isCheckIn(day) ? "Check-in" : isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`;
7887
7988 export interface Asker {
8089 readonly name: string;
@@ -348,6 +357,17 @@ export function confirmationDraft(
348357 return `Hi ${first},\n\nA quick note before your showing: ${line(address)}\n\nBest,`;
349358 }
350359
360 /**
361 * The morning a lead put away comes back: they said to get in touch around
362 * now. Short enough to text; it says nothing of the agent's private note.
363 */
364 export function checkInDraft(lead: Asker): string {
365 const first = firstName(lead.name);
366 const ask = "you said to get back in touch around now, so here I am. Is it still a good time to talk about your search? Just say the word and we'll pick it up.";
367 if (channelFor(lead) === "text") return `Hi ${first}, ${ask}`;
368 return `Hi ${first},\n\nA quick note: ${ask}\n\nBest,`;
369 }
370
351371 const AGREES = /\b(yes|yeah|yep|sure|sounds good|works for me|that works|perfect|great)\b/i;
352372
353373 /**
src/leads.ts +64 −8
@@ -16,6 +16,9 @@ import {
1616 AFTER_SHOWING_DAY,
1717 afterShowingDraft,
1818 BEFORE_SHOWING_DAY,
19 CHECK_IN_DAY,
20 checkInDraft,
21 isCheckIn,
1922 confirmationDraft,
2023 isBeforeShowing,
2124 ANSWER_DAY,
@@ -34,6 +37,7 @@ import { GREEN_MS } from "./clock.ts";
3437 import type { Agent } from "./env.ts";
3538 import { isQuiet, nextOpening } from "./quiet.ts";
3639 import { type LostReason } from "./lost.ts";
40 import { morningOn } from "./putaway.ts";
3741 import { clockTime, dayName, holdUntil, morningAfter, morningBefore, type Showing } from "./showings.ts";
3842
3943 export type State = "new" | "contacted" | "qualified" | "lost";
@@ -63,6 +67,8 @@ export interface Lead {
6367 readonly lostReason: LostReason | null;
6468 /** When the lead was marked lost; null unless it is lost. */
6569 readonly lostAt: string | null;
70 /** The day (`YYYY-MM-DD`, the agent's calendar) a lead put away comes back; null when it is not put away. */
71 readonly back_on: string | null;
6672 }
6773
6874 export interface Message {
@@ -126,14 +132,15 @@ export interface DeskLead extends Lead {
126132 /**
127133 * Ways to look at the desk. `needs`: a first reply or a follow-up is waiting
128134 * on the agent. `open`: still in the cadence, nothing waiting. `closed`:
129 * qualified or lost. `all`: everyone. The first three never overlap.
135 * qualified or lost. `all`: everyone. The first three never overlap, and a
136 * lead put away until a date is in none of them until its check-in is ready.
130137 */
131138 export const VIEWS = ["needs", "open", "closed", "all"] as const;
132139 export type View = (typeof VIEWS)[number];
133140
134141 /** What a door says about the views, in one place. */
135142 export const VIEW_HELP =
136 "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting; closed: qualified or lost; all (default, also for any other value).";
143 "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value).";
137144
138145 /** A view from user text; anything unknown is `all`. */
139146 export const viewOf = (text: unknown): View =>
@@ -145,7 +152,7 @@ export const inView = (lead: DeskLead, view: View): boolean => {
145152 case "needs":
146153 return !closed && lead.ready !== null;
147154 case "open":
148 return !closed && lead.ready === null;
155 return !closed && lead.ready === null && lead.back_on === null;
149156 case "closed":
150157 return closed;
151158 case "all":
@@ -568,6 +575,8 @@ export function send(
568575 );
569576 // Their answer is out: the follow-ups paused for it start again from today.
570577 if (isAnswer(message.day)) respace(db, found.id, at);
578 // The check-in is out: the lead is no longer put away, and the follow-ups start again from today.
579 if (isCheckIn(message.day)) bringBack(db, found, at);
571580 }
572581 })();
573582 }
@@ -720,7 +729,7 @@ function respace(db: Database, id: number, at: string): void {
720729 .query<{ id: number; day: number }, [number, number]>(
721730 "SELECT id, day FROM message WHERE lead_id = ?1 AND status = 'scheduled' AND day < ?2",
722731 )
723 .all(id, BEFORE_SHOWING_DAY);
732 .all(id, CHECK_IN_DAY);
724733 for (const m of waiting)
725734 db.query("UPDATE message SET due_at = ?1 WHERE id = ?2").run(
726735 later(at, m.day),
@@ -749,6 +758,8 @@ export function recordInbound(
749758 "INSERT INTO inbound (lead_id, channel, body, at) VALUES (?1, ?2, ?3, ?4) RETURNING id",
750759 )
751760 .get(found.id, channel, body, at)!;
761 // Writing back is coming back: the lead is no longer put away.
762 bringBack(db, found, at);
752763 if (answerSince(messagesOf(db, found.id)) === null) {
753764 db.query(
754765 "UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due'",
@@ -801,6 +812,7 @@ export function redraftUnsent(db: Database, agent: Agent): void {
801812
802813 /** The words for an unsent touch or showing note: the cadence's, or the note for the lead's showing as it stands. */
803814 const wordsFor = (db: Database, found: Lead, day: number, agent: Agent): string => {
815 if (isCheckIn(day)) return checkInDraft(found);
804816 if (!isAfterShowing(day) && !isBeforeShowing(day)) return draft(found, day, agent);
805817 const showing = showingOf(db, found.id);
806818 if (isAfterShowing(day)) return afterShowingDraft(found, showing?.address ?? "");
@@ -904,7 +916,7 @@ export type Closing = { readonly state: "qualified" } | { readonly state: "lost"
904916 export function close(db: Database, id: number, closing: Closing, at: string): void {
905917 db.transaction(() => {
906918 db.query(
907 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5 WHERE id = ?3",
919 "UPDATE lead SET state = ?1, updated_at = ?2, lost_reason = ?4, lost_at = ?5, back_on = NULL WHERE id = ?3",
908920 ).run(
909921 closing.state,
910922 at,
@@ -937,7 +949,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
937949 const channel = channelFor(found);
938950 const skipped = db
939951 .query<{ id: number; day: number; due_at: string }, [number, number, number]>(
940 `SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND skipped_by_hand = 0 AND day < ?2 AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY}) AND NOT (day = 0 AND ?3 = 1)`,
952 `SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND skipped_by_hand = 0 AND day < ?2 AND NOT (day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY}) AND NOT (day = 0 AND ?3 = 1)`,
941953 )
942954 .all(found.id, ANSWER_DAY, replied ? 1 : 0);
943955 for (const m of skipped)
@@ -953,7 +965,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
953965 );
954966 respace(db, found.id, at);
955967 db.query(
956 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`,
968 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${AFTER_SHOWING_DAY} AND status = 'skipped'`,
957969 ).run(found.id);
958970 const showing = showingOf(db, found.id);
959971 if (showing !== null)
@@ -964,6 +976,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
964976 /** Why a follow-up cannot be skipped, or null when it can: only its lead's own scheduled or due cadence touches. */
965977 export function whyNotSkip(message: Message): string | null {
966978 if (message.day === 0) return "The first reply is not a follow-up: send it, or close the lead.";
979 if (isCheckIn(message.day)) return "That is the check-in for a lead put away: bring the lead back instead.";
967980 if (message.day >= ANSWER_DAY) return "An answer to something the lead wrote is not a follow-up to skip.";
968981 if (message.status === "sent") return "That follow-up has already been sent.";
969982 if (message.status === "held") return "That text is approved and held for 8:00 a.m.: take it back first.";
@@ -1017,7 +1030,7 @@ export function advance(db: Database, at: string, only?: number): number[] {
10171030 `UPDATE message SET status = 'due'
10181031 WHERE status = 'scheduled' AND due_at <= ?1 AND (?2 = 0 OR id = ?2)
10191032 AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted')
1020 AND (day >= ${BEFORE_SHOWING_DAY} AND day < ${ANSWER_DAY}
1033 AND (day >= ${CHECK_IN_DAY} AND day < ${ANSWER_DAY}
10211034 OR lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1))
10221035 AND NOT (day >= ${BEFORE_SHOWING_DAY} AND day < ${AFTER_SHOWING_DAY}
10231036 AND lead_id IN (SELECT lead_id FROM showing WHERE at <= ?1))
@@ -1167,6 +1180,49 @@ function placeShowingMessage(
11671180 const reachable = (lead: Pick<Lead, "consent" | "phone" | "email">): boolean =>
11681181 channelFor(lead) === "text" || lead.email !== "";
11691182
1183 /**
1184 * The lead is put away until `on` (a `YYYY-MM-DD` on the agent's calendar):
1185 * every follow-up not yet sent is set aside, and at 8:00 that morning in the
1186 * agent's zone a check-in draft comes due for the agent to approve. Putting
1187 * it away again moves the date (and the unsent check-in).
1188 */
1189 export function putAway(db: Database, found: Lead, on: string, at: string, agent: Agent): void {
1190 db.transaction(() => {
1191 db.query("UPDATE lead SET back_on = ?1, updated_at = ?2 WHERE id = ?3").run(on, at, found.id);
1192 db.query(
1193 `UPDATE message SET status = 'skipped', goes_at = NULL WHERE lead_id = ?1 AND day > 0 AND day < ${CHECK_IN_DAY} AND status IN ('scheduled', 'due')`,
1194 ).run(found.id);
1195 placeShowingMessage(
1196 db,
1197 found,
1198 CHECK_IN_DAY,
1199 BEFORE_SHOWING_DAY,
1200 () => checkInDraft(found),
1201 morningOn(on, Date.parse(at), agent.timeZone),
1202 agent,
1203 );
1204 })();
1205 }
1206
1207 /**
1208 * The lead is no longer put away: its date is cleared, an unsent check-in
1209 * goes, and the follow-ups put aside for it are scheduled again from `at` on
1210 * the cadence's spacing. Nothing happens to a lead that is not put away.
1211 */
1212 export function bringBack(db: Database, found: Lead, at: string): void {
1213 if (found.back_on === null) return;
1214 db.transaction(() => {
1215 db.query("UPDATE lead SET back_on = NULL, updated_at = ?1 WHERE id = ?2").run(at, found.id);
1216 db.query(
1217 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${BEFORE_SHOWING_DAY} AND status IN ${UNSENT_SQL}`,
1218 ).run(found.id);
1219 db.query(
1220 `UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND day > 0 AND day < ${CHECK_IN_DAY} AND status = 'skipped' AND skipped_by_hand = 0`,
1221 ).run(found.id);
1222 respace(db, found.id, at);
1223 })();
1224 }
1225
11701226 /** The showing is off: follow-ups whose day has come are due again at once. */
11711227 export function cancelShowing(db: Database, found: Lead, at: string): void {
11721228 db.transaction(() => {
src/mcp.ts +16
@@ -24,6 +24,7 @@ import {
2424 logCall,
2525 bookShowing,
2626 cancelShowing,
27 setBackOn,
2728 restoreFollowUp,
2829 skipFollowUp,
2930 logLeadReply,
@@ -200,6 +201,21 @@ export const tools: readonly Tool[] = [
200201 run: (db, who, args) =>
201202 bookShowing(db, who, { id: Number(args.id), when: args.at, address: args.address }),
202203 },
204 {
205 name: "put_lead_away",
206 description:
207 "A lead said 'not until spring': put an open lead away until a day (back_on, YYYY-MM-DD on the agent's calendar, from tomorrow to 365 days out), or bring it back now with back_on null. Unsent follow-ups are set aside, and at 8:00 that morning a check-in draft waits on the desk for approval. Nothing is sent.",
208 inputSchema: {
209 type: "object",
210 properties: {
211 id: { type: "integer" },
212 back_on: { type: ["string", "null"], description: "YYYY-MM-DD, or null to bring the lead back now." },
213 },
214 required: ["id", "back_on"],
215 },
216 run: (db, who, args) =>
217 setBackOn(db, who, { id: Number(args.id), back_on: args.back_on === undefined ? "" : args.back_on }),
218 },
203219 {
204220 name: "cancel_showing",
205221 description:
src/pages/desk.ts +12 −2
@@ -7,7 +7,8 @@ import { day, clock, consent, source, STATE_LABEL } from "./parts.ts";
77 import { deskTitle, layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import { recordLine, sourceLine } from "../clock.ts";
10 import { isAfterShowing, isBeforeShowing, isAnswer } from "../drafts.ts";
10 import { isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts";
11 import { dateName } from "../putaway.ts";
1112 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
1213 import { MAX_LISTED, showingWhen } from "../showings.ts";
1314 import { MAX_EMAIL_TEXT, missingLine } from "../intake.ts";
@@ -176,6 +177,11 @@ const showingBadge = (lead: DeskLead, now: number, zone: string): string =>
176177 ["Showing", showingWhen(lead.showing.at, now, zone), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "),
177178 )}</span>`;
178179
180 const backBadge = (lead: DeskLead): string =>
181 lead.back_on === null || (lead.ready !== null && isCheckIn(lead.ready.day))
182 ? ""
183 : `<span class="badge" data-back title="Put away: no follow-ups until then, when a check-in draft waits for you">${escape(`Back on ${dateName(lead.back_on)}`)}</span>`;
184
179185 function status(lead: DeskLead, now: number, zone: string): string {
180186 if (lead.state === "qualified" || lead.state === "lost")
181187 return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`;
@@ -185,8 +191,12 @@ function status(lead: DeskLead, now: number, zone: string): string {
185191 return `<span class="status" data-ready>Reply drafted — approve and send</span>`;
186192 if (lead.ready !== null && isAnswer(lead.ready.day))
187193 return `<span class="status" data-ready>They wrote back — answer drafted</span>`;
194 if (lead.ready !== null && isCheckIn(lead.ready.day))
195 return `<span class="status" data-ready>Check-in ready — they asked you to come back</span>`;
188196 if (lead.ready !== null)
189197 return `<span class="status" data-ready>${isBeforeShowing(lead.ready.day) ? "Before the showing — confirmation ready" : isAfterShowing(lead.ready.day) ? "After the showing — note ready" : `Day ${lead.ready.day} follow-up ready`}</span>`;
198 if (lead.back_on !== null)
199 return `<span class="status">Put away until ${escape(dateName(lead.back_on))}</span>`;
190200 if (lead.next_at !== null)
191201 return `<span class="status">Next follow-up ${escape(day(held(lead, lead.next_at), zone))}</span>`;
192202 return `<span class="status">Follow-ups done</span>`;
@@ -197,7 +207,7 @@ const row = (lead: DeskLead, now: number, zone: string): string => `<li>
197207 <span class="lead-main">
198208 <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : `
199209 <span class="note-line">${escape(noteLine(lead.note))}</span>`}
200 <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}</span>
210 <span class="tags">${source(lead)}${consent(lead, zone)}${showingBadge(lead, now, zone)}${backBadge(lead)}</span>
201211 <span class="ask">${escape(lead.message)}</span>
202212 ${status(lead, now, zone)}
203213 </span>
src/pages/lead.ts +21
@@ -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 { escape } from "../http.ts";
1010 import { handoff } from "../handoff.ts";
11 import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts";
1112 import { MAX_ADDRESS, MAX_AHEAD_DAYS, localInput, showingLine, showingWhen } from "../showings.ts";
1213 import { elapsed, between } from "../clock.ts";
1314 import { goesLabel, isQuiet, nextOpening } from "../quiet.ts";
@@ -254,6 +255,25 @@ export function leadPage(input: {
254255 </details>`
255256 : "";
256257
258 const tomorrow = today(now + 86_400_000, agent.timeZone);
259 const furthest = today(now + MAX_AWAY_DAYS * 86_400_000, agent.timeZone);
260 const away =
261 mayUpdate && !closed && lead.replied_at !== null
262 ? `<details class="card add record" id="come-back"${lead.back_on === null ? "" : " open"}>
263 <summary>${lead.back_on === null ? "Come back on…" : `Back on ${escape(dateName(lead.back_on))}`}</summary>
264 <form class="stack" method="post" action="${path}/back-on">
265 <label>Day (${escape(agent.timeZone)}) <input class="input" type="date" name="back_on" required min="${tomorrow}" max="${furthest}"${lead.back_on === null ? "" : ` value="${escape(lead.back_on)}"`}></label>
266 <p class="hint">Unsent follow-ups are set aside. That morning at 8:00 a check-in draft waits on the desk for you to approve; nothing is sent until you do.</p>
267 <button class="button">${lead.back_on === null ? "Put away until then" : "Move the date"}</button>
268 </form>${
269 lead.back_on === null
270 ? ""
271 : `
272 <form method="post" action="${path}/bring-back"><button class="button button-quiet">Bring back now</button></form>`
273 }
274 </details>`
275 : "";
276
257277 const stop =
258278 mayUpdate && lead.consent
259279 ? `<section class="states">
@@ -304,6 +324,7 @@ export function leadPage(input: {
304324 ${thread}
305325 ${call}
306326 ${showing}
327 ${away}
307328 ${record}
308329 ${details}
309330 ${plan}
src/put-away.test.ts added +246
@@ -0,0 +1,246 @@
1 /**
2 * A lead who says "not until spring" is put away until a date: unsent
3 * follow-ups are set aside, and at 8:00 that morning in the agent's zone a
4 * check-in draft waits for approval. Writing back or "bring back now" ends it.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addLead, getLead, listLeads, logLeadReply, sendReply, setBackOn, setNote, setState, skipFollowUp, turn } from "./actions.ts";
11 import { openDb } from "./db.ts";
12 import { CHECK_IN_DAY, BEFORE_SHOWING_DAY } from "./drafts.ts";
13 import { dateOf, morningOn } from "./putaway.ts";
14 import { activityPage } from "./pages/activity.ts";
15 import { deskPage } from "./pages/desk.ts";
16 import { currentAgent, storeAgent } from "./profile.ts";
17 import { seed } from "./sample.ts";
18 import { terminal, plain } from "./terminal.ts";
19 import type { Who } from "./who.ts";
20
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const anon = { role: "anon" } as Who;
23 const T0 = new Date("2026-03-01T10:00:00Z");
24 const DAY = 86_400_000;
25 const at = (days: number) => new Date(T0.getTime() + days * DAY);
26
27 const fresh = (zone = "UTC") => {
28 const db = openDb(mkdtempSync(join(tmpdir(), "app-away-")));
29 storeAgent(db, { ...currentAgent(db), timeZone: zone }, "test", T0.toISOString());
30 return db;
31 };
32 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
33 if (!r.ok) throw new Error(r.message);
34 return r.value as T;
35 };
36 const answered = (db: ReturnType<typeof fresh>, consent = false) => {
37 const id = value(
38 addLead(db, alice, {
39 name: "Dana Reyes",
40 email: "[email protected]",
41 phone: "(206) 555-0111",
42 source: "zillow",
43 message: "Can I see 12 Oak Street?",
44 consent,
45 }, T0),
46 ).id;
47 value(sendReply(db, alice, { id }, T0));
48 return id;
49 };
50 const lead = (db: ReturnType<typeof fresh>, id: number) => value(getLead(db, alice, { id }));
51 const checkIns = (db: ReturnType<typeof fresh>, id: number) =>
52 lead(db, id).messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY);
53 const view = (db: ReturnType<typeof fresh>, show: string) =>
54 value(listLeads(db, alice, { show })).leads.map((l) => l.name);
55
56 test("the date is checked at the boundary, on the agent's calendar", () => {
57 const now = T0.getTime();
58 expect(dateOf("2026-03-02", now, "UTC")).toEqual({ on: "2026-03-02" });
59 expect(dateOf("2027-03-01", now, "UTC")).toEqual({ on: "2027-03-01" });
60 for (const bad of ["2026-03-01", "2026-02-28", "2027-03-02", "2026-02-30", "2026-3-5", "tomorrow", "", 20260305, null, {}, "2026-03-05T10:00"])
61 expect("error" in dateOf(bad, now, "UTC")).toBe(true);
62 // 02:00 UTC on Mar 2 is still Mar 1 in Los Angeles: Mar 2 is then tomorrow, not today.
63 const late = Date.parse("2026-03-02T02:00:00Z");
64 expect("error" in dateOf("2026-03-02", late, "UTC")).toBe(true);
65 expect(dateOf("2026-03-02", late, "America/Los_Angeles")).toEqual({ on: "2026-03-02" });
66 expect(morningOn("2026-03-05", now, "America/Los_Angeles")).toBe("2026-03-05T16:00:00.000Z");
67 });
68
69 test("putting a lead away sets the follow-ups aside and takes it out of Needs you and In follow-up", () => {
70 const db = fresh();
71 const id = answered(db);
72 expect(view(db, "open")).toEqual(["Dana Reyes"]);
73 const away = value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
74 expect(away.back_on).toBe("2026-05-01");
75 expect(away.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY).every((m) => m.status === "skipped")).toBe(true);
76 expect(view(db, "needs")).toEqual([]);
77 expect(view(db, "open")).toEqual([]);
78 expect(view(db, "all")).toEqual(["Dana Reyes"]);
79 // Nothing comes due, however long it is left.
80 turn(db, at(30));
81 expect(lead(db, id).messages.some((m) => m.status === "due" && m.day < CHECK_IN_DAY)).toBe(false);
82 expect(view(db, "needs")).toEqual([]);
83 });
84
85 test("the desk row carries a Back on badge", () => {
86 const db = fresh();
87 const id = answered(db);
88 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
89 const desk = value(listLeads(db, alice, { show: "all" }));
90 const html = deskPage({ who: alice, agent: currentAgent(db), leads: desk.leads, record: desk.record, show: "all", counts: desk.counts, mayAdd: true, mayReset: false });
91 expect(html).toContain("Back on May 1, 2026");
92 });
93
94 test("a check-in draft waits at 8:00 that morning in the agent's zone, and not before", () => {
95 const db = fresh("America/Los_Angeles");
96 const id = answered(db);
97 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
98 const [check] = checkIns(db, id);
99 expect(check!.due_at).toBe("2026-05-01T15:00:00.000Z");
100 expect(check!.status).toBe("scheduled");
101 turn(db, new Date("2026-05-01T14:59:00Z"));
102 expect(checkIns(db, id)[0]!.status).toBe("scheduled");
103 expect(view(db, "needs")).toEqual([]);
104 turn(db, new Date("2026-05-01T15:00:00Z"));
105 expect(checkIns(db, id)[0]!.status).toBe("due");
106 expect(view(db, "needs")).toEqual(["Dana Reyes"]);
107 expect(checkIns(db, id)).toHaveLength(1);
108 });
109
110 test("the check-in speaks of coming back, is signed, goes by the lead's channel and never shows the private note", () => {
111 const db = fresh();
112 const id = answered(db, true);
113 value(setNote(db, alice, { id, note: "SECRET budget is tight" }, T0));
114 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
115 const [check] = checkIns(db, id);
116 expect(check!.channel).toBe("text");
117 expect(check!.body).toContain("Hi Dana");
118 expect(check!.body).toContain("get back in touch around now");
119 expect(check!.body).not.toContain("SECRET");
120 expect(check!.signature).not.toBe("");
121 const plan = lead(db, id);
122 expect(plan.messages.some((m) => m.day === 0 && m.status === "sent")).toBe(true);
123 });
124
125 test("nothing is sent without approval; approving sends it and brings the lead back into follow-ups", () => {
126 const db = fresh();
127 const id = answered(db);
128 value(setBackOn(db, alice, { id, back_on: "2026-03-10" }, at(1)));
129 turn(db, at(20));
130 expect(checkIns(db, id)[0]!.status).toBe("due");
131 value(sendReply(db, alice, { id }, at(20)));
132 const after = lead(db, id);
133 expect(checkIns(db, id)[0]!.status).toBe("sent");
134 expect(after.back_on).toBeNull();
135 const follow = after.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY);
136 expect(follow.every((m) => m.status === "scheduled")).toBe(true);
137 expect(Date.parse(follow[0]!.due_at)).toBe(at(20).getTime() + DAY);
138 });
139
140 test("Bring back now clears the date, deletes the check-in and schedules the follow-ups again", () => {
141 const db = fresh();
142 const id = answered(db);
143 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
144 const back = value(setBackOn(db, alice, { id, back_on: null }, at(2)));
145 expect(back.back_on).toBeNull();
146 expect(checkIns(db, id)).toHaveLength(0);
147 expect(back.messages.filter((m) => m.day > 0).every((m) => m.status === "scheduled")).toBe(true);
148 expect(view(db, "open")).toEqual(["Dana Reyes"]);
149 });
150
151 test("a follow-up skipped by hand stays skipped through put away and bring back", () => {
152 const db = fresh();
153 const id = answered(db);
154 const three = lead(db, id).messages.find((m) => m.day === 3)!;
155 value(skipFollowUp(db, alice, { id, messageId: three.id }, at(0.5)));
156 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
157 const back = value(setBackOn(db, alice, { id, back_on: null }, at(2)));
158 expect(back.messages.find((m) => m.day === 3)!.status).toBe("skipped");
159 expect(back.messages.find((m) => m.day === 7)!.status).toBe("scheduled");
160 });
161
162 test("a lead writing back clears the date", () => {
163 const db = fresh();
164 const id = answered(db);
165 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
166 const wrote = value(logLeadReply(db, alice, { id, body: "Actually, we're ready now.", channel: "email" }, at(2)));
167 expect(wrote.back_on).toBeNull();
168 expect(wrote.messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY)).toHaveLength(0);
169 expect(wrote.messages.some((m) => m.day >= 1000 && m.status === "draft")).toBe(true);
170 expect(view(db, "open")).toEqual([]);
171 expect(view(db, "needs")).toEqual(["Dana Reyes"]);
172 });
173
174 test("putting away again moves the date and the one check-in; closing clears it for good", () => {
175 const db = fresh();
176 const id = answered(db);
177 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
178 value(setBackOn(db, alice, { id, back_on: "2026-06-01" }, at(2)));
179 expect(checkIns(db, id)).toHaveLength(1);
180 expect(checkIns(db, id)[0]!.due_at.slice(0, 10)).toBe("2026-06-01");
181 const lost = value(setState(db, alice, { id, state: "lost", reason: "not_ready" }, at(3)));
182 expect(lost.back_on).toBeNull();
183 const reopened = value(setState(db, alice, { id, state: "open" }, at(4)));
184 expect(reopened.messages.filter((m) => m.day >= CHECK_IN_DAY && m.day < BEFORE_SHOWING_DAY)).toHaveLength(0);
185 expect(reopened.messages.filter((m) => m.day > 0 && m.day < CHECK_IN_DAY).every((m) => m.status === "scheduled")).toBe(true);
186 });
187
188 test("a bad date is refused naming the field; a lead not yet answered or closed cannot be put away", () => {
189 const db = fresh();
190 const id = answered(db);
191 const bad = setBackOn(db, alice, { id, back_on: "2026-03-01" }, at(0));
192 expect(!bad.ok && bad.error === "invalid" && bad.message.startsWith("back_on:")).toBe(true);
193 const fresher = value(addLead(db, alice, { name: "New Person", email: "[email protected]", phone: "", source: "website", message: "Hi", consent: false }, T0)).id;
194 expect(setBackOn(db, alice, { id: fresher, back_on: "2026-05-01" }, at(1)).ok).toBe(false);
195 value(setState(db, alice, { id, state: "qualified" }, at(1)));
196 expect(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)).ok).toBe(false);
197 });
198
199 test("it is a lead update: a visitor is refused", () => {
200 const db = fresh();
201 const id = answered(db);
202 const refused = setBackOn(db, anon, { id, back_on: "2026-05-01" }, at(1));
203 expect(!refused.ok && refused.error).toBe("signin_required");
204 expect(lead(db, id).back_on).toBeNull();
205 });
206
207 test("the Activity page says who put a lead away until when, and who brought it back", () => {
208 const db = fresh();
209 const id = answered(db);
210 value(setBackOn(db, alice, { id, back_on: "2026-05-01" }, at(1)));
211 value(setBackOn(db, alice, { id, back_on: null }, at(2)));
212 const rows = db.query("SELECT * FROM audit ORDER BY id").all() as never[];
213 const html = activityPage({ who: alice, agent: currentAgent(db), rows, names: new Map([[id, "Dana Reyes"]]), older: undefined, lost: [], sentOnly: false });
214 expect(html).toContain("put <a href=\"/leads/" + id + "\">Dana Reyes</a> away until May 1, 2026");
215 expect(html).toContain("brought <a href=\"/leads/" + id + "\">Dana Reyes</a> back");
216 });
217
218 test("one sample lead is already put away", () => {
219 const db = fresh();
220 seed(db, T0);
221 const away = value(listLeads(db, alice, { show: "all" })).leads.filter((l) => l.back_on !== null);
222 expect(away.map((l) => l.name)).toEqual(["Hannah Wright"]);
223 expect(away[0]!.back_on! > "2026-03-01").toBe(true);
224 });
225
226 test("the terminal's lead screen puts a lead away with a, and brings it back with A", () => {
227 const db = fresh();
228 const id = answered(db);
229 const t = terminal(db, alice);
230 t.key("\r");
231 expect(t.screen(100).map(plain).join("\n")).toContain("a put away until a date");
232 t.key("a");
233 for (const ch of "2020-01-01") t.key(ch);
234 t.key("\r");
235 expect(t.screen(100).map(plain).join("\n")).toContain("Pick a day from tomorrow on.");
236 const on = new Date(Date.now() + 30 * DAY).toISOString().slice(0, 10);
237 for (let i = 0; i < 10; i++) t.key("\x7f");
238 for (const ch of on) t.key(ch);
239 t.key("\r");
240 const shown = t.screen(100).map(plain).join("\n");
241 expect(shown).toContain("Put away until");
242 expect(lead(db, id).back_on).toBe(on);
243 expect(shown).toContain("A bring back now");
244 t.key("A");
245 expect(lead(db, id).back_on).toBeNull();
246 });
src/putaway.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * Putting a lead away until a date: "call me in March". The date is a
3 * calendar day on the agent's wall clock (their profile's time zone, never
4 * the server's); that morning at 8:00 a check-in draft waits on the desk.
5 * Nothing here is sent anywhere.
6 */
7
8 import { localInput, wallAt } from "./showings.ts";
9
10 /** How far ahead a lead may be put away. */
11 export const MAX_AWAY_DAYS = 365;
12
13 const DAY_MS = 86_400_000;
14 const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
15
16 /** The calendar day of `ms` on the wall clock of `zone`: `YYYY-MM-DD`. */
17 export const today = (ms: number, zone: string): string => localInput(ms, zone).slice(0, 10);
18
19 /** Whole days from the calendar day `from` to `to`, both `YYYY-MM-DD`. */
20 const daysBetween = (from: string, to: string): number =>
21 Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / DAY_MS);
22
23 /**
24 * A come-back date from user text: a real `YYYY-MM-DD`, at least tomorrow
25 * and at most 365 days out, counted on the agent's calendar in `zone`.
26 */
27 export function dateOf(
28 text: unknown,
29 now: number,
30 zone: string,
31 ): { on: string } | { error: string } {
32 const bad = { error: "A come-back date is a day, like 2027-03-01." };
33 if (typeof text !== "string") return bad;
34 const m = DATE.exec(text.trim());
35 if (m === null) return bad;
36 const [y, mo, d] = [+m[1]!, +m[2]!, +m[3]!];
37 // Date.parse rolls 02-30 over to March; a real date reads back as itself.
38 const real = new Date(Date.UTC(y, mo - 1, d));
39 if (real.getUTCFullYear() !== y || real.getUTCMonth() !== mo - 1 || real.getUTCDate() !== d) return bad;
40 const on = text.trim();
41 const away = daysBetween(today(now, zone), on);
42 if (away < 1) return { error: "Pick a day from tomorrow on." };
43 if (away > MAX_AWAY_DAYS) return { error: `Pick a day within ${MAX_AWAY_DAYS} days.` };
44 return { on };
45 }
46
47 /** When the check-in on `on` comes due: 8:00 that morning in `zone`, the agent's. */
48 export function morningOn(on: string, now: number, zone: string): string {
49 const days = daysBetween(today(now, zone), on);
50 return new Date(wallAt(now, days, 8, zone) ?? Date.parse(`${on}T08:00:00Z`)).toISOString();
51 }
52
53 /** "Mar 1, 2027": a come-back date said plainly. */
54 export const dateName = (on: string): string =>
55 new Date(`${on}T12:00:00Z`).toLocaleDateString("en-US", {
56 month: "short",
57 day: "numeric",
58 year: "numeric",
59 timeZone: "UTC",
60 });
src/routes.ts +41 −4
@@ -38,6 +38,7 @@ import {
3838 logCall,
3939 bookShowing,
4040 cancelShowing,
41 setBackOn,
4142 restoreFollowUp,
4243 skipFollowUp,
4344 logLeadReply,
@@ -175,6 +176,11 @@ const LEAD_FIELDS = {
175176 format: "date-time",
176177 description: "When the lead was marked lost; null unless it is lost.",
177178 },
179 back_on: {
180 type: ["string", "null"],
181 pattern: "^\\d{4}-\\d{2}-\\d{2}$",
182 description: "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away.",
183 },
178184 created_at: STAMP,
179185 replied_at: { type: ["string", "null"], format: "date-time" },
180186 updated_at: STAMP,
@@ -501,6 +507,11 @@ const REASON_FIELD = {
501507 description: "Why the lead is lost; required when state is lost.",
502508 } as const;
503509
510 const BACK_ON_FIELD = {
511 type: ["string", "null"],
512 description: "YYYY-MM-DD: put the lead away until then; null brings it back now.",
513 } as const;
514
504515 const NOTE_FIELD = {
505516 type: "string",
506517 maxLength: MAX_LEAD_NOTE,
@@ -726,11 +737,13 @@ export const routes: readonly Route[] = [
726737 // One change at a time: a mark, or a correction of the details.
727738 const details = CONTACT.some((field) => input[field] !== undefined);
728739 const noted = input.note !== undefined;
729 if ([details, noted, input.state !== undefined].filter(Boolean).length > 1)
740 const away = input.back_on !== undefined;
741 if ([details, noted, away, input.state !== undefined].filter(Boolean).length > 1)
730742 return json(
731 { error: "invalid", message: "Send one change at a time: a state, details to correct, or a note." },
743 { error: "invalid", message: "Send one change at a time: a state, details to correct, a note, or a come-back date." },
732744 422,
733745 );
746 if (away) return answer(setBackOn(c.db, c.who, { id: ID(c), back_on: input.back_on }));
734747 if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note }));
735748 if (details)
736749 return answer(editLead(c.db, c.who, { id: ID(c), ...contactOf(input) }));
@@ -738,10 +751,10 @@ export const routes: readonly Route[] = [
738751 },
739752 api: {
740753 summary:
741 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
754 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
742755 body: {
743756 type: "object",
744 properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD },
757 properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD, back_on: BACK_ON_FIELD },
745758 },
746759 answer: LEAD,
747760 },
@@ -884,6 +897,30 @@ export const routes: readonly Route[] = [
884897 answer: LEAD,
885898 },
886899 },
900 {
901 // The page's forms for `back_on` on PATCH: a form can only post.
902 method: "POST",
903 path: "/leads/:id/back-on",
904 handle: (c) =>
905 posted(
906 c,
907 (input) => setBackOn(c.db, c.who, { id: ID(c), back_on: input.back_on }),
908 (lead) => ({
909 to: `/leads/${ID(c)}`,
910 said: `Put away until ${lead?.back_on ?? "the day you chose"}. Nothing goes until then.`,
911 }),
912 ),
913 },
914 {
915 method: "POST",
916 path: "/leads/:id/bring-back",
917 handle: (c) =>
918 posted(
919 c,
920 () => setBackOn(c.db, c.who, { id: ID(c), back_on: null }),
921 () => ({ to: `/leads/${ID(c)}`, said: "Brought back." }),
922 ),
923 },
887924 {
888925 method: "DELETE",
889926 path: "/leads/:id/showing",
src/sample.ts +9 −1
@@ -11,9 +11,11 @@ import type { Database } from "bun:sqlite";
1111 import type { Source } from "./drafts.ts";
1212 import { morningAfter, wallAt } from "./showings.ts";
1313 import { currentAgent } from "./profile.ts";
14 import { today } from "./putaway.ts";
1415 import {
1516 advance,
1617 bookShowing,
18 putAway,
1719 close,
1820 findLead,
1921 insertLead,
@@ -36,6 +38,8 @@ interface Sample extends NewLead {
3638 readonly showedAgo?: number;
3739 /** A showing booked ahead: this many days from today at 10:00 in the agent's zone. */
3840 readonly showingInDays?: number;
41 /** Put away until this many days from today, on the agent's calendar: "call me in the spring". */
42 readonly awayInDays?: number;
3943 /** The agent's private note on the lead, as of the first reply or the inquiry. */
4044 readonly note?: string;
4145 }
@@ -78,7 +82,7 @@ export const SAMPLES: readonly Sample[] = [
7882 person("Rosa Alvarez", "referral", false, "My cousin Elena recommended you. We need a bigger place before the baby comes in March.", { ago: 4 * D + 2 * H, answeredIn: 3 * M + 20 * S, touched: [1], showedAgo: D }),
7983 person("Ethan Brooks", "realtor_com", true, "What would my 2-bed condo on Seaview Ave sell for? Considering upsizing next year.", { ago: 8 * D + 5 * H, answeredIn: 2 * M + 5 * S, touched: [1, 3], showingInDays: 1 }),
8084 person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: { state: "qualified" } }),
81 person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14] }),
85 person("Hannah Wright", "open_house", false, "Thanks for the tour of the Maple Ave home. Still deciding whether we want to stay in the city.", { ago: 31 * D, answeredIn: 4 * M + 15 * S, touched: [1, 3, 7, 14], awayInDays: 60 }),
8286 person("Owen Hart", "zillow", false, "Is 55 Cedar Ln still on the market? We'd like a second showing.", { ago: 9 * D, answeredIn: 2 * M + 40 * S, touched: [1, 3], closed: { state: "lost", reason: "bought_elsewhere" } }),
8387 person("Nadia Petrov", "website", true, "We might sell, but not before our kids finish school in two years. What should we do now?", { ago: 12 * D, answeredIn: 3 * M + 5 * S, touched: [1, 3], closed: { state: "lost", reason: "not_ready" } }),
8488 person("Carl Dunn", "referral", false, "A friend gave me your name. Call me about listing the duplex.", { ago: 20 * D, answeredIn: 5 * M, touched: [1, 3, 7], closed: { state: "lost", reason: "never_answered" } }),
@@ -113,6 +117,10 @@ export function seed(db: Database, now: Date): number {
113117 const ahead = wallAt(t, sample.showingInDays, 10, agent.timeZone) ?? t + sample.showingInDays * D;
114118 bookShowing(db, findLead(db, id)!, iso(ahead), "27 Alder Ct", iso(asked), agent);
115119 }
120 if (sample.awayInDays !== undefined) {
121 const agent = currentAgent(db);
122 putAway(db, findLead(db, id)!, today(t + sample.awayInDays * D, agent.timeZone), iso(t), agent);
123 }
116124 if (sample.note !== undefined)
117125 writeNote(db, findLead(db, id)!, sample.note, iso(asked + 30 * M));
118126 if (sample.closed !== undefined) close(db, id, sample.closed, iso(t - 2 * D));
src/sentences.ts +23
@@ -6,6 +6,7 @@
66 */
77
88 import { readMergeDetail, type AuditRow } from "./audit.ts";
9 import { dateName } from "./putaway.ts";
910 import { SOURCE_LABEL, type Source } from "./drafts.ts";
1011
1112 /** What a correction changed, as ": phone “a” → “b”, …"; "" when the row names nothing readable. */
@@ -32,6 +33,16 @@ function mergeWords(detail: string | null, esc: (text: string) => string): strin
3233 return label === undefined ? "" : ` (via ${esc(label)})`;
3334 }
3435
36 /** A put-away's date: " until Mar 1, 2027"; "" when the row names none. */
37 function awayWords(detail: string | null, esc: (text: string) => string): string {
38 try {
39 const { on } = JSON.parse(detail ?? "") as { on?: unknown };
40 return typeof on === "string" && /^\d{4}-\d{2}-\d{2}$/.test(on) ? ` until ${esc(dateName(on))}` : "";
41 } catch {
42 return "";
43 }
44 }
45
3546 export function deed(
3647 row: AuditRow,
3748 lead: string,
@@ -77,6 +88,18 @@ export function deed(
7788 tried: skip ? `skip a follow-up to ${lead}` : `bring back a skipped follow-up to ${lead}`,
7889 };
7990 }
91 if (row.act === "put_away") {
92 const on = awayWords(row.detail, esc);
93 return {
94 done: `put ${lead} away${on}`,
95 tried: `put ${lead} away`,
96 };
97 }
98 if (row.act === "brought_back")
99 return {
100 done: `brought ${lead} back`,
101 tried: `bring ${lead} back`,
102 };
80103 if (row.act === "qualified" || row.act === "lost")
81104 return {
82105 done: `marked ${lead} ${row.act}`,
src/server.test.ts +27
@@ -257,6 +257,32 @@ test("POST /leads/:id/state and PATCH /leads/:id: qualified or lost leaves the c
257257 ).toBe(422);
258258 });
259259
260 test("PATCH /leads/:id with back_on puts a lead away (null brings it back); a bad date is a 422 naming the field", async () => {
261 const one = await created({ ...NEW, name: "Not Until Spring" });
262 await api(`/leads/${one.id}/reply`, { method: "POST", ...jsonBody({}) }, alice);
263 const tomorrow = new Date(Date.now() + 2 * 86_400_000).toISOString().slice(0, 10);
264 const away = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow }) }, alice);
265 expect(away.status).toBe(200);
266 const put = (await away.json()) as Lead & { back_on: string | null };
267 expect(put.back_on).toBe(tomorrow);
268 expect(put.messages.some((m) => m.day === 300 && m.status === "scheduled")).toBe(true);
269 const bad = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: "2020-01-01" }) }, alice);
270 expect(bad.status).toBe(422);
271 expect(((await bad.json()) as { message: string }).message).toContain("back_on");
272 expect((await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow, note: "x" }) }, alice)).status).toBe(422);
273 expect((await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: tomorrow }) })).status).toBe(401);
274 const back = await api(`/leads/${one.id}`, { method: "PATCH", ...jsonBody({ back_on: null }) }, alice);
275 expect(((await back.json()) as { back_on: string | null }).back_on).toBeNull();
276 // The page's forms reach the same actions.
277 const form1 = await api(`/leads/${one.id}/back-on`, { method: "POST", body: form({ back_on: tomorrow }), redirect: "manual" }, alice);
278 expect(form1.status).toBe(303);
279 expect((await lead(one.id) as Lead & { back_on: string | null }).back_on).toBe(tomorrow);
280 const page = await (await api(`/leads/${one.id}`, {}, alice)).text();
281 expect(page).toContain("Bring back now");
282 expect((await api(`/leads/${one.id}/bring-back`, { method: "POST", body: form({}), redirect: "manual" }, alice)).status).toBe(303);
283 expect((await lead(one.id) as Lead & { back_on: string | null }).back_on).toBeNull();
284 });
285
260286 test("POST /tick: the day turns for whoever may update leads; a stranger may not", async () => {
261287 const ticked = await api("/tick", { method: "POST", ...jsonBody({}) }, alice);
262288 expect(ticked.status).toBe(200);
@@ -299,6 +325,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
299325 "log_lead_reply",
300326 "log_call",
301327 "book_showing",
328 "put_lead_away",
302329 "cancel_showing",
303330 "mark_lead",
304331 "edit_lead",
src/terminal.ts +39 −4
@@ -45,6 +45,7 @@ import {
4545 logCall,
4646 bookShowing,
4747 cancelShowing,
48 setBackOn,
4849 logLeadReply,
4950 nextLead,
5051 parseLeadEmail,
@@ -53,13 +54,14 @@ import {
5354 CADENCE_MAX_TOUCHES,
5455 } from "./actions.ts";
5556 import { missingLine } from "./intake.ts";
57 import { dateName, MAX_AWAY_DAYS } from "./putaway.ts";
5658 import { showingLine, showingWhen } from "./showings.ts";
5759 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
5860 import { between, elapsed, recordLine, sourceLine, tone } from "./clock.ts";
5961 import { permit } from "./contract.ts";
6062 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
6163 import { said as saidOf } from "./sentences.ts";
62 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, planLabel, type Channel, type Source } from "./drafts.ts";
64 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, planLabel, type Channel, type Source } from "./drafts.ts";
6365 import { ssh, title, where } from "./env.ts";
6466 import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts";
6567 import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
@@ -161,6 +163,7 @@ type View =
161163 | { name: "edit"; id: number; text: string }
162164 | { name: "call"; id: number; outcome: Outcome; text: string }
163165 | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string }
166 | { name: "away"; id: number; typed: string }
164167 | { name: "wrote"; id: number; text: string; channel: Channel }
165168 | { name: "note"; id: number; text: string }
166169 | { name: "lost"; id: number }
@@ -276,12 +279,12 @@ export function terminal(
276279 l.goes_at !== null
277280 ? dim(goesLabel(l.goes_at, now(), zone))
278281 : l.ready === null
279 ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "")
282 ? dim(l.state === "qualified" || l.state === "lost" ? l.state : l.back_on !== null ? `back on ${dateName(l.back_on)}` : "")
280283 : l.ready.day === 0
281284 ? "reply drafted"
282285 : isAnswer(l.ready.day)
283286 ? "wrote back · answer drafted"
284 : isBeforeShowing(l.ready.day) ? "before the showing · confirmation ready" : isAfterShowing(l.ready.day) ? "after the showing · note ready" : `day ${l.ready.day} follow-up ready`;
287 : isCheckIn(l.ready.day) ? "check-in ready" : isBeforeShowing(l.ready.day) ? "before the showing · confirmation ready" : isAfterShowing(l.ready.day) ? "after the showing · note ready" : `day ${l.ready.day} follow-up ready`;
285288 const name = clean(l.name).padEnd(18).slice(0, 18);
286289 const showing =
287290 l.showing === null
@@ -407,6 +410,8 @@ export function terminal(
407410 ? [dim(` Follow-ups due before it wait until ${showingWhen(l.showing.hold_until, now(), currentAgent(db).timeZone)}.`)]
408411 : []),
409412 );
413 if (l.back_on !== null)
414 lines.push(dim(`Put away until ${dateName(l.back_on)}: no follow-ups; a check-in draft waits that morning at 8:00.`));
410415 const sent = l.messages.filter((m) => m.status === "sent").length;
411416 for (const c of l.calls)
412417 lines.push(dim(`${callLine(c.outcome)} — ${c.at.slice(0, 16).replace("T", " ")}${c.note === "" ? "" : `: ${clean(c.note)}`}`));
@@ -431,6 +436,8 @@ export function terminal(
431436 ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []),
432437 ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]),
433438 ...(l.showing === null || CLOSED.includes(l.state) ? [] : ["u cancel the showing"]),
439 ...(l.replied_at === null || CLOSED.includes(l.state) ? [] : [l.back_on === null ? "a put away until a date" : "a move the date"]),
440 ...(l.back_on === null ? [] : ["A bring back now"]),
434441 ...(l.state === "qualified" || l.state === "lost"
435442 ? ["o put back in follow-ups"]
436443 : ["q qualified", "x lost"]),
@@ -616,6 +623,14 @@ export function terminal(
616623 "",
617624 dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"),
618625 ]
626 : view.name === "away"
627 ? [
628 bold(`Put ${clean(lead(view.id)?.name ?? "the lead")} away`),
629 "",
630 `Back on (YYYY-MM-DD, your calendar, from tomorrow to ${MAX_AWAY_DAYS} days out): ${clean(view.typed)}█`,
631 "",
632 dim("Unsent follow-ups are set aside; that morning at 8:00 a check-in draft waits for you. enter save · esc cancel"),
633 ]
619634 : view.name === "showing"
620635 ? [
621636 bold(`A showing with ${clean(lead(view.id)?.name ?? "the lead")}`),
@@ -811,7 +826,12 @@ export function terminal(
811826 view = { name: "call", id, outcome: "talked", text: "" };
812827 else if (input === "b" && !CLOSED.includes(l.state))
813828 view = { name: "showing", id, step: 0, typed: "", when: "" };
814 else if (input === "u" && l.showing !== null) {
829 else if (input === "a" && l.replied_at !== null && !CLOSED.includes(l.state))
830 view = { name: "away", id, typed: l.back_on ?? "" };
831 else if (input === "A" && l.back_on !== null) {
832 const back = setBackOn(db, me, { id, back_on: null });
833 said = back.ok ? `${l.name}: brought back. Follow-ups are scheduled again.` : back.message;
834 } else if (input === "u" && l.showing !== null) {
815835 const off = cancelShowing(db, me, { id });
816836 said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message;
817837 } else if (input === "w")
@@ -841,6 +861,21 @@ export function terminal(
841861 }
842862 return;
843863 }
864 case "away": {
865 if (input === "\x1b") {
866 said = "Not put away.";
867 view = { name: "lead", id: view.id };
868 } else if (input === "\r") {
869 const away = setBackOn(db, me, { id: view.id, back_on: view.typed });
870 said = away.ok ? `Put away until ${dateName(view.typed.trim())}. A check-in draft waits that morning.` : away.message;
871 // A refused date is typed again; anything else goes back to the lead.
872 if (away.ok || away.error !== "invalid") view = { name: "lead", id: view.id };
873 } else {
874 const next = typing(view.typed, input);
875 if (next !== undefined) view = { ...view, typed: next };
876 }
877 return;
878 }
844879 case "showing": {
845880 if (input === "\x1b") {
846881 said = "No showing booked.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs