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

The agent can correct a party's name or contact, remove a party, and remove a date the contract dropped #16

Merged opened this

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

Merged

mason/deal-clock:mason/9-the-agent-can-correct-a-party-s-name-or → main 2 commits fork

  • Merged. mason/9-the-agent-can-correct-a-party-s-name-or was merged into main as f62bfce.

Review

Sign in to review this change.
14 files changed +661 −29
README.md +11 −2
@@ -28,7 +28,14 @@ in `/api/deals/:id`, in MCP and in the terminal.
2828 **A deal's page** (tap its address) lists every date and party. Add a date
2929 the contract adds (an HOA review, a repair deadline), add the lender or the
3030 title company, and **Add to calendar** downloads an `.ics` file with every
31 date and its alarms for your own calendar.
31 date and its alarms for your own calendar. Nothing is stuck once added: each
32 party has **Edit** (a mistyped name or email, which the next reminder draft
33 uses) and **Remove**; a date you added opens a sheet with **Remove this
34 date** for when the contract drops it. The standard contract dates cannot be
35 removed — move them or mark them done. Removing a party or a date drops the
36 reminders not yet sent; reminders already marked sent stay on record. Over
37 the API: `PATCH` or `DELETE /api/deals/:id/parties/:party` and `DELETE
38 /api/deals/:id/deadlines/:deadline`.
3239
3340 **New deal** takes the address, buyer, seller, contract date and closing
3441 date, and works out the rest from the contingency lengths. The defaults —
@@ -79,7 +86,9 @@ first: `n` opens a new deal (address, buyer, seller, contract date, closing
7986 date; the standard lengths do the rest), `x` marks the date under the cursor
8087 done, `u` reopens it, `m` moves it (the new date, then the reason), `o` opens
8188 its deal — where `a` adds a date,
82 `p` adds a party and `D` removes the deal after you type `yes` — and `h`
89 `p` adds a party, `e` edits the party under the cursor (the cursor walks the
90 dates, then the parties), `X` removes the date or party under it after you
91 type `yes`, and `D` removes the deal likewise — and `h`
8392 shows done dates. `r` lists today's reminders: enter reads a draft, `e`
8493 types new words for it (a subject, then a message, where `\n` is a line
8594 break and an empty answer keeps the draft's), and `s` sends what you read,
contract/openapi.json +211
@@ -346,6 +346,217 @@
346346 }
347347 }
348348 },
349 "/api/deals/{id}/parties/{party}": {
350 "patch": {
351 "summary": "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
352 "operationId": "patchApiDealsIdPartiesParty",
353 "parameters": [
354 {
355 "name": "id",
356 "in": "path",
357 "required": true,
358 "schema": {
359 "type": "integer"
360 }
361 },
362 {
363 "name": "party",
364 "in": "path",
365 "required": true,
366 "schema": {
367 "type": "integer"
368 }
369 }
370 ],
371 "requestBody": {
372 "required": true,
373 "content": {
374 "application/json": {
375 "schema": {
376 "type": "object",
377 "properties": {
378 "name": {
379 "type": "string",
380 "minLength": 1,
381 "maxLength": 100
382 },
383 "contact": {
384 "type": "string",
385 "maxLength": 120
386 }
387 },
388 "required": [
389 "name"
390 ]
391 }
392 }
393 }
394 },
395 "responses": {
396 "200": {
397 "description": "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
398 "content": {
399 "application/json": {
400 "schema": {
401 "type": "object",
402 "properties": {
403 "id": {
404 "type": "integer"
405 },
406 "role": {
407 "enum": [
408 "buyer",
409 "seller",
410 "lender",
411 "title",
412 "other_agent"
413 ]
414 },
415 "name": {
416 "type": "string"
417 },
418 "contact": {
419 "type": "string"
420 }
421 }
422 }
423 }
424 }
425 },
426 "default": {
427 "description": "{ error, message }: why not",
428 "content": {
429 "application/json": {
430 "schema": {
431 "$ref": "#/components/schemas/Error"
432 }
433 }
434 }
435 }
436 },
437 "x-contract": {
438 "resource": "deal",
439 "verb": "update",
440 "least": "user"
441 }
442 },
443 "delete": {
444 "summary": "Remove a party and the reminders not yet sent to them; reminders already sent stay in the record.",
445 "operationId": "deleteApiDealsIdPartiesParty",
446 "parameters": [
447 {
448 "name": "id",
449 "in": "path",
450 "required": true,
451 "schema": {
452 "type": "integer"
453 }
454 },
455 {
456 "name": "party",
457 "in": "path",
458 "required": true,
459 "schema": {
460 "type": "integer"
461 }
462 }
463 ],
464 "responses": {
465 "200": {
466 "description": "Remove a party and the reminders not yet sent to them; reminders already sent stay in the record.",
467 "content": {
468 "application/json": {
469 "schema": {
470 "type": "object",
471 "properties": {
472 "id": {
473 "type": "integer"
474 }
475 },
476 "required": [
477 "id"
478 ]
479 }
480 }
481 }
482 },
483 "default": {
484 "description": "{ error, message }: why not",
485 "content": {
486 "application/json": {
487 "schema": {
488 "$ref": "#/components/schemas/Error"
489 }
490 }
491 }
492 }
493 },
494 "x-contract": {
495 "resource": "deal",
496 "verb": "update",
497 "least": "user"
498 }
499 }
500 },
501 "/api/deals/{id}/deadlines/{deadline}": {
502 "delete": {
503 "summary": "Remove a custom date the contract dropped, and its unsent reminders. A standard contract date is refused (422): move it or mark it done.",
504 "operationId": "deleteApiDealsIdDeadlinesDeadline",
505 "parameters": [
506 {
507 "name": "id",
508 "in": "path",
509 "required": true,
510 "schema": {
511 "type": "integer"
512 }
513 },
514 {
515 "name": "deadline",
516 "in": "path",
517 "required": true,
518 "schema": {
519 "type": "integer"
520 }
521 }
522 ],
523 "responses": {
524 "200": {
525 "description": "Remove a custom date the contract dropped, and its unsent reminders. A standard contract date is refused (422): move it or mark it done.",
526 "content": {
527 "application/json": {
528 "schema": {
529 "type": "object",
530 "properties": {
531 "id": {
532 "type": "integer"
533 }
534 },
535 "required": [
536 "id"
537 ]
538 }
539 }
540 }
541 },
542 "default": {
543 "description": "{ error, message }: why not",
544 "content": {
545 "application/json": {
546 "schema": {
547 "$ref": "#/components/schemas/Error"
548 }
549 }
550 }
551 }
552 },
553 "x-contract": {
554 "resource": "deal",
555 "verb": "update",
556 "least": "user"
557 }
558 }
559 },
349560 "/api/audit": {
350561 "get": {
351562 "summary": "The audit trail, newest first; `before` pages back by id.",
src/db.ts +24
@@ -101,6 +101,30 @@ export const migrations: string[] = [
101101 // before this carry '' and read as the draft they were sent from.
102102 `ALTER TABLE reminder ADD COLUMN subject TEXT NOT NULL DEFAULT ''`,
103103 `ALTER TABLE reminder ADD COLUMN body TEXT NOT NULL DEFAULT ''`,
104 // A reminder marked sent outlives the date or party it was about: removing
105 // either leaves the record, which now names them in words and hangs off the
106 // deal (removing the deal still removes it).
107 `CREATE TABLE reminder_kept (
108 id INTEGER PRIMARY KEY,
109 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
110 deadline_id INTEGER NOT NULL,
111 party_id INTEGER NOT NULL,
112 label TEXT NOT NULL,
113 party_name TEXT NOT NULL,
114 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of')),
115 due TEXT NOT NULL,
116 by_name TEXT NOT NULL,
117 subject TEXT NOT NULL DEFAULT '',
118 body TEXT NOT NULL DEFAULT '',
119 sent_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
120 UNIQUE (deadline_id, party_id, moment, due)
121 );
122 INSERT INTO reminder_kept (id, deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body, sent_at)
123 SELECT r.id, d.deal_id, r.deadline_id, r.party_id, d.label, p.name, r.moment, r.due, r.by_name, r.subject, r.body, r.sent_at
124 FROM reminder r JOIN deadline d ON d.id = r.deadline_id JOIN party p ON p.id = r.party_id;
125 DROP TABLE reminder;
126 ALTER TABLE reminder_kept RENAME TO reminder;
127 CREATE INDEX reminder_deal ON reminder (deal_id)`,
104128 ];
105129
106130 export function openDb(dir = dataDir): Database {
src/deals.test.ts +65
@@ -13,10 +13,13 @@ import {
1313 addParty,
1414 createDeal,
1515 deleteDeal,
16 editParty,
1617 getDeal,
1718 listDeals,
1819 markDone,
1920 moveDeadline,
21 removeDeadline,
22 removeParty,
2023 sendReminder,
2124 type DealView,
2225 } from "./deals.ts";
@@ -289,3 +292,65 @@ test("a field keeps no control characters, C1 included", () => {
289292 const deal = open({ address: "7 Oak\u009b31m Lane\u0007\u0085" });
290293 expect(deal.address).toBe("7 Oak 31m Lane");
291294 });
295
296 test("an edited contact shows in the next draft; a removed party gets none", () => {
297 const deal = open();
298 const lender = addParty(db, alice, { dealId: deal.id, role: "lender", name: "Lee Lender", contact: "[email protected]" });
299 if (!lender.ok) throw new Error(lender.message);
300 const draftFor = (d: DealView) =>
301 drafts(d, agent).find((r) => r.party_id === lender.value.id && r.deadline_id === due(d, "financing").id);
302 expect(draftFor(fresh(deal.id))?.contact).toBe("[email protected]");
303 const fixed = editParty(db, bob, { id: lender.value.id, name: "Lena Lender", contact: "[email protected]" });
304 expect(fixed.ok && fixed.value.role).toBe("lender");
305 const after = draftFor(fresh(deal.id));
306 expect(after?.contact).toBe("[email protected]");
307 expect(after?.party_name).toBe("Lena Lender");
308 expect(editParty(db, alice, { id: lender.value.id, name: "", contact: "" })).toMatchObject({ ok: false, error: "invalid" });
309 expect(editParty(db, alice, { id: lender.value.id, name: "L", contact: "x".repeat(121) })).toMatchObject({ ok: false, error: "invalid" });
310 expect(removeParty(db, alice, { id: lender.value.id }).ok).toBe(true);
311 expect(fresh(deal.id).parties.some((p) => p.id === lender.value.id)).toBe(false);
312 expect(draftFor(fresh(deal.id))).toBeUndefined();
313 expect(removeParty(db, alice, { id: lender.value.id })).toMatchObject({ ok: false, error: "not_found" });
314 });
315
316 test("a standard date cannot be removed; a custom one goes with its drafts, and a sent reminder stays", () => {
317 const deal = open();
318 const inspection = due(deal, "inspection");
319 expect(removeDeadline(db, alice, { id: inspection.id })).toMatchObject({ ok: false, error: "invalid" });
320 expect(due(fresh(deal.id), "inspection").id).toBe(inspection.id);
321 const hoa = addDeadline(db, alice, { dealId: deal.id, label: "HOA review", due: "2026-10-20", owes: "buyer" });
322 if (!hoa.ok) throw new Error(hoa.message);
323 const buyer = fresh(deal.id).parties.find((p) => p.role === "buyer")!;
324 const seller = fresh(deal.id).parties.find((p) => p.role === "seller")!;
325 expect(drafts(fresh(deal.id), agent).some((r) => r.deadline_id === hoa.value.id)).toBe(true);
326 expect(sendReminder(db, alice, { deadlineId: hoa.value.id, partyId: buyer.id, moment: "before" }).ok).toBe(true);
327 expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: seller.id, moment: "before" }).ok).toBe(true);
328 expect(removeDeadline(db, alice, { id: hoa.value.id, dealId: deal.id + 999 })).toMatchObject({ ok: false, error: "not_found" });
329 expect(removeDeadline(db, alice, { id: hoa.value.id, dealId: deal.id }).ok).toBe(true);
330 const after = fresh(deal.id);
331 expect(after.deadlines.some((d) => d.id === hoa.value.id)).toBe(false);
332 expect(drafts(after, agent).some((r) => r.deadline_id === hoa.value.id)).toBe(false);
333 // Sent reminders stay in the record, for the removed date and for the standard one.
334 expect(after.sent.map((r) => r.label).sort()).toEqual(["HOA review", "Inspection period ends"]);
335 // A removed party's sent reminder stays, named in words.
336 expect(removeParty(db, alice, { id: buyer.id }).ok).toBe(true);
337 expect(fresh(deal.id).sent.some((r) => r.party_name === "Ann Buyer")).toBe(true);
338 });
339
340 test("correcting and removing are updates of the deal: audited, and refused to a guest", () => {
341 const deal = open();
342 const party = deal.parties[0]!;
343 const hoa = addDeadline(db, alice, { dealId: deal.id, label: "HOA review", due: "2026-10-20", owes: "buyer" });
344 if (!hoa.ok) throw new Error(hoa.message);
345 expect(editParty(db, anon, { id: party.id, name: "X" })).toMatchObject({ ok: false, error: "signin_required" });
346 expect(removeParty(db, anon, { id: party.id })).toMatchObject({ ok: false, error: "signin_required" });
347 expect(removeDeadline(db, anon, { id: hoa.value.id })).toMatchObject({ ok: false, error: "signin_required" });
348 expect(fresh(deal.id).parties.length).toBe(2);
349 expect(fresh(deal.id).deadlines.some((d) => d.id === hoa.value.id)).toBe(true);
350 editParty(db, alice, { id: party.id, name: "Ann B." });
351 const rows = db
352 .query<{ verb: string; allowed: number; outcome: string }, []>("SELECT verb, allowed, outcome FROM audit WHERE resource = 'deal' ORDER BY id DESC LIMIT 4")
353 .all();
354 expect(rows[0]).toMatchObject({ verb: "update", allowed: 1, outcome: "ok" });
355 expect(rows.slice(1).map((r) => [r.verb, r.outcome])).toEqual([["update", "signin_required"], ["update", "signin_required"], ["update", "signin_required"]]);
356 });
src/deals.ts +104 −13
@@ -52,8 +52,12 @@ export interface Move {
5252 }
5353 export interface Sent {
5454 readonly id: number;
55 readonly deal_id: number;
5556 readonly deadline_id: number;
5657 readonly party_id: number;
58 /** The date's and the party's words when it was sent: they stay if either is removed. */
59 readonly label: string;
60 readonly party_name: string;
5761 readonly moment: Moment;
5862 readonly due: string;
5963 readonly by_name: string;
@@ -156,7 +160,7 @@ function view(db: Database, deal: Deal): DealView {
156160 })),
157161 sent: db
158162 .query<Sent, [number]>(
159 "SELECT r.* FROM reminder r JOIN deadline d ON d.id = r.deadline_id WHERE d.deal_id = ?1 ORDER BY r.id",
163 "SELECT * FROM reminder WHERE deal_id = ?1 ORDER BY id",
160164 )
161165 .all(deal.id),
162166 };
@@ -388,10 +392,13 @@ function deadlineFor(
388392 db: Database,
389393 who: Who,
390394 id: number,
395 scope?: number,
391396 ): { dealId?: number; found: Result<{ deal: Deal; deadline: Deadline }> } {
392 const deadline = Number.isInteger(id)
397 const row = Number.isInteger(id)
393398 ? db.query<Deadline, [number]>("SELECT * FROM deadline WHERE id = ?1").get(id)
394399 : null;
400 // A door that names the deal in its path means that deal's date or none.
401 const deadline = row !== null && (scope === undefined || row.deal_id === scope) ? row : null;
395402 const deal = dealFor(db, who, "update", deadline?.deal_id ?? Number.NaN);
396403 if (!deal.ok && (deal.error === "signin_required" || deal.error === "forbidden"))
397404 return { found: deal };
@@ -471,6 +478,16 @@ export function addDeadline(
471478 return within(db, who, dealId, ok(made));
472479 }
473480
481 /** A party's name and contact, checked: the same rules to add one and to correct one. */
482 function partyText(input: { name: unknown; contact?: unknown }): Result<{ name: string; contact: string }> {
483 const name = line(input.name, 1, 100);
484 if (name === undefined) return fail("invalid", "A name is 1 to 100 characters.");
485 const contact =
486 input.contact === undefined || input.contact === "" ? "" : line(input.contact, 1, 120);
487 if (contact === undefined) return fail("invalid", "A contact is up to 120 characters.");
488 return ok({ name, contact });
489 }
490
474491 export function addParty(
475492 db: Database,
476493 who: Who,
@@ -481,21 +498,95 @@ export function addParty(
481498 if (!deal.ok) return within(db, who, Number.isInteger(input.dealId) ? input.dealId : undefined, deal);
482499 if (!isPartyRole(input.role))
483500 return within(db, who, dealId, fail("invalid", "A party is a buyer, seller, lender, title company or the other agent."));
484 const name = line(input.name, 1, 100);
485 if (name === undefined)
486 return within(db, who, dealId, fail("invalid", "A name is 1 to 100 characters."));
487 const contact =
488 input.contact === undefined || input.contact === "" ? "" : line(input.contact, 1, 120);
489 if (contact === undefined)
490 return within(db, who, dealId, fail("invalid", "A contact is up to 120 characters."));
501 const text = partyText(input);
502 if (!text.ok) return within(db, who, dealId, text);
491503 const made = db
492504 .query<Party, [number, string, string, string]>(
493505 "INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4) RETURNING *",
494506 )
495 .get(deal.value.id, input.role, name, contact)!;
507 .get(deal.value.id, input.role, text.value.name, text.value.contact)!;
496508 return within(db, who, dealId, ok(made));
497509 }
498510
511 /** The party and its deal, when `who` may change the deal. */
512 function partyFor(
513 db: Database,
514 who: Who,
515 id: number,
516 scope?: number,
517 ): { dealId?: number; found: Result<{ deal: Deal; party: Party }> } {
518 const row = Number.isInteger(id)
519 ? db.query<Party, [number]>("SELECT * FROM party WHERE id = ?1").get(id)
520 : null;
521 const party = row !== null && (scope === undefined || row.deal_id === scope) ? row : null;
522 const deal = dealFor(db, who, "update", party?.deal_id ?? Number.NaN);
523 if (!deal.ok && (deal.error === "signin_required" || deal.error === "forbidden"))
524 return { found: deal };
525 if (party === null || !deal.ok)
526 return {
527 found: Number.isInteger(id)
528 ? fail("not_found", "No such party.")
529 : fail("invalid", "A party id is a whole number."),
530 };
531 return { dealId: deal.value.id, found: ok({ deal: deal.value, party }) };
532 }
533
534 /** Correct a party's name and contact. Their role stays: it decides which dates they are told about. */
535 export function editParty(
536 db: Database,
537 who: Who,
538 input: { id: number; dealId?: number; name: unknown; contact?: unknown },
539 ): Result<Party> {
540 const { dealId, found } = partyFor(db, who, input.id, input.dealId);
541 if (!found.ok) return within(db, who, dealId, found);
542 const text = partyText(input);
543 if (!text.ok) return within(db, who, dealId, text);
544 const made = db
545 .query<Party, [string, string, number]>(
546 "UPDATE party SET name = ?1, contact = ?2 WHERE id = ?3 RETURNING *",
547 )
548 .get(text.value.name, text.value.contact, input.id)!;
549 return within(db, who, dealId, ok(made));
550 }
551
552 /**
553 * Remove a party. Reminders are computed, so the ones not yet sent go with
554 * them; those already marked sent stay in the record, named in words.
555 */
556 export function removeParty(
557 db: Database,
558 who: Who,
559 input: { id: number; dealId?: number },
560 ): Result<{ id: number }> {
561 const { dealId, found } = partyFor(db, who, input.id, input.dealId);
562 if (!found.ok) return within(db, who, dealId, found);
563 db.query("DELETE FROM party WHERE id = ?1").run(input.id);
564 return within(db, who, dealId, ok({ id: input.id }));
565 }
566
567 /**
568 * Remove a date the contract dropped. Only custom dates go: the standard
569 * ones can be moved or marked done, never removed. Its unsent reminders go
570 * with it; reminders already sent stay in the record.
571 */
572 export function removeDeadline(
573 db: Database,
574 who: Who,
575 input: { id: number; dealId?: number },
576 ): Result<{ id: number }> {
577 const { dealId, found } = deadlineFor(db, who, input.id, input.dealId);
578 if (!found.ok) return within(db, who, dealId, found);
579 if (found.value.deadline.kind !== "custom")
580 return within(
581 db,
582 who,
583 dealId,
584 fail("invalid", "A standard contract date cannot be removed; move it or mark it done."),
585 );
586 db.query("DELETE FROM deadline WHERE id = ?1").run(input.id);
587 return within(db, who, dealId, ok({ id: input.id }));
588 }
589
499590 /**
500591 * Mark a reminder sent, with the words the agent approved: the subject and
501592 * body given, or — when neither is given — the draft as it stands. The words
@@ -531,10 +622,10 @@ export function sendReminder(
531622 if (body === undefined)
532623 return within(db, who, dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`));
533624 const sent = db
534 .query<Sent, [number, number, string, string, string, string, string]>(
535 `INSERT INTO reminder (deadline_id, party_id, moment, due, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
625 .query<Sent, [number, number, number, string, string, string, string, string, string, string]>(
626 `INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, moment, due, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
536627 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET sent_at = sent_at RETURNING *`,
537628 )
538 .get(deadline.id, party.id, input.moment, deadline.due, authorOf(who).name, subject, body)!;
629 .get(found.value.deal.id, deadline.id, party.id, deadline.label, party.name, input.moment, deadline.due, authorOf(who).name, subject, body)!;
539630 return within(db, who, dealId, ok(sent));
540631 }
src/pages/deal.ts +16 −2
@@ -5,7 +5,7 @@
55 */
66
77 import { addDays, relative, spoken } from "../dates.ts";
8 import { canChange, canRemove, type DealView } from "../deals.ts";
8 import { canChange, canRemove, type DealView, type Party } from "../deals.ts";
99 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1010 import { escape } from "../http.ts";
1111 import type { Who } from "../who.ts";
@@ -17,6 +17,20 @@ const roleOptions = (selected?: string): string =>
1717 (r) => `<option value="${r}"${r === selected ? " selected" : ""}>${escape(PARTY_LABEL[r])}</option>`,
1818 ).join("");
1919
20 /** Correct a party or remove them: a plain form each, back to this page. */
21 const partyControls = (p: Party, to: string): string => `<div class="party-controls">
22 <details class="party-edit">
23 <summary class="button button-quiet button-small">Edit</summary>
24 <form class="stack" method="post" action="/parties/${p.id}/edit">
25 <input type="hidden" name="to" value="${escape(to)}">
26 <label>Name<input class="input" name="name" required maxlength="100" value="${escape(p.name)}"></label>
27 <label>Email or phone <span class="muted">(optional)</span><input class="input" name="contact" maxlength="120" value="${escape(p.contact)}"></label>
28 <button class="button">Save</button>
29 </form>
30 </details>
31 <form method="post" action="/parties/${p.id}/remove"><input type="hidden" name="to" value="${escape(to)}"><button class="button button-quiet button-small" aria-label="Remove ${escape(p.name)}">Remove</button></form>
32 </div>`;
33
2034 export function dealPage(input: {
2135 who: Who;
2236 deal: DealView;
@@ -44,7 +58,7 @@ export function dealPage(input: {
4458 : `<ul class="parties">${deal.parties
4559 .map(
4660 (p) =>
47 `<li><span class="muted">${escape(PARTY_LABEL[p.role])}</span><b>${escape(p.name)}</b>${p.contact === "" ? "" : `<span class="mono">${escape(p.contact)}</span>`}</li>`,
61 `<li><span class="muted">${escape(PARTY_LABEL[p.role])}</span><b>${escape(p.name)}</b>${p.contact === "" ? "" : `<span class="mono">${escape(p.contact)}</span>`}${may ? partyControls(p, path) : ""}</li>`,
4862 )
4963 .join("")}</ul>`;
5064 const forms = may
src/pages/sheet.ts +8
@@ -115,6 +115,14 @@ export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to:
115115 <button class="button button-quiet">Move this date</button>
116116 </form>
117117 <p class="muted small">Moving a date moves nothing else; the reason is kept.</p>
118 ${
119 d.kind === "custom"
120 ? `<form method="post" action="/deadlines/${d.id}/remove">${hidden({ to: `/deals/${deal.id}` })}
121 <button class="button button-quiet">Remove this date</button>
122 </form>
123 <p class="muted small">For a date the contract dropped. Its unsent reminders go too; ones already sent stay on record.</p>`
124 : ""
125 }
118126 </section>`
119127 : `<p class="muted"><a href="/__forge/signin?to=${encodeURIComponent(to)}">Sign in</a> to mark it done, move it, or send reminders.</p>`;
120128 return `<div popover id="${id}" class="sheet" aria-labelledby="${id}-h">
src/routes.ts +75 −4
@@ -38,12 +38,15 @@ import { today } from "./dates.ts";
3838 import {
3939 addDeadline,
4040 addParty,
41 editParty,
4142 createDeal,
4243 deleteDeal,
4344 getDeal,
4445 listDeals,
4546 markDone,
4647 moveDeadline,
48 removeDeadline,
49 removeParty,
4750 sendReminder,
4851 updateDeal,
4952 type NewDeal,
@@ -106,6 +109,10 @@ export const AUDIT_ROW: Schema = {
106109 };
107110 const DATE: Schema = { type: "string", format: "date" };
108111 const ROLE: Schema = { enum: ["buyer", "seller", "lender", "title", "other_agent"] };
112 const PARTY: Schema = {
113 type: "object",
114 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, contact: { type: "string" } },
115 };
109116 export const DEAL: Schema = {
110117 type: "object",
111118 properties: {
@@ -119,10 +126,7 @@ export const DEAL: Schema = {
119126 created_at: { type: "string", format: "date-time" },
120127 parties: {
121128 type: "array",
122 items: {
123 type: "object",
124 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, contact: { type: "string" } },
125 },
129 items: PARTY,
126130 },
127131 deadlines: {
128132 type: "array",
@@ -394,6 +398,33 @@ export const routes: readonly Route[] = [
394398 return done(moveDeadline(c.db, c.who, { id: Number(c.params.id), due: f.due, reason: f.reason }), backTo(f.to), "Date moved; nothing else did.");
395399 },
396400 },
401 {
402 method: "POST",
403 path: "/deadlines/:id/remove",
404 handle: async (c) => {
405 const f = await form(c);
406 if (f instanceof Response) return f;
407 return done(removeDeadline(c.db, c.who, { id: Number(c.params.id) }), backTo(f.to), "Date removed.");
408 },
409 },
410 {
411 method: "POST",
412 path: "/parties/:id/edit",
413 handle: async (c) => {
414 const f = await form(c);
415 if (f instanceof Response) return f;
416 return done(editParty(c.db, c.who, { id: Number(c.params.id), name: f.name, contact: f.contact }), backTo(f.to), "Party corrected.");
417 },
418 },
419 {
420 method: "POST",
421 path: "/parties/:id/remove",
422 handle: async (c) => {
423 const f = await form(c);
424 if (f instanceof Response) return f;
425 return done(removeParty(c.db, c.who, { id: Number(c.params.id) }), backTo(f.to), "Party removed.");
426 },
427 },
397428 {
398429 method: "POST",
399430 path: "/reminders",
@@ -470,6 +501,46 @@ export const routes: readonly Route[] = [
470501 answer: DEAL,
471502 },
472503 },
504 {
505 method: "PATCH",
506 path: "/api/deals/:id/parties/:party",
507 handle: async (c) => {
508 const body = await readJson(c.request);
509 if (body === undefined) return json({ error: "too_large" }, 413);
510 const f = fields(body);
511 return answer(
512 editParty(c.db, c.who, { id: Number(c.params.party), dealId: Number(c.params.id), name: f.name, contact: f.contact }),
513 );
514 },
515 api: {
516 summary: "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
517 body: {
518 type: "object",
519 properties: { name: { type: "string", minLength: 1, maxLength: 100 }, contact: { type: "string", maxLength: 120 } },
520 required: ["name"],
521 },
522 answer: PARTY,
523 },
524 },
525 {
526 method: "DELETE",
527 path: "/api/deals/:id/parties/:party",
528 handle: (c) => answer(removeParty(c.db, c.who, { id: Number(c.params.party), dealId: Number(c.params.id) })),
529 api: {
530 summary: "Remove a party and the reminders not yet sent to them; reminders already sent stay in the record.",
531 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
532 },
533 },
534 {
535 method: "DELETE",
536 path: "/api/deals/:id/deadlines/:deadline",
537 handle: (c) => answer(removeDeadline(c.db, c.who, { id: Number(c.params.deadline), dealId: Number(c.params.id) })),
538 api: {
539 summary:
540 "Remove a custom date the contract dropped, and its unsent reminders. A standard contract date is refused (422): move it or mark it done.",
541 answer: { type: "object", properties: { id: { type: "integer" } }, required: ["id"] },
542 },
543 },
473544 {
474545 method: "DELETE",
475546 path: "/api/deals/:id",
src/sample.ts +1 −1
@@ -163,7 +163,7 @@ export function refresh(db: Database, on = today()): void {
163163 "SELECT count(*) AS n FROM party WHERE deal_id = ?1 AND role NOT IN ('buyer', 'seller')",
164164 ).get(deal.id)!.n;
165165 const reminders = db.query<{ n: number }, [number]>(
166 "SELECT count(*) AS n FROM reminder r JOIN deadline d ON d.id = r.deadline_id WHERE d.deal_id = ?1",
166 "SELECT count(*) AS n FROM reminder WHERE deal_id = ?1",
167167 ).get(deal.id)!.n;
168168 const state: SampleState = {
169169 address: deal.address,
src/security.ts +4 −1
@@ -96,6 +96,9 @@ export function doorOf(
9696 const verb = ROW_VERB[method];
9797 return verb === undefined ? undefined : { resource, verb };
9898 }
99 // `<api>/:id/<children>/:child`: a change inside the row is an update of it.
100 if (rest !== undefined && /^[^/]+\/[^/]+\/[^/]+$/.test(rest))
101 return method === "PATCH" || method === "DELETE" ? { resource, verb: "update" } : undefined;
99102 }
100103 return undefined;
101104 }
@@ -180,7 +183,7 @@ export function door(
180183 target:
181184 url.pathname === contract.resources[found.resource]?.api
182185 ? undefined
183 : url.pathname.split("/").at(-1),
186 : url.pathname.slice(contract.resources[found.resource]!.api!.length + 1).split("/")[0],
184187 outcome,
185188 });
186189 return stranger
src/server.test.ts +36
@@ -572,3 +572,39 @@ test("the page offers an unsent draft as an edit form, and shows a sent one as i
572572 expect(after).toContain("Sent &lt;script&gt;x&lt;/script&gt; body");
573573 expect(after).not.toContain("<script>x</script>");
574574 });
575
576 // Last: it opens a deal that closes after every other, which the tests above take as the latest.
577 const mia = as("u10", "mia");
578 test("a party is corrected and removed from the page and the API; a custom date goes, a standard one is refused", async () => {
579 const made = await api("/api/deals", { method: "POST", ...jsonBody({ address: "5 Fix It Way", buyer: "Bo Buyer", seller: "Su Seller", contract_date: "2027-03-01", closing_date: "2027-04-05" }) }, mia);
580 const deal = (await made.json()) as { id: number; deadlines: { id: number; kind: string }[]; parties: { id: number }[] };
581 const buyer = deal.parties[0]!.id;
582 const page = await (await api(`/deals/${deal.id}`, {}, alice)).text();
583 expect(page).toContain(`action="/parties/${buyer}/edit"`);
584 expect(page).toContain(`action="/parties/${buyer}/remove"`);
585 expect(await (await fetch(`${base}/deals/${deal.id}`)).text()).not.toContain(`/parties/${buyer}/edit`);
586 const post = (path: string, fields: Record<string, string>, who = mia) => {
587 const body = new FormData();
588 for (const [k, v] of Object.entries(fields)) body.set(k, v);
589 return api(path, { method: "POST", body, redirect: "manual" }, who);
590 };
591 const edited = await post(`/parties/${buyer}/edit`, { name: "Bo B.", contact: "[email protected]", to: `/deals/${deal.id}` });
592 expect(edited.headers.get("location")).toBe(`/deals/${deal.id}`);
593 const patched = await api(`/api/deals/${deal.id}/parties/${buyer}`, { method: "PATCH", ...jsonBody({ name: "Bo Buyer", contact: "[email protected]" }) }, mia);
594 expect(await patched.json()).toMatchObject({ id: buyer, name: "Bo Buyer", contact: "[email protected]" });
595 expect((await api(`/api/deals/${deal.id}/parties/${buyer}`, { method: "PATCH", ...jsonBody({ name: "" }) }, mia)).status).toBe(422);
596 expect((await api(`/api/deals/${deal.id}/parties/${buyer}`, { method: "DELETE" })).status).toBe(401);
597 // The deal named in the path is the deal the party must be on.
598 expect((await api(`/api/deals/${deal.id + 1}/parties/${buyer}`, { method: "DELETE" }, mia)).status).toBe(404);
599 expect((await api(`/api/deals/${deal.id}/parties/${buyer}`, { method: "DELETE" }, mia)).status).toBe(200);
600 const standard = deal.deadlines.find((d) => d.kind === "inspection")!;
601 const refused = await api(`/api/deals/${deal.id}/deadlines/${standard.id}`, { method: "DELETE" }, mia);
602 expect(refused.status).toBe(422);
603 await post(`/deals/${deal.id}/deadlines`, { label: "HOA review", due: "2027-03-20", owes: "buyer", to: "/" });
604 const now = (await (await api(`/api/deals/${deal.id}`, {}, alice)).json()) as typeof deal & { parties: { id: number }[] };
605 const hoa = now.deadlines.find((d) => d.kind === "custom")!;
606 expect(now.parties.some((p) => p.id === buyer)).toBe(false);
607 expect(await (await api(`/deals/${deal.id}`, {}, alice)).text()).toContain(`action="/deadlines/${hoa.id}/remove"`);
608 expect((await post(`/deadlines/${hoa.id}/remove`, { to: `/deals/${deal.id}` })).status).toBe(303);
609 expect((await api(`/api/deals/${deal.id}/deadlines/${hoa.id}`, { method: "DELETE" }, mia)).status).toBe(404);
610 });
src/terminal.test.ts +45 −1
@@ -7,7 +7,7 @@ import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { addDays, today } from "./dates.ts";
10 import { createDeal, getDeal, listDeals, type DealView } from "./deals.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, type DealView } from "./deals.ts";
1111 import { openDb } from "./db.ts";
1212 import { terminal, type Terminal } from "./terminal.ts";
1313 import type { Who } from "./who.ts";
@@ -174,3 +174,47 @@ test("a guest sees no deals, and is asked to sign in before anything — n inclu
174174 t.press("rdq");
175175 expect(t.done).toBe(true);
176176 });
177
178 test("e edits the party under the cursor; X removes a party or a custom date after yes", () => {
179 const own = createDeal(db, alice, {
180 address: "7 Cedar Ct",
181 buyer: "Bea Buyer",
182 seller: "Sid Seller",
183 contractDate: today(),
184 closingDate: addDays(today(), 30),
185 });
186 if (!own.ok) throw new Error(own.message);
187 const lender = addParty(db, alice, { dealId: own.value.id, role: "lender", name: "Lee Lender", contact: "[email protected]" });
188 const hoa = addDeadline(db, alice, { dealId: own.value.id, label: "HOA review", due: addDays(today(), 9), owes: "buyer" });
189 if (!lender.ok || !hoa.ok) throw new Error("setup");
190 const read = () => {
191 const got = getDeal(db, alice, { id: own.value.id });
192 if (!got.ok) throw new Error(got.message);
193 return got.value;
194 };
195 const t = terminal(db, alice, context);
196 goTo(t, "Closing — 7 Cedar Ct");
197 t.press("o");
198 // On a date, e has no party to edit; the dates come first, then the parties.
199 t.press("e");
200 expect(lines(t).join("\n")).toContain("Move to a party");
201 const rows = read().deadlines.length;
202 for (let i = 0; i < rows + 2; i++) t.press("j");
203 expect(under(t)).toContain("Lee Lender");
204 press(t, "e", "Lee Lender\r", "[email protected]\r");
205 expect(read().parties.find((p) => p.id === lender.value.id)?.contact).toBe("[email protected]");
206 expect(under(t)).toContain("[email protected]");
207 // X asks first; anything but yes keeps it.
208 press(t, "X", "no\r");
209 expect(read().parties.length).toBe(3);
210 press(t, "X", "yes\r");
211 expect(read().parties.some((p) => p.id === lender.value.id)).toBe(false);
212 expect(lines(t).join("\n")).toContain("Removed Lee Lender.");
213 // On a standard date X is the named failure; on a custom one it removes it.
214 for (let i = 0; i < 20 && !under(t).includes("Inspection"); i++) t.press("k");
215 press(t, "X", "yes\r");
216 expect(lines(t).join("\n")).toContain("cannot be removed");
217 for (let i = 0; i < 20 && !under(t).includes("HOA review"); i++) t.press("k");
218 press(t, "X", "yes\r");
219 expect(read().deadlines.some((d) => d.id === hoa.value.id)).toBe(false);
220 });
src/terminal.ts +38 −5
@@ -18,6 +18,7 @@ import { isDate, relative, spoken, today, urgency, type Urgency } from "./dates.
1818 import {
1919 addDeadline,
2020 addParty,
21 editParty,
2122 BODY_MAX,
2223 canChange,
2324 createDeal,
@@ -27,6 +28,8 @@ import {
2728 markDone,
2829 mayOpen,
2930 moveDeadline,
31 removeDeadline,
32 removeParty,
3033 sendReminder,
3134 type DealView,
3235 type DeadlineView,
@@ -113,7 +116,13 @@ export function terminal(
113116 const editKey = (d: Draft): string => `${d.deadline_id}:${d.party_id}:${d.moment}`;
114117 /** The draft with any words typed for it; a sent one is as it went. */
115118 const edited = (d: Draft): Draft => (d.sent_at === null ? { ...d, ...edits.get(editKey(d)) } : d);
116 const rowCount = (): number => (view === "reminders" ? reminderRows().length : dateRows().length);
119 // On a deal the cursor walks its dates, then its parties.
120 const rowCount = (): number =>
121 view === "reminders"
122 ? reminderRows().length
123 : view === "deal"
124 ? dateRows().length + (openDeal()?.parties.length ?? 0)
125 : dateRows().length;
117126
118127 const report = <T>(result: Result<T>, success: string): string => (result.ok ? success : result.message);
119128 /** Only someone who may work the deal is asked to type anything. */
@@ -149,7 +158,28 @@ export function terminal(
149158
150159 function onDeal(key: string): boolean {
151160 const deal = openDeal();
152 if (deal === undefined || !["a", "p", "D"].includes(key)) return false;
161 if (deal === undefined || !["a", "p", "D", "e", "X"].includes(key)) return false;
162 const party = deal.parties[cursor - deal.deadlines.length];
163 const date = deal.deadlines[cursor];
164 if (key === "e") {
165 if (party === undefined) said = "Move to a party to edit it.";
166 else
167 ask(deal, [`Name (now ${party.name})`, `Email or phone (now ${party.contact === "" ? "none" : party.contact}; blank clears)`], ([name, contact]) =>
168 report(editParty(db, me, { id: party.id, name, contact }), `Corrected ${name}.`),
169 );
170 }
171 if (key === "X") {
172 const target = party ?? date;
173 if (target === undefined) said = "Nothing here to remove.";
174 else
175 ask(deal, [`Type yes to remove ${party === undefined ? date!.label : party.name}`], ([yes]) => {
176 if (yes !== "yes") return "Kept.";
177 return report(
178 party === undefined ? removeDeadline(db, me, { id: date!.id }) : removeParty(db, me, { id: party.id }),
179 `Removed ${party === undefined ? date!.label : party.name}.`,
180 );
181 });
182 }
153183 if (key === "a")
154184 ask(deal, ["What is the date (e.g. HOA review ends)", "Date (YYYY-MM-DD)", `Owed by (${PARTY_ROLES.join(", ")})`, "Details (optional)"], ([label, due, owes, what]) =>
155185 report(addDeadline(db, me, { dealId: deal.id, label, due, owes, what }), `Added ${label}.`),
@@ -238,6 +268,7 @@ export function terminal(
238268 if (p.answers.length === p.steps.length) {
239269 prompt = undefined;
240270 said = p.finish(p.answers);
271 cursor = Math.min(cursor, Math.max(0, rowCount() - 1));
241272 return;
242273 }
243274 } else if (ch >= " " && p.text.length < (p.max ?? 200)) p.text += ch;
@@ -323,8 +354,10 @@ export function terminal(
323354 lines.push(bold(deal.address), dim(`under contract ${spoken(deal.contract_date)} · closes ${spoken(deal.closing)}, ${relative(deal.closing, day)}`), "");
324355 deal.deadlines.forEach((date, i) => lines.push(dateLine({ deal, date }, i, false)));
325356 lines.push("", bold("Parties"));
326 for (const p of deal.parties)
327 lines.push(` ${PARTY_LABEL[p.role].padEnd(14)} ${p.name}${p.contact === "" ? "" : dim(` ${p.contact}`)}`);
357 deal.parties.forEach((p, i) => {
358 const at = deal.deadlines.length + i === cursor;
359 lines.push(`${at ? "▸" : " "} ${PARTY_LABEL[p.role].padEnd(14)} ${at ? bold(p.name) : p.name}${p.contact === "" ? "" : dim(` ${p.contact}`)}`);
360 });
328361 }
329362 } else {
330363 const rows = reminderRows();
@@ -348,7 +381,7 @@ export function terminal(
348381 view === "reminders"
349382 ? "j/k move · enter read · e edit · s send · d dates · q quit"
350383 : view === "deal"
351 ? "j/k move · x done · u reopen · m move · a add date · p add party · D remove · b back · q quit"
384 ? "j/k move · x done · u reopen · m move · a add date · p add party · e edit party · X remove date/party · D remove deal · b back · q quit"
352385 : `j/k move · x done · u reopen · m move · o open deal · n new deal · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;
353386 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
354387 }
static/app.css +23
@@ -636,6 +636,29 @@ footer code {
636636 grid-column: 2;
637637 overflow-wrap: anywhere;
638638 }
639 .party-controls {
640 grid-column: 1 / -1;
641 display: flex;
642 flex-wrap: wrap;
643 align-items: flex-start;
644 gap: var(--space-2);
645 }
646 .party-edit[open] {
647 flex: 1 1 100%;
648 }
649 .party-edit summary {
650 list-style: none;
651 width: max-content;
652 }
653 .party-edit summary::-webkit-details-marker {
654 display: none;
655 }
656 .party-edit[open] summary {
657 margin-bottom: var(--space-2);
658 }
659 .party-controls > form {
660 order: 1;
661 }
639662 .stack {
640663 display: grid;
641664 gap: var(--space-3);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs