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

Each deal says which side the agent represents (buyer, seller or both), set when it is opened, shown on the clock, and the clock can be narrowed to one side #127

Merged opened this

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

Merged

mason/deal-clock:mason/118-each-deal-says-which-side-the-agent-repr → main 5 commits fork 2 threads · 2 unresolved

  • Merged. mason/118-each-deal-says-which-side-the-agent-repr was merged into main as 4edae99.

Review

Sign in to review this change.
20 files changed +504 −51
README.md +9
@@ -174,6 +174,15 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
174174 with none shows nothing, and the earnest money reminder says the amount
175175 ("Your $12,750 earnest money deposit is due Nov 7"). The sample deals carry
176176 figures. Over MCP, the `update_figures` tool; the terminal does not edit them.
177 **Which side you are on.** Each deal says whether you are the buyer's agent,
178 the listing agent or both, chosen when you open it (Buyer's agent unless you
179 say otherwise) and changed with Save side on its page. A small label, "Buyer
180 side", "Listing" or "Both sides", sits beside the address on the clock, the
181 deal's page, This week and the Closed list. The **Side** choice beside Find
182 narrows the clock to Buyer or Listing deals (a deal for both sides shows under
183 each) and combines with a search; the Print link keeps it. 9 Orchard Row is a
184 listing in the samples, and Restore the sample deals brings that back. Over MCP,
185 In the terminal, `n` asks the side last (Buyer's agent, Listing agent or Both; enter is Buyer's agent, any other word is refused), the clock, This week and the deal show the label, and Y on a deal changes it. A side that is not buyer, listing or both is refused with 422 on the page, the API and the terminal alike. `list_deals` takes `side` and `set_side` changes it; `GET /api/deals?side=listing` does the same.
177186 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.
178187 15. **Put the samples back.** After the walk-through, an admin taps Sample
179188 deals below the clock, then Restore the sample deals and confirms: the four
contract/openapi.json +47 −4
@@ -277,7 +277,7 @@
277277 },
278278 "/api/deals": {
279279 "get": {
280 "summary": "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it.",
280 "summary": "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it; side=buyer or side=listing keeps the deals on that side (a deal for both sides is on each).",
281281 "operationId": "getApiDeals",
282282 "parameters": [
283283 {
@@ -287,11 +287,22 @@
287287 "type": "string",
288288 "maxLength": 100
289289 }
290 },
291 {
292 "name": "side",
293 "in": "query",
294 "schema": {
295 "enum": [
296 "buyer",
297 "listing",
298 "all"
299 ]
300 }
290301 }
291302 ],
292303 "responses": {
293304 "200": {
294 "description": "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it.",
305 "description": "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it; side=buyer or side=listing keeps the deals on that side (a deal for both sides is on each).",
295306 "content": {
296307 "application/json": {
297308 "schema": {
@@ -411,6 +422,15 @@
411422 "maximum": 100000000,
412423 "description": "Optional, whole dollars; the earnest money reminder says it."
413424 },
425 "side": {
426 "enum": [
427 "buyer",
428 "listing",
429 "both"
430 ],
431 "default": "buyer",
432 "description": "Which side the agent represents."
433 },
414434 "open_anyway": {
415435 "type": "boolean",
416436 "default": false
@@ -683,6 +703,14 @@
683703 ],
684704 "description": "Who marked it."
685705 },
706 "side": {
707 "enum": [
708 "buyer",
709 "listing",
710 "both"
711 ],
712 "description": "Which side the agent represents: buyer, listing or both."
713 },
686714 "sale_price": {
687715 "type": [
688716 "integer",
@@ -1061,7 +1089,7 @@
10611089 }
10621090 },
10631091 "patch": {
1064 "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).",
1092 "summary": "Correct a deal's address, sale price, earnest money amount or side (buyer, listing or both); 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).",
10651093 "operationId": "patchApiDealsId",
10661094 "parameters": [
10671095 {
@@ -1100,6 +1128,13 @@
11001128 ],
11011129 "minimum": 0,
11021130 "maximum": 100000000
1131 },
1132 "side": {
1133 "enum": [
1134 "buyer",
1135 "listing",
1136 "both"
1137 ]
11031138 }
11041139 }
11051140 }
@@ -1108,7 +1143,7 @@
11081143 },
11091144 "responses": {
11101145 "200": {
1111 "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).",
1146 "description": "Correct a deal's address, sale price, earnest money amount or side (buyer, listing or both); 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).",
11121147 "content": {
11131148 "application/json": {
11141149 "schema": {
@@ -2597,6 +2632,14 @@
25972632 ],
25982633 "description": "Who marked it."
25992634 },
2635 "side": {
2636 "enum": [
2637 "buyer",
2638 "listing",
2639 "both"
2640 ],
2641 "description": "Which side the agent represents: buyer, listing or both."
2642 },
26002643 "sale_price": {
26012644 "type": [
26022645 "integer",
docs/TECHNICAL.md +5 −1
@@ -165,7 +165,7 @@ marked sent, as JSON — call it each morning as a signed-in account (a
165165 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
166166 `/api/deals`, described at `/openapi.json`; the same operations are MCP
167167 tools at `POST /mcp` (`list_deals`, `get_deal`, `client_timeline`, `reminders_today`, `this_week`, `list_people`,
168 `open_deal`, `add_date`, `update_address`, `update_figures`, `add_party`, `edit_party`, `remove_party`,
168 `open_deal`, `add_date`, `update_address`, `update_figures`, `set_side`, `add_party`, `edit_party`, `remove_party`,
169169 `remove_date` — custom dates only — `remove_deal` — its author or an admin —
170170 `mark_done` — with `done: false` to
171171 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
@@ -334,3 +334,7 @@ The forge sets `PORT`, `FORGE_APP_DATA`, `FORGE_APP_ENV` (`production` or
334334 `FORGE_APP_IDENTITY_KEY` when it starts the app. `forge.json` says how.
335335
336336 `conflicts` on a deal (`GET /api/deals/:id`, the list, MCP `get_deal`, the terminal deal view) lists each open, non-Closing date due on or after the open Closing date: `{deadline_id, label, due, closing}`. It is computed once per assembled deal by `src/order.ts` and is empty for a closed deal and for done dates. A move still succeeds; the form notice names the conflict.
337
338 ### Side
339
340 `deal.side` (`buyer`, `listing` or `both`; migration default `buyer`) says which side the agent represents. `src/side.ts` holds the words, `sideOf` (nothing or blank is `buyer`, anything but the three words is refused with 422 and `field: "side"`) and `onSide` (the narrowing: a `both` deal is on each side). It is an `update` of the deal, audited as one: `PATCH /api/deals/:id` with `side`, `POST /deals/:id/side`, MCP `set_side`. `GET /` and `GET /week` take `?side=buyer|listing|all` beside `?q=`; `GET /api/deals` and `list_deals` take `side` too. `GET /reminders/today` does not narrow by side. No new contract cell.
docs/design/areas/side.md added +8
@@ -0,0 +1,8 @@
1 # Side
2
3 New classes on the clock, the deal's page and the week sheet:
4
5 - `.side` — the small text label naming which side the agent is on ("Buyer side", "Listing", "Both sides"), inline beside an address; it is words, so a screen reader reads it, and it takes no box of its own.
6 - `.side-edit` — the deal's page form that changes the side: a label, one select and a Save side button, wrapping at 360px.
7
8 The clock's Side filter is a select inside the existing `.find` form.
src/db.ts +2
@@ -416,6 +416,8 @@ export const migrations: string[] = [
416416 AND length(trim(contact)) - length(replace(trim(contact), '@', '')) = 1 AND length(trim(contact)) <= 200`,
417417 `UPDATE party SET phone = trim(contact)
418418 WHERE email = '' AND trim(contact) NOT GLOB '*[^0-9 +().-]*' AND trim(contact) GLOB '*[0-9]*' AND length(trim(contact)) <= 30`,
419 // Which side the agent represents: the buyer's, a listing, or both.
420 `ALTER TABLE deal ADD COLUMN side TEXT NOT NULL DEFAULT 'buyer' CHECK (side IN ('buyer', 'listing', 'both'))`,
419421 ];
420422
421423 export function openDb(dir = dataDir): Database {
src/deals.ts +18 −7
@@ -29,6 +29,7 @@ import { LENGTH_MAX, standard, validEmail, validPhone } from "./env.ts";
2929 import { agentOf } from "./profile.ts";
3030 import { emit } from "./live.ts";
3131 import { amount } from "./money.ts";
32 import { SIDE_REFUSAL, sideOf, type Side } from "./side.ts";
3233 import { outboxes } from "./outbox.ts";
3334 import { conflictLine, conflicts, type Conflict } from "./order.ts";
3435 import { SEND_SPAN, draftOfMoment, statusDrafts, type Agent, type Draft } from "./reminders.ts";
@@ -50,6 +51,8 @@ export interface Deal {
5051 /** The sale price and the earnest money amount, in whole dollars; null while none is set. */
5152 readonly sale_price: number | null;
5253 readonly earnest_amount: number | null;
54 /** Which side the agent represents on this deal. */
55 readonly side: Side;
5356 }
5457 export interface Party {
5558 readonly id: number;
@@ -472,6 +475,8 @@ export interface NewDeal {
472475 /** Optional whole dollars: nothing, or blank, is none set. */
473476 readonly salePrice?: unknown;
474477 readonly earnestAmount?: unknown;
478 /** buyer, listing or both; nothing is buyer. */
479 readonly side?: unknown;
475480 /** `true` (or a ticked box) opens the deal although its address is already open. */
476481 readonly openAnyway?: unknown;
477482 }
@@ -487,6 +492,7 @@ export interface Plan {
487492 readonly businessDays: boolean;
488493 readonly salePrice: number | null;
489494 readonly earnestAmount: number | null;
495 readonly side: Side;
490496 }
491497
492498 export function plan(input: NewDeal): Result<Plan> {
@@ -527,7 +533,9 @@ export function plan(input: NewDeal): Result<Plan> {
527533 if (!salePrice.ok) return salePrice;
528534 const earnestAmount = amount(input.earnestAmount, "earnest_amount", "earnest money amount");
529535 if (!earnestAmount.ok) return earnestAmount;
530 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays, salePrice: salePrice.value, earnestAmount: earnestAmount.value });
536 const side = sideOf(input.side);
537 if (side === undefined) return fail("invalid", SIDE_REFUSAL, "side");
538 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays, salePrice: salePrice.value, earnestAmount: earnestAmount.value, side });
531539 }
532540
533541 /** An address as two typings of one house agree on it: trimmed, spaces collapsed, lower case, no trailing period. */
@@ -583,10 +591,10 @@ export function insertDeal(
583591 ): Deal {
584592 return db.transaction(() => {
585593 const deal = db
586 .query<Deal, [string, string, number, string, string, number | null, number | null]>(
587 "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 *",
594 .query<Deal, [string, string, number, string, string, number | null, number | null, string]>(
595 "INSERT INTO deal (address, contract_date, business_days, author_id, author_name, sale_price, earnest_amount, side) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) RETURNING *",
588596 )
589 .get(p.address, p.contractDate, p.businessDays ? 1 : 0, author.id, author.name, p.salePrice ?? null, p.earnestAmount ?? null)!;
597 .get(p.address, p.contractDate, p.businessDays ? 1 : 0, author.id, author.name, p.salePrice ?? null, p.earnestAmount ?? null, p.side ?? "buyer")!;
590598 const party = db.query(
591599 "INSERT INTO party (deal_id, role, name) VALUES (?1, ?2, ?3)",
592600 );
@@ -635,6 +643,7 @@ export interface DealEdit {
635643 readonly address?: unknown;
636644 readonly salePrice?: unknown;
637645 readonly earnestAmount?: unknown;
646 readonly side?: unknown;
638647 }
639648
640649 export const updateDeal = (db: Database, who: Who, input: DealEdit): Result<DealView> =>
@@ -643,7 +652,7 @@ export const updateDeal = (db: Database, who: Who, input: DealEdit): Result<Deal
643652 function update(db: Database, who: Who, input: DealEdit): Result<DealView> {
644653 const found = dealFor(db, who, "update", input.id);
645654 if (!found.ok) return found;
646 const bare = input.address === undefined && input.salePrice === undefined && input.earnestAmount === undefined;
655 const bare = input.address === undefined && input.salePrice === undefined && input.earnestAmount === undefined && input.side === undefined;
647656 const address = input.address === undefined && !bare ? found.value.address : line(input.address, 3, 200);
648657 if (address === undefined)
649658 return fail("invalid", "The address is 3 to 200 characters.", "address");
@@ -651,9 +660,11 @@ function update(db: Database, who: Who, input: DealEdit): Result<DealView> {
651660 if (!price.ok) return price;
652661 const earnest = input.earnestAmount === undefined ? ok(found.value.earnest_amount) : amount(input.earnestAmount, "earnest_amount", "earnest money amount");
653662 if (!earnest.ok) return earnest;
654 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);
663 const side = input.side === undefined ? found.value.side : input.side === "" || input.side === null ? undefined : sideOf(input.side);
664 if (side === undefined) return fail("invalid", SIDE_REFUSAL, "side");
665 db.query("UPDATE deal SET address = ?1, sale_price = ?2, earnest_amount = ?3, side = ?4 WHERE id = ?5").run(address, price.value, earnest.value, side, found.value.id);
655666 emit("deal.changed", { id: found.value.id });
656 return ok(view(db, { ...found.value, address, sale_price: price.value, earnest_amount: earnest.value }));
667 return ok(view(db, { ...found.value, address, sale_price: price.value, earnest_amount: earnest.value, side }));
657668 }
658669
659670 /** What the audit trail calls a deal falling through, and its reopening. */
src/duplicate.test.ts +2 −2
@@ -48,11 +48,11 @@ test("a closed deal does not block: a house can sell again", () => {
4848 test("the terminal says so and opens a second deal only on a yes", () => {
4949 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent: { name: "D", brokerage: "H", phone: "5", email: "[email protected]" } });
5050 const text = () => t.screen().join("\n").replace(/\x1b\[[0-9;]*m/g, "");
51 for (const c of ["n", "1418 Alder Court\r", "Ann\r", "Sam\r", "2026-10-01\r", "2026-11-01\r"]) t.press(c);
51 for (const c of ["n", "1418 Alder Court\r", "Ann\r", "Sam\r", "2026-10-01\r", "2026-11-01\r", "\r"]) t.press(c);
5252 expect(text()).toContain("1418 Alder Court is already open");
5353 t.press("no\r");
5454 expect(text()).toContain(`Kept: deal ${first.value.id}`);
55 for (const c of ["n", "1418 Alder Court\r", "Ann\r", "Sam\r", "2026-10-01\r", "2026-11-01\r", "yes\r"]) t.press(c);
55 for (const c of ["n", "1418 Alder Court\r", "Ann\r", "Sam\r", "2026-10-01\r", "2026-11-01\r", "\r", "yes\r"]) t.press(c);
5656 expect(text()).toContain("Opened 1418 Alder Court");
5757 });
5858
src/mcp.ts +13 −2
@@ -43,6 +43,7 @@ import { AMOUNT_MAX } from "./money.ts";
4343 import { LENGTH_MAX, standard, title } from "./env.ts";
4444 import { dueOn } from "./reminders.ts";
4545 import { FIND_REFUSAL, find, query } from "./find.ts";
46 import { SIDES, SIDE_REFUSAL, onSide, sideFilter } from "./side.ts";
4647 import { fields } from "./http.ts";
4748 import { agentOf, getProfile, setProfile } from "./profile.ts";
4849 import { people } from "./people.ts";
@@ -65,12 +66,14 @@ export const tools: readonly Tool[] = [
6566 {
6667 name: "list_deals",
6768 description: "Every deal with its dates, parties and sent reminders, soonest closing first. With query, only the deals whose address, or a party's name, phone or email, contains it (case-insensitive, up to 100 characters): ask for \"Elm Street\" or a client's name instead of listing every deal.",
68 inputSchema: { type: "object", properties: { query: { type: "string", maxLength: 100 } } },
69 inputSchema: { type: "object", properties: { query: { type: "string", maxLength: 100 }, side: { enum: ["all", "buyer", "listing"], description: "Only the deals on that side; a deal for both sides is on each." } } },
6970 run: (db, who, args) => {
7071 const q = args.query === undefined ? "" : typeof args.query === "string" ? query(args.query) : undefined;
7172 if (q === undefined) return { ok: false, error: "invalid", message: FIND_REFUSAL };
73 const side = args.side === undefined ? "" : typeof args.side === "string" ? sideFilter(args.side) : undefined;
74 if (side === undefined) return { ok: false, error: "invalid", message: SIDE_REFUSAL };
7275 const deals = listDeals(db, who);
73 return deals.ok ? { ok: true, value: find(deals.value, q) } : deals;
76 return deals.ok ? { ok: true, value: onSide(find(deals.value, q), side) } : deals;
7477 },
7578 },
7679 {
@@ -338,6 +341,7 @@ export const tools: readonly Tool[] = [
338341 business_days: { type: "boolean", default: standard.businessDays },
339342 sale_price: { type: "integer", minimum: 0, maximum: AMOUNT_MAX, description: "Optional sale price in whole dollars." },
340343 earnest_amount: { type: "integer", minimum: 0, maximum: AMOUNT_MAX, description: "Optional earnest money amount in whole dollars; the earnest money reminder says it." },
344 side: { enum: [...SIDES], default: "buyer", description: "Which side you represent: buyer, listing or both." },
341345 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)." },
342346 },
343347 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
@@ -351,6 +355,7 @@ export const tools: readonly Tool[] = [
351355 closingDate: a.closing_date,
352356 salePrice: a.sale_price,
353357 earnestAmount: a.earnest_amount,
358 side: a.side,
354359 lengths: {
355360 earnest: a.earnest,
356361 inspection: a.inspection,
@@ -392,6 +397,12 @@ export const tools: readonly Tool[] = [
392397 },
393398 run: (db, who, a) => updateDeal(db, who, { id: Number(a.deal_id), address: a.address }),
394399 },
400 {
401 name: "set_side",
402 description: "Set which side of a deal you represent: buyer, listing or both.",
403 inputSchema: { type: "object", properties: { deal_id: { type: "integer" }, side: { enum: [...SIDES] } }, required: ["deal_id", "side"] },
404 run: (db, who, a) => updateDeal(db, who, { id: Number(a.deal_id), side: a.side ?? "" }),
405 },
395406 {
396407 name: "update_figures",
397408 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.",
src/pages/clock.ts +24 −12
@@ -17,6 +17,8 @@ import { layout } from "./layout.ts";
1717 import { mayRestore } from "../actions.ts";
1818 import { badge, draftLink, opens, owedBy, URGENCY_LABEL } from "./sheet.ts";
1919 import { find } from "../find.ts";
20 import { onSide, type SideFilter } from "../side.ts";
21 import { sideFilterSelect, sideLabel } from "./side.ts";
2022 import { memoizer, print } from "../memo.ts";
2123 import { progressLine } from "./progress.ts";
2224
@@ -66,7 +68,7 @@ function drawLane(deal: DealView, start: string, on: string): string {
6668 })
6769 .join("");
6870 return `<li class="lane">
69 <div class="lane-head"><a href="/deals/${deal.id}">${escape(deal.address)}</a> <small class="muted">${deal.conflicts.length === 0 ? "" : `<b class="u-overdue">${deal.conflicts.length} out of order</b> · `}${progressLine(deal, on)}</small></div>
71 <div class="lane-head"><a href="/deals/${deal.id}">${escape(deal.address)}</a> <small class="muted">${sideLabel(deal.side)} · ${deal.conflicts.length === 0 ? "" : `<b class="u-overdue">${deal.conflicts.length} out of order</b> · `}${progressLine(deal, on)}</small></div>
7072 <div class="track" style="height:calc(${height} * 3rem)">${markers}</div>
7173 </li>`;
7274 }
@@ -87,10 +89,16 @@ export function axis(start: string, days: number, on: string): string {
8789 return out.join("");
8890 }
8991
92 /** The query a link to the week sheet carries to keep the clock's narrowing. */
93 const weekQuery = (q: string, side: SideFilter): string => {
94 const parts = [q === "" ? "" : `q=${encodeURIComponent(q)}`, side === "" ? "" : `side=${side}`].filter((p) => p !== "");
95 return parts.length === 0 ? "" : `?${parts.join("&")}`;
96 };
97
9098 const weekRows = memoizer<string>(3000);
9199
92100 /** Open dates due within the week, under day headings; each row opens its sheet. */
93 export function weekCard(deals: readonly DealView[], on: string, q = ""): string {
101 export function weekCard(deals: readonly DealView[], on: string, q = "", side: SideFilter = ""): string {
94102 const groups = byDay(thisWeek(deals, on), on);
95103 const body =
96104 groups.length === 0
@@ -100,14 +108,14 @@ export function weekCard(deals: readonly DealView[], on: string, q = ""): string
100108 (g) => `<h3 class="week-day">${escape(g.heading)}</h3>
101109 <ul class="week-list">${g.items
102110 .map(({ deal, deadline: d }) =>
103 weekRows(`${on}|${print(deal)}|${d.id}`, () => `<li><a class="week-row" ${opens(deal, d)}><span class="week-what"><b>${escape(d.label)}</b><small class="muted">${escape(deal.address)} · ${owedBy(deal, d)}</small>${d.nonBusinessDay === null ? "" : `<small class="muted">Not a business day · next is ${escape(spoken(d.nonBusinessDay.next))}</small>`}${d.note === "" ? "" : `<small class="muted">${escape(d.note)}</small>`}</span>${badge(d, on)}</a></li>`),
111 weekRows(`${on}|${print(deal)}|${d.id}`, () => `<li><a class="week-row" ${opens(deal, d)}><span class="week-what"><b>${escape(d.label)}</b><small class="muted">${escape(deal.address)} · ${sideLabel(deal.side)} · ${owedBy(deal, d)}</small>${d.nonBusinessDay === null ? "" : `<small class="muted">Not a business day · next is ${escape(spoken(d.nonBusinessDay.next))}</small>`}${d.note === "" ? "" : `<small class="muted">${escape(d.note)}</small>`}</span>${badge(d, on)}</a></li>`),
104112 )
105113 .join("")}</ul>`,
106114 )
107115 .join("");
108116 return `<section id="week" class="card" data-live="deal.changed">
109117 <h2>This week</h2>
110 <p class="small"><a href="/week${q === "" ? "" : `?q=${encodeURIComponent(q)}`}">Print this week</a></p>
118 <p class="small"><a href="/week${weekQuery(q, side)}">Print this week</a></p>
111119 ${body}
112120 </section>`;
113121 }
@@ -139,9 +147,10 @@ export function clock(input: {
139147 notice?: string | undefined;
140148 open?: number | undefined;
141149 q?: string | undefined;
150 side?: SideFilter | undefined;
142151 }): string {
143152 const key = Bun.hash(
144 JSON.stringify([input.who, input.on, input.notice ?? null, input.open ?? null, input.q ?? "", input.agent, input.waiting]) +
153 JSON.stringify([input.who, input.on, input.notice ?? null, input.open ?? null, input.q ?? "", input.side ?? "", input.agent, input.waiting]) +
145154 input.deals.map(print).join(),
146155 );
147156 return pages(`${input.deals.length}:${key}`, () => render(input));
@@ -157,13 +166,15 @@ function render(input: {
157166 notice?: string | undefined;
158167 open?: number | undefined;
159168 q?: string | undefined;
169 side?: SideFilter | undefined;
160170 }): string {
161171 const { who, on, notice } = input;
162172 const agent = input.agent ?? defaults;
163173 const opened =
164174 input.open === undefined ? undefined : input.deals.flatMap((d) => d.sent).find((m) => m.id === input.open);
165175 const q = input.q ?? "";
166 const found = find(input.deals, q);
176 const side = input.side ?? "";
177 const found = onSide(find(input.deals, q), side);
167178 const deals = found.filter((deal) => !deal.closed && !deal.fell_through);
168179 const closed = found
169180 .filter((deal) => deal.closed && !deal.fell_through)
@@ -177,11 +188,11 @@ function render(input: {
177188 const { start, days } = span(deals, on);
178189 const today = deals.map((deal) => reminderRows(deal, on, agent));
179190 const todayCount = today.reduce((n, t) => n + t.count, 0);
180 const none = q !== "" && found.length === 0;
191 const none = (q !== "" || side !== "") && found.length === 0;
181192 const toSend = today.reduce((n, t) => n + t.toSend, 0);
182193 const nothing =
183 q !== ""
184 ? `<p class="empty">No deal matches “${escape(q)}”. <a href="/">Clear</a></p>`
194 q !== "" || side !== ""
195 ? `<p class="empty">No deal matches${q === "" ? " that side" : ` “${escape(q)}”`}. <a href="/">Clear</a></p>`
185196 : `<p class="empty">No deals yet. <a href="/deals/new">Open the first one</a>.</p>`;
186197 const timeline =
187198 deals.length === 0 && closed.length === 0 && fell.length === 0
@@ -200,7 +211,7 @@ function render(input: {
200211 : `<section id="closed" class="card" data-live="deal.changed">
201212 <h2>Closed <span class="muted">· ${closed.length + fell.length}</span></h2>
202213 ${who.role === "anon" ? "" : `<p class="small"><a href="/deals/csv?closed=1" download>Download spreadsheet with closed deals</a></p>`}
203 <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></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></li>`).join("")}</ul>
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>
204215 </section>`;
205216 const restoreCard =
206217 !mayRestore(who).ok
@@ -224,7 +235,8 @@ function render(input: {
224235 <form class="find" method="get" action="/" role="search">
225236 <label for="find-q">Find a deal</label>
226237 <input id="find-q" class="input" type="search" name="q" value="${escape(q)}" maxlength="100" placeholder="Address, client or party" autocomplete="off">
227 <button class="button button-quiet">Find</button>${q === "" ? "" : ` <a href="/">Clear</a>`}
238 ${sideFilterSelect(side)}
239 <button class="button button-quiet">Find</button>${q === "" && side === "" ? "" : ` <a href="/">Clear</a>`}
228240 </form>
229241 <section id="clock" class="card clock" data-live="deal.changed">
230242 ${timeline}
@@ -238,7 +250,7 @@ function render(input: {
238250 </section>
239251 ${closedCard}
240252 ${restoreCard}
241 ${deals.length === 0 ? "" : weekCard(deals, on, q)}
253 ${deals.length === 0 ? "" : weekCard(deals, on, q, side)}
242254 ${none ? "" : `<section id="today" class="card" data-live="deal.changed">
243255 <h2>Reminders for today <span class="muted">· ${toSend === 0 ? "all sent" : `${toSend} to send`}</span></h2>
244256 ${toSend === 0 ? "" : `<p><a class="button" href="/reminders/today${q === "" ? "" : `?q=${encodeURIComponent(q)}`}">Review all</a></p>`}
src/pages/deal.ts +11
@@ -16,6 +16,8 @@ import { amendForm, type AmendState } from "./amend.ts";
1616 import { partyContact } from "./contact.ts";
1717 import { confirmRemove } from "./confirm.ts";
1818 import { layout } from "./layout.ts";
19 import { sideOf } from "../side.ts";
20 import { sideLabel, sideSelect } from "./side.ts";
1921 import { progressLine } from "./progress.ts";
2022 import { badge, conflictLines, nonBusinessLine, noteLine, owesChangedLine, rollForm, draftItem, dueLine, outboxLine, owedBy, releaseForm, sheet, sheetId } from "./sheet.ts";
2123
@@ -180,6 +182,12 @@ export function dealPage(input: {
180182 </form>
181183 </details>`
182184 : "";
185 const editSide = may
186 ? `<form class="side-edit" method="post" action="${path}/side">
187 <label for="deal-side">Side</label> ${sideSelect(deal.side, "deal-side")}
188 <button class="button button-quiet button-small">Save side</button>
189 </form>`
190 : "";
183191 const dates = deal.deadlines
184192 .map(
185193 (d) => `<li class="date-row">
@@ -236,7 +244,9 @@ export function dealPage(input: {
236244 <div>
237245 <h1>${escape(deal.address)}</h1>
238246 <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>
247 <p class="summary">${sideLabel(deal.side)}</p>
239248 ${figuresLine(deal)}
249 ${editSide}
240250 ${editAddress}
241251 ${editFigures}
242252 </div>
@@ -352,6 +362,7 @@ export function newDealPage(input: {
352362 <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>
353363 </div>
354364 ${figureFields((n) => values[n] ?? "", problem)}
365 <label>Which side do you represent?${sideSelect(sideOf(values.side) ?? "buyer", "side")}${why("side")}</label>
355366 <fieldset>
356367 <legend>Contingency lengths, in days from the contract date</legend>
357368 <div class="lengths">
src/pages/side.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * The side a deal is on, as the pages say it: a small text label beside the
3 * address, the choice on the new-deal form and the deal's page, and the
4 * clock's Side filter. The words live in `src/side.ts`.
5 */
6
7 import { escape } from "../http.ts";
8 import { SIDES, SIDE_CHOICE, SIDE_LABEL, type Side, type SideFilter } from "../side.ts";
9
10 /** The label, as text: a screen reader says it where it sits. */
11 export const sideLabel = (side: Side): string => `<span class="side" data-side="${side}">${SIDE_LABEL[side]}</span>`;
12
13 /** The choice of side as a select named `side`. */
14 export const sideSelect = (selected: Side, id = "side"): string =>
15 `<select class="input" id="${id}" name="side">${SIDES.map((s) => `<option value="${s}"${s === selected ? " selected" : ""}>${escape(SIDE_CHOICE[s])}</option>`).join("")}</select>`;
16
17 /** The clock's Side filter: a select that is part of the Find form, so it narrows without script. */
18 export const sideFilterSelect = (side: SideFilter): string =>
19 `<label for="find-side">Side</label>
20 <select id="find-side" class="input" name="side">${(
21 [
22 ["", "All"],
23 ["buyer", "Buyer"],
24 ["listing", "Listing"],
25 ] as const
26 )
27 .map(([v, name]) => `<option value="${v}"${v === side ? " selected" : ""}>${name}</option>`)
28 .join("")}</select>`;
src/pages/week.ts +7 −3
@@ -14,12 +14,16 @@ import { STATUS } from "../timeline.ts";
1414 import type { Who } from "../who.ts";
1515 import { byDay, owner, thisWeek } from "../week.ts";
1616 import { layout } from "./layout.ts";
17 import { sideLabel } from "./side.ts";
18 import type { SideFilter } from "../side.ts";
1719
18 export function weekPage(input: { who: Who; agent?: Agent | undefined; deals: readonly DealView[]; on: string; q?: string }): string {
20 export function weekPage(input: { who: Who; agent?: Agent | undefined; deals: readonly DealView[]; on: string; q?: string; side?: SideFilter }): string {
1921 const { who, deals, on } = input;
2022 const agent = input.agent ?? defaults;
2123 const q = input.q ?? "";
22 const back = q === "" ? "/" : `/?q=${encodeURIComponent(q)}`;
24 const side = input.side ?? "";
25 const kept = [q === "" ? "" : `q=${encodeURIComponent(q)}`, side === "" ? "" : `side=${side}`].filter((p) => p !== "");
26 const back = kept.length === 0 ? "/" : `/?${kept.join("&")}`;
2327 const groups = byDay(thisWeek(deals, on), on);
2428 const days =
2529 groups.length === 0
@@ -32,7 +36,7 @@ export function weekPage(input: { who: Who; agent?: Agent | undefined; deals: re
3236 const { name, role } = owner(deal, d);
3337 const s = STATUS[urgencyOf(d, on)];
3438 return `<li class="timeline-row" data-u="${urgencyOf(d, on)}">
35 <p class="timeline-date">${escape(deal.address)}</p>
39 <p class="timeline-date">${escape(deal.address)} · ${sideLabel(deal.side)}</p>
3640 <p class="timeline-label"><b>${escape(d.label)}</b></p>
3741 <p class="timeline-owner">${escape(role)}${name === undefined ? "" : ` · ${escape(name)}`}</p>
3842 ${d.note === "" ? "" : `<p class="timeline-owner">${escape(d.note)}</p>`}
src/routes.ts +35 −8
@@ -86,6 +86,7 @@ import { profilePage } from "./pages/profile.ts";
8686 import { permit } from "./contract.ts";
8787 import { rpc } from "./mcp.ts";
8888 import { FIND_REFUSAL, find, query } from "./find.ts";
89 import { SIDES, SIDE_REFUSAL, onSide, sideFilter } from "./side.ts";
8990 import { clock } from "./pages/clock.ts";
9091 import { dealSheets } from "./pages/sheet.ts";
9192 import { dealPage, newDealPage } from "./pages/deal.ts";
@@ -230,6 +231,7 @@ export const DEAL: Schema = {
230231 fell_at: { type: ["string", "null"], format: "date-time", description: "When it was marked fell through; null while it stands." },
231232 fell_reason: { type: ["string", "null"], description: "The reason given, 1 to 200 characters." },
232233 fell_by: { type: ["string", "null"], description: "Who marked it." },
234 side: { enum: [...SIDES], description: "Which side the agent represents: buyer, listing or both." },
233235 sale_price: { ...FIGURE, description: "The sale price in whole dollars; null while none is set." },
234236 earnest_amount: { ...FIGURE, description: "The earnest money amount in whole dollars; null while none is set." },
235237 business_days: { enum: [0, 1] },
@@ -356,6 +358,7 @@ const NEW_DEAL: Schema = {
356358 business_days: { type: "boolean", default: standard.businessDays },
357359 sale_price: { ...FIGURE, description: "Optional, whole dollars." },
358360 earnest_amount: { ...FIGURE, description: "Optional, whole dollars; the earnest money reminder says it." },
361 side: { enum: [...SIDES], default: "buyer", description: "Which side the agent represents." },
359362 open_anyway: { type: "boolean", default: false },
360363 },
361364 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
@@ -605,6 +608,7 @@ const newDeal = (f: Record<string, unknown>): NewDeal => ({
605608 businessDays: f.business_days,
606609 salePrice: f.sale_price,
607610 earnestAmount: f.earnest_amount,
611 side: f.side,
608612 openAnyway: f.open_anyway,
609613 });
610614
@@ -645,7 +649,10 @@ export const routes: readonly Route[] = [
645649 400,
646650 clear,
647651 );
648 return html(clock({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deals: deals.value, on: today(), notice, open, q }), 200, clear);
652 const side = sideFilter(c.url.searchParams.get("side"));
653 if (side === undefined)
654 return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/", heading: "The clock", error: "invalid", message: SIDE_REFUSAL }), 422, clear);
655 return html(clock({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deals: deals.value, on: today(), notice, open, q, side }), 200, clear);
649656 },
650657 },
651658 {
@@ -664,7 +671,10 @@ export const routes: readonly Route[] = [
664671 refusedPage({ who: c.who, agent: agentFor(c), path: "/week", heading: "This week", error: "invalid", message: FIND_REFUSAL }),
665672 400,
666673 );
667 return html(weekPage({ who: c.who, agent: agentFor(c), deals: find(deals.value, q), on: today(), q }));
674 const side = sideFilter(c.url.searchParams.get("side"));
675 if (side === undefined)
676 return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/week", heading: "This week", error: "invalid", message: SIDE_REFUSAL }), 422);
677 return html(weekPage({ who: c.who, agent: agentFor(c), deals: onSide(find(deals.value, q), side), on: today(), q, side }));
668678 },
669679 },
670680 {
@@ -949,6 +959,21 @@ export const routes: readonly Route[] = [
949959 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);
950960 },
951961 },
962 {
963 method: "POST",
964 path: "/deals/:id/side",
965 handle: async (c) => {
966 const f = await form(c);
967 if (f instanceof Response) return f;
968 const id = Number(c.params.id);
969 const saved = updateDeal(c.db, c.who, { id, side: f.side ?? "" });
970 if (saved.ok) return back("Side saved.", `/deals/${id}`);
971 if (saved.error !== "invalid") return back(saved.message, `/deals/${id}`);
972 const found = getDeal(c.db, c.who, { id });
973 if (!found.ok) return back(found.message, `/deals/${id}`);
974 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice: saved.message }), STATUS.invalid);
975 },
976 },
952977 {
953978 method: "POST",
954979 path: "/deals/:id/figures",
@@ -1261,13 +1286,15 @@ export const routes: readonly Route[] = [
12611286 handle: (c) => {
12621287 const q = query(c.url.searchParams.get("q"));
12631288 if (q === undefined) return json({ error: "invalid", field: "q", message: FIND_REFUSAL }, 400);
1289 const side = sideFilter(c.url.searchParams.get("side"));
1290 if (side === undefined) return json({ error: "invalid", field: "side", message: SIDE_REFUSAL }, 422);
12641291 const deals = listDeals(c.db, c.who);
1265 return answer(deals.ok ? { ok: true, value: find(deals.value, q) } : deals);
1292 return answer(deals.ok ? { ok: true, value: onSide(find(deals.value, q), side) } : deals);
12661293 },
12671294 api: {
1268 summary: "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it.",
1295 summary: "Every deal with its dates, parties and sent reminders, soonest closing first; q keeps the deals whose address or a party's name or contact contains it; side=buyer or side=listing keeps the deals on that side (a deal for both sides is on each).",
12691296 answer: list(DEAL),
1270 query: { q: { type: "string", maxLength: 100 } },
1297 query: { q: { type: "string", maxLength: 100 }, side: { enum: ["buyer", "listing", "all"] } },
12711298 },
12721299 },
12731300 {
@@ -1331,11 +1358,11 @@ export const routes: readonly Route[] = [
13311358 const body = await readJson(c.request);
13321359 if (body === undefined) return json({ error: "too_large" }, 413);
13331360 const f = fields(body);
1334 return answer(updateDeal(c.db, c.who, { id: Number(c.params.id), address: f.address, salePrice: f.sale_price, earnestAmount: f.earnest_amount }));
1361 return answer(updateDeal(c.db, c.who, { id: Number(c.params.id), address: f.address, salePrice: f.sale_price, earnestAmount: f.earnest_amount, side: f.side }));
13351362 },
13361363 api: {
1337 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).",
1338 body: { type: "object", properties: { address: { type: "string", minLength: 3, maxLength: 200 }, sale_price: FIGURE, earnest_amount: FIGURE } },
1364 summary: "Correct a deal's address, sale price, earnest money amount or side (buyer, listing or both); 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).",
1365 body: { type: "object", properties: { address: { type: "string", minLength: 3, maxLength: 200 }, sale_price: FIGURE, earnest_amount: FIGURE, side: { enum: [...SIDES] } } },
13391366 answer: DEAL,
13401367 },
13411368 },
src/sample.ts +5
@@ -10,6 +10,7 @@ import { addDays, daysBetween, today } from "./dates.ts";
1010 import { type PartyRole } from "./deadlines.ts";
1111 import { BRIEF_LENGTHS, validEmail } from "./env.ts";
1212 import { insertDeal } from "./deals.ts";
13 import type { Side } from "./side.ts";
1314
1415 export const SAMPLE = { id: "sample", name: "Sample data" };
1516
@@ -23,6 +24,8 @@ interface Sample {
2324 /** Whole dollars. */
2425 readonly price: number;
2526 readonly earnest: number;
27 /** Which side the agent is on; buyer unless said. */
28 readonly side?: Side;
2629 readonly lengths?: Partial<typeof BRIEF_LENGTHS>;
2730 /** Role, name, email or phone, and a phone besides when the first is an email. */
2831 readonly parties: readonly (readonly [PartyRole, string, string] | readonly [PartyRole, string, string, string])[];
@@ -80,6 +83,7 @@ const SAMPLES: readonly Sample[] = [
8083 },
8184 {
8285 address: "9 Orchard Row",
86 side: "listing",
8387 buyer: "Leah Brennan",
8488 seller: "Estate of Walter Pike",
8589 contract: -20,
@@ -245,6 +249,7 @@ function writeSamples(db: Database, on: string): void {
245249 businessDays: false,
246250 salePrice: s.price,
247251 earnestAmount: s.earnest,
252 side: s.side ?? "buyer",
248253 });
249254 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);
250255 for (const [role, name, first, second] 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 "set_side",
199200 "update_figures",
200201 "add_party",
201202 "edit_party",
src/side.test.ts added +162
@@ -0,0 +1,162 @@
1 /** Which side the agent represents: refused when unknown at every door, shown as text, narrowing the clock, carried by the samples and the migration. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { Database } from "bun:sqlite";
4 import { mkdtempSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { migrations, openDb } from "./db.ts";
8 import { createDeal, getDeal, listDeals, updateDeal } from "./deals.ts";
9 import { find } from "./find.ts";
10 import { restore } from "./sample.ts";
11 import { forgetRationing } from "./security.ts";
12 import { serve } from "./server.ts";
13 import { onSide, sideFilter, sideOf } from "./side.ts";
14 import { tools } from "./mcp.ts";
15 import { sign, type Who } from "./who.ts";
16
17 const KEY = "a-key-only-the-forge-holds";
18 const dir = mkdtempSync(join(tmpdir(), "app-side-"));
19 const db = openDb(dir);
20 const alice: Who = { role: "user", id: "u1", name: "alice" };
21 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
22 const base = `http://${server.hostname}:${server.port}`;
23 afterAll(() => server.stop(true));
24 beforeEach(forgetRationing);
25
26 const identity = `u1|alice|user|${Date.now() + 600_000}`;
27 const user = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
28 const base1 = { address: "5 Side Way", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01", openAnyway: true };
29 const open = (extra: object = {}, address = "5 Side Way") => {
30 const made = createDeal(db, alice, { ...base1, address, ...extra });
31 if (!made.ok) throw new Error(made.message);
32 return made.value;
33 };
34 const post = (path: string, fields: Record<string, string>) =>
35 fetch(base + path, { method: "POST", redirect: "manual", headers: { ...user, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(fields) });
36
37 test("a deal is on the buyer side unless said, and only three words are accepted", () => {
38 expect(open().side).toBe("buyer");
39 expect(open({ side: "listing" }, "6 Side Way").side).toBe("listing");
40 expect(open({ side: "both" }, "7 Side Way").side).toBe("both");
41 for (const bad of ["seller", "Buyer", 3, {}]) {
42 const made = createDeal(db, alice, { ...base1, address: "8 Side Way", side: bad });
43 expect(made).toMatchObject({ ok: false, error: "invalid", field: "side" });
44 }
45 expect(sideOf(undefined)).toBe("buyer");
46 expect(sideFilter("seller")).toBeUndefined();
47 expect(sideFilter("all")).toBe("");
48 });
49
50 test("updating a side keeps it, changes it and refuses the unknown", () => {
51 const deal = open({}, "9 Side Way");
52 expect(updateDeal(db, alice, { id: deal.id, side: "listing" })).toMatchObject({ ok: true, value: { side: "listing" } });
53 expect(updateDeal(db, alice, { id: deal.id, side: "nobody" })).toMatchObject({ ok: false, error: "invalid", field: "side" });
54 expect(updateDeal(db, alice, { id: deal.id, side: "" })).toMatchObject({ ok: false, error: "invalid" });
55 expect(updateDeal(db, alice, { id: deal.id, salePrice: 1000 })).toMatchObject({ ok: true, value: { side: "listing" } });
56 expect(getDeal(db, alice, { id: deal.id })).toMatchObject({ ok: true, value: { side: "listing" } });
57 });
58
59 test("the filter narrows, keeps both-sides deals on each side, and combines with a query", () => {
60 const rows = [
61 { id: 1, side: "buyer", address: "1 Elm" },
62 { id: 2, side: "listing", address: "2 Elm" },
63 { id: 3, side: "both", address: "3 Oak" },
64 ] as never[];
65 const ids = (side: "" | "buyer" | "listing") => onSide(rows, side).map((d: { id: number }) => d.id);
66 expect(ids("")).toEqual([1, 2, 3]);
67 expect(ids("buyer")).toEqual([1, 3]);
68 expect(ids("listing")).toEqual([2, 3]);
69 const some = rows.map((r: { address: string }) => ({ ...r, parties: [] })) as never[];
70 expect(onSide(find(some, "elm"), "listing").map((d: { id: number }) => d.id)).toEqual([2]);
71 });
72
73 test("the form refuses an unknown side with 422 and saves a known one", async () => {
74 const deal = open({}, "10 Side Way");
75 const bad = await post(`/deals/${deal.id}/side`, { side: "seller" });
76 expect(bad.status).toBe(422);
77 expect(await bad.text()).toContain("Side is buyer, listing or both.");
78 const good = await post(`/deals/${deal.id}/side`, { side: "both" });
79 expect(good.status).toBe(303);
80 expect((await post(`/deals/${deal.id}/side`, { side: "both" })).status).toBe(303);
81 const other = await fetch(`${base}/deals/${deal.id}/side`, { method: "POST", headers: { ...user, origin: "https://evil.example", "sec-fetch-site": "cross-site", "content-type": "application/x-www-form-urlencoded" }, body: "side=listing" });
82 expect(other.status).toBeGreaterThanOrEqual(400);
83 expect(getDeal(db, alice, { id: deal.id })).toMatchObject({ value: { side: "both" } });
84 const page = await (await fetch(`${base}/deals/${deal.id}`, { headers: user })).text();
85 expect(page).toContain('<span class="side" data-side="both">Both sides</span>');
86 });
87
88 test("the new-deal form defaults to Buyer's agent and refuses an unknown side", async () => {
89 const page = await (await fetch(`${base}/deals/new`, { headers: user })).text();
90 expect(page).toMatch(/<option value="buyer" selected>Buyer&#39;s agent<\/option>/);
91 expect(page).toContain("Listing agent");
92 const fields = { address: "11 Side Way", buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01", earnest: "3", inspection: "10", appraisal: "21", financing: "28", title: "14", walkthrough: "2", side: "nope", open_anyway: "1" };
93 expect((await post("/deals", fields)).status).toBe(422);
94 expect((await post("/deals", { ...fields, side: "listing" })).status).toBe(303);
95 });
96
97 test("the clock labels and filters by side without script, and the Closed list keeps the label", async () => {
98 restore(db);
99 const all = await (await fetch(`${base}/`, { headers: user })).text();
100 expect(all).toContain('data-side="listing">Listing</span>');
101 expect(all).toContain('name="side"');
102 const listing = await (await fetch(`${base}/?side=listing`, { headers: user })).text();
103 expect(listing).toContain("9 Orchard Row");
104 expect(listing).not.toContain("1418 Alder Lane");
105 const buyer = await (await fetch(`${base}/?side=buyer&q=alder`, { headers: user })).text();
106 expect(buyer).toContain("1418 Alder Lane");
107 expect(buyer).not.toContain("9 Orchard Row");
108 expect((await fetch(`${base}/?side=listing&q=alder`, { headers: user })).status).toBe(200);
109 expect(await (await fetch(`${base}/?side=listing&q=alder`, { headers: user })).text()).not.toContain("1418 Alder Lane</a>");
110 expect((await fetch(`${base}/?side=seller`, { headers: user })).status).toBe(422);
111 const week = await (await fetch(`${base}/week?side=listing`, { headers: user })).text();
112 expect(week).not.toContain("1418 Alder Lane");
113 expect(await (await fetch(`${base}/week`, { headers: user })).text()).toContain("Buyer side");
114 const orchard = listDeals(db, alice);
115 const id = orchard.ok ? orchard.value.find((d) => d.address === "9 Orchard Row")!.id : 0;
116 db.query("UPDATE deadline SET done_at = '2026-01-01T00:00:00.000Z' WHERE deal_id = ?1").run(id);
117 const closed = await (await fetch(`${base}/`, { headers: user })).text();
118 expect(closed.slice(closed.indexOf('id="closed"'))).toContain("Listing");
119 });
120
121 test("the API and MCP narrow and read the side, and refuse an unknown one", async () => {
122 restore(db);
123 const api = async (q: string) => fetch(`${base}/api/deals${q}`, { headers: user });
124 const listing = (await (await api("?side=listing")).json()) as { address: string; side: string }[];
125 expect(listing.length).toBeGreaterThan(0);
126 expect(listing.every((d) => d.side === "listing" || d.side === "both")).toBe(true);
127 expect((await api("?side=all")).status).toBe(200);
128 expect((await api("?side=nobody")).status).toBe(422);
129 const created = await fetch(`${base}/api/deals`, { method: "POST", headers: { ...user, "content-type": "application/json" }, body: JSON.stringify({ address: "12 Side Way", buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01", side: "both", open_anyway: true }) });
130 expect(created.status).toBe(201);
131 expect(((await created.json()) as { side: string }).side).toBe("both");
132 const bad = await fetch(`${base}/api/deals`, { method: "POST", headers: { ...user, "content-type": "application/json" }, body: JSON.stringify({ address: "13 Side Way", buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01", side: "x" }) });
133 expect(bad.status).toBe(422);
134 const list = tools.find((t) => t.name === "list_deals")!;
135 const narrowed = list.run(db, alice, { side: "buyer" });
136 expect(narrowed.ok && (narrowed.value as { side: string }[]).every((d) => d.side !== "listing")).toBe(true);
137 expect(list.run(db, alice, { side: "nobody" })).toMatchObject({ ok: false, error: "invalid" });
138 const set = tools.find((t) => t.name === "set_side")!;
139 const id = (listing[0] as unknown as { id: number }).id;
140 expect(set.run(db, alice, { deal_id: id, side: "buyer" })).toMatchObject({ ok: true, value: { side: "buyer" } });
141 expect(set.run(db, alice, { deal_id: id, side: "zzz" })).toMatchObject({ ok: false, error: "invalid" });
142 });
143
144 test("the samples include a listing-side deal and Restore brings the sides back", () => {
145 restore(db);
146 const sides = () => { const l = listDeals(db, alice); return l.ok ? l.value.filter((d) => d.author_id === "sample").map((d) => d.side) : []; };
147 expect(sides()).toContain("listing");
148 expect(sides()).toContain("buyer");
149 db.query("UPDATE deal SET side = 'buyer' WHERE author_id = 'sample'").run();
150 restore(db);
151 expect(sides()).toContain("listing");
152 });
153
154 test("a deal that existed before the migration reads as the buyer side", () => {
155 const old = new Database(":memory:");
156 const last = migrations.findIndex((m) => m.includes("ADD COLUMN side"));
157 for (const m of migrations.slice(0, last)) old.run(m);
158 old.run("INSERT INTO deal (address, contract_date, author_id, author_name) VALUES ('1 Old Rd', '2026-01-01', 'u', 'u')");
159 old.run(migrations[last]!);
160 expect(old.query<{ side: string }, []>("SELECT side FROM deal").get()!.side).toBe("buyer");
161 expect(() => old.run("UPDATE deal SET side = 'seller'")).toThrow();
162 });
src/side.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * Which side of a deal the agent represents: the buyer's, the seller's
3 * (a listing) or both. Plain strings in, plain strings out; the clock, the
4 * deal's page, the week sheet and every door read the one table.
5 */
6
7 export const SIDES = ["buyer", "listing", "both"] as const;
8 export type Side = (typeof SIDES)[number];
9
10 /** What a new deal starts as, and what every deal opened before sides existed is. */
11 export const DEFAULT_SIDE: Side = "buyer";
12
13 /** The short label shown beside a deal. */
14 export const SIDE_LABEL: Readonly<Record<Side, string>> = {
15 buyer: "Buyer side",
16 listing: "Listing",
17 both: "Both sides",
18 };
19
20 /** The choice as the agent names it on a form. */
21 export const SIDE_CHOICE: Readonly<Record<Side, string>> = {
22 buyer: "Buyer's agent",
23 listing: "Listing agent",
24 both: "Both",
25 };
26
27 /** What the clock can be narrowed to; "" is every deal. */
28 export type SideFilter = "" | "buyer" | "listing";
29
30 /** `value` as a side: nothing or blank is the default; anything but the three words is undefined. */
31 export function sideOf(value: unknown): Side | undefined {
32 if (value === undefined || value === null || value === "") return DEFAULT_SIDE;
33 return SIDES.find((s) => s === value);
34 }
35
36 /** `value` as a filter: nothing or "all" is every deal; anything but buyer or listing is undefined. */
37 export function sideFilter(value: string | null): SideFilter | undefined {
38 if (value === null || value === "" || value === "all") return "";
39 return value === "buyer" || value === "listing" ? value : undefined;
40 }
41
42 /** The deals on a side: a deal for both sides is on each of them. */
43 export function onSide<T extends { readonly side: Side }>(deals: readonly T[], side: SideFilter): T[] {
44 return side === "" ? [...deals] : deals.filter((d) => d.side === side || d.side === "both");
45 }
46
47 export const SIDE_REFUSAL = "Side is buyer, listing or both.";
48
49 /** A side as typed in the terminal: the three words or the choice as the form names it; nothing is the default; anything else is undefined. */
50 export function sideTyped(text: string): Side | undefined {
51 const t = text.trim().toLowerCase();
52 if (t === "") return DEFAULT_SIDE;
53 return SIDES.find((s) => s === t || SIDE_CHOICE[s].toLowerCase() === t);
54 }
src/terminal.test.ts +40 −4
@@ -151,7 +151,7 @@ test("e with an empty answer keeps that part of the draft; too long a message is
151151
152152 test("n opens a deal from five answers, and shows it", () => {
153153 const t = terminal(db, alice, context);
154 press(t, "n", "31 Birch Row\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`);
154 press(t, "n", "31 Birch Row\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "\r");
155155 const listed = listDeals(db, alice);
156156 if (!listed.ok) throw new Error(listed.message);
157157 const made = listed.value.find((d) => d.address === "31 Birch Row");
@@ -160,7 +160,7 @@ test("n opens a deal from five answers, and shows it", () => {
160160 expect(lines(t).join("\n")).toContain("Opened 31 Birch Row");
161161 expect(lines(t)).toContain("31 Birch Row");
162162 // A bad answer is the action's to refuse, and nothing is opened.
163 press(t, "d", "n", "x\r", "A\r", "B\r", "soon\r", "later\r");
163 press(t, "d", "n", "x\r", "A\r", "B\r", "soon\r", "later\r", "\r");
164164 expect(lines(t).join("\n")).toContain("The address is 3 to 200 characters.");
165165 });
166166
@@ -168,7 +168,7 @@ test("c lists the dates n would create and writes nothing; a guest is asked to s
168168 const before = listDeals(db, alice);
169169 if (!before.ok) throw new Error(before.message);
170170 const t = terminal(db, alice, context);
171 press(t, "c", "44 Cedar Way\r", "Kim Buyer\r", "Lou Seller\r", "2026-10-02\r", "2026-11-20\r");
171 press(t, "c", "44 Cedar Way\r", "Kim Buyer\r", "Lou Seller\r", "2026-10-02\r", "2026-11-20\r", "\r");
172172 const shown = lines(t).join("\n");
173173 expect(shown).toContain("Dates for 44 Cedar Way");
174174 expect(shown).toContain("Mon, Oct 12");
@@ -177,7 +177,7 @@ test("c lists the dates n would create and writes nothing; a guest is asked to s
177177 const after = listDeals(db, alice);
178178 if (!after.ok) throw new Error(after.message);
179179 expect(after.value.length).toBe(before.value.length);
180 press(t, "c", "x\r", "A\r", "B\r", "soon\r", "later\r");
180 press(t, "c", "x\r", "A\r", "B\r", "soon\r", "later\r", "\r");
181181 expect(lines(t).join("\n")).toContain("The address is 3 to 200 characters.");
182182 const guest = terminal(db, { role: "anon" }, context);
183183 guest.press("c");
@@ -774,3 +774,39 @@ test("T sets and clears a date's note, shown beside the date, through setNote",
774774 expect(under(t)).not.toContain("note:");
775775 expect(db.query("SELECT count(*) AS n FROM deadline WHERE note = ?1").get("Title co. confirms Friday")).toEqual({ n: 0 });
776776 });
777
778 test("n asks which side, defaults to Buyer's agent, and refuses an unknown word", () => {
779 const t = terminal(db, alice, context);
780 press(t, "n", "51 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "Listing agent\r");
781 const listed = listDeals(db, alice);
782 if (!listed.ok) throw new Error(listed.message);
783 expect(listed.value.find((d) => d.address === "51 Side St")?.side).toBe("listing");
784 press(t, "d", "n", "52 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "\r");
785 const again = listDeals(db, alice);
786 if (!again.ok) throw new Error(again.message);
787 expect(again.value.find((d) => d.address === "52 Side St")?.side).toBe("buyer");
788 press(t, "d", "n", "53 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "seller\r");
789 expect(lines(t).join("\n")).toContain("Side is buyer, listing or both.");
790 const last = listDeals(db, alice);
791 if (!last.ok) throw new Error(last.message);
792 expect(last.value.some((d) => d.address === "53 Side St")).toBe(false);
793 });
794
795 test("the side is shown on the deal, the clock and the week, and Y changes it", () => {
796 const t = terminal(db, alice, context);
797 press(t, "d");
798 goTo(t, "Inspection period ends — 12 Elm St");
799 expect(under(t)).toContain("[Buyer side]");
800 t.press("o");
801 expect(lines(t).join("\n")).toContain("Buyer side · under contract");
802 press(t, "Y", "both\r");
803 expect(deal().side).toBe("both");
804 expect(lines(t).join("\n")).toContain("Both sides · under contract");
805 press(t, "Y", "seller\r");
806 expect(deal().side).toBe("both");
807 expect(lines(t).join("\n")).toContain("Side is buyer, listing or both.");
808 press(t, "Y", "Listing agent\r");
809 expect(deal().side).toBe("listing");
810 press(t, "w");
811 expect(lines(t).join("\n")).toContain("[Listing]");
812 });
src/terminal.ts +17 −8
@@ -10,11 +10,11 @@
1010 * timeline a deal's dates as a client would get them (t on a deal)
1111 * activity who approved, declined or changed what, newest first (L, admins); m only messages, o older, y newer
1212 * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults
13 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, S drafts a status update for the party under the cursor, D removes it, F marks it fell through (or brings it back)
13 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, S drafts a status update for the party under the cursor, D removes it, F marks it fell through (or brings it back), Y changes the side (buyer, listing or both)
1414 *
1515 * On a date (dates or deal view): x marks it done, W waives it (the buyer gave it up), u reopens it or un-waives it, m moves it
1616 * (a new date, then the reason), N moves one flagged "not a business day" to the next business day, l sets how many days before it reminds. o or enter opens its deal; n opens a new
17 * deal (address, buyer, seller, contract and closing dates); d, r and b move
17 * deal (address, buyer, seller, contract and closing dates, side); d, r and b move
1818 * between views; esc cancels a prompt; q leaves. / finds a deal by address or
1919 * party and narrows dates, week and reminders to it; / then enter clears it.
2020 */
@@ -76,6 +76,7 @@ import { reachedAt } from "./outbox.ts";
7676 import { addresses, refusal, when, wording } from "./activity.ts";
7777 import { listAudit } from "./actions.ts";
7878 import { owner, thisWeek } from "./week.ts";
79 import { SIDE_CHOICE, SIDE_LABEL, SIDE_REFUSAL, sideTyped } from "./side.ts";
7980
8081 const esc = "\x1b[";
8182 const dim = (s: string): string => `${esc}2m${s}${esc}0m`;
@@ -246,7 +247,7 @@ export function terminal(
246247
247248 function onDeal(key: string): boolean {
248249 const deal = openDeal();
249 if (deal === undefined || !["a", "p", "D", "e", "X", "A", "M", "S", "F"].includes(key)) return false;
250 if (deal === undefined || !["a", "p", "D", "e", "X", "A", "M", "S", "F", "Y"].includes(key)) return false;
250251 const party = deal.parties[cursor - deal.deadlines.length];
251252 const date = deal.deadlines[cursor];
252253 if (key === "S") {
@@ -276,6 +277,12 @@ export function terminal(
276277 report(markFellThrough(db, me, { id: deal.id, fell: true, reason }), `${deal.address} fell through; it has left the clock.`),
277278 REASON_MAX);
278279 }
280 if (key === "Y")
281 ask(deal, [`Side (now ${SIDE_CHOICE[deal.side]}): Buyer's agent, Listing agent or Both`], ([typed]) => {
282 const side = sideTyped(typed ?? "");
283 if (side === undefined || (typed ?? "").trim() === "") return side === undefined ? SIDE_REFUSAL : "Kept.";
284 return report(updateDeal(db, me, { id: deal.id, side }), `Side is now ${SIDE_CHOICE[side]}.`);
285 });
279286 if (key === "A")
280287 ask(deal, [`Address (now ${deal.address})`], ([address]) =>
281288 report(updateDeal(db, me, { id: deal.id, address }), `Address is now ${address!.trim()}.`),
@@ -612,11 +619,13 @@ export function terminal(
612619 if (!may.ok) said = may.message;
613620 else
614621 prompt = {
615 steps: ["Property address", "Buyer", "Seller", "Contract date (YYYY-MM-DD)", "Closing date (YYYY-MM-DD)"],
622 steps: ["Property address", "Buyer", "Seller", "Contract date (YYYY-MM-DD)", "Closing date (YYYY-MM-DD)", "Side: Buyer's agent, Listing agent or Both (enter for Buyer's agent)"],
616623 answers: [],
617624 text: "",
618 finish: ([address, buyer, seller, contractDate, closingDate]) => {
619 const input: NewDeal = { address, buyer, seller, contractDate, closingDate };
625 finish: ([address, buyer, seller, contractDate, closingDate, typedSide]) => {
626 const side = sideTyped(typedSide ?? "");
627 if (side === undefined) return SIDE_REFUSAL;
628 const input: NewDeal = { address, buyer, seller, contractDate, closingDate, side };
620629 if (key === "c") return previewDates(input);
621630 const made = createDeal(db, me, input);
622631 if (!made.ok && made.error === "conflict" && made.existing !== undefined) {
@@ -661,7 +670,7 @@ export function terminal(
661670 const when = tint(u, `${spoken(date.due).padEnd(12)} ${(isOpen(date) ? relative(date.due, on()) : date.waived_at !== null ? "waived" : "done").padEnd(12)}`);
662671 const who = owner(deal, date);
663672 const label = view === "week" ? `${date.label} — ${deal.address} · ${who.name ?? who.role}` : withDeal ? `${date.label} — ${deal.address}` : date.label;
664 const text = label + (deal.fell_through && withDeal ? dim(" (fell through)") : deal.closed && withDeal ? dim(" (closed)") : "");
673 const text = label + (withDeal || view === "week" ? dim(` [${SIDE_LABEL[deal.side]}]`) : "") + (deal.fell_through && withDeal ? dim(" (fell through)") : deal.closed && withDeal ? dim(" (closed)") : "");
665674 const moved = date.moves.length > 0 ? dim(` moved: ${date.moves.at(-1)!.reason}`) : "";
666675 const flag = date.nonBusinessDay === null ? "" : dim(` not a business day · next is ${spoken(date.nonBusinessDay.next)} (N moves it)`);
667676 const lead = isOpen(date) ? dim(` reminds ${date.lead_days}d before`) : "";
@@ -788,7 +797,7 @@ export function terminal(
788797 const deal = openDeal();
789798 if (deal === undefined) lines.push(dim("That deal is gone."));
790799 else {
791 lines.push(bold(deal.address), ...(deal.fell_through ? [bold(`Fell through on ${spoken(fellOn(deal))}: ${deal.fell_reason ?? ""}`)] : []), ...(deal.closed ? [bold(`Closed on ${spoken(closedOn(deal))}`)] : []), dim(`under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
800 lines.push(bold(deal.address), ...(deal.fell_through ? [bold(`Fell through on ${spoken(fellOn(deal))}: ${deal.fell_reason ?? ""}`)] : []), ...(deal.closed ? [bold(`Closed on ${spoken(closedOn(deal))}`)] : []), dim(`${SIDE_LABEL[deal.side]} · under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
792801 deal.deadlines.forEach((date, i) => lines.push(dateLine({ deal, date }, i, false)));
793802 if (deal.conflicts.length > 0) lines.push("", ...deal.conflicts.map((c) => tint("overdue", `! ${conflictLine(c)}`)));
794803 lines.push("", bold("Parties"));
static/app.css +16
@@ -973,6 +973,22 @@ a.marker {
973973 font-variant-numeric: tabular-nums;
974974 }
975975
976 /* Which side of a deal the agent is on: a text label beside the address, no box of its own to shift. */
977 .side {
978 font-weight: 600;
979 white-space: nowrap;
980 }
981 .side-edit {
982 display: flex;
983 flex-wrap: wrap;
984 align-items: center;
985 gap: var(--space-2);
986 margin-top: var(--space-2);
987 }
988 .side-edit label {
989 font-weight: 600;
990 }
991
976992 @media print {
977993 .timeline-page {
978994 background: white;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs