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

Opening a deal at an address that already has an open deal says so and links to it, and opens a second one only when the agent says so #91

Merged opened this

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

Merged

mason/deal-clock:mason/86-opening-a-deal-at-an-address-that-alread → main 4 commits fork

  • Merged. mason/86-opening-a-deal-at-an-address-that-alread was merged into main as 595fa28.

Review

Sign in to review this change.
23 files changed +281 −30
contract/openapi.json +32
@@ -386,6 +386,10 @@
386386 "business_days": {
387387 "type": "boolean",
388388 "default": false
389 },
390 "open_anyway": {
391 "type": "boolean",
392 "default": false
389393 }
390394 },
391395 "required": [
@@ -410,6 +414,34 @@
410414 }
411415 }
412416 },
417 "409": {
418 "description": "Already there: { error, message, existing_id }",
419 "content": {
420 "application/json": {
421 "schema": {
422 "type": "object",
423 "properties": {
424 "error": {
425 "type": "string",
426 "enum": [
427 "conflict"
428 ]
429 },
430 "message": {
431 "type": "string"
432 },
433 "existing_id": {
434 "type": "integer"
435 }
436 },
437 "required": [
438 "error",
439 "existing_id"
440 ]
441 }
442 }
443 }
444 },
413445 "default": {
414446 "description": "{ error, message }: why not",
415447 "content": {
docs/TECHNICAL.md +2
@@ -105,6 +105,8 @@ deal (`b` goes back). Its print rules in `static/app.css` apply to that page onl
105105
106106 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.
107107
108 **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.
109
108110 `POST /tick` answers the reminders that go out today and are not yet
109111 marked sent, as JSON — call it each morning as a signed-in account (a
110112 stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` is a deal's calendar file. The JSON API is
src/activity.test.ts +1 −1
@@ -29,7 +29,7 @@ const get = (path: string, who: Record<string, string> = {}) => fetch(base + pat
2929
3030 let dealId = 0;
3131 beforeAll(() => {
32 const made = createDeal(db, alice, { address: "9 <i>Audit</i> Row", buyer: "Ann", seller: "Sam", contractDate: "2026-10-01", closingDate: "2026-11-06" });
32 const made = createDeal(db, alice, { openAnyway: true, address: "9 <i>Audit</i> Row", buyer: "Ann", seller: "Sam", contractDate: "2026-10-01", closingDate: "2026-11-06" });
3333 if (!made.ok) throw new Error(made.message);
3434 dealId = made.value.id;
3535 const inspection = made.value.deadlines.find((d) => d.kind === "inspection")!;
src/activity.ts +1
@@ -35,6 +35,7 @@ const REFUSALS: Readonly<Record<string, string>> = {
3535 forbidden: "they may not do that",
3636 invalid: "what they sent was not valid",
3737 not_found: "it was not there",
38 conflict: "that deal was already open",
3839 cross_site: "it came from another site",
3940 };
4041
src/amend.test.ts +2 −2
@@ -19,7 +19,7 @@ const alice: Who = { role: "user", id: "u1", name: "alice" };
1919 const agent = { name: "Dana", brokerage: "Harbor", phone: "555", email: "[email protected]" };
2020
2121 const open = (): DealView => {
22 const made = createDeal(db, alice, { address: "4 Addendum Way", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01" });
22 const made = createDeal(db, alice, { openAnyway: true, address: "4 Addendum Way", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01" });
2323 if (!made.ok) throw new Error(made.message);
2424 return made.value;
2525 };
@@ -136,7 +136,7 @@ const postJson = (path: string, body: unknown) =>
136136 fetch(base + path, { method: "POST", headers: { ...me, "content-type": "application/json" }, body: JSON.stringify(body) });
137137
138138 const served = async (): Promise<DealView> => {
139 const made = await postJson("/api/deals", { address: "9 Door Lane", buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01" });
139 const made = await postJson("/api/deals", { address: "9 Door Lane", open_anyway: true, buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01" });
140140 return (await made.json()) as DealView;
141141 };
142142
src/contract.test.ts +1
@@ -63,6 +63,7 @@ const doors: Record<
6363 deal: {
6464 create: (who) =>
6565 createDeal(db, who, {
66 openAnyway: true,
6667 address: "1 Test St",
6768 buyer: "B",
6869 seller: "S",
src/deals.test.ts +3
@@ -40,6 +40,7 @@ const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty", phone
4040
4141 const open = (over: Record<string, unknown> = {}): DealView => {
4242 const made = createDeal(db, alice, {
43 openAnyway: true,
4344 address: "12 Elm St",
4445 buyer: "Ann Buyer",
4546 seller: "Sam Seller",
@@ -101,6 +102,7 @@ test("a deal's facts are checked at the boundary", () => {
101102 { lengths: { appraisal: "2.5" } },
102103 ]) {
103104 const r = createDeal(db, alice, {
105 openAnyway: true,
104106 address: "12 Elm St",
105107 buyer: "Ann",
106108 seller: "Sam",
@@ -111,6 +113,7 @@ test("a deal's facts are checked at the boundary", () => {
111113 expect([bad, r.ok ? "ok" : r.error]).toEqual([bad, "invalid"]);
112114 }
113115 const refused = createDeal(db, anon, {
116 openAnyway: true,
114117 address: "12 Elm St",
115118 buyer: "Ann",
116119 seller: "Sam",
src/deals.ts +37 −2
@@ -28,7 +28,7 @@ import { emit } from "./live.ts";
2828 import { outbox } from "./outbox.ts";
2929 import { conflictLine, conflicts, type Conflict } from "./order.ts";
3030 import { SEND_SPAN, draftOfMoment, statusDrafts, type Agent, type Draft } from "./reminders.ts";
31 import { audited, fail, ok, refuse, type Result } from "./result.ts";
31 import { audited, conflict, fail, ok, refuse, type Result } from "./result.ts";
3232 import type { Who } from "./who.ts";
3333
3434 export interface Deal {
@@ -395,6 +395,8 @@ export interface NewDeal {
395395 readonly closingDate: unknown;
396396 readonly lengths?: Partial<Record<keyof Lengths, unknown>>;
397397 readonly businessDays?: unknown;
398 /** `true` (or a ticked box) opens the deal although its address is already open. */
399 readonly openAnyway?: unknown;
398400 }
399401
400402 /** A deal's facts, checked, ready to write. */
@@ -445,6 +447,39 @@ export function plan(input: NewDeal): Result<Plan> {
445447 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays });
446448 }
447449
450 /** An address as two typings of one house agree on it: trimmed, spaces collapsed, lower case, no trailing period. */
451 export const sameAddress = (address: string): string =>
452 address.trim().replace(/\s+/g, " ").replace(/\.+$/, "").trim().toLowerCase();
453
454 /** `who`'s open deal at this address, if there is one: a closed deal does not count, nor does another agent's (or a sample's). */
455 export function openDealAt(
456 db: Database,
457 who: Who,
458 address: string,
459 ): { id: number; address: string } | undefined {
460 const wanted = sameAddress(address);
461 return db
462 .query<{ id: number; address: string }, [string]>(
463 `SELECT id, address FROM deal WHERE author_id = ?1
464 AND NOT EXISTS (SELECT 1 FROM deadline WHERE deal_id = deal.id AND kind = 'closing' AND done_at IS NOT NULL)
465 ORDER BY id`,
466 )
467 .all(authorOf(who).id)
468 .find((d) => sameAddress(d.address) === wanted);
469 }
470
471 const isAnyway = (v: unknown): boolean => v === true || v === "on" || v === "1" || v === "true";
472
473 /** `plan`, and a refusal naming the open deal when the address already has one and the input does not say `openAnyway`. */
474 export function planFor(db: Database, who: Who, input: NewDeal): Result<Plan> {
475 const planned = plan(input);
476 if (!planned.ok || isAnyway(input.openAnyway)) return planned;
477 const there = openDealAt(db, who, planned.value.address);
478 return there === undefined
479 ? planned
480 : conflict(`${there.address} is already open. Open a second deal anyway only if you mean it.`, there.id);
481 }
482
448483 /** A date a plan would create, as `insertDeal` writes it. */
449484 export interface PlannedDate {
450485 readonly label: string;
@@ -503,7 +538,7 @@ export const createDeal = (
503538 function create(db: Database, who: Who, input: NewDeal): Result<DealView> {
504539 const may = mayOpen(who);
505540 if (!may.ok) return may;
506 const planned = plan(input);
541 const planned = planFor(db, who, input);
507542 if (!planned.ok) return planned;
508543 const deal = view(db, insertDeal(db, authorOf(who), planned.value));
509544 emit("deal.changed", { id: deal.id });
src/duplicate.test.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * Typing the same listing twice leaves one clock: the second opening is
3 * refused as a conflict naming the first, until the agent says otherwise.
4 */
5 import { afterAll, beforeEach, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createDeal, markDone, sameAddress } from "./deals.ts";
10 import { openDb } from "./db.ts";
11 import { serve } from "./server.ts";
12 import { forgetRationing } from "./security.ts";
13 import { terminal } from "./terminal.ts";
14 import { sign, type Who } from "./who.ts";
15
16 const db = openDb(mkdtempSync(join(tmpdir(), "app-dup-")));
17 const alice: Who = { role: "user", id: "u1", name: "alice" };
18 const facts = { buyer: "Ann", seller: "Sam", contractDate: "2026-10-01", closingDate: "2026-11-01" };
19 const first = createDeal(db, alice, { ...facts, address: "1418 Alder Court" });
20 if (!first.ok) throw new Error(first.message);
21
22 test("the same address in another case, spacing or with a trailing period is refused, naming the deal", () => {
23 expect(sameAddress(" 1418 ALDER court. ")).toBe("1418 alder court");
24 for (const again of ["1418 alder court", " 1418 Alder Court ", "1418 Alder Court."]) {
25 const r = createDeal(db, alice, { ...facts, address: again });
26 expect(r.ok).toBe(false);
27 if (r.ok) continue;
28 expect(r.error).toBe("conflict");
29 expect(r.existing).toBe(first.value.id);
30 expect(r.message).toContain("1418 Alder Court is already open");
31 }
32 });
33
34 test("openAnyway opens the second deal; another address is not in the way", () => {
35 const second = createDeal(db, alice, { ...facts, address: "1418 Alder Court", openAnyway: true });
36 expect(second.ok).toBe(true);
37 expect(createDeal(db, alice, { ...facts, address: "1420 Alder Court" }).ok).toBe(true);
38 });
39
40 test("a closed deal does not block: a house can sell again", () => {
41 const sold = createDeal(db, alice, { ...facts, address: "7 Sold Street" });
42 if (!sold.ok) throw new Error(sold.message);
43 const closing = sold.value.deadlines.find((d) => d.kind === "closing")!;
44 expect(markDone(db, alice, { id: closing.id, done: true }).ok).toBe(true);
45 expect(createDeal(db, alice, { ...facts, address: "7 sold street" }).ok).toBe(true);
46 });
47
48 test("the terminal says so and opens a second deal only on a yes", () => {
49 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent: { name: "D", brokerage: "H", phone: "5", email: "[email protected]" } });
50 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);
52 expect(text()).toContain("1418 Alder Court is already open");
53 t.press("no\r");
54 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);
56 expect(text()).toContain("Opened 1418 Alder Court");
57 });
58
59 const KEY = "a-key-only-the-forge-holds";
60 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-dup-")), identityKey: KEY });
61 const base = `http://${server.hostname}:${server.port}`;
62 afterAll(() => server.stop(true));
63 beforeEach(forgetRationing);
64 const who = (() => {
65 const identity = `u1|alice|user|${Date.now() + 600_000}`;
66 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
67 })();
68 const fields = { address: "55 Oak Court", buyer: "B", seller: "S", contract_date: "2026-10-01", closing_date: "2026-11-01" };
69 const post = (path: string, body: unknown) =>
70 fetch(base + path, { method: "POST", headers: { ...who, "content-type": "application/json" }, body: JSON.stringify(body) });
71
72 test("the API answers 409 with the existing deal's id, and open_anyway goes through", async () => {
73 const one = (await (await post("/api/deals", fields)).json()) as { id: number };
74 const refused = await post("/api/deals", { ...fields, address: "55 OAK COURT." });
75 expect(refused.status).toBe(409);
76 const body = (await refused.json()) as { error: string; existing_id: number };
77 expect(body).toMatchObject({ error: "conflict", existing_id: one.id });
78 expect((await post("/api/deals", { ...fields, open_anyway: true })).status).toBe(201);
79 });
80
81 test("MCP open_deal carries the refusal and the override", async () => {
82 const call = async (args: object) =>
83 (await (await post("/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "open_deal", arguments: args } })).json()) as any;
84 const mcp = { address: "66 Pine Road", buyer: "B", seller: "S", contract_date: "2026-10-01", closing_date: "2026-11-01" };
85 expect((await call(mcp)).result.isError).toBeFalsy();
86 const refused = await call(mcp);
87 expect(JSON.stringify(refused)).toContain("already open");
88 expect(JSON.stringify(refused)).toContain("conflict");
89 expect(refused.result.content[0].text).toMatch(/\(existing_id: \d+\)/);
90 expect(JSON.stringify(await call({ ...mcp, open_anyway: true }))).not.toContain("already open");
91 });
92
93 test("the form shows the link, keeps what was typed, and the checkbox sends it through", async () => {
94 const form = (extra: Record<string, string> = {}) => {
95 const f = new FormData();
96 for (const [k, v] of Object.entries({ ...fields, address: "77 Elm Way", ...extra })) f.set(k, v);
97 return f;
98 };
99 const go = (f: FormData) => fetch(base + "/deals", { method: "POST", body: f, headers: who, redirect: "manual" });
100 const made = await go(form());
101 expect(made.status).toBe(303);
102 const id = made.headers.get("location")!.split("/").pop();
103 const refused = await go(form({ address: "77 elm way", buyer: "Kept Buyer" }));
104 expect(refused.status).toBe(409);
105 const page = await refused.text();
106 expect(page).toContain(`<a href="/deals/${id}">77 Elm Way</a> is already open`);
107 expect(page).toContain('value="Kept Buyer"');
108 expect(page).toContain("Open a second deal anyway");
109 expect((await go(form({ open_anyway: "on" }))).status).toBe(303);
110 });
src/lead.test.ts +4 −4
@@ -23,7 +23,7 @@ const anon: Who = { role: "anon" };
2323 const agent = { name: "Dana", brokerage: "Harbor", phone: "555", email: "[email protected]" };
2424
2525 const open = (): DealView => {
26 const made = createDeal(db, alice, { address: "5 Lead Lane", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01" });
26 const made = createDeal(db, alice, { openAnyway: true, address: "5 Lead Lane", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-12-01" });
2727 if (!made.ok) throw new Error(made.message);
2828 return made.value;
2929 };
@@ -110,7 +110,7 @@ test("a bad lead is refused by the action, naming the field, and nothing changes
110110 test("a database from before the column gains it in place, at three days", () => {
111111 const dir = mkdtempSync(join(tmpdir(), "app-lead-old-"));
112112 const old = openDb(dir);
113 const made = createDeal(old, alice, { address: "1 Old Rd", buyer: "A", seller: "B", contractDate: "2026-10-01", closingDate: "2026-12-01" });
113 const made = createDeal(old, alice, { openAnyway: true, address: "1 Old Rd", buyer: "A", seller: "B", contractDate: "2026-10-01", closingDate: "2026-12-01" });
114114 expect(made.ok).toBe(true);
115115 old.close();
116116 const again = new Database(join(dir, "app.db"));
@@ -134,7 +134,7 @@ const get = (path: string) => fetch(base + path, { headers: me });
134134 const sendJson = (method: string, path: string, body: unknown) =>
135135 fetch(base + path, { method, headers: { ...me, "content-type": "application/json" }, body: JSON.stringify(body) });
136136 const served = async (): Promise<DealView> => {
137 const made = await sendJson("POST", "/api/deals", { address: "9 Door Lane", buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01" });
137 const made = await sendJson("POST", "/api/deals", { address: "9 Door Lane", open_anyway: true, buyer: "A", seller: "B", contract_date: "2026-10-01", closing_date: "2026-12-01" });
138138 return (await made.json()) as DealView;
139139 };
140140
@@ -191,7 +191,7 @@ test("MCP set_reminder_lead sets it and refuses a bad one", async () => {
191191 });
192192
193193 test("the terminal shows the lead and sets it with l; a bad one is refused", () => {
194 const made = createDeal(db, alice, { address: "7 Tty Row", buyer: "A", seller: "B", contractDate: today(), closingDate: addDays(today(), 45) });
194 const made = createDeal(db, alice, { openAnyway: true, address: "7 Tty Row", buyer: "A", seller: "B", contractDate: today(), closingDate: addDays(today(), 45) });
195195 if (!made.ok) throw new Error(made.message);
196196 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent });
197197 const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "");
src/lengths.test.ts +1 −1
@@ -51,7 +51,7 @@ test("with business days as the agent's standard, a form's unticked box still me
5151 const base = "http://" + server.hostname + ":" + server.port;
5252 const identity = "u1|alice|user|" + (Date.now() + 60000);
5353 const who = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
54 const fields = { address: "1 Oak", buyer: "A", seller: "B", contract_date: "2026-10-02", closing_date: "2026-12-01" };
54 const fields = { address: "1 Oak", open_anyway: true, buyer: "A", seller: "B", contract_date: "2026-10-02", closing_date: "2026-12-01" };
5555 const form = () => { const f = new FormData(); for (const [k, v] of Object.entries(fields)) f.set(k, v); return f; };
5656 const first = await (await fetch(base + "/deals/new", { headers: who })).text();
5757 const check = await (await fetch(base + "/deals/check", { method: "POST", body: form(), headers: who })).text();
src/mcp.ts +4 −2
@@ -247,7 +247,7 @@ export const tools: readonly Tool[] = [
247247 },
248248 {
249249 name: "open_deal",
250 description: "Open a deal with its buyer and seller; the standard dates are scheduled from the contract and closing dates.",
250 description: "Open a deal with its buyer and seller; the standard dates are scheduled from the contract and closing dates. Refused as a conflict, naming the deal, when the address already has an open one; pass open_anyway to open a second.",
251251 inputSchema: {
252252 type: "object",
253253 properties: {
@@ -262,6 +262,7 @@ export const tools: readonly Tool[] = [
262262 title: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.title },
263263 walkthrough: { type: "integer", minimum: 0, maximum: LENGTH_MAX, default: DEFAULT_LENGTHS.walkthrough },
264264 business_days: { type: "boolean", default: standard.businessDays },
265 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)." },
265266 },
266267 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
267268 },
@@ -280,6 +281,7 @@ export const tools: readonly Tool[] = [
280281 walkthrough: a.walkthrough,
281282 },
282283 businessDays: a.business_days,
284 openAnyway: a.open_anyway,
283285 }),
284286 },
285287 {
@@ -445,7 +447,7 @@ export function rpc(
445447 ? { content: [{ type: "text", text: JSON.stringify(result.value) }] }
446448 : {
447449 content: [
448 { type: "text", text: `${result.error}: ${result.message}` },
450 { type: "text", text: `${result.error}: ${result.message}${result.existing === undefined ? "" : ` (existing_id: ${result.existing})`}` },
449451 ],
450452 isError: true,
451453 },
src/openapi.ts +4 −1
@@ -42,7 +42,7 @@ export function openapi(): Record<string, unknown> {
4242 const paths: Record<string, Record<string, unknown>> = {};
4343 for (const route of routes) {
4444 if (route.api === undefined) continue;
45 const { summary, body, answer, status, query, cell } = route.api;
45 const { summary, body, answer, status, query, cell, conflict } = route.api;
4646 const path = route.path.replace(/:(\w+)/g, "{$1}");
4747 const params = [...route.path.matchAll(/:(\w+)/g)].map(([, name]) => ({
4848 name,
@@ -79,6 +79,9 @@ export function openapi(): Record<string, unknown> {
7979 description: summary,
8080 content: content(answer),
8181 },
82 ...(conflict === undefined
83 ? {}
84 : { "409": { description: "Already there: { error, message, existing_id }", content: content(conflict) } }),
8285 default: {
8386 description: "{ error, message }: why not",
8487 content: content(ERROR),
src/pages/deal.ts +9
@@ -198,6 +198,8 @@ export function dealPage(input: {
198198 export interface NewDealState {
199199 readonly values: Readonly<Record<string, string>>;
200200 readonly problem?: { readonly field?: string | undefined; readonly message: string } | undefined;
201 /** The open deal already at the address typed: named with a link, and the way past it offered. */
202 readonly existing?: { readonly id: number; readonly address: string } | undefined;
201203 readonly preview?: { readonly plan: Plan; readonly dates: readonly PlannedDate[] } | undefined;
202204 }
203205
@@ -238,6 +240,12 @@ export function newDealPage(input: {
238240 problem !== undefined && problem.field === undefined
239241 ? `<p class="field-error" role="alert">${escape(problem.message)}</p>`
240242 : "";
243 const existing = state?.existing;
244 const existingNotice =
245 existing === undefined
246 ? ""
247 : `<div class="conflict" role="alert" id="existing"><p><a href="/deals/${existing.id}">${escape(existing.address)}</a> is already open.</p>
248 <label class="check"><input type="checkbox" name="open_anyway"${values.open_anyway !== undefined ? " checked" : ""}> Open a second deal anyway</label></div>`;
241249 const length = (name: keyof typeof DEFAULT_LENGTHS, label: string) =>
242250 `<label>${label}<input class="input" type="number" inputmode="numeric" name="${name}" min="0" max="180" value="${val(name, String(DEFAULT_LENGTHS[name]))}" required${bad(name)}>${why(name)}</label>`;
243251 const ticked = state === undefined ? standard.businessDays : values.business_days !== undefined;
@@ -251,6 +259,7 @@ export function newDealPage(input: {
251259 <p class="muted small">The lengths start from your standard ones; change any for this deal.</p>
252260 <form class="stack" method="post" action="/deals">
253261 ${general}
262 ${existingNotice}
254263 <label>Property address<input class="input" name="address" required minlength="3" maxlength="200" autocomplete="off" placeholder="1418 Alder Lane" value="${val("address", "")}"${bad("address")}>${why("address")}</label>
255264 <div class="pair">
256265 <label>Buyer<input class="input" name="buyer" required maxlength="100" value="${val("buyer", "")}"${bad("buyer")}>${why("buyer")}</label>
src/progress.test.ts +1 −1
@@ -16,7 +16,7 @@ const alice: Who = { role: "user", id: "u1", name: "alice" };
1616 const on = "2026-10-10";
1717
1818 const open = (): number => {
19 const made = createDeal(db, alice, { address: "3 Progress Way", buyer: "B", seller: "S", contractDate: "2026-10-01", closingDate: "2026-10-22" });
19 const made = createDeal(db, alice, { openAnyway: true, address: "3 Progress Way", buyer: "B", seller: "S", contractDate: "2026-10-01", closingDate: "2026-10-22" });
2020 if (!made.ok) throw new Error(made.message);
2121 return made.value.id;
2222 };
src/restore.test.ts +1 −1
@@ -23,7 +23,7 @@ const samples = () => all().filter((d) => d.author_id === "sample");
2323 const sample = (address: string) => samples().find((d) => d.address.includes(address))!;
2424 const date = (deal: DealView, kind: string) => deal.deadlines.find((d) => d.kind === kind)!;
2525
26 const mine = createDeal(db, alice, { address: "12 Elm St", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: on, closingDate: addDays(on, 45) });
26 const mine = createDeal(db, alice, { openAnyway: true, address: "12 Elm St", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: on, closingDate: addDays(on, 45) });
2727 if (!mine.ok) throw new Error(mine.message);
2828
2929 /** What a demo does to the samples. */
src/result.ts +10 −2
@@ -9,10 +9,10 @@ import type { Database } from "bun:sqlite";
99 import { record } from "./audit.ts";
1010 import type { Who } from "./who.ts";
1111
12 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
12 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid" | "conflict";
1313 export type Result<T> =
1414 | { ok: true; value: T }
15 | { ok: false; error: Failure; message: string; field?: string };
15 | { ok: false; error: Failure; message: string; field?: string; existing?: number };
1616 export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
1717 /** `field` names the input a form should put the message beside. */
1818 export const fail = <T>(error: Failure, message: string, field?: string): Result<T> => ({
@@ -51,3 +51,11 @@ export const audited = <T extends { readonly id: number }>(
5151 });
5252 return result;
5353 };
54
55 /** A refusal because the thing is already there: `existing` is the id of the row in the way. */
56 export const conflict = <T>(message: string, existing: number): Result<T> => ({
57 ok: false,
58 error: "conflict",
59 message,
60 existing,
61 });
src/routes.ts +20 −2
@@ -51,7 +51,9 @@ import {
5151 listDeals,
5252 markDone,
5353 mayOpen,
54 openDealAt,
5455 plan,
56 planFor,
5557 plannedDates,
5658 amendDeal,
5759 amendment,
@@ -111,6 +113,8 @@ export interface Api {
111113 readonly status?: number;
112114 /** The query parameters it reads. */
113115 readonly query?: Readonly<Record<string, Schema>>;
116 /** Also answers 409 with this shape when what it makes is already there. */
117 readonly conflict?: Schema;
114118 /** The cell of the table a route outside its resource's `api` path reads through, for the description. */
115119 readonly cell?: { readonly resource: string; readonly verb: Verb };
116120 }
@@ -289,6 +293,7 @@ const NEW_DEAL: Schema = {
289293 title: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.title },
290294 walkthrough: { type: "integer", minimum: 0, maximum: 180, default: DEFAULT_LENGTHS.walkthrough },
291295 business_days: { type: "boolean", default: standard.businessDays },
296 open_anyway: { type: "boolean", default: false },
292297 },
293298 required: ["address", "buyer", "seller", "contract_date", "closing_date"],
294299 };
@@ -334,6 +339,12 @@ export const ERROR: Schema = {
334339 properties: { error: { type: "string" }, message: { type: "string" } },
335340 required: ["error"],
336341 };
342 /** The 409 for a thing that is already there: the error, and the id of the row in the way. */
343 export const CONFLICT: Schema = {
344 type: "object",
345 properties: { error: { type: "string", enum: ["conflict"] }, message: { type: "string" }, existing_id: { type: "integer" } },
346 required: ["error", "existing_id"],
347 };
337348 const LIMIT: Schema = {
338349 type: "integer",
339350 minimum: 1,
@@ -346,6 +357,7 @@ const STATUS: Record<Failure, number> = {
346357 forbidden: 403,
347358 not_found: 404,
348359 invalid: 422,
360 conflict: 409,
349361 };
350362
351363 /** A deal that is not there, for a reader who may read deals: the product's own 404. */
@@ -369,7 +381,7 @@ const answer = <T>(result: Result<T>, status = 200): Response =>
369381 result.ok
370382 ? json(result.value, status)
371383 : json(
372 { error: result.error, message: result.message },
384 { error: result.error, message: result.message, ...(result.existing === undefined ? {} : { existing_id: result.existing }) },
373385 STATUS[result.error],
374386 );
375387
@@ -485,6 +497,7 @@ const newDeal = (f: Record<string, unknown>): NewDeal => ({
485497 walkthrough: f.walkthrough,
486498 },
487499 businessDays: f.business_days,
500 openAnyway: f.open_anyway,
488501 });
489502
490503 /** A whole number from the query, or undefined. */
@@ -665,6 +678,8 @@ export const routes: readonly Route[] = [
665678 if (f instanceof Response) return f;
666679 const made = createDeal(c.db, c.who, newDeal(fromForm(f)));
667680 if (made.ok) return back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`);
681 if (made.error === "conflict")
682 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, existing: openDealAt(c.db, c.who, String(f.address)) } }), 409);
668683 if (made.error !== "invalid") return back(made.message, "/deals/new");
669684 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, problem: made } }), 422);
670685 },
@@ -682,7 +697,9 @@ export const routes: readonly Route[] = [
682697 if (!planned.ok)
683698 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, problem: planned } }), 422);
684699 const preview = { plan: planned.value, dates: plannedDates(planned.value) };
685 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, preview } }));
700 const there = planFor(c.db, c.who, newDeal(fromForm(f)));
701 const existing = there.ok ? undefined : openDealAt(c.db, c.who, planned.value.address);
702 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, preview, existing } }));
686703 },
687704 },
688705 {
@@ -1027,6 +1044,7 @@ export const routes: readonly Route[] = [
10271044 body: NEW_DEAL,
10281045 answer: DEAL,
10291046 status: 201,
1047 conflict: CONFLICT,
10301048 },
10311049 },
10321050 {
src/server.test.ts +1
@@ -115,6 +115,7 @@ test("a form post opens a deal as the person; a guest is sent to sign in", async
115115
116116 const NEW_DEAL = {
117117 address: "9 Api Lane",
118 open_anyway: true,
118119 buyer: "B",
119120 seller: "S",
120121 contract_date: "2026-10-01",
src/signoff.test.ts +1 −1
@@ -16,7 +16,7 @@ const alice: Who = { role: "user", id: "u1", name: "alice" };
1616 const dana = { name: "Dana", brokerage: "HP", phone: "(555) 010-0142", email: "[email protected]" };
1717 const lee = { name: "Lee", brokerage: "Bay", phone: "+1 555 0199", email: "[email protected]" };
1818
19 const made = createDeal(db, alice, { address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-20" });
19 const made = createDeal(db, alice, { openAnyway: true, address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-20" });
2020 if (!made.ok) throw new Error(made.message);
2121 const view = () => {
2222 const got = getDeal(db, alice, { id: made.value.id });
src/terminal.test.ts +14 −6
@@ -27,6 +27,7 @@ function goTo(t: Terminal, text: string): void {
2727 const press = (t: Terminal, ...chunks: string[]) => chunks.forEach((c) => t.press(c));
2828
2929 const made = createDeal(db, alice, {
30 openAnyway: true,
3031 address: "12 Elm St",
3132 buyer: "Ann Buyer",
3233 seller: "Sam Seller",
@@ -90,6 +91,7 @@ test("o opens a deal; a adds a date, p a party; D removes it after a yes", () =>
9091 expect(lines(t).join("\n")).toContain("Kept.");
9192 expect(getDeal(db, alice, { id }).ok).toBe(true);
9293 const other = createDeal(db, alice, {
94 openAnyway: true,
9395 address: "99 Gone Rd",
9496 buyer: "B",
9597 seller: "S",
@@ -199,6 +201,7 @@ test("a guest sees no deals, and is asked to sign in before anything — n inclu
199201
200202 test("e edits the party under the cursor; X removes a party or a custom date after yes", () => {
201203 const own = createDeal(db, alice, {
204 openAnyway: true,
202205 address: "7 Cedar Ct",
203206 buyer: "Bea Buyer",
204207 seller: "Sid Seller",
@@ -269,6 +272,7 @@ test("n declines a reminder with a reason, u undoes it; anon is not asked to typ
269272 test("a closed deal's dates leave the date list and reminders, it is listed under Closed, and u reopens it", () => {
270273 // The inspection ends in three days, so its "3 days before" reminder goes out today.
271274 const other = createDeal(db, alice, {
275 openAnyway: true,
272276 address: "88 Shut Ave",
273277 buyer: "B",
274278 seller: "S",
@@ -351,6 +355,7 @@ test("s on a deal lists what was sent, newest first, with the words; b comes bac
351355
352356 test("r lists an overdue follow-up as late, as the clock page does, until it is sent", () => {
353357 const slipped = createDeal(db, alice, {
358 openAnyway: true,
354359 address: "5 Late Ln",
355360 buyer: "Lena Buyer",
356361 seller: "Sid Seller",
@@ -393,6 +398,7 @@ test("R then yes puts the sample deals back, leaving a person's deal alone", ()
393398
394399 test("/ finds a deal and narrows dates, week and reminders to it; / then enter clears it", () => {
395400 const other = createDeal(db, alice, {
401 openAnyway: true,
396402 address: "9 Oak Ln",
397403 buyer: "Zed Zimmer",
398404 seller: "Yan Yates",
@@ -435,7 +441,7 @@ test("/ finds a deal and narrows dates, week and reminders to it; / then enter c
435441 });
436442
437443 test("A corrects the address of the open deal; a too-short one is refused and nothing changes", () => {
438 const own = createDeal(db, alice, { address: "3 Oak St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 30) });
444 const own = createDeal(db, alice, { openAnyway: true, address: "3 Oak St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 30) });
439445 if (!own.ok) throw new Error(own.message);
440446 const read = () => {
441447 const got = getDeal(db, alice, { id: own.value.id });
@@ -462,7 +468,7 @@ test("a signed-out terminal is not asked for an address", () => {
462468 test("P lists each person once with the dates they owe across deals; a guest is refused", () => {
463469 const own = openDb(mkdtempSync(join(tmpdir(), "app-terminal-people-")));
464470 const open = (address: string) => {
465 const made = createDeal(own, alice, { address, buyer: "B", seller: "S", contractDate: today(), closingDate: addDays(today(), 30) });
471 const made = createDeal(own, alice, { openAnyway: true, address, buyer: "B", seller: "S", contractDate: today(), closingDate: addDays(today(), 30) });
466472 if (!made.ok) throw new Error(made.message);
467473 addParty(own, alice, { dealId: made.value.id, role: "lender", name: "Lena Lender", contact: "[email protected]" });
468474 };
@@ -482,6 +488,7 @@ test("P lists each person once with the dates they owe across deals; a guest is
482488
483489 test("the deal view lists a date that falls after closing, in words", () => {
484490 const other = createDeal(db, alice, {
491 openAnyway: true,
485492 address: "3 Fig Ct",
486493 buyer: "B",
487494 seller: "S",
@@ -500,6 +507,7 @@ test("the deal view lists a date that falls after closing, in words", () => {
500507
501508 test("m past closing moves the date and the status line names the conflict; a is the same", () => {
502509 const other = createDeal(db, alice, {
510 openAnyway: true,
503511 address: "5 Gum Rd",
504512 buyer: "B",
505513 seller: "S",
@@ -522,7 +530,7 @@ test("m past closing moves the date and the status line names the conflict; a is
522530 });
523531
524532 test("a moved date's Date changed notice is on the reminders list; s sends it and the sent list reads its date", () => {
525 const made2 = createDeal(db, alice, { address: "31 Moved Way", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 45) });
533 const made2 = createDeal(db, alice, { openAnyway: true, address: "31 Moved Way", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 45) });
526534 if (!made2.ok) throw new Error(made2.message);
527535 const insp = made2.value.deadlines.find((d) => d.kind === "inspection")!;
528536 const to = addDays(insp.due, 5);
@@ -548,7 +556,7 @@ test("a moved date's Date changed notice is on the reminders list; s sends it an
548556 });
549557
550558 test("n declines a Date changed notice with a reason and u undoes it", () => {
551 const made3 = createDeal(db, alice, { address: "32 Moved Way", buyer: "Cy Buyer", seller: "Sol Seller", contractDate: today(), closingDate: addDays(today(), 45) });
559 const made3 = createDeal(db, alice, { openAnyway: true, address: "32 Moved Way", buyer: "Cy Buyer", seller: "Sol Seller", contractDate: today(), closingDate: addDays(today(), 45) });
552560 if (!made3.ok) throw new Error(made3.message);
553561 const insp = made3.value.deadlines.find((d) => d.kind === "inspection")!;
554562 moveDeadline(db, alice, { id: insp.id, due: addDays(insp.due, 5), reason: "x" });
@@ -633,7 +641,7 @@ test("a reader who may not change a deal sees no contact and no link", () => {
633641 });
634642
635643 test("M amends the contract: a blank answer keeps a date, the rest move together with one reason", () => {
636 const own = createDeal(db, alice, { address: "8 Amend Rd", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 60) });
644 const own = createDeal(db, alice, { openAnyway: true, address: "8 Amend Rd", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 60) });
637645 if (!own.ok) throw new Error(own.message);
638646 const read = () => {
639647 const got = getDeal(db, alice, { id: own.value.id });
@@ -657,7 +665,7 @@ test("L reads the audit trail in words for an admin, filters to messages and pag
657665 const root: Who = { role: "admin", id: "u0", name: "root" };
658666 // A book of its own, so the newest rows are these.
659667 const db = openDb(mkdtempSync(join(tmpdir(), "app-terminal-activity-")));
660 const mine = createDeal(db, alice, { address: "7 Trail Row", buyer: "Ann", seller: "Sam", contractDate: today(), closingDate: addDays(today(), 45) });
668 const mine = createDeal(db, alice, { openAnyway: true, address: "7 Trail Row", buyer: "Ann", seller: "Sam", contractDate: today(), closingDate: addDays(today(), 45) });
661669 if (!mine.ok) throw new Error(mine.message);
662670 const inspection = mine.value.deadlines.find((d) => d.kind === "inspection")!;
663671 const party = db.query<{ id: number }, [number]>("SELECT id FROM party WHERE deal_id = ?1 LIMIT 1").get(mine.value.id)!;
src/terminal.ts +21 −3
@@ -36,7 +36,7 @@ import {
3636 listDeals,
3737 markDone,
3838 mayOpen,
39 plan,
39 planFor,
4040 plannedDates,
4141 type NewDeal,
4242 amendDeal,
@@ -440,7 +440,7 @@ export function terminal(
440440
441441 /** The dates `n` would create for these answers, one per line; nothing is written. */
442442 function previewDates(input: NewDeal): string {
443 const planned = plan(input);
443 const planned = planFor(db, me, input);
444444 if (!planned.ok) return planned.message;
445445 const p = planned.value;
446446 const owner = (role: PartyRole): string => (role === "buyer" ? p.buyer : role === "seller" ? p.seller : PARTY_LABEL[role]);
@@ -537,9 +537,27 @@ export function terminal(
537537 answers: [],
538538 text: "",
539539 finish: ([address, buyer, seller, contractDate, closingDate]) => {
540 const input = { address, buyer, seller, contractDate, closingDate };
540 const input: NewDeal = { address, buyer, seller, contractDate, closingDate };
541541 if (key === "c") return previewDates(input);
542542 const made = createDeal(db, me, input);
543 if (!made.ok && made.error === "conflict" && made.existing !== undefined) {
544 const existing = made.existing;
545 prompt = {
546 steps: [`${made.message} Type yes to open a second deal anyway`],
547 answers: [],
548 text: "",
549 finish: ([yes]) => {
550 if (yes !== "yes") return `Kept: deal ${existing} is the one at that address.`;
551 const second = createDeal(db, me, { ...input, openAnyway: true });
552 if (!second.ok) return second.message;
553 view = "deal";
554 dealId = second.value.id;
555 cursor = 0;
556 return `Opened ${second.value.address}: every date is on the clock.`;
557 },
558 };
559 return "";
560 }
543561 if (!made.ok) return made.message;
544562 view = "deal";
545563 dealId = made.value.id;
src/timeline.test.ts +1 −1
@@ -12,7 +12,7 @@ import type { Who } from "./who.ts";
1212 const db = openDb(mkdtempSync(join(tmpdir(), "app-timeline-")));
1313 const alice: Who = { role: "user", id: "u1", name: "alice" };
1414
15 const made = createDeal(db, alice, { address: "9 <b>Oak</b> Rd", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-06" });
15 const made = createDeal(db, alice, { openAnyway: true, address: "9 <b>Oak</b> Rd", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: "2026-10-01", closingDate: "2026-11-06" });
1616 if (!made.ok) throw new Error(made.message);
1717 const id = made.value.id;
1818 addParty(db, alice, { dealId: id, role: "lender", name: "Lena Lender", contact: "[email protected]" });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs