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

A listing drops its price: the agent enters the address and new price, and every lead who asked about that home gets a drafted note waiting on the desk #97

Merged opened this

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

Merged

mason/speed-to-lead:mason/89-a-listing-drops-its-price-the-agent-ente → main 2 commits fork

  • Merged. mason/89-a-listing-drops-its-price-the-agent-ente was merged into main as 97dc121.

Review

Sign in to review this change.
17 files changed +717 −20
README.md +7
@@ -83,6 +83,13 @@ what you see right after a restart. Do step 1 first.
8383 lead's name (one tap, no JavaScript needed). Starred open leads sort first
8484 under every filter, and *Starred* is a filter of its own. A first reply
8585 that has waited past five minutes still comes before the stars.
86 When a listing drops its price, press "Price change" on the desk, enter
87 `418 Juniper Ln` and a new price, and every open buyer whose inquiry or
88 booked showing names that address (**Maria Gonzalez** and **Rosa Alvarez**
89 in the samples) gets a drafted note on the desk; it says how many, and
90 entering it twice drafts nothing new. Nothing is sent until you approve.
91 In the terminal, press `$` on the desk, type the address, press enter, type
92 the price and press enter: the same notes, the same count.
8693 8. Set your profile (admin to save). Press "Your profile" at the top, fill
8794 in your name, brokerage, license number, phone and email, and save. Every
8895 draft not yet sent takes it at once.
contract/openapi.json +77
@@ -222,6 +222,83 @@
222222 }
223223 }
224224 },
225 "/leads/price-change": {
226 "post": {
227 "summary": "A listing's price dropped: every open lead who asked about the address (in their inquiry, or by a showing booked there) gets one drafted note naming it and the new price, waiting on the desk. Nothing is sent, and the same change twice drafts nothing new. Answers with how many drafts were made, zero included; a bad address or price is a 422 naming the field.",
228 "operationId": "postLeadsPriceChange",
229 "requestBody": {
230 "required": true,
231 "content": {
232 "application/json": {
233 "schema": {
234 "type": "object",
235 "properties": {
236 "address": {
237 "type": "string",
238 "maxLength": 200,
239 "description": "The street address, starting with the number: 12 Oak St."
240 },
241 "price": {
242 "type": "integer",
243 "minimum": 1,
244 "maximum": 1000000000,
245 "description": "The new price in whole dollars."
246 }
247 },
248 "required": [
249 "address",
250 "price"
251 ]
252 }
253 }
254 }
255 },
256 "responses": {
257 "200": {
258 "description": "A listing's price dropped: every open lead who asked about the address (in their inquiry, or by a showing booked there) gets one drafted note naming it and the new price, waiting on the desk. Nothing is sent, and the same change twice drafts nothing new. Answers with how many drafts were made, zero included; a bad address or price is a 422 naming the field.",
259 "content": {
260 "application/json": {
261 "schema": {
262 "type": "object",
263 "properties": {
264 "address": {
265 "type": "string"
266 },
267 "price": {
268 "type": "integer"
269 },
270 "matched": {
271 "type": "integer",
272 "description": "Open leads who asked about the address."
273 },
274 "drafted": {
275 "type": "integer",
276 "description": "Drafts made now."
277 },
278 "leads": {
279 "type": "array",
280 "items": {
281 "type": "integer"
282 }
283 }
284 }
285 }
286 }
287 }
288 },
289 "default": {
290 "description": "{ error, message }: why not",
291 "content": {
292 "application/json": {
293 "schema": {
294 "$ref": "#/components/schemas/Error"
295 }
296 }
297 }
298 }
299 }
300 }
301 },
225302 "/leads/parse": {
226303 "post": {
227304 "summary": "Read a pasted lead notification email (Zillow, Realtor.com, a website form) into a new lead's fields. Only what the email labels is returned, never consent. Nothing is written; add the lead with POST /leads once checked. Needs the same role as adding a lead.",
src/actions.ts +48
@@ -86,6 +86,7 @@ import { nextInquiry, seed } from "./sample.ts";
8686 import { goesAt, isZone } from "./quiet.ts";
8787 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
8888 import { MAX_ADDRESS, timeOf } from "./showings.ts";
89 import { draftPriceChange, readChange, type Outcome as PriceChanged } from "./price-change.ts";
8990 import { dateOf } from "./putaway.ts";
9091 import { MAX_SIGNIN_LINES, MAX_SIGNIN_TEXT, readSignIns, type SignIn } from "./signins.ts";
9192 import type { Who } from "./who.ts";
@@ -1051,6 +1052,53 @@ function starring(
10511052 return ok(detail(db, found.value.id)!);
10521053 }
10531054
1055 /**
1056 * A listing's price dropped: every open lead who asked about `address` (in
1057 * their inquiry, or by a showing booked there) gets one drafted note naming it
1058 * and the new price, waiting on the desk for the agent to approve. Nothing is
1059 * sent. The same change twice drafts nothing new. Answers with how many drafts
1060 * were made, zero included.
1061 */
1062 export function changePrice(
1063 db: Database,
1064 who: Who,
1065 input: { address?: unknown; price?: unknown },
1066 at?: Date,
1067 ): Result<PriceChanged> {
1068 const read = readChange(input);
1069 const result: Result<PriceChanged> =
1070 permit(who, "lead", "update") !== "yes"
1071 ? refuse(who, "Sign in to change a price.", "You may not change a price.")
1072 : !read.ok
1073 ? fail("invalid", read.message)
1074 : ok(draftPriceChange(db, read.value, stamp(at), currentAgent(db)));
1075 record(db, {
1076 who,
1077 resource: "lead",
1078 verb: "update",
1079 target: "price",
1080 outcome: result.ok ? "ok" : result.error,
1081 act: "price_change",
1082 detail: JSON.stringify(
1083 result.ok
1084 ? { address: result.value.address, price: result.value.price, drafted: result.value.drafted }
1085 : { address: typeof input.address === "string" ? input.address.slice(0, MAX_ADDRESS) : "" },
1086 ),
1087 });
1088 if (result.ok) for (const id of result.value.leads) emit("lead.changed", { id });
1089 return result;
1090 }
1091
1092 /** What the price change did, in a sentence for the agent. */
1093 export const priceChangeWords = (done: PriceChanged): string => {
1094 const buyers = (n: number): string => `${n} buyer${n === 1 ? "" : "s"}`;
1095 const already = done.matched - done.drafted;
1096 if (done.matched === 0) return `No open buyers asked about ${done.address} — nothing drafted.`;
1097 const had = already > 0 ? ` (${already} already had one)` : "";
1098 if (done.drafted === 0) return `${buyers(done.matched)} asked about ${done.address}, and all already have a draft — nothing new drafted.`;
1099 return `${buyers(done.drafted)} asked about ${done.address} — ${done.drafted === 1 ? "the draft is" : "drafts are"} on the desk${had}.`;
1100 };
1101
10541102 /** Take the showing off a lead; the follow-ups held for it return to their usual place. */
10551103 export const cancelShowing = (
10561104 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; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go; `unsent` takes back a send within its minute; `referred` is a lead added with the person who sent them (the detail holds `{"referrer":"name"}`); `thanked` approves the thank-you to a referrer, `thanks_held` approves it as a text held for quiet hours, `thanks_skipped` sets it aside. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred", "unsent", "referred", "thanked", "thanks_held", "thanks_skipped"] as const;
37 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go; `unsent` takes back a send within its minute; `referred` is a lead added with the person who sent them (the detail holds `{"referrer":"name"}`); `thanked` approves the thank-you to a referrer, `thanks_held` approves it as a text held for quiet hours, `thanks_skipped` sets it aside; `price_change` is a listing's new price drafting a note to each lead who asked about it (the detail holds `{"address","price","drafted"}`). */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred", "unsent", "referred", "thanked", "thanks_held", "thanks_skipped", "price_change"] 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 +7
@@ -34,6 +34,7 @@ import {
3434 setNote,
3535 setState,
3636 setStarred,
37 changePrice,
3738 sendThanks,
3839 skipThanksFor,
3940 } from "./actions.ts";
@@ -194,6 +195,10 @@ const doors: Record<
194195 // POST /leads/:id/star, the MCP tool star_lead).
195196 const starred = setStarred(db, who, { id: replied, starred: true }).ok;
196197 const starredViaTool = (tools.find((t) => t.name === "star_lead")!.run(db, who, { id: replied, starred: false }) as { ok: boolean }).ok;
198 // And so is a listing's price change (POST /leads/price-change, the MCP tool
199 // change_price, `$` in the terminal): lead update, for no row at all.
200 const priced = changePrice(db, who, { address: "12 Oak St", price: 700000 }).ok;
201 const pricedViaTool = (tools.find((t) => t.name === "change_price")!.run(db, who, { address: "12 Oak St", price: 690000 }) as { ok: boolean }).ok;
197202 // And so is thanking a lead's referrer, or setting the thank-you aside
198203 // (POST /leads/:id/thanks and /thanks/skip, the MCP tools send_thanks and
199204 // skip_thanks, `r` and `R` in the terminal): lead update.
@@ -206,6 +211,8 @@ const doors: Record<
206211 expect(thankedViaTool).toBe(changed);
207212 expect(thanksSkipped).toBe(changed);
208213 expect(skippedViaTool).toBe(changed);
214 expect(priced).toBe(changed);
215 expect(pricedViaTool).toBe(changed);
209216 expect(starred).toBe(changed);
210217 expect(starredViaTool).toBe(changed);
211218 expect(skipped).toBe(changed);
src/db.ts +12
@@ -294,6 +294,18 @@ export const migrations: string[] = [
294294 sent_at TEXT,
295295 sent_by TEXT
296296 )`,
297 // A listing's price change, one row per lead it drafted a note for (the note is the message numbered `day`). The unique
298 // (lead, street, price) is what keeps the same change entered twice from drafting twice.
299 `CREATE TABLE IF NOT EXISTS price_change (
300 lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE,
301 day INTEGER NOT NULL,
302 street TEXT NOT NULL,
303 address TEXT NOT NULL,
304 price INTEGER NOT NULL CHECK (price > 0),
305 created_at TEXT NOT NULL,
306 PRIMARY KEY (lead_id, day),
307 UNIQUE (lead_id, street, price)
308 )`,
297309 ];
298310
299311 /**
src/drafts.ts +29 −8
@@ -61,6 +61,13 @@ export const BEFORE_SHOWING_DAY = 400;
6161 * `BEFORE_SHOWING_DAY`, so it meets neither.
6262 */
6363 export const CHECK_IN_DAY = 300;
64 /**
65 * A note about a listing's new price is numbered from here (200, 201, …, one
66 * per price change that reached the lead), above every cadence day and below
67 * `CHECK_IN_DAY`. It is a draft from the start, never part of the cadence.
68 */
69 export const PRICE_CHANGE_DAY = 200;
70 export const isPriceChange = (day: number): boolean => day >= PRICE_CHANGE_DAY && day < CHECK_IN_DAY;
6471 export const isCheckIn = (day: number): boolean => day >= CHECK_IN_DAY && day < BEFORE_SHOWING_DAY;
6572 export const isBeforeShowing = (day: number): boolean =>
6673 day >= BEFORE_SHOWING_DAY && day < AFTER_SHOWING_DAY;
@@ -73,17 +80,19 @@ export const dayLabel = (day: number): string =>
7380 ? "First reply"
7481 : isAnswer(day)
7582 ? "Answer to their reply"
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`;
83 : isPriceChange(day)
84 ? "Price change"
85 : isCheckIn(day)
86 ? "Check-in"
87 : isAfterShowing(day)
88 ? "After the showing"
89 : isBeforeShowing(day)
90 ? "Before the showing"
91 : `Day ${day} follow-up`;
8392
8493 /** A message's short name in the follow-up plan: "Day 7", "Before the showing". */
8594 export const planLabel = (day: number): string =>
86 isCheckIn(day) ? "Check-in" : isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`;
95 isPriceChange(day) ? "Price change" : isCheckIn(day) ? "Check-in" : isBeforeShowing(day) ? "Before the showing" : isAfterShowing(day) ? "After the showing" : `Day ${day}`;
8796
8897 export interface Asker {
8998 readonly name: string;
@@ -372,6 +381,18 @@ export function openHouseDraft(lead: Asker, address: string): string {
372381 return `Hi ${first},\n\nIt was great to meet you — ${thanks(address)}\n\nTalk soon,`;
373382 }
374383
384 /**
385 * A listing the lead asked about has dropped its price: the address as the
386 * agent entered it and the new price (`price`, already formatted). Short
387 * enough to text: an address is at most 200 characters.
388 */
389 export function priceChangeDraft(lead: Asker, address: string, price: string): string {
390 const first = firstName(lead.name);
391 const news = `good news on ${address}: the price is now ${price}. If you'd like to see it, or talk it over, just say the word.`;
392 if (channelFor(lead) === "text") return `Hi ${first}, ${news}`;
393 return `Hi ${first},\n\nYou asked about ${address}, so I wanted you to hear it from me first: the price is now ${price}. If you'd like to see it, or talk it over, just say the word.\n\nBest,`;
394 }
395
375396 /**
376397 * The morning a lead put away comes back: they said to get in touch around
377398 * now. Short enough to text; it says nothing of the agent's private note.
src/finished.ts +3 −3
@@ -5,7 +5,7 @@
55 * holds for any cadence the agent chose.
66 */
77
8 import { CHECK_IN_DAY } from "./drafts.ts";
8 import { PRICE_CHANGE_DAY } from "./drafts.ts";
99 import type { Lead } from "./leads.ts";
1010
1111 /** What the desk says of such a lead, in the agent's words. */
@@ -18,7 +18,7 @@ export const FINISHED_ACTION = "Mark lost — never answered";
1818 * True when the lead is still new or contacted, was replied to, is not put
1919 * away, has no showing, has never written back or been called, and every
2020 * message it has is sent or skipped with at least one follow-up among them.
21 * A check-in, a showing's note or an answer to a reply is not a follow-up
21 * A price-change note, a check-in, a showing's note or an answer to a reply is not a follow-up
2222 * on the cadence, so a lead with one is never flagged.
2323 */
2424 export function followUpsFinished(
@@ -30,6 +30,6 @@ export function followUpsFinished(
3030 if (lead.state !== "new" && lead.state !== "contacted") return false;
3131 if (lead.replied_at === null || lead.back_on !== null || heardFrom || showing) return false;
3232 if (!messages.every((m) => m.status === "sent" || m.status === "skipped")) return false;
33 if (messages.some((m) => m.day >= CHECK_IN_DAY)) return false;
33 if (messages.some((m) => m.day >= PRICE_CHANGE_DAY)) return false;
3434 return messages.some((m) => m.day > 0);
3535 }
src/leads.ts +6 −2
@@ -17,8 +17,10 @@ import {
1717 afterShowingDraft,
1818 BEFORE_SHOWING_DAY,
1919 CHECK_IN_DAY,
20 PRICE_CHANGE_DAY,
2021 checkInDraft,
2122 isCheckIn,
23 isPriceChange,
2224 confirmationDraft,
2325 isBeforeShowing,
2426 ANSWER_DAY,
@@ -33,6 +35,7 @@ import {
3335 type Channel,
3436 type Source,
3537 } from "./drafts.ts";
38 import { priceChangeWords } from "./price-change.ts";
3639 import { answers, type Call, type Outcome } from "./calls.ts";
3740 import { between, GREEN_MS } from "./clock.ts";
3841 import type { Agent } from "./env.ts";
@@ -927,6 +930,7 @@ export function redraftUnsent(db: Database, agent: Agent): void {
927930 /** The words for an unsent touch or showing note: the cadence's, or the note for the lead's showing as it stands. */
928931 const wordsFor = (db: Database, found: Lead, day: number, agent: Agent): string => {
929932 if (isCheckIn(day)) return checkInDraft(found);
933 if (isPriceChange(day)) return priceChangeWords(db, found, day);
930934 if (!isAfterShowing(day) && !isBeforeShowing(day)) return draft(found, day, agent);
931935 const showing = showingOf(db, found.id);
932936 if (isAfterShowing(day)) return afterShowingDraft(found, showing?.address ?? "");
@@ -1063,7 +1067,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
10631067 const channel = channelFor(found);
10641068 const skipped = db
10651069 .query<{ id: number; day: number; due_at: string }, [number, number, number]>(
1066 `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)`,
1070 `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 >= ${PRICE_CHANGE_DAY} AND day < ${AFTER_SHOWING_DAY}) AND NOT (day = 0 AND ?3 = 1)`,
10671071 )
10681072 .all(found.id, ANSWER_DAY, replied ? 1 : 0);
10691073 for (const m of skipped)
@@ -1336,7 +1340,7 @@ export function bringBack(db: Database, found: Lead, at: string): void {
13361340 `DELETE FROM message WHERE lead_id = ?1 AND day >= ${CHECK_IN_DAY} AND day < ${BEFORE_SHOWING_DAY} AND status IN ${UNSENT_SQL}`,
13371341 ).run(found.id);
13381342 db.query(
1339 `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`,
1343 `UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND day > 0 AND day < ${PRICE_CHANGE_DAY} AND status = 'skipped' AND skipped_by_hand = 0`,
13401344 ).run(found.id);
13411345 respace(db, found.id, at);
13421346 })();
src/mcp.ts +15
@@ -30,6 +30,7 @@ import {
3030 cancelShowing,
3131 setBackOn,
3232 setStarred,
33 changePrice,
3334 restoreFollowUp,
3435 skipFollowUp,
3536 logLeadReply,
@@ -277,6 +278,20 @@ export const tools: readonly Tool[] = [
277278 },
278279 run: (db, who, args) => setStarred(db, who, { id: Number(args.id), starred: args.starred }),
279280 },
281 {
282 name: "change_price",
283 description:
284 "A listing's price dropped: give the street address (like 12 Oak St) and the new price in whole dollars. Every open lead whose inquiry or booked showing names that address gets one drafted note about the new price, waiting on the desk for the agent to approve; lost, qualified and put-away leads get none, and a lead who replied STOP gets an email. Entering the same change twice drafts nothing new. Answers with how many drafts were made, zero included. Nothing is sent.",
285 inputSchema: {
286 type: "object",
287 properties: {
288 address: { type: "string", maxLength: 200 },
289 price: { type: "integer", minimum: 1 },
290 },
291 required: ["address", "price"],
292 },
293 run: (db, who, args) => changePrice(db, who, { address: args.address, price: args.price }),
294 },
280295 {
281296 name: "cancel_showing",
282297 description:
src/pages/desk.ts +16 −1
@@ -7,7 +7,7 @@ import { day, clock, consent, source, starForm, STATE_LABEL } from "./parts.ts";
77 import { deskTitle, layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import { recordLine, sourceLine, trendLine } from "../clock.ts";
10 import { firstName, isAfterShowing, isBeforeShowing, isAnswer, isCheckIn } from "../drafts.ts";
10 import { firstName, isAfterShowing, isBeforeShowing, isAnswer, isCheckIn, isPriceChange } from "../drafts.ts";
1111 import { FINISHED_ACTION, FINISHED_LABEL } from "../finished.ts";
1212 import { dateName } from "../putaway.ts";
1313 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
@@ -37,6 +37,8 @@ export function deskPage(input: {
3737 mayAdd: boolean;
3838 /** Whether a star shows on each row: the same word as `lead update`. */
3939 mayStar: boolean;
40 /** Whether the price-change form shows: the same word as `lead update`. */
41 mayPrice?: boolean | undefined;
4042 mayReset: boolean;
4143 notice?: string | undefined;
4244 /** What a pasted email was read into: the add form opens with it filled in. */
@@ -108,6 +110,7 @@ export function deskPage(input: {
108110 <p class="export"><a href="${escape(exportHref(show, q))}" download>Download leads (CSV)</a></p>
109111 </div>
110112 ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${pasteForm}${signInForm(input.signIns)}${addForm(input.prefill)}` : ""}
113 ${input.mayPrice === true ? priceForm : ""}
111114 ${
112115 input.mayReset
113116 ? `<form class="reset" method="post" action="/sample/reset"><button class="button button-quiet">Restart the sample leads from now</button></form>`
@@ -206,6 +209,8 @@ function status(lead: DeskLead, now: number, zone: string): string {
206209 return `<span class="status" data-ready>Reply drafted — approve and send</span>`;
207210 if (lead.ready !== null && isAnswer(lead.ready.day))
208211 return `<span class="status" data-ready>They wrote back — answer drafted</span>`;
212 if (lead.ready !== null && isPriceChange(lead.ready.day))
213 return `<span class="status" data-ready>Price change — note drafted</span>`;
209214 if (lead.ready !== null && isCheckIn(lead.ready.day))
210215 return `<span class="status" data-ready>Check-in ready — they asked you to come back</span>`;
211216 if (lead.ready !== null)
@@ -239,6 +244,16 @@ const row = (lead: DeskLead, now: number, zone: string, back?: string): string =
239244 ${starForm(lead, back)}`}${closeOut(lead, back !== undefined)}
240245 </li>`;
241246
247 const priceForm = `<details class="card add">
248 <summary>Price change</summary>
249 <form class="stack" method="post" action="/leads/price-change">
250 <label>Address <input class="input" name="address" required maxlength="${MAX_ADDRESS}" autocomplete="off" placeholder="12 Oak St"></label>
251 <label>New price, in dollars <input class="input" name="price" required inputmode="numeric" maxlength="14" autocomplete="off" placeholder="725000"></label>
252 <p class="muted">Every open buyer who asked about this address gets a drafted note on the desk. Nothing is sent until you approve it.</p>
253 <button class="button">Draft the notes</button>
254 </form>
255 </details>`;
256
242257 const pasteForm = `<details class="card add">
243258 <summary>Paste a lead email</summary>
244259 <form class="stack" method="post" action="/leads/parse">
src/price-change.test.ts added +247
@@ -0,0 +1,247 @@
1 /**
2 * A listing's price drops: the agent enters the address and the new price and
3 * each open lead who asked about it gets one draft, sent only when approved.
4 */
5 import { afterAll, expect, test } from "bun:test";
6 import type { Database } from "bun:sqlite";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { addLead, bookShowing, changePrice, optOutTexts, setBackOn, sendReply, setState } from "./actions.ts";
11 import { saveProfile } from "./actions.ts";
12 import { subscribe } from "./live.ts";
13 import { plain, terminal } from "./terminal.ts";
14 import { openDb } from "./db.ts";
15 import { names, normalize, readChange, streetKey } from "./price-change.ts";
16 import { seed } from "./sample.ts";
17 import { serve } from "./server.ts";
18 import { sign } from "./who.ts";
19 import type { Who } from "./who.ts";
20
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const anon: Who = { role: "anon" };
23 const NOW = new Date();
24 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-price-")));
25 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
26 if (!r.ok) throw new Error(r.message);
27 return r.value as T;
28 };
29 let n = 0;
30 const arrive = (db: Database, name: string, message: string, consent = false): number =>
31 value(
32 addLead(db, alice, { name, email: `p${++n}@example.com`, phone: consent ? `(206) 555-09${String(n).padStart(2, "0")}` : "", source: "zillow", message, consent }, NOW),
33 ).id;
34 const drafts = (db: Database, id: number) =>
35 db.query<{ day: number; channel: string; body: string; status: string; signature: string }, [number]>(
36 "SELECT day, channel, body, status, signature FROM message WHERE lead_id = ?1 AND day >= 200 AND day < 300",
37 ).all(id);
38
39 test("matching ignores case, punctuation and street suffix spelling, and nothing looser", () => {
40 expect(streetKey("12 OAK Street, Seattle, WA")).toBe("12 oak st");
41 expect(normalize("12 Oak St.")).toBe("12 oak st");
42 const key = streetKey("12 Oak St");
43 expect(names("Is 12 oak street still available?", key)).toBe(true);
44 expect(names("Tour of 12 Oak St.!", key)).toBe(true);
45 expect(names("What about 112 Oak St?", key)).toBe(false);
46 expect(names("12 Oak Ln please", key)).toBe(false);
47 expect(names("Oak St, number 12", key)).toBe(false);
48 });
49
50 test("bad input is refused with the field named", () => {
51 const bad = (input: object) => {
52 const r = readChange(input);
53 return r.ok ? "ok" : r.message;
54 };
55 expect(bad({ address: "", price: 1 })).toContain("address");
56 expect(bad({ address: "Oak St", price: 1 })).toContain("address");
57 expect(bad({ address: "x".repeat(201), price: 1 })).toContain("200");
58 expect(bad({ address: "12 Oak St", price: "12.5" })).toContain("price");
59 expect(bad({ address: "12 Oak St", price: 12.5 })).toContain("price");
60 expect(bad({ address: "12 Oak St", price: 0 })).toContain("price");
61 expect(bad({ address: "12 Oak St", price: -4 })).toContain("price");
62 expect(bad({ address: "12 Oak St", price: 2_000_000_000 })).toContain("price");
63 expect(bad({ address: "12 Oak St", price: "abc" })).toContain("price");
64 expect(bad({ address: "12 Oak St", price: undefined })).toContain("price");
65 expect(readChange({ address: " 12 Oak St ", price: "$725,000" })).toEqual({ ok: true, value: { address: "12 Oak St", price: 725000 } });
66 const db = fresh();
67 const r = changePrice(db, alice, { address: "12 Oak St", price: "lots" });
68 expect(!r.ok && r.error).toBe("invalid");
69 });
70
71 test("each matching open lead gets one draft naming the address and price, in the agent's name", () => {
72 const db = fresh();
73 const asked = arrive(db, "Ann Asker", "Is 12 Oak St still available?", true);
74 const toured = arrive(db, "Tom Toured", "Do you have anything on the east side?");
75 value(bookShowing(db, alice, { id: toured, when: new Date(NOW.getTime() + 3 * 86_400_000).toISOString(), address: "12 Oak St, Seattle" }));
76 const other = arrive(db, "Olive Other", "Is 112 Oak St still available?");
77 const done = value(changePrice(db, alice, { address: "12 oak street", price: 725000 }));
78 expect(done.drafted).toBe(2);
79 expect(done.leads.toSorted()).toEqual([asked, toured].toSorted());
80 const mine = drafts(db, asked);
81 expect(mine).toHaveLength(1);
82 expect(mine[0]!.status).toBe("draft");
83 expect(mine[0]!.channel).toBe("text");
84 expect(mine[0]!.body).toContain("12 oak street");
85 expect(mine[0]!.body).toContain("$725,000");
86 expect(mine[0]!.signature).toContain("Reply STOP");
87 expect(drafts(db, toured)[0]!.channel).toBe("email");
88 expect(drafts(db, other)).toHaveLength(0);
89 // Nothing was sent.
90 expect(db.query("SELECT count(*) AS n FROM message WHERE status = 'sent'").get()).toEqual({ n: 0 });
91 });
92
93 test("entering the same change twice makes no second draft; a new price does", () => {
94 const db = fresh();
95 const id = arrive(db, "Ann", "Is 12 Oak St open?");
96 expect(value(changePrice(db, alice, { address: "12 Oak St", price: 700000 })).drafted).toBe(1);
97 const again = value(changePrice(db, alice, { address: "12 OAK ST.", price: "$700,000" }));
98 expect(again.drafted).toBe(0);
99 expect(again.matched).toBe(1);
100 expect(drafts(db, id)).toHaveLength(1);
101 expect(value(changePrice(db, alice, { address: "12 Oak St", price: 650000 })).drafted).toBe(1);
102 expect(drafts(db, id).map((d) => d.day)).toEqual([200, 201]);
103 });
104
105 test("lost, qualified, put-away and unreachable leads get no draft; STOP gets an email", () => {
106 const db = fresh();
107 const lost = arrive(db, "Lola Lost", "12 Oak St?");
108 const away = arrive(db, "Pat Away", "12 Oak St?");
109 const stopped = arrive(db, "Stan Stop", "12 Oak St?", true);
110 const open = arrive(db, "Ola Open", "12 Oak St?");
111 value(sendReply(db, alice, { id: away }, NOW));
112 value(setBackOn(db, alice, { id: away, back_on: new Date(NOW.getTime() + 20 * 86_400_000).toISOString().slice(0, 10) }));
113 value(setState(db, alice, { id: lost, state: "lost", reason: "not_ready" }));
114 value(optOutTexts(db, alice, { id: stopped }));
115 const done = value(changePrice(db, alice, { address: "12 Oak St", price: 500000 }));
116 expect(done.leads.toSorted()).toEqual([stopped, open].toSorted());
117 expect(drafts(db, lost)).toHaveLength(0);
118 expect(drafts(db, away)).toHaveLength(0);
119 expect(drafts(db, stopped)[0]!.channel).toBe("email");
120 // Closing a lead sets its unsent price note aside.
121 value(setState(db, alice, { id: open, state: "lost", reason: "not_ready" }));
122 expect(drafts(db, open)[0]!.status).toBe("skipped");
123 value(setState(db, alice, { id: open, state: "open" }));
124 expect(drafts(db, open)[0]!.status).toBe("skipped");
125 });
126
127 test("zero matches is an answer, not an error; anon is refused; the audit says so", () => {
128 const db = fresh();
129 arrive(db, "Ann", "Is 12 Oak St open?");
130 const none = value(changePrice(db, alice, { address: "99 Nowhere Rd", price: 1 }));
131 expect(none.drafted).toBe(0);
132 expect(none.matched).toBe(0);
133 const refused = changePrice(db, anon, { address: "12 Oak St", price: 5 });
134 expect(!refused.ok && refused.error).toBe("signin_required");
135 expect(db.query("SELECT count(*) AS n FROM message WHERE day >= 200 AND day < 300").get()).toEqual({ n: 0 });
136 const rows = db.query<{ act: string; outcome: string; allowed: number }, []>("SELECT act, outcome, allowed FROM audit WHERE act = 'price_change' ORDER BY id").all();
137 expect(rows.map((r) => [r.outcome, r.allowed])).toEqual([["ok", 1], ["signin_required", 0]]);
138 });
139
140 test("the samples have two open leads who asked about the same address", () => {
141 const db = fresh();
142 seed(db, NOW);
143 const done = value(changePrice(db, alice, { address: "418 Juniper Ln", price: 799000 }));
144 expect(done.drafted).toBeGreaterThanOrEqual(2);
145 });
146
147 test("putting a lead away, bringing them back, and changing the cadence leave an unsent price note alone", () => {
148 const db = fresh();
149 const id = arrive(db, "Ann", "Is 12 Oak St open?");
150 value(sendReply(db, alice, { id }, NOW));
151 value(changePrice(db, alice, { address: "12 Oak St", price: 700000 }));
152 const before = drafts(db, id);
153 expect(before).toHaveLength(1);
154 value(setBackOn(db, alice, { id, back_on: new Date(NOW.getTime() + 20 * 86_400_000).toISOString().slice(0, 10) }));
155 expect(drafts(db, id)).toEqual(before);
156 value(setBackOn(db, alice, { id, back_on: null }));
157 expect(drafts(db, id)).toEqual(before);
158 const mine = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
159 value(saveProfile(db, { role: "admin", id: "u0", name: "root" }, { ...mine, cadence: "2, 5" }));
160 const after = drafts(db, id);
161 expect(after).toHaveLength(1);
162 expect(after[0]!.status).toBe("draft");
163 expect(after[0]!.body).toBe(before[0]!.body);
164 });
165
166 test("the terminal changes a price with $, gated like the page, and tells web viewers", () => {
167 const db = fresh();
168 seed(db, NOW);
169 const heard: string[] = [];
170 const stop = subscribe((e) => heard.push(e.type));
171 const t = terminal(db, alice);
172 expect(t.screen(100).map(plain).join("\n")).toContain("$ price change");
173 const type = (text: string) => { for (const ch of text) t.key(ch); };
174 t.key("$");
175 type("418 Juniper Ln");
176 t.key("\r");
177 type("799000");
178 t.key("\r");
179 const screen = t.screen(100).map(plain).join("\n");
180 stop();
181 expect(screen).toMatch(/\d+ buyers? asked about 418 Juniper Ln/);
182 expect(heard).toContain("lead.changed");
183 expect(db.query("SELECT count(*) AS n FROM message WHERE day = 200 AND status = 'draft'").get()).not.toEqual({ n: 0 });
184 // A bad price stays on the screen to correct, and drafts nothing new.
185 t.key("$");
186 type("418 Juniper Ln");
187 t.key("\r");
188 type("cheap");
189 t.key("\r");
190 expect(t.screen(100).map(plain).join("\n")).toContain("price:");
191 // A guest is refused and nothing is written.
192 const guest = terminal(db, anon);
193 expect(guest.screen(100).map(plain).join("\n")).not.toContain("$ price change");
194 const before = db.query("SELECT count(*) AS n FROM message").get();
195 for (const ch of "$12 Oak St\r500000\r") guest.key(ch);
196 expect(db.query("SELECT count(*) AS n FROM message").get()).toEqual(before);
197 });
198
199 // The doors.
200 const KEY = "a-key-only-the-forge-holds";
201 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-price-srv-")), identityKey: KEY, sample: false });
202 const base = `http://${server.hostname}:${server.port}`;
203 afterAll(() => server.stop(true));
204 let grants = 0;
205 const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => {
206 const identity = `price-${++grants}|alice|user|${Date.now() + 60_000}`;
207 return fetch(base + path, {
208 redirect: "manual",
209 ...init,
210 headers: { ...(init.headers as Record<string, string>), ...headers, "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) },
211 });
212 };
213 const json = (method: string, path: string, body: unknown) =>
214 api(path, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
215
216 test("the API, the page form and MCP all reach it; a bad price is a 422; cross-site is refused", async () => {
217 await json("POST", "/leads", { name: "Web Buyer", email: "[email protected]", phone: "", source: "website", message: "Thinking about 8 Elm Ct.", consent: false });
218 const res = await json("POST", "/leads/price-change", { address: "8 Elm Ct", price: 400000 });
219 expect(res.status).toBe(200);
220 expect(((await res.json()) as { drafted: number }).drafted).toBe(1);
221 const bad = await json("POST", "/leads/price-change", { address: "8 Elm Ct", price: "cheap" });
222 expect(bad.status).toBe(422);
223 expect(((await bad.json()) as { message: string }).message).toContain("price");
224
225 const desk = await (await api("/")).text();
226 expect(desk).toContain('action="/leads/price-change"');
227 const post = (fields: Record<string, string>, headers: Record<string, string> = {}) =>
228 api("/leads/price-change", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(fields).toString() }, headers);
229 expect((await post({ address: "8 Elm Ct", price: "1" }, { origin: "https://evil.example", "sec-fetch-site": "cross-site" })).status).toBe(403);
230 const form = await post({ address: "8 Elm Ct", price: "390000" });
231 expect(form.status).toBe(303);
232 const invalid = await post({ address: "8 Elm Ct", price: "-3" });
233 expect(invalid.status).toBe(422);
234 expect(await invalid.text()).toContain("price");
235 const zero = await post({ address: "500 Nowhere Rd", price: "100000" });
236 expect(zero.status).toBe(303);
237
238 const spec = (await (await api("/openapi.json")).json()) as { paths: Record<string, unknown> };
239 expect(spec.paths["/leads/price-change"]).toBeDefined();
240 const call = async (args: unknown) =>
241 (await (await json("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "change_price", arguments: args } })).json()) as { result: { isError?: boolean; content: { text: string }[] } };
242 expect((await call({ address: "8 Elm Ct", price: 380000 })).result.isError).toBeUndefined();
243 expect((await call({ address: "8 Elm Ct", price: "x" })).result.isError).toBe(true);
244
245 const anonymous = await fetch(`${base}/leads/price-change`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ address: "8 Elm Ct", price: 5 }) });
246 expect([401, 403]).toContain(anonymous.status);
247 });
src/price-change.ts added +144
@@ -0,0 +1,144 @@
1 /**
2 * A listing drops its price: the agent enters the address and the new price,
3 * and every open lead who asked about that home (in their inquiry, or by a
4 * showing booked there) gets one drafted note waiting on the desk. Nothing is
5 * sent: each draft is approved like any other. No permission is asked here.
6 *
7 * Matching is exact on normalized street text, never fuzzy: case and
8 * punctuation are ignored and "Street" is "St", but "12 Oak St" is not
9 * "112 Oak St" and not "12 Oak Ln".
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { PRICE_CHANGE_DAY, channelFor, priceChangeDraft, signature, type Asker } from "./drafts.ts";
14 import type { Agent } from "./env.ts";
15 import { MAX_ADDRESS } from "./showings.ts";
16
17 export const MAX_PRICE = 1_000_000_000;
18
19 /** How many price-change notes one lead can hold (the days 200 to 299). */
20 const SLOTS = 100;
21
22 const WORDS: Readonly<Record<string, string>> = {
23 street: "st", avenue: "ave", road: "rd", drive: "dr", lane: "ln", court: "ct",
24 boulevard: "blvd", place: "pl", circle: "cir", terrace: "ter",
25 north: "n", south: "s", east: "e", west: "w",
26 };
27
28 /** Street text with case and punctuation taken out and the usual abbreviations made one: tokens joined by one space. */
29 export const normalize = (text: string): string =>
30 text
31 .toLowerCase()
32 .split(/[^a-z0-9]+/)
33 .filter((t) => t !== "")
34 .map((t) => WORDS[t] ?? t)
35 .join(" ");
36
37 /** The street part of an address: what comes before its first comma, normalized. */
38 export const streetKey = (address: string): string => normalize(address.split(",")[0] ?? "");
39
40 /** Whether `text` names the street `key`, on whole words. */
41 export const names = (text: string, key: string): boolean => ` ${normalize(text)} `.includes(` ${key} `);
42
43 export interface Change {
44 readonly address: string;
45 readonly price: number;
46 }
47
48 /** The address and price as typed, or why not. */
49 export function readChange(input: {
50 address?: unknown;
51 price?: unknown;
52 }): { ok: true; value: Change } | { ok: false; message: string } {
53 const address = typeof input.address === "string" ? input.address.replace(/\s+/g, " ").trim() : "";
54 if (address === "") return { ok: false, message: "address: say which home, like 12 Oak St." };
55 if (address.length > MAX_ADDRESS) return { ok: false, message: `address: at most ${MAX_ADDRESS} characters.` };
56 if (/\p{Cc}/u.test(address)) return { ok: false, message: "address: plain text only." };
57 const key = streetKey(address);
58 if (!/^\d/.test(key) || key.split(" ").length < 2)
59 return { ok: false, message: "address: start with the street number and name, like 12 Oak St." };
60 const raw = input.price;
61 const price =
62 typeof raw === "number"
63 ? raw
64 : typeof raw === "string" && /^\s*\$?\s*(\d{1,3}(,\d{3})+|\d+)\s*$/.test(raw)
65 ? Number(raw.replace(/\D/g, ""))
66 : NaN;
67 if (!Number.isInteger(price) || price < 1 || price > MAX_PRICE)
68 return { ok: false, message: `price: a whole number of dollars from 1 to ${MAX_PRICE.toLocaleString("en-US")}, like 725000.` };
69 return { ok: true, value: { address, price } };
70 }
71
72 export const dollars = (price: number): string => `$${price.toLocaleString("en-US")}`;
73
74 /** What one price change did. */
75 export interface Outcome {
76 readonly address: string;
77 readonly price: number;
78 /** Open leads who asked about the address and can be written to. */
79 readonly matched: number;
80 /** Drafts made now. */
81 readonly drafted: number;
82 /** The lead ids drafted for. */
83 readonly leads: readonly number[];
84 }
85
86 interface Candidate extends Asker {
87 readonly id: number;
88 readonly email: string;
89 readonly showing: string | null;
90 }
91
92 /**
93 * Draft the note for every open lead who asked about `change.address`. A lost
94 * or qualified lead, one put away, and one who cannot be reached get none; a
95 * lead who replied STOP gets an email (their consent is already gone). The
96 * same change twice makes no second draft for a lead.
97 */
98 export function draftPriceChange(db: Database, change: Change, at: string, agent: Agent): Outcome {
99 const key = streetKey(change.address);
100 return db.transaction(() => {
101 const open = db
102 .query<Omit<Candidate, "consent"> & { consent: number }, []>(
103 `SELECT lead.id, lead.name, lead.email, lead.phone, lead.source, lead.message, lead.consent, showing.address AS showing
104 FROM lead LEFT JOIN showing ON showing.lead_id = lead.id
105 WHERE lead.state IN ('new', 'contacted') AND lead.back_on IS NULL ORDER BY lead.id`,
106 )
107 .all();
108 const leads: number[] = [];
109 let matched = 0;
110 for (const row of open) {
111 const lead: Candidate = { ...row, consent: row.consent === 1 };
112 if (!names(lead.message, key) && !(lead.showing !== null && names(lead.showing, key))) continue;
113 const channel = channelFor(lead);
114 if (channel === "email" && lead.email === "") continue;
115 matched++;
116 const used = new Set(
117 db.query<{ day: number }, [number]>("SELECT day FROM message WHERE lead_id = ?1").all(lead.id).map((m) => m.day),
118 );
119 let day = PRICE_CHANGE_DAY;
120 while (used.has(day) && day < PRICE_CHANGE_DAY + SLOTS) day++;
121 if (day >= PRICE_CHANGE_DAY + SLOTS) continue;
122 const made = db
123 .query(
124 "INSERT OR IGNORE INTO price_change (lead_id, day, street, address, price, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
125 )
126 .run(lead.id, day, key, change.address, change.price, at);
127 if (made.changes === 0) continue;
128 db.query(
129 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, 'draft', ?6)",
130 ).run(lead.id, day, channel, priceChangeDraft(lead, change.address, dollars(change.price)), signature(channel, agent), at);
131 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, lead.id);
132 leads.push(lead.id);
133 }
134 return { address: change.address, price: change.price, matched, drafted: leads.length, leads };
135 })();
136 }
137
138 /** The words of the price-change note numbered `day` on a lead, for the lead as they are now; empty when none is on record. */
139 export function priceChangeWords(db: Database, lead: Asker & { readonly id: number }, day: number): string {
140 const row = db
141 .query<{ address: string; price: number }, [number, number]>("SELECT address, price FROM price_change WHERE lead_id = ?1 AND day = ?2")
142 .get(lead.id, day);
143 return row === null ? "" : priceChangeDraft(lead, row.address, dollars(row.price));
144 }
src/routes.ts +41
@@ -47,6 +47,8 @@ import {
4747 cancelShowing,
4848 setBackOn,
4949 setStarred,
50 changePrice,
51 priceChangeWords,
5052 restoreFollowUp,
5153 skipFollowUp,
5254 logLeadReply,
@@ -710,6 +712,7 @@ function desk(
710712 ahead: leads.ok ? showingsAhead(c.db, Date.now()) : undefined,
711713 mayAdd: permit(c.who, "lead", "create") === "yes",
712714 mayStar: permit(c.who, "lead", "update") === "yes",
715 mayPrice: permit(c.who, "lead", "update") === "yes",
713716 mayReset: permit(c.who, "lead", "delete") === "yes",
714717 notice: pasted?.notice ?? refused ?? notice,
715718 prefill: pasted?.found,
@@ -792,6 +795,44 @@ export const routes: readonly Route[] = [
792795 status: 201,
793796 },
794797 },
798 {
799 // A listing's new price: a note is drafted for each open lead who asked about
800 // the address, and nothing is sent. Not under /leads/:id; the action asks the
801 // lead-update cell. The form answers with the count; a bad field is a 422.
802 method: "POST",
803 path: "/leads/price-change",
804 handle: async (c) => {
805 const input = await readFields(c.request);
806 if (input === undefined)
807 return scripted(c.request) ? json({ error: "too_large" }, 413) : text("too large", 413);
808 const changed = changePrice(c.db, c.who, input);
809 if (scripted(c.request)) return answer(changed);
810 if (!changed.ok && changed.error === "invalid") return desk(c, { status: 422, notice: changed.message });
811 return done(changed, "/", changed.ok ? priceChangeWords(changed.value) : undefined);
812 },
813 api: {
814 summary:
815 "A listing's price dropped: every open lead who asked about the address (in their inquiry, or by a showing booked there) gets one drafted note naming it and the new price, waiting on the desk. Nothing is sent, and the same change twice drafts nothing new. Answers with how many drafts were made, zero included; a bad address or price is a 422 naming the field.",
816 body: {
817 type: "object",
818 properties: {
819 address: { type: "string", maxLength: 200, description: "The street address, starting with the number: 12 Oak St." },
820 price: { type: "integer", minimum: 1, maximum: 1_000_000_000, description: "The new price in whole dollars." },
821 },
822 required: ["address", "price"],
823 },
824 answer: {
825 type: "object",
826 properties: {
827 address: { type: "string" },
828 price: { type: "integer" },
829 matched: { type: "integer", description: "Open leads who asked about the address." },
830 drafted: { type: "integer", description: "Drafts made now." },
831 leads: list({ type: "integer" }),
832 },
833 },
834 },
835 },
795836 {
796837 // Reads a pasted notification email into a new lead's fields and writes
797838 // nothing. A script gets JSON; the desk's form gets the desk back with
src/sentences.ts +17
@@ -43,6 +43,19 @@ function awayWords(detail: string | null, esc: (text: string) => string): string
4343 }
4444 }
4545
46 /** A price change's address and new price: " for 12 Oak St: $725,000 (3 drafts)"; "" when the row names none. */
47 function priceWords(detail: string | null, esc: (text: string) => string): string {
48 try {
49 const { address, price, drafted } = JSON.parse(detail ?? "") as { address?: unknown; price?: unknown; drafted?: unknown };
50 if (typeof address !== "string" || address === "") return "";
51 const to = typeof price === "number" ? `: $${price.toLocaleString("en-US")}` : "";
52 const made = typeof drafted === "number" ? ` (${drafted} draft${drafted === 1 ? "" : "s"})` : "";
53 return ` for ${esc(address)}${to}${made}`;
54 } catch {
55 return "";
56 }
57 }
58
4659 /** A referral's sender: " (referred by Sarah Patel)"; "" when the row names none. */
4760 function referrerWords(detail: string | null, esc: (text: string) => string): string {
4861 try {
@@ -115,6 +128,10 @@ export function deed(
115128 tried: `put ${lead} away`,
116129 };
117130 }
131 if (row.act === "price_change") {
132 const priced = priceWords(row.detail, esc);
133 return { done: `changed a listing's price${priced}`, tried: "change a listing's price" };
134 }
118135 if (row.act === "starred" || row.act === "unstarred") {
119136 const star = row.act === "starred";
120137 return {
src/server.test.ts +1
@@ -331,6 +331,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
331331 "book_showing",
332332 "put_lead_away",
333333 "star_lead",
334 "change_price",
334335 "cancel_showing",
335336 "mark_lead",
336337 "edit_lead",
src/terminal.ts +45 −4
@@ -5,12 +5,13 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · $ price change · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1010 * q qualified · x lost · m lost, never answered (follow-ups finished) · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
1212 * wrote type what they wrote · ctrl-t text/email (text only with consent) · ctrl-d record it and draft the answer · esc cancel
1313 * paste paste the notification email · ctrl-d read it, then check each field in the add screen (consent starts as n) · esc cancel
14 * price the address, then the new price · enter next, then draft a note for every open buyer who asked about it (nothing is sent) · esc cancel
1415 * signins the property address, then paste the sheet (one visitor per line) · ctrl-d read it · y add them · esc cancel
1516 * add one field at a time; enter next · esc cancel
1617 * profile the name, brokerage and license every message carries ·
@@ -54,6 +55,8 @@ import {
5455 cancelShowing,
5556 setBackOn,
5657 setStarred,
58 changePrice,
59 priceChangeWords,
5760 logLeadReply,
5861 nextLead,
5962 parseLeadEmail,
@@ -72,7 +75,7 @@ import { between, elapsed, recordLine, sourceLine, tone, trendLine } from "./clo
7275 import { permit } from "./contract.ts";
7376 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
7477 import { said as saidOf } from "./sentences.ts";
75 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, planLabel, type Channel, type Source } from "./drafts.ts";
78 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, isPriceChange, planLabel, type Channel, type Source } from "./drafts.ts";
7679 import { ssh, title, where } from "./env.ts";
7780 import { FINISHED_ACTION, FINISHED_LABEL } from "./finished.ts";
7881 import { LOST_REASONS, REASON_LABEL, lostSaid } from "./lost.ts";
@@ -193,6 +196,7 @@ type View =
193196 | { name: "lost"; id: number }
194197 | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> }
195198 | { name: "paste"; text: string }
199 | { name: "price"; step: "address" | "price"; address: string; price: string }
196200 | { name: "signins"; step: "address" | "text" | "check"; address: string; text: string; preview?: SignInPreview }
197201 | { name: "add"; step: number; typed: string; fields: Record<string, string>; found?: Record<string, string>; note?: string }
198202 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
@@ -312,7 +316,7 @@ export function terminal(
312316 ? "reply drafted"
313317 : isAnswer(l.ready.day)
314318 ? "wrote back · answer drafted"
315 : 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`;
319 : isPriceChange(l.ready.day) ? "price change · note ready" : 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`;
316320 const name = `${l.starred ? "★ " : ""}${clean(l.name)}`.padEnd(18).slice(0, 18);
317321 const showing =
318322 l.showing === null
@@ -325,7 +329,7 @@ export function terminal(
325329 lines.push(
326330 "",
327331 dim(
328 `j/k move · enter open · f view · / find · n log a lead · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
332 `j/k move · enter open · f view · / find · n log a lead${permit(me, "lead", "update") === "yes" ? " · $ price change" : ""} · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
329333 ),
330334 );
331335 return lines;
@@ -589,6 +593,19 @@ export function terminal(
589593 return lines;
590594 }
591595
596 function priceScreen(v: Extract<View, { name: "price" }>): string[] {
597 const lines = [bold("Price change"), ""];
598 if (v.step === "address")
599 return [...lines, `Address: ${clean(v.address)}█`, "", dim("the street address, like 12 Oak St · enter next · esc cancel")];
600 return [
601 ...lines,
602 `Address: ${clean(v.address)}`,
603 `New price: ${clean(v.price)}█`,
604 "",
605 dim("whole dollars · enter drafts a note for every open buyer who asked about it (nothing is sent) · esc cancel"),
606 ];
607 }
608
592609 function signinsScreen(v: Extract<View, { name: "signins" }>): string[] {
593610 const lines = [bold("Open house sign-ins"), ""];
594611 if (v.step === "address")
@@ -745,6 +762,8 @@ export function terminal(
745762 ? detailsScreen(view)
746763 : view.name === "paste"
747764 ? pasteScreen(view)
765 : view.name === "price"
766 ? priceScreen(view)
748767 : view.name === "signins"
749768 ? signinsScreen(view)
750769 : view.name === "add"
@@ -785,6 +804,7 @@ export function terminal(
785804 cursor = 0;
786805 } else if (input === "/") view = { name: "search", typed: q };
787806 else if (input === "v") view = { name: "paste", text: "" };
807 else if (input === "$") view = { name: "price", step: "address", address: "", price: "" };
788808 else if (input === "o") view = { name: "signins", step: "address", address: "", text: "" };
789809 else if (input === "n")
790810 view = { name: "add", step: 0, typed: "", fields: {} };
@@ -1122,6 +1142,27 @@ export function terminal(
11221142 }
11231143 return;
11241144 }
1145 case "price": {
1146 if (input === "\x1b") {
1147 said = "Nothing drafted.";
1148 view = { name: "desk" };
1149 } else if (view.step === "address") {
1150 if (input === "\r") view = { ...view, step: "price" };
1151 else {
1152 const next = typing(view.address, input);
1153 if (next !== undefined) view = { ...view, address: next };
1154 }
1155 } else if (input === "\r") {
1156 const changed = changePrice(db, me, { address: view.address, price: view.price }, new Date(now()));
1157 said = changed.ok ? priceChangeWords(changed.value) : changed.message;
1158 // A bad field keeps what was typed, to correct it.
1159 if (changed.ok || changed.error !== "invalid") view = { name: "desk" };
1160 } else {
1161 const next = typing(view.price, input);
1162 if (next !== undefined) view = { ...view, price: next };
1163 }
1164 return;
1165 }
11251166 case "signins": {
11261167 if (input === "\x1b") {
11271168 said = "Nothing added.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs