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

The clock opens with the agent's book in one line: open deals, dollars under contract, closing this month, and closed this year with its sales volume #134

Merged opened this

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

Merged

mason/deal-clock:mason/130-the-clock-opens-with-the-agent-s-book-in → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/130-the-clock-opens-with-the-agent-s-book-in was merged into main as 7234c8c.

Review

Sign in to review this change.
10 files changed +288 −3
README.md +1 −1
@@ -171,7 +171,7 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
171171 terminal open the deal and press A; over MCP, the `update_address` tool.
172172 **Price and earnest money.** A deal may carry a sale price and an earnest
173173 money amount, in whole dollars (digits only, up to 100,000,000): set them
174 when you open the deal, or tap Edit price and earnest money on its page.
174 when you open the deal, or tap Edit price and earnest money on its page. Under the clock's heading one line adds up your book ("6 open · $2,410,000 under contract · 2 close in November · 3 closed this year, $1,180,000"; deals without a price add no dollars and are noted, deals that fell through count in none), and each Closed line shows its price.
175175 The deal's page and the client timeline show them as `$425,000`, a deal
176176 with none shows nothing, and the earnest money reminder says the amount
177177 ("Your $12,750 earnest money deposit is due Nov 7"). The sample deals carry
contract/openapi.json +59
@@ -548,6 +548,65 @@
548548 }
549549 }
550550 },
551 "/api/book": {
552 "get": {
553 "summary": "The agent's book as numbers: open deals, dollars under contract, open deals closing this month, deals closed this year with their sales volume, and how many counted deals have no price. Deals that fell through count in none.",
554 "operationId": "getApiBook",
555 "responses": {
556 "200": {
557 "description": "The agent's book as numbers: open deals, dollars under contract, open deals closing this month, deals closed this year with their sales volume, and how many counted deals have no price. Deals that fell through count in none.",
558 "content": {
559 "application/json": {
560 "schema": {
561 "type": "object",
562 "description": "The book in whole dollars; deals that fell through count in none of it.",
563 "properties": {
564 "open": {
565 "type": "integer"
566 },
567 "under_contract": {
568 "type": "integer",
569 "description": "Prices of the open deals added; a deal with no price adds nothing."
570 },
571 "closing_this_month": {
572 "type": "integer",
573 "description": "Open deals closing in the current month."
574 },
575 "closed_this_year": {
576 "type": "integer",
577 "description": "Closed deals whose closing date is in the current year."
578 },
579 "closed_volume": {
580 "type": "integer",
581 "description": "Their prices added."
582 },
583 "without_price": {
584 "type": "integer",
585 "description": "Counted deals with no price."
586 }
587 }
588 }
589 }
590 }
591 },
592 "default": {
593 "description": "{ error, message }: why not",
594 "content": {
595 "application/json": {
596 "schema": {
597 "$ref": "#/components/schemas/Error"
598 }
599 }
600 }
601 }
602 },
603 "x-contract": {
604 "resource": "deal",
605 "verb": "list",
606 "least": "user"
607 }
608 }
609 },
551610 "/api/people": {
552611 "get": {
553612 "summary": "Each person on your deals once (parties with the same contact are one), with their roles and every open date they owe across deals, soonest first; people who owe nothing open come last.",
docs/TECHNICAL.md +2
@@ -154,6 +154,8 @@ deal (`b` goes back). Its print rules in `static/app.css` apply to that page onl
154154
155155 `GET /people` (and `GET /api/people`, described in `openapi.json` under the `deal` list cell) groups every party on the deals the viewer may list into people — parties with the same contact, trimmed and case-insensitive, are one, under the newest name — each with the open dates they owe (`src/people.ts`, pure). Dates of a closed deal are not listed. The terminal's `P` view shows the same.
156156
157 `GET /api/book` (the `deal` list cell) gives the totals the clock's book line shows, as numbers: `open`, `under_contract`, `closing_this_month`, `closed_this_year`, `closed_volume`, `without_price` (`src/book.ts`, pure). Fell-through deals count in none; a closed deal counts on its closing date.
158
157159 A deal is **closed** when its Closing date is marked done (derived, no column; `closed` on `GET /api/deals` and `list_deals`). It leaves the clock for the Closed card, sends no reminders (`/tick`, `reminders_today`, the terminal `r` list), and the terminal date list shows its dates only after `h`. Reopening the Closing date reopens the deal.
158160
159161 **One clock per house.** `planFor` (`src/deals.ts`) refuses to open a deal at an address that already has an open one of the same author, comparing after trimming, collapsing spaces, ignoring case and a trailing period (`sameAddress`). A closed deal (see above) does not count, and the sample deals are another author's. The refusal is a `conflict` Result naming the deal (`existing`): the API and MCP answer 409 `{error: "conflict", message, existing_id}`; the New deal form re-renders with a link to that deal, everything typed kept, and an "Open a second deal anyway" checkbox (`open_anyway`); the terminal asks `yes` to go on. Send `openAnyway: true` (API/MCP: `open_anyway`) to open the second deal. The date preview shows the same notice. `insertDeal` is unguarded, so Restore the sample deals is unaffected. No new contract cell.
src/book.closed.test.ts added +62
@@ -0,0 +1,62 @@
1 /** The Closed card shows a deal's price, the book line notes deals without one, and the terminal opens with the same line. */
2 import { afterAll, 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 { bookLine, tally } from "./book.ts";
7 import { spoken, today } from "./dates.ts";
8 import { createDeal, getDeal, listDeals, markDone } from "./deals.ts";
9 import { openDb } from "./db.ts";
10 import { forgetRationing } from "./security.ts";
11 import { serve } from "./server.ts";
12 import { terminal } from "./terminal.ts";
13 import { sign, type Who } from "./who.ts";
14
15 const KEY = "a-key-only-the-forge-holds";
16 const dir = mkdtempSync(join(tmpdir(), "app-bookclosed-"));
17 const alice: Who = { role: "user", id: "u1", name: "alice" };
18 const year = today().slice(0, 4);
19
20 const db = openDb(dir);
21 function closedDeal(address: string, closingDate: string, salePrice: number | undefined): void {
22 const made = createDeal(db, alice, { openAnyway: true, address, buyer: "B", seller: "S", contractDate: `${year}-01-05`, closingDate, ...(salePrice === undefined ? {} : { salePrice }) });
23 if (!made.ok) throw new Error(made.message);
24 const got = getDeal(db, alice, { id: made.value.id });
25 if (!got.ok) throw new Error(got.message);
26 const r = markDone(db, alice, { id: got.value.deadlines.find((d) => d.kind === "closing")!.id, done: true });
27 if (!r.ok) throw new Error(r.message);
28 }
29 closedDeal("1 Priced Court", `${year}-02-02`, 612_000);
30 closedDeal("2 Unpriced Court", `${year}-02-03`, undefined);
31 db.close();
32
33 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
34 afterAll(() => server.stop(true));
35 const identity = `u1|alice|user|${Date.now() + 600_000}`;
36 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
37
38 test("the Closed card shows the price beside the closing day, and nothing for a deal with none", async () => {
39 forgetRationing();
40 const html = await (await fetch(`http://${server.hostname}:${server.port}/`, { headers })).text();
41 const card = html.slice(html.indexOf('id="closed"'));
42 const row = (address: string) => card.split("<li>").find((li) => li.includes(address)) ?? "";
43 expect(row("1 Priced Court")).toContain(`closed ${spoken(`${year}-02-02`)} · $612,000`);
44 expect(row("2 Unpriced Court")).toContain(`closed ${spoken(`${year}-02-03`)}`);
45 expect(row("2 Unpriced Court")).not.toContain("$");
46 // The two closed deals count this year, and the unpriced one is noted in the line.
47 const line = html.match(/<p class="summary muted">([^<]*)<\/p>/)?.[1] ?? "";
48 expect(line).toContain("closed this year, ");
49 expect(line).toMatch(/\(\d+ without a price\)$/);
50 });
51
52 test("the terminal's clock view opens with the same book line", () => {
53 const listed = listDeals(openDb(dir), alice);
54 if (!listed.ok) throw new Error(listed.message);
55 const want = bookLine(tally(listed.value, today()), today());
56 const t = terminal(openDb(dir), alice, { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" } });
57 const screen = t.screen().map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
58 expect(screen).toContain(want);
59 expect(want).toContain("2 closed this year, $612,000 (");
60 const guest = terminal(openDb(dir), { role: "anon" }, { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" } });
61 expect(guest.screen().map((l) => l.replace(/\x1b\[[0-9;]*m/g, "")).some((l) => l.includes("under contract"))).toBe(false);
62 });
src/book.page.test.ts added +30
@@ -0,0 +1,30 @@
1 /** The book's line on the clock, and GET /api/book, with the sample deals. */
2 import { afterAll, 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 { forgetRationing } from "./security.ts";
7 import { serve } from "./server.ts";
8 import { sign } from "./who.ts";
9
10 const KEY = "a-key-only-the-forge-holds";
11 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-bookpage-")), identityKey: KEY });
12 const base = `http://${server.hostname}:${server.port}`;
13 afterAll(() => server.stop(true));
14 const identity = `u1|alice|user|${Date.now() + 600_000}`;
15 const alice = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
16 const get = (path: string, headers: Record<string, string> = alice) => fetch(base + path, { headers });
17
18 test("the clock opens with the book in one line, and GET /api/book says the same as numbers", async () => {
19 forgetRationing();
20 const html = await (await get("/")).text();
21 const line = html.match(/<p class="summary muted">([^<]*)<\/p>/)?.[1] ?? "";
22 expect(line).toMatch(/^\d+ open · \$[\d,]+ under contract · \d+ closes? in \w+ · \d+ closed this year, \$[\d,]+/);
23 const res = await get("/api/book");
24 expect(res.status).toBe(200);
25 const b = (await res.json()) as Record<string, number>;
26 expect(b["under_contract"]).toBeGreaterThan(0);
27 expect(line.startsWith(`${b["open"]} open · $${b["under_contract"]!.toLocaleString("en-US")} under contract`)).toBe(true);
28 expect((await get("/api/book", {})).status).not.toBe(200);
29 expect(JSON.stringify(await (await get("/openapi.json")).json())).toContain("/api/book");
30 });

Only the sample deals are covered. Add the Closed-card price and the without-a-price note, and a terminal test for the same line.

src/book.test.ts added +37
@@ -0,0 +1,37 @@
1 import { expect, test } from "bun:test";
2 import { bookLine, tally } from "./book.ts";
3
4 const deal = (closing: string, sale_price: number | null, o: { closed?: boolean; fell_through?: boolean } = {}) => ({
5 closing,
6 sale_price,
7 closed: o.closed ?? false,
8 fell_through: o.fell_through ?? false,
9 });
10 const ON = "2026-11-08";
11
12 test("an empty book is zeros", () => {
13 const b = tally([], ON);
14 expect(b).toEqual({ open: 0, underContract: 0, closingThisMonth: 0, closedThisYear: 0, closedVolume: 0, withoutPrice: 0 });
15 expect(bookLine(b, ON)).toBe("0 open · $0 under contract · 0 close in November · 0 closed this year, $0");
16 });
17
18 test("a deal with no price counts as a deal and adds no dollars", () => {
19 const b = tally([deal("2026-11-20", 400_000), deal("2026-12-02", null)], ON);
20 expect(b).toMatchObject({ open: 2, underContract: 400_000, closingThisMonth: 1, withoutPrice: 1 });
21 expect(bookLine(b, ON)).toContain("(1 without a price)");
22 });
23
24 test("a deal that fell through counts in none of it", () => {
25 const b = tally([deal("2026-11-20", 400_000, { fell_through: true }), deal("2026-03-01", 300_000, { closed: true, fell_through: true })], ON);
26 expect(b.open + b.closedThisYear + b.underContract + b.closedVolume + b.withoutPrice).toBe(0);
27 });
28
29 test("a deal that closed last year is not closed this year", () => {
30 const b = tally([deal("2025-12-30", 500_000, { closed: true }), deal("2026-02-02", 250_000, { closed: true })], ON);
31 expect(b).toMatchObject({ open: 0, closedThisYear: 1, closedVolume: 250_000 });
32 expect(bookLine(b, ON)).toBe("0 open · $0 under contract · 0 close in November · 1 closed this year, $250,000");
33 });
34
35 test("closings in other months are not this month's", () => {
36 expect(tally([deal("2026-10-31", 1), deal("2026-11-01", 1), deal("2027-11-05", 1)], ON).closingThisMonth).toBe(1);
37 });
src/book.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The agent's book in one line: open deals, dollars under contract, closings
3 * this month, and what closed this year. Plain deals in, plain totals out. A
4 * deal that fell through counts in none of it; a deal counts as closed on its
5 * closing date. Deals with no price count as deals and add no dollars.
6 */
7
8 import { dollars } from "./money.ts";
9
10 export type Book = {
11 /** Deals neither closed nor fallen through. */
12 open: number;
13 /** Their prices added, in whole dollars. */
14 underContract: number;
15 /** Open deals whose closing date is in this month. */
16 closingThisMonth: number;
17 /** Closed deals whose closing date is in this year. */
18 closedThisYear: number;
19 /** Their prices added, in whole dollars. */
20 closedVolume: number;
21 /** Counted deals (open, or closed this year) that have no price. */
22 withoutPrice: number;
23 };
24
25 type Counted = { closing: string; closed: boolean; fell_through: boolean; sale_price: number | null };
26
27 /** Totals over `deals`, as of `on` (YYYY-MM-DD). */
28 export function tally(deals: readonly Counted[], on: string): Book {
29 const totals: Book = { open: 0, underContract: 0, closingThisMonth: 0, closedThisYear: 0, closedVolume: 0, withoutPrice: 0 };
30 for (const deal of deals) {
31 if (deal.fell_through) continue;
32 const counted = deal.closed ? deal.closing.slice(0, 4) === on.slice(0, 4) : true;
33 if (!counted) continue;
34 if (deal.sale_price === null) totals.withoutPrice++;
35 if (deal.closed) {
36 totals.closedThisYear++;
37 totals.closedVolume += deal.sale_price ?? 0;
38 } else {
39 totals.open++;
40 totals.underContract += deal.sale_price ?? 0;
41 if (deal.closing.slice(0, 7) === on.slice(0, 7)) totals.closingThisMonth++;
42 }
43 }
44 return totals;
45 }
46
47 const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
48
49 /** "6 open · $2,410,000 under contract · 2 close in November · 3 closed this year, $1,180,000". */
50 export function bookLine(b: Book, on: string): string {
51 const month = MONTHS[Number(on.slice(5, 7)) - 1] ?? "";
52 const parts = [
53 `${b.open} open`,
54 `${dollars(b.underContract)} under contract`,
55 `${b.closingThisMonth} ${b.closingThisMonth === 1 ? "closes" : "close"} in ${month}`,
56 `${b.closedThisYear} closed this year, ${dollars(b.closedVolume)}`,
57 ];
58 return parts.join(" · ") + (b.withoutPrice > 0 ? ` (${b.withoutPrice} without a price)` : "");
59 }
src/pages/clock.ts +4 −1
@@ -20,6 +20,8 @@ import { find } from "../find.ts";
2020 import { onSide, type SideFilter } from "../side.ts";
2121 import { sideFilterSelect, sideLabel } from "./side.ts";
2222 import { memoizer, print } from "../memo.ts";
23 import { bookLine, tally } from "../book.ts";
24 import { dollars } from "../money.ts";
2325 import { progressLine } from "./progress.ts";
2426
2527 /** The days the clock shows: a week behind today (further, if something open is older), to a few days past the last closing. */
@@ -211,7 +213,7 @@ function render(input: {
211213 : `<section id="closed" class="card" data-live="deal.changed">
212214 <h2>Closed <span class="muted">· ${closed.length + fell.length}</span></h2>
213215 ${who.role === "anon" ? "" : `<p class="small"><a href="/deals/csv?closed=1" download>Download spreadsheet with closed deals</a></p>`}
214 <ul class="closed">${closed.map((deal) => `<li><a href="/deals/${deal.id}">${escape(deal.address)}</a> <span class="muted">closed ${escape(spoken(deal.closing))}</span> ${sideLabel(deal.side)}</li>`).join("")}${fell.map((deal) => `<li><a href="/deals/${deal.id}">${escape(deal.address)}</a> <b>Fell through</b> <span class="muted">${escape(spoken(fellOn(deal)))} · ${escape(deal.fell_reason ?? "")}</span> ${sideLabel(deal.side)}</li>`).join("")}</ul>
216 <ul class="closed">${closed.map((deal) => `<li><a href="/deals/${deal.id}">${escape(deal.address)}</a> <span class="muted">closed ${escape(spoken(deal.closing))}${deal.sale_price === null ? "" : ` · ${dollars(deal.sale_price)}`}</span> ${sideLabel(deal.side)}</li>`).join("")}${fell.map((deal) => `<li><a href="/deals/${deal.id}">${escape(deal.address)}</a> <b>Fell through</b> <span class="muted">${escape(spoken(fellOn(deal)))} · ${escape(deal.fell_reason ?? "")}</span> ${sideLabel(deal.side)}</li>`).join("")}</ul>

Closed-card price is untested. Add a page test asserting closed Nov 2 · $X for a priced closed deal and no dollar sign for an unpriced one.

215217 </section>`;
216218 const restoreCard =
217219 !mayRestore(who).ok
@@ -229,6 +231,7 @@ function render(input: {
229231 <div>
230232 <h1>The clock</h1>
231233 <p class="summary"><span>${escape(spoken(on))}</span> · <span>${deals.length} ${deals.length === 1 ? "deal" : "deals"}</span>${overdue > 0 ? ` · <b class="u-overdue">${overdue} overdue</b>` : ""}${soon > 0 ? ` · <b class="u-soon">${soon} due within 3 days</b>` : ""}</p>
234 ${input.deals.length === 0 ? "" : `<p class="summary muted">${escape(bookLine(tally(input.deals, on), on))}</p>`}
232235 </div>
233236 ${who.role === "anon" ? "" : `<span class="actions"><a class="button button-quiet" href="/deals/ics">Add all to calendar</a> <a class="button button-quiet" href="/deals/csv" download>Download spreadsheet</a> <a class="button" href="/deals/new">New deal</a></span>`}
234237 </section>
src/routes.ts +31
@@ -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 { tally } from "./book.ts";
4243 import { AMOUNT_MAX } from "./money.ts";
4344 import { progress } from "./progress.ts";
4445 import {
@@ -185,6 +186,18 @@ const PARTY: Schema = {
185186 type: "object",
186187 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, email: { type: "string", maxLength: 200 }, phone: { type: "string", maxLength: 30 }, contact: CONTACT },
187188 };
189 const BOOK: Schema = {
190 type: "object",
191 description: "The book in whole dollars; deals that fell through count in none of it.",
192 properties: {
193 open: { type: "integer" },
194 under_contract: { type: "integer", description: "Prices of the open deals added; a deal with no price adds nothing." },
195 closing_this_month: { type: "integer", description: "Open deals closing in the current month." },
196 closed_this_year: { type: "integer", description: "Closed deals whose closing date is in the current year." },
197 closed_volume: { type: "integer", description: "Their prices added." },
198 without_price: { type: "integer", description: "Counted deals with no price." },
199 },
200 };
188201 export const PERSON: Schema = {
189202 type: "object",
190203 properties: {
@@ -1339,6 +1352,24 @@ export const routes: readonly Route[] = [
13391352 cell: { resource: "deal", verb: "list" },
13401353 },
13411354 },
1355 {
1356 method: "GET",
1357 path: "/api/book",
1358 handle: (c) => {
1359 const deals = listDeals(c.db, c.who);
1360 if (!deals.ok) return answer(deals);
1361 const b = tally(deals.value, today());
1362 return answer({
1363 ok: true,
1364 value: { open: b.open, under_contract: b.underContract, closing_this_month: b.closingThisMonth, closed_this_year: b.closedThisYear, closed_volume: b.closedVolume, without_price: b.withoutPrice },
1365 });
1366 },
1367 api: {
1368 summary: "The agent's book as numbers: open deals, dollars under contract, open deals closing this month, deals closed this year with their sales volume, and how many counted deals have no price. Deals that fell through count in none.",
1369 answer: BOOK,
1370 cell: { resource: "deal", verb: "list" },
1371 },
1372 },
13421373 {
13431374 method: "GET",
13441375 path: "/api/people",
src/terminal.ts +3 −1
@@ -20,6 +20,7 @@
2020 */
2121
2222 import type { Database } from "bun:sqlite";
23 import { bookLine, tally } from "./book.ts";
2324 import { closingLine } from "./closing.ts";
2425 import { timelineRows } from "./timeline.ts";
2526 import { isDate, relative, spoken, today, urgencyOf, type Urgency } from "./dates.ts";
@@ -701,7 +702,8 @@ export function terminal(
701702 const rows = dateRows();
702703 const listed = listDeals(db, me);
703704 if (!listed.ok) lines.push(listed.message);
704 else if (rows.length === 0) lines.push(dim("Nothing open. Every date is done."));
705 else lines.push(dim(bookLine(tally(listed.value, day), day)));
706 if (listed.ok && rows.length === 0) lines.push(dim("Nothing open. Every date is done."));
705707 rows.forEach((row, i) => lines.push(dateLine(row, i, true)));
706708 const closed = all.filter((d) => d.closed && !d.fell_through);
707709 if (closed.length > 0)

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs