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

Each deal carries its sale price and earnest money amount, shown on its page and the client timeline, and the earnest money reminder says how much is due #121

Merged opened this

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

Merged

mason/deal-clock:mason/117-each-deal-carries-its-sale-price-and-ear → main 2 commits fork

  • Merged. mason/117-each-deal-carries-its-sale-price-and-ear was merged into main as b035e47.

Review

Sign in to review this change.
14 files changed +441 −32
README.md +7
@@ -165,6 +165,13 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
165165 place: the clock, the client timeline, the calendar file and unsent drafts
166166 carry the new address, and reminders already sent keep their words. In the
167167 terminal open the deal and press A; over MCP, the `update_address` tool.
168 **Price and earnest money.** A deal may carry a sale price and an earnest
169 money amount, in whole dollars (digits only, up to 100,000,000): set them
170 when you open the deal, or tap Edit price and earnest money on its page.
171 The deal's page and the client timeline show them as `$425,000`, a deal
172 with none shows nothing, and the earnest money reminder says the amount
173 ("Your $12,750 earnest money deposit is due Nov 7"). The sample deals carry
174 figures. Over MCP, the `update_figures` tool; the terminal does not edit them.
168175 Each date also carries a short working note only you see, such as "Appraisal ordered, AMC says Thursday": write it in the date's sheet (Save note), or press T on a date in the terminal; it shows under the date, in This week and on the printed week, and never on a client page or in a message.
169176 15. **Put the samples back.** After the walk-through, an admin taps Sample
170177 deals below the clock, then Restore the sample deals and confirms: the four
contract/openapi.json +73 −6
@@ -393,6 +393,24 @@
393393 "type": "boolean",
394394 "default": false
395395 },
396 "sale_price": {
397 "type": [
398 "integer",
399 "null"
400 ],
401 "minimum": 0,
402 "maximum": 100000000,
403 "description": "Optional, whole dollars."
404 },
405 "earnest_amount": {
406 "type": [
407 "integer",
408 "null"
409 ],
410 "minimum": 0,
411 "maximum": 100000000,
412 "description": "Optional, whole dollars; the earnest money reminder says it."
413 },
396414 "open_anyway": {
397415 "type": "boolean",
398416 "default": false
@@ -657,6 +675,24 @@
657675 ],
658676 "description": "Who marked it."
659677 },
678 "sale_price": {
679 "type": [
680 "integer",
681 "null"
682 ],
683 "minimum": 0,
684 "maximum": 100000000,
685 "description": "The sale price in whole dollars; null while none is set."
686 },
687 "earnest_amount": {
688 "type": [
689 "integer",
690 "null"
691 ],
692 "minimum": 0,
693 "maximum": 100000000,
694 "description": "The earnest money amount in whole dollars; null while none is set."
695 },
660696 "business_days": {
661697 "enum": [
662698 0,
@@ -1000,7 +1036,7 @@
10001036 }
10011037 },
10021038 "patch": {
1003 "summary": "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
1039 "summary": "Correct a deal's address, sale price or earnest money amount; a field left out stays as it is, and a figure sent as null is cleared. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
10041040 "operationId": "patchApiDealsId",
10051041 "parameters": [
10061042 {
@@ -1023,18 +1059,31 @@
10231059 "type": "string",
10241060 "minLength": 3,
10251061 "maxLength": 200
1062 },
1063 "sale_price": {
1064 "type": [
1065 "integer",
1066 "null"
1067 ],
1068 "minimum": 0,
1069 "maximum": 100000000
1070 },
1071 "earnest_amount": {
1072 "type": [
1073 "integer",
1074 "null"
1075 ],
1076 "minimum": 0,
1077 "maximum": 100000000
10261078 }
1027 },
1028 "required": [
1029 "address"
1030 ]
1079 }
10311080 }
10321081 }
10331082 }
10341083 },
10351084 "responses": {
10361085 "200": {
1037 "description": "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
1086 "description": "Correct a deal's address, sale price or earnest money amount; a field left out stays as it is, and a figure sent as null is cleared. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
10381087 "content": {
10391088 "application/json": {
10401089 "schema": {
@@ -2497,6 +2546,24 @@
24972546 ],
24982547 "description": "Who marked it."
24992548 },
2549 "sale_price": {
2550 "type": [
2551 "integer",
2552 "null"
2553 ],
2554 "minimum": 0,
2555 "maximum": 100000000,
2556 "description": "The sale price in whole dollars; null while none is set."
2557 },
2558 "earnest_amount": {
2559 "type": [
2560 "integer",
2561 "null"
2562 ],
2563 "minimum": 0,
2564 "maximum": 100000000,
2565 "description": "The earnest money amount in whole dollars; null while none is set."
2566 },
25002567 "business_days": {
25012568 "enum": [
25022569 0,
docs/TECHNICAL.md +1 −1
@@ -159,7 +159,7 @@ marked sent, as JSON — call it each morning as a signed-in account (a
159159 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. `GET /deals/csv` (and `GET /api/deals.csv`, in openapi) is the spreadsheet, below. The JSON API is
160160 `/api/deals`, described at `/openapi.json`; the same operations are MCP
161161 tools at `POST /mcp` (`list_deals`, `get_deal`, `client_timeline`, `reminders_today`, `this_week`, `list_people`,
162 `open_deal`, `add_date`, `update_address`, `add_party`, `edit_party`, `remove_party`,
162 `open_deal`, `add_date`, `update_address`, `update_figures`, `add_party`, `edit_party`, `remove_party`,
163163 `remove_date` — custom dates only — `remove_deal` — its author or an admin —
164164 `mark_done` — with `done: false` to
165165 reopen a date — `waive_date` — with `waived: false` to un-waive it — `move_date`, `set_reminder_lead`, `amend_deal` (several dates, one reason), `send_reminder`, `restore_samples` — admin only: puts the
src/db.ts +3
@@ -404,6 +404,9 @@ export const migrations: string[] = [
404404 // The words the agent edited before holding a reminder; '' while none were held with it.
405405 `ALTER TABLE reminder_hold ADD COLUMN subject TEXT NOT NULL DEFAULT ''`,
406406 `ALTER TABLE reminder_hold ADD COLUMN body TEXT NOT NULL DEFAULT ''`,
407 // The two figures a deal is about, in whole dollars; null while none is set.
408 `ALTER TABLE deal ADD COLUMN sale_price INTEGER CHECK (sale_price IS NULL OR sale_price BETWEEN 0 AND 100000000)`,
409 `ALTER TABLE deal ADD COLUMN earnest_amount INTEGER CHECK (earnest_amount IS NULL OR earnest_amount BETWEEN 0 AND 100000000)`,
407410 ];
408411
409412 export function openDb(dir = dataDir): Database {
src/deals.ts +35 −17
@@ -28,6 +28,7 @@ import {
2828 import { LENGTH_MAX, standard } from "./env.ts";
2929 import { agentOf } from "./profile.ts";
3030 import { emit } from "./live.ts";
31 import { amount } from "./money.ts";
3132 import { outbox } from "./outbox.ts";
3233 import { conflictLine, conflicts, type Conflict } from "./order.ts";
3334 import { SEND_SPAN, draftOfMoment, statusDrafts, type Agent, type Draft } from "./reminders.ts";
@@ -46,6 +47,9 @@ export interface Deal {
4647 readonly fell_at: string | null;
4748 readonly fell_reason: string | null;
4849 readonly fell_by: string | null;
50 /** The sale price and the earnest money amount, in whole dollars; null while none is set. */
51 readonly sale_price: number | null;
52 readonly earnest_amount: number | null;
4953 }
5054 export interface Party {
5155 readonly id: number;
@@ -453,6 +457,9 @@ export interface NewDeal {
453457 readonly closingDate: unknown;
454458 readonly lengths?: Partial<Record<keyof Lengths, unknown>>;
455459 readonly businessDays?: unknown;
460 /** Optional whole dollars: nothing, or blank, is none set. */
461 readonly salePrice?: unknown;
462 readonly earnestAmount?: unknown;
456463 /** `true` (or a ticked box) opens the deal although its address is already open. */
457464 readonly openAnyway?: unknown;
458465 }
@@ -466,6 +473,8 @@ export interface Plan {
466473 readonly closingDate: string;
467474 readonly lengths: Lengths;
468475 readonly businessDays: boolean;
476 readonly salePrice: number | null;
477 readonly earnestAmount: number | null;
469478 }
470479
471480 export function plan(input: NewDeal): Result<Plan> {
@@ -502,7 +511,11 @@ export function plan(input: NewDeal): Result<Plan> {
502511 input.businessDays === undefined
503512 ? standard.businessDays
504513 : input.businessDays === true || input.businessDays === "on" || input.businessDays === "1";
505 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays });
514 const salePrice = amount(input.salePrice, "sale_price", "sale price");
515 if (!salePrice.ok) return salePrice;
516 const earnestAmount = amount(input.earnestAmount, "earnest_amount", "earnest money amount");
517 if (!earnestAmount.ok) return earnestAmount;
518 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays, salePrice: salePrice.value, earnestAmount: earnestAmount.value });
506519 }
507520
508521 /** An address as two typings of one house agree on it: trimmed, spaces collapsed, lower case, no trailing period. */
@@ -558,10 +571,10 @@ export function insertDeal(
558571 ): Deal {
559572 return db.transaction(() => {
560573 const deal = db
561 .query<Deal, [string, string, number, string, string]>(
562 "INSERT INTO deal (address, contract_date, business_days, author_id, author_name) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING *",
574 .query<Deal, [string, string, number, string, string, number | null, number | null]>(
575 "INSERT INTO deal (address, contract_date, business_days, author_id, author_name, sale_price, earnest_amount) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) RETURNING *",
563576 )
564 .get(p.address, p.contractDate, p.businessDays ? 1 : 0, author.id, author.name)!;
577 .get(p.address, p.contractDate, p.businessDays ? 1 : 0, author.id, author.name, p.salePrice ?? null, p.earnestAmount ?? null)!;
565578 const party = db.query(
566579 "INSERT INTO party (deal_id, role, name) VALUES (?1, ?2, ?3)",
567580 );
@@ -604,26 +617,31 @@ function create(db: Database, who: Who, input: NewDeal): Result<DealView> {
604617 return ok(deal);
605618 }
606619
607 export const updateDeal = (
608 db: Database,
609 who: Who,
610 input: { id: number; address: unknown },
611 ): Result<DealView> =>
620 /** What `updateDeal` changes: each field left out stays as it is; a figure sent blank or null is cleared. */
621 export interface DealEdit {
622 readonly id: number;
623 readonly address?: unknown;
624 readonly salePrice?: unknown;
625 readonly earnestAmount?: unknown;
626 }
627
628 export const updateDeal = (db: Database, who: Who, input: DealEdit): Result<DealView> =>
612629 audited(db, who, "deal", "update", input.id, update(db, who, input));
613630
614 function update(
615 db: Database,
616 who: Who,
617 input: { id: number; address: unknown },
618 ): Result<DealView> {
631 function update(db: Database, who: Who, input: DealEdit): Result<DealView> {
619632 const found = dealFor(db, who, "update", input.id);
620633 if (!found.ok) return found;
621 const address = line(input.address, 3, 200);
634 const bare = input.address === undefined && input.salePrice === undefined && input.earnestAmount === undefined;
635 const address = input.address === undefined && !bare ? found.value.address : line(input.address, 3, 200);
622636 if (address === undefined)
623637 return fail("invalid", "The address is 3 to 200 characters.", "address");
624 db.query("UPDATE deal SET address = ?1 WHERE id = ?2").run(address, found.value.id);
638 const price = input.salePrice === undefined ? ok(found.value.sale_price) : amount(input.salePrice, "sale_price", "sale price");
639 if (!price.ok) return price;
640 const earnest = input.earnestAmount === undefined ? ok(found.value.earnest_amount) : amount(input.earnestAmount, "earnest_amount", "earnest money amount");
641 if (!earnest.ok) return earnest;
642 db.query("UPDATE deal SET address = ?1, sale_price = ?2, earnest_amount = ?3 WHERE id = ?4").run(address, price.value, earnest.value, found.value.id);
625643 emit("deal.changed", { id: found.value.id });
626 return ok(view(db, { ...found.value, address }));
644 return ok(view(db, { ...found.value, address, sale_price: price.value, earnest_amount: earnest.value }));
627645 }
628646
629647 /** What the audit trail calls a deal falling through, and its reopening. */
src/figures.test.ts added +173
@@ -0,0 +1,173 @@
1 /** A deal's sale price and earnest money amount: validated at every door, shown, said in the earnest reminder, audited, carried by the samples. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { openDb } from "./db.ts";
7 import { addParty, createDeal, getDeal, updateDeal, plan } from "./deals.ts";
8 import { amount, dollars } from "./money.ts";
9 import { timelinePage } from "./pages/timeline.ts";
10 import { drafts } from "./reminders.ts";
11 import { restore } from "./sample.ts";
12 import { forgetRationing } from "./security.ts";
13 import { serve } from "./server.ts";
14 import { sign, type Who } from "./who.ts";
15
16 const KEY = "a-key-only-the-forge-holds";
17 const dir = mkdtempSync(join(tmpdir(), "app-figures-"));
18 const db = openDb(dir);
19 const alice: Who = { role: "user", id: "u1", name: "alice" };
20 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
21 const base = `http://${server.hostname}:${server.port}`;
22 afterAll(() => server.stop(true));
23 beforeEach(forgetRationing);
24
25 const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => {
26 const identity = `${id}|${name}|${role}|${Date.now() + 600_000}`;
27 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
28 };
29 const user = as("u1", "alice", "user");
30 const root = as("u0", "root", "admin");
31 const json = (path: string, method: string, body: object) =>
32 fetch(base + path, { method, headers: { ...user, "content-type": "application/json" }, body: JSON.stringify(body) });
33 const base1 = { address: "5 Figure Way", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01", openAnyway: true };
34 const agent = { name: "Dana", brokerage: "Harbor", phone: "555", email: "[email protected]" };
35
36 const open = (extra: object = {}, address = "5 Figure Way") => {
37 const made = createDeal(db, alice, { ...base1, address, ...extra });
38 if (!made.ok) throw new Error(made.message);
39 return made.value;
40 };
41
42 test("dollars are said with commas, and only digits within range are taken", () => {
43 expect(dollars(425000)).toBe("$425,000");
44 expect(dollars(0)).toBe("$0");
45 for (const bad of ["12,5x", "12,500", "-1", "1.5", "abc", "100000001", "1e3", " 5 5", -5, 1.5, true]) {
46 const got = amount(bad, "sale_price", "sale price");
47 expect(got.ok).toBe(false);
48 }
49 for (const [given, want] of [["", null], [undefined, null], [null, null], [" ", null], ["0", 0], ["425000", 425000], [425000, 425000], ["100000000", 100000000]] as const)
50 expect(amount(given, "x", "x")).toEqual({ ok: true, value: want });
51 const refused = plan({ ...base1, salePrice: "12,5x" });
52 expect(refused.ok === false && refused.field).toBe("sale_price");
53 });
54
55 test("a deal opens with figures or none, and none is null, not zero", () => {
56 const none = open({}, "1 None St");
57 expect([none.sale_price, none.earnest_amount]).toEqual([null, null]);
58 const some = open({ salePrice: "425000", earnestAmount: 12750 }, "2 Some St");
59 expect([some.sale_price, some.earnest_amount]).toEqual([425000, 12750]);
60 });
61
62 test("updateDeal changes one figure and leaves the rest; blank clears; a bad one changes nothing", () => {
63 const deal = open({ salePrice: 300000, earnestAmount: 9000 }, "3 Edit St");
64 const price = updateDeal(db, alice, { id: deal.id, salePrice: "310000" });
65 expect(price.ok && [price.value.address, price.value.sale_price, price.value.earnest_amount]).toEqual(["3 Edit St", 310000, 9000]);
66 const bad = updateDeal(db, alice, { id: deal.id, earnestAmount: "-4" });
67 expect(bad.ok === false && bad.error).toBe("invalid");
68 const cleared = updateDeal(db, alice, { id: deal.id, earnestAmount: "" });
69 expect(cleared.ok && cleared.value.earnest_amount).toBeNull();
70 expect(updateDeal(db, alice, { id: deal.id }).ok).toBe(false);
71 });
72
73 const earnestDraft = (deal: ReturnType<typeof open>, moment: string, role = "buyer") => {
74 const got = getDeal(db, alice, { id: deal.id });
75 if (!got.ok) throw new Error(got.message);
76 return drafts(got.value, agent).find((d) => d.label === "Earnest money deposit" && d.moment === moment && d.party_role === role)!;
77 };
78
79 test("the earnest money reminder and its follow-up say the amount when one is set, and read as before when none is", () => {
80 const without = open({}, "4 Words St");
81 expect(earnestDraft(without, "before").body).not.toContain("$");
82 const deal = open({ earnestAmount: 12750 }, "6 Words St");
83 addParty(db, alice, { dealId: deal.id, role: "title", name: "Tina Title", contact: "[email protected]" });
84 const before = earnestDraft(deal, "before");
85 expect(before.body).toContain("Your $12,750 earnest money deposit is due Oct 4.");
86 expect(earnestDraft(deal, "day_of").body).toContain("Your $12,750 earnest money deposit is due Oct 4.");
87 expect(earnestDraft(deal, "late").body).toContain("Your $12,750 earnest money deposit is still outstanding.");
88 expect(earnestDraft(deal, "before", "title").body).toContain("The buyer's $12,750 earnest money deposit is due Oct 4.");
89 // Another date's reminder never names it.
90 const got = getDeal(db, alice, { id: deal.id });
91 if (!got.ok) throw new Error(got.message);
92 expect(drafts(got.value, agent).filter((d) => d.label !== "Earnest money deposit").some((d) => d.body.includes("12,750"))).toBe(false);
93 });
94
95 test("the client timeline shows the figures, escaped, and nothing when there are none", () => {
96 const timeline = (d: ReturnType<typeof open>) => {
97 const got = getDeal(db, alice, { id: d.id });
98 if (!got.ok) throw new Error(got.message);
99 return timelinePage({ who: alice, deal: got.value, on: "2026-10-05" });
100 };
101 const html = timeline(open({ salePrice: 425000, earnestAmount: 12750 }, "7 Show St"));
102 expect(html).toContain("Sale price $425,000 · Earnest money $12,750");
103 const bare = timeline(open({}, "8 Show St"));
104 expect(bare).not.toContain("Sale price");
105 expect(bare).not.toContain("$0");
106 });
107
108 test("the deal's page edits them by form, keeps what was typed when refused, and the change is audited", async () => {
109 const deal = open({}, "9 Page St");
110 const post = (fields: Record<string, string>) => {
111 const form = new FormData();
112 for (const [k, v] of Object.entries(fields)) form.set(k, v);
113 return fetch(`${base}/deals/${deal.id}/figures`, { method: "POST", body: form, headers: user, redirect: "manual" });
114 };
115 const refused = await post({ sale_price: "12,5x", earnest_amount: "9000" });
116 expect(refused.status).toBe(422);
117 const page = await refused.text();
118 expect(page).toContain('value="12,5x"');
119 expect(page).toContain('value="9000"');
120 expect(page).toContain("digits only");
121 expect(getDeal(db, alice, { id: deal.id }).ok).toBe(true);
122 const saved = await post({ sale_price: "425000", earnest_amount: "12750" });
123 expect(saved.status).toBe(303);
124 const shown = await (await fetch(`${base}/deals/${deal.id}`, { headers: user })).text();
125 expect(shown).toContain("<b>$425,000</b>");
126 expect(shown).toContain("<b>$12,750</b>");
127 const crossSite = new FormData();
128 crossSite.set("sale_price", "1");
129 const foreign = await fetch(`${base}/deals/${deal.id}/figures`, { method: "POST", body: crossSite, headers: { ...user, origin: "https://evil.example", "sec-fetch-site": "cross-site" }, redirect: "manual" });
130 expect(foreign.status).toBeGreaterThanOrEqual(400);
131 const activity = await (await fetch(`${base}/activity`, { headers: root })).text();
132 expect(activity).toContain("changed a deal");
133 expect(activity).toContain("9 Page St");
134 });
135
136 test("the API and the MCP tools round-trip both figures and refuse bad ones", async () => {
137 const made = await json("/api/deals", "POST", { address: "10 Api St", buyer: "B", seller: "S", contract_date: "2026-10-01", closing_date: "2026-12-01", sale_price: 500000, earnest_amount: 10000 });
138 expect(made.status).toBe(201);
139 const deal = (await made.json()) as { id: number; sale_price: number; earnest_amount: number };
140 expect([deal.sale_price, deal.earnest_amount]).toEqual([500000, 10000]);
141 const patched = await json(`/api/deals/${deal.id}`, "PATCH", { sale_price: 510000, earnest_amount: null });
142 expect(patched.status).toBe(200);
143 const got = (await (await fetch(`${base}/api/deals/${deal.id}`, { headers: user })).json()) as { address: string; sale_price: number; earnest_amount: number | null };
144 expect([got.address, got.sale_price, got.earnest_amount]).toEqual(["10 Api St", 510000, null]);
145 const bad = await json(`/api/deals/${deal.id}`, "PATCH", { sale_price: "12,5x" });
146 expect(bad.status).toBe(422);
147 expect((await json("/api/deals", "POST", { address: "11 Api St", buyer: "B", seller: "S", contract_date: "2026-10-01", closing_date: "2026-12-01", sale_price: -1 })).status).toBe(422);
148 const call = async (name: string, args: object) =>
149 (await (await json("/mcp", "POST", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } })).json()) as any;
150 const set = await call("update_figures", { deal_id: deal.id, earnest_amount: 11000 });
151 expect(set.result.isError).toBeFalsy();
152 expect(JSON.parse(set.result.content[0].text)).toMatchObject({ sale_price: 510000, earnest_amount: 11000 });
153 expect((await call("update_figures", { deal_id: deal.id, sale_price: 100000001 })).result.isError).toBe(true);
154 const timeline = await call("client_timeline", { id: deal.id });
155 expect(JSON.parse(timeline.result.content[0].text)).toMatchObject({ sale_price: 510000, earnest_amount: 11000 });
156 });
157
158 test("the sample deals carry plausible figures, and restoring them brings them back", () => {
159 const figures = () => {
160 const rows = db.query<{ address: string; sale_price: number | null; earnest_amount: number | null }, [string]>("SELECT address, sale_price, earnest_amount FROM deal WHERE author_id = ?1 ORDER BY id").all("sample");
161 return rows;
162 };
163 expect(figures().length).toBe(4);
164 for (const r of figures()) {
165 expect(r.sale_price).toBeGreaterThan(100_000);
166 expect(r.earnest_amount).toBeGreaterThan(0);
167 expect(r.earnest_amount!).toBeLessThan(r.sale_price! / 10);
168 }
169 const before = figures();
170 db.query("UPDATE deal SET sale_price = NULL, earnest_amount = NULL WHERE author_id = 'sample'").run();
171 restore(db);
172 expect(figures()).toEqual(before);
173 });
src/mcp.ts +20 −1
@@ -39,6 +39,7 @@ import {
3939 releaseReminder,
4040 undoDecline,
4141 } from "./deals.ts";
42 import { AMOUNT_MAX } from "./money.ts";
4243 import { LENGTH_MAX, standard, title } from "./env.ts";
4344 import { dueOn } from "./reminders.ts";
4445 import { FIND_REFUSAL, find, query } from "./find.ts";
@@ -86,7 +87,7 @@ export const tools: readonly Tool[] = [
8687 const got = getDeal(db, who, { id: Number(args.id) });
8788 if (!got.ok) return got;
8889 const dates = timelineRows(got.value, today()).map(({ label, due, role, name, status }) => ({ label, due, owed_by: { role, name: name ?? null }, status }));
89 return { ok: true, value: { address: got.value.address, agent: agentOf(db), dates } };
90 return { ok: true, value: { address: got.value.address, sale_price: got.value.sale_price, earnest_amount: got.value.earnest_amount, agent: agentOf(db), dates } };
9091 },
9192 },
9293 {
@@ -335,6 +336,8 @@ export const tools: readonly Tool[] = [
335336 title: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.title },
336337 walkthrough: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.walkthrough },
337338 business_days: { type: "boolean", default: standard.businessDays },
339 sale_price: { type: "integer", minimum: 0, maximum: AMOUNT_MAX, description: "Optional sale price in whole dollars." },
340 earnest_amount: { type: "integer", minimum: 0, maximum: AMOUNT_MAX, description: "Optional earnest money amount in whole dollars; the earnest money reminder says it." },
338341 open_anyway: { type: "boolean", default: false, description: "Open a second deal although this address already has an open one (otherwise refused as a conflict naming it)." },
339342 },
340343 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
@@ -346,6 +349,8 @@ export const tools: readonly Tool[] = [
346349 seller: a.seller,
347350 contractDate: a.contract_date,
348351 closingDate: a.closing_date,
352 salePrice: a.sale_price,
353 earnestAmount: a.earnest_amount,
349354 lengths: {
350355 earnest: a.earnest,
351356 inspection: a.inspection,
@@ -387,6 +392,20 @@ export const tools: readonly Tool[] = [
387392 },
388393 run: (db, who, a) => updateDeal(db, who, { id: Number(a.deal_id), address: a.address }),
389394 },
395 {
396 name: "update_figures",
397 description: "Set a deal's sale price and earnest money amount, in whole dollars (0 to 100,000,000). A figure left out stays as it is; null clears it. The earnest money reminder drafts say the amount; reminders already sent keep their words.",
398 inputSchema: {
399 type: "object",
400 properties: {
401 deal_id: { type: "integer" },
402 sale_price: { type: ["integer", "null"], minimum: 0, maximum: AMOUNT_MAX },
403 earnest_amount: { type: ["integer", "null"], minimum: 0, maximum: AMOUNT_MAX },
404 },
405 required: ["deal_id"],
406 },
407 run: (db, who, a) => updateDeal(db, who, { id: Number(a.deal_id), salePrice: a.sale_price, earnestAmount: a.earnest_amount }),
408 },
390409 {
391410 name: "add_party",
392411 description: "Add a party (lender, title company, the other agent…) to a deal.",
src/money.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * The two figures a deal carries: its sale price and earnest money amount, in
3 * whole dollars. Pure functions: `amount` checks what a person or a door sent,
4 * `dollars` says it the one way every page, draft and message does.
5 */
6
7 import { fail, ok, type Result } from "./result.ts";
8
9 /** The most either figure may be. */
10 export const AMOUNT_MAX = 100_000_000;
11
12 const COMMAS = new Intl.NumberFormat("en-US");
13
14 /** "$425,000". */
15 export const dollars = (n: number): string => `$${COMMAS.format(n)}`;
16
17 /**
18 * A figure from a form, a JSON body or a prompt: digits only, 0 to
19 * `AMOUNT_MAX`. Nothing (undefined, null, or blank) is "none set": null.
20 */
21 export function amount(value: unknown, field: string, name: string): Result<number | null> {
22 if (value === undefined || value === null) return ok(null);
23 const text = typeof value === "number" ? String(value) : typeof value === "string" ? value.trim() : undefined;
24 if (text === "") return ok(null);
25 const n = text !== undefined && /^[0-9]{1,9}$/.test(text) ? Number(text) : NaN;
26 if (!Number.isInteger(n) || n > AMOUNT_MAX)
27 return fail("invalid", `The ${name} is whole dollars, digits only, 0 to ${COMMAS.format(AMOUNT_MAX)}.`, field);
28 return ok(n);
29 }
src/pages/deal.ts +41
@@ -9,6 +9,7 @@ import { canChange, canRemove, closedOn, fellOn, REASON_MAX, type DealView, type
99 import { agent as defaults, standard } from "../env.ts";
1010 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
12 import { dollars } from "../money.ts";
1213 import { drafts, sentLabel, statusDrafts, type Agent } from "../reminders.ts";
1314 import type { Who } from "../who.ts";
1415 import { amendForm, type AmendState } from "./amend.ts";
@@ -85,6 +86,31 @@ function messages(deal: DealView, may: boolean, agent: Agent, to: string): strin
8586 return `${waiting}<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
8687 }
8788
89 /** What was typed into the price form and why it was refused, to show beside the field. */
90 export interface FiguresProblem {
91 readonly values: { readonly sale_price: string; readonly earnest_amount: string };
92 readonly field: string | undefined;
93 readonly message: string;
94 }
95
96 /** The two optional figure fields, shared by the new-deal form and the deal's own: `value` is what each holds, `problem` what was refused. */
97 function figureFields(value: (name: "sale_price" | "earnest_amount") => string, problem: { field?: string | undefined; message: string } | undefined): string {
98 const field = (name: "sale_price" | "earnest_amount", label: string): string => {
99 const bad = problem?.field === name;
100 return `<label>${label} <span class="muted">(optional, whole dollars)</span><input class="input" name="${name}" inputmode="numeric" maxlength="12" autocomplete="off" placeholder="425000" value="${escape(value(name))}"${bad ? ` aria-invalid="true" aria-describedby="${name}-why"` : ""}>${bad ? `<span class="field-error" id="${name}-why" role="alert">${escape(problem.message)}</span>` : ""}</label>`;
101 };
102 return `<div class="pair">${field("sale_price", "Sale price")}${field("earnest_amount", "Earnest money")}</div>`;
103 }
104
105 /** The figures a deal is about, said in the one way: nothing at all when neither is set. */
106 function figuresLine(deal: DealView): string {
107 const parts = [
108 deal.sale_price === null ? "" : `Sale price <b>${escape(dollars(deal.sale_price))}</b>`,
109 deal.earnest_amount === null ? "" : `Earnest money <b>${escape(dollars(deal.earnest_amount))}</b>`,
110 ].filter((p) => p !== "");
111 return parts.length === 0 ? "" : `<p class="summary" id="figures">${parts.join(" · ")}</p>`;
112 }
113
88114 export function dealPage(input: {
89115 who: Who;
90116 /** How many of today's messages wait for approval, for the header. */
@@ -101,6 +127,8 @@ export function dealPage(input: {
101127 problem?: { readonly value: string; readonly message: string } | undefined;
102128 /** An amendment that was refused: what was typed and what was wrong. */
103129 amend?: AmendState | undefined;
130 /** A sale price or earnest money amount that was refused: what was typed and why. */
131 figures?: FiguresProblem | undefined;
104132 }): string {
105133 const { who, agent, deal, on, notice, problem } = input;
106134 const opened = input.open === undefined ? undefined : deal.sent.find((m) => m.id === input.open);
@@ -115,6 +143,16 @@ export function dealPage(input: {
115143 </form>
116144 </details>`
117145 : "";
146 const figures = input.figures;
147 const editFigures = may
148 ? `<details class="address-edit"${figures === undefined ? "" : " open"}>
149 <summary class="button button-quiet button-small">Edit price and earnest money</summary>
150 <form class="stack" method="post" action="${path}/figures">
151 ${figureFields((n) => figures?.values[n] ?? (deal[n]?.toString() ?? ""), figures)}
152 <button class="button">Save</button>
153 </form>
154 </details>`
155 : "";
118156 const dates = deal.deadlines
119157 .map(
120158 (d) => `<li class="date-row">
@@ -170,7 +208,9 @@ export function dealPage(input: {
170208 <div>
171209 <h1>${escape(deal.address)}</h1>
172210 <p class="summary">${deal.fell_through ? `<b>Fell through on ${escape(spoken(fellOn(deal)))}</b> · ${escape(deal.fell_reason ?? "")}${deal.fell_by ? ` (${escape(deal.fell_by)})` : ""} · ` : ""}${deal.closed ? `<b>Closed on ${escape(spoken(closedOn(deal)))}</b> · ` : ""}Under contract ${escape(spoken(deal.contract_date))} · closes ${escape(spoken(deal.closing))}, ${escape(relative(deal.closing, on))}${deal.business_days ? " · business days" : ""}</p>
211 ${figuresLine(deal)}
173212 ${editAddress}
213 ${editFigures}
174214 </div>
175215 <div class="row"><a class="button button-quiet" href="${path}/timeline">Client timeline</a> <a class="button button-quiet" href="${path}/ics" download>Add to calendar</a></div>
176216 </section>
@@ -283,6 +323,7 @@ export function newDealPage(input: {
283323 <label>Contract date<input class="input" type="date" name="contract_date" required value="${val("contract_date", on)}"${bad("contract_date")}>${why("contract_date")}</label>
284324 <label>Closing date<input class="input" type="date" name="closing_date" required value="${val("closing_date", addDays(on, 35))}"${bad("closing_date")}>${why("closing_date")}</label>
285325 </div>
326 ${figureFields((n) => values[n] ?? "", problem)}
286327 <fieldset>
287328 <legend>Contingency lengths, in days from the contract date</legend>
288329 <div class="lengths">
src/pages/timeline.ts +6 −1
@@ -9,6 +9,7 @@
99 import type { DealView } from "../deals.ts";
1010 import type { Agent } from "../reminders.ts";
1111 import { agent as defaults } from "../env.ts";
12 import { dollars } from "../money.ts";
1213 import { asset, escape } from "../http.ts";
1314 import { timelineRows } from "../timeline.ts";
1415 import type { Who } from "../who.ts";
@@ -29,10 +30,14 @@ export function timelinePage(input: { who: Who; agent?: Agent | undefined; deal:
2930 </li>`,
3031 )
3132 .join("");
33 const figures = [
34 deal.sale_price === null ? "" : `Sale price ${dollars(deal.sale_price)}`,
35 deal.earnest_amount === null ? "" : `Earnest money ${dollars(deal.earnest_amount)}`,
36 ].filter((p) => p !== "");
3237 const body = `<p class="crumb timeline-tools"><a href="/deals/${deal.id}">← Back to the deal</a> · <button type="button" class="button button-small" data-print hidden>Print</button> <span class="muted">or your browser's print (Ctrl/Cmd+P)</span></p>
3338 <section class="timeline">
3439 <h1>${escape(deal.address)}</h1>
35 <p class="summary">Key dates, prepared by ${escape(agent.name)}, ${escape(agent.brokerage)}</p>
40 ${figures.length === 0 ? "" : `<p class="summary" id="figures">${escape(figures.join(" · "))}</p>`}<p class="summary">Key dates, prepared by ${escape(agent.name)}, ${escape(agent.brokerage)}</p>
3641 <p class="summary">${contactLinks(agent)}</p>
3742 <ol class="timeline-list">${rows}</ol>
3843 </section>
src/reminders.ts +10 −3
@@ -8,7 +8,8 @@
88 * sent one, with the words approved; a sent draft reads back those words.
99 */
1010
11 import { addDays, relative, spoken, today, weekday } from "./dates.ts";
11 import { addDays, relative, short, spoken, today, weekday } from "./dates.ts";
12 import { dollars } from "./money.ts";
1213 import { memoizer, print } from "./memo.ts";
1314 import { DEFAULT_LEAD, isOpen, KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
1415 import type { DealView, DeadlineView, Move, Moment, Party } from "./deals.ts";
@@ -139,6 +140,12 @@ function words(
139140 ): { subject: string; body: string } {
140141 const owner = deal.parties.find((p) => p.role === deadline.owes);
141142 const owed = deadline.what === "" ? "" : `${deadline.what}. `;
143 const sum = deadline.kind === "earnest" && deal.earnest_amount !== null ? deal.earnest_amount : null;
144 // "Your $12,750 earnest money deposit is due Nov 7." — the amount, when the deal has one.
145 const deposit = (late: boolean): string =>
146 sum === null
147 ? ""
148 : `${party.role === "buyer" ? "Your" : "The buyer's"} ${dollars(sum)} earnest money deposit ${late ? "is still outstanding" : `is due ${short(deadline.due)}`}. `;
142149 if (moment === "moved" && notice !== undefined && notice.items.length > 1) {
143150 const changes = notice.items
144151 .map(({ deadline: d, move }) => `• ${d.label}: from ${spoken(move.from_due)} to ${spoken(move.to_due)}`)
@@ -158,7 +165,7 @@ function words(
158165 if (moment === "late") {
159166 return {
160167 subject: `${deadline.label} — ${deal.address} — overdue`,
161 body: `Hi ${first(party.name)}, the ${deadline.label.toLowerCase()} for ${deal.address} was due ${spoken(deadline.due)} and has passed without being marked done. ${owed}Could you send me an update today on where it stands and when it will be done?\n\n${signOff(agent)}`,
168 body: `Hi ${first(party.name)}, the ${deadline.label.toLowerCase()} for ${deal.address} was due ${spoken(deadline.due)} and has passed without being marked done. ${deposit(true)}${owed}Could you send me an update today on where it stands and when it will be done?\n\n${signOff(agent)}`,
162169 };
163170 }
164171 const when = moment === "before" ? `in ${days(deadline.lead_days)}, on ${spoken(deadline.due)}` : `today, ${spoken(deadline.due)}`;
@@ -168,7 +175,7 @@ function words(
168175 : `${owner === undefined ? PARTY_LABEL[deadline.owes] : owner.name} (${PARTY_LABEL[deadline.owes].toLowerCase()}) is on it; nothing is needed from you unless you hear otherwise.`;
169176 return {
170177 subject: `${deadline.label} — ${deal.address} — ${moment === "before" ? spoken(deadline.due) : "today"}`,
171 body: `Hi ${first(party.name)}, a reminder that the ${deadline.label.toLowerCase()} for ${deal.address} is ${when}. ${owed}${ask}\n\n${signOff(agent)}`,
178 body: `Hi ${first(party.name)}, a reminder that the ${deadline.label.toLowerCase()} for ${deal.address} is ${when}. ${deposit(false)}${owed}${ask}\n\n${signOff(agent)}`,
172179 };
173180 }
174181
src/routes.ts +29 −3
@@ -39,6 +39,7 @@ import {
3939 import type { Verb } from "./can.ts";
4040 import { events } from "./live.ts";
4141 import { today } from "./dates.ts";
42 import { AMOUNT_MAX } from "./money.ts";
4243 import { progress } from "./progress.ts";
4344 import {
4445 addDeadline,
@@ -212,6 +213,8 @@ const PROGRESS: Schema = {
212213 },
213214 required: ["done", "total", "overdue", "days_to_closing"],
214215 };
216 /** A sale price or earnest money amount: whole dollars, or null for none. */
217 const FIGURE: Schema = { type: ["integer", "null"], minimum: 0, maximum: AMOUNT_MAX };
215218 export const DEAL: Schema = {
216219 type: "object",
217220 properties: {
@@ -224,6 +227,8 @@ export const DEAL: Schema = {
224227 fell_at: { type: ["string", "null"], format: "date-time", description: "When it was marked fell through; null while it stands." },
225228 fell_reason: { type: ["string", "null"], description: "The reason given, 1 to 200 characters." },
226229 fell_by: { type: ["string", "null"], description: "Who marked it." },
230 sale_price: { ...FIGURE, description: "The sale price in whole dollars; null while none is set." },
231 earnest_amount: { ...FIGURE, description: "The earnest money amount in whole dollars; null while none is set." },
227232 business_days: { enum: [0, 1] },
228233 author_id: { type: "string" },
229234 author_name: { type: "string" },
@@ -341,6 +346,8 @@ const NEW_DEAL: Schema = {
341346 title: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.title },
342347 walkthrough: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.walkthrough },
343348 business_days: { type: "boolean", default: standard.businessDays },
349 sale_price: { ...FIGURE, description: "Optional, whole dollars." },
350 earnest_amount: { ...FIGURE, description: "Optional, whole dollars; the earnest money reminder says it." },
344351 open_anyway: { type: "boolean", default: false },
345352 },
346353 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
@@ -574,6 +581,8 @@ const newDeal = (f: Record<string, unknown>): NewDeal => ({
574581 walkthrough: f.walkthrough,
575582 },
576583 businessDays: f.business_days,
584 salePrice: f.sale_price,
585 earnestAmount: f.earnest_amount,
577586 openAnyway: f.open_anyway,
578587 });
579588
@@ -917,6 +926,22 @@ export const routes: readonly Route[] = [
917926 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), problem: { value: f.address, message: saved.message } }), STATUS.invalid);
918927 },
919928 },
929 {
930 method: "POST",
931 path: "/deals/:id/figures",
932 handle: async (c) => {
933 const f = await form(c);
934 if (f instanceof Response) return f;
935 const id = Number(c.params.id);
936 const saved = updateDeal(c.db, c.who, { id, salePrice: f.sale_price ?? "", earnestAmount: f.earnest_amount ?? "" });
937 if (saved.ok) return back("Price and earnest money saved.", `/deals/${id}`);
938 if (saved.error !== "invalid") return back(saved.message, `/deals/${id}`);
939 const found = getDeal(c.db, c.who, { id });
940 if (!found.ok) return back(found.message, `/deals/${id}`);
941 const values = { sale_price: String(f.sale_price ?? ""), earnest_amount: String(f.earnest_amount ?? "") };
942 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), figures: { values, field: saved.field, message: saved.message } }), STATUS.invalid);
943 },
944 },
920945 {
921946 method: "POST",
922947 path: "/deals/:id/amend",
@@ -1278,11 +1303,12 @@ export const routes: readonly Route[] = [
12781303 handle: async (c) => {
12791304 const body = await readJson(c.request);
12801305 if (body === undefined) return json({ error: "too_large" }, 413);
1281 return answer(updateDeal(c.db, c.who, { id: Number(c.params.id), address: fields(body).address }));
1306 const f = fields(body);
1307 return answer(updateDeal(c.db, c.who, { id: Number(c.params.id), address: f.address, salePrice: f.sale_price, earnestAmount: f.earnest_amount }));
12821308 },
12831309 api: {
1284 summary: "Correct a deal's address. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
1285 body: { type: "object", properties: { address: { type: "string", minLength: 3, maxLength: 200 } }, required: ["address"] },
1310 summary: "Correct a deal's address, sale price or earnest money amount; a field left out stays as it is, and a figure sent as null is cleared. Dates move one at a time, with a reason (POST /deadlines/:id/move).",
1311 body: { type: "object", properties: { address: { type: "string", minLength: 3, maxLength: 200 }, sale_price: FIGURE, earnest_amount: FIGURE } },
12861312 answer: DEAL,
12871313 },
12881314 },
src/sample.ts +13
@@ -20,6 +20,9 @@ interface Sample {
2020 /** Days from today. */
2121 readonly contract: number;
2222 readonly closing: number;
23 /** Whole dollars. */
24 readonly price: number;
25 readonly earnest: number;
2326 readonly lengths?: Partial<typeof BRIEF_LENGTHS>;
2427 readonly parties: readonly [PartyRole, string, string][];
2528 readonly done?: readonly string[];
@@ -40,6 +43,8 @@ const SAMPLES: readonly Sample[] = [
4043 seller: "Ruth Lindqvist",
4144 contract: -26,
4245 closing: 4,
46 price: 425_000,
47 earnest: 12_750,
4348 lengths: { financing: 28 },
4449 parties: [
4550 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
@@ -61,6 +66,8 @@ const SAMPLES: readonly Sample[] = [
6166 seller: "Grace & Henry Whitcombe",
6267 contract: -12,
6368 closing: 33,
69 price: 318_500,
70 earnest: 6_000,
6471 parties: [
6572 ["lender", "Owen Brandt, First Keel Bank", "[email protected]"],
6673 ["title", "Bayside Title", "[email protected]"],
@@ -76,6 +83,8 @@ const SAMPLES: readonly Sample[] = [
7683 seller: "Estate of Walter Pike",
7784 contract: -20,
7885 closing: 18,
86 price: 560_000,
87 earnest: 15_000,
7988 parties: [
8089 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
8190 ["title", "Northgate Title & Escrow", "[email protected]"],
@@ -92,6 +101,8 @@ const SAMPLES: readonly Sample[] = [
92101 seller: "Carla Mendes",
93102 contract: -3,
94103 closing: 40,
104 price: 389_900,
105 earnest: 8_000,
95106 lengths: { earnest: 5 },
96107 parties: [
97108 ["lender", "Owen Brandt, First Keel Bank", "[email protected]"],
@@ -231,6 +242,8 @@ function writeSamples(db: Database, on: string): void {
231242 closingDate: addDays(on, s.closing),
232243 lengths: { ...BRIEF_LENGTHS, ...s.lengths },
233244 businessDays: false,
245 salePrice: s.price,
246 earnestAmount: s.earnest,
234247 });
235248 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);
236249 for (const [role, name, contact] of s.parties)
src/server.test.ts +1
@@ -196,6 +196,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
196196 "open_deal",
197197 "add_date",
198198 "update_address",
199 "update_figures",
199200 "add_party",
200201 "edit_party",
201202 "remove_party",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs