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

Adding a party to a deal offers the people already on the agent's other deals, so a lender or title officer used before is picked, not retyped #128

Merged opened this

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

Merged

mason/deal-clock:mason/124-adding-a-party-to-a-deal-offers-the-peop → main 3 commits fork 4 threads · 4 unresolved

  • Merged. mason/124-adding-a-party-to-a-deal-offers-the-peop was merged into main as 91e82f9.

Review

Sign in to review this change.
6 files changed +246 −5
README.md +2
@@ -25,6 +25,8 @@ meeting (with Find on, only the matching deals); press Print or your
2525 browser's print. In the terminal, press w
2626 for the same list; over MCP, an agent asks for the `this_week` tool.
2727
28 Adding a party on a deal's page offers **Use someone from your other deals**: tap Use beside a lender from another sample deal and the form fills with their name, role, email and phone, which you can still change before Add party.
29
2830 Before calling a lender or an inspector, open **People** in the header: each
2931 person on your deals appears once, with every open date they owe across all
3032 deals, soonest first (try Priya Nair, who works both 1418 Alder Lane and 9 Orchard
src/deals.ts +14
@@ -412,6 +412,20 @@ export function listDeals(db: Database, who: Who): Result<DealView[]> {
412412 );
413413 }
414414
415 /** Every party of every deal `who` may list, oldest first: the light read behind the add-party choice. */
416 export function listParties(db: Database, who: Who): Result<Party[]> {
417 const may = permit(who, "deal", "list");
418 if (may === "no") return refuse(who, "Sign in to see deals.", "You may not see these deals.");
419 const base = "SELECT party.* FROM party JOIN deal ON deal.id = party.deal_id";
420 return ok(
421 may === "yes"
422 ? db.query<Party, []>(`${base} ORDER BY party.id`).all()
423 : db
424 .query<Party, [string]>(`${base} WHERE ${may.where.map((c) => `deal.${c} = ?1`).join(" OR ")} ORDER BY party.id`)
425 .all(who.role === "anon" ? "" : who.id),
426 );
427 }
428
415429 /**
416430 * One deal, for `who` to do `verb` to. The table is asked before the row is
417431 * looked for, so whoever may not learns nothing about what exists.
src/known.test.ts added +133
@@ -0,0 +1,133 @@
1 /** The add-party form offers people from the agent's other deals, once each, escaped, and picking one prefills it. */
2 import { afterAll, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { escape } from "./http.ts";
7 import { knownPeople, matchKnown } from "./people.ts";
8 import type { Party } from "./deals.ts";
9 import { forgetRationing } from "./security.ts";
10 import { serve } from "./server.ts";
11 import { sign } from "./who.ts";
12
13 const KEY = "a-key-only-the-forge-holds";
14 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-known-")), identityKey: KEY });
15 const base = `http://${server.hostname}:${server.port}`;
16 afterAll(() => server.stop(true));
17
18 const identity = `u1|alice|user|${Date.now() + 600_000}`;
19 const alice = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
20 type Deal = { id: number; address: string; parties: { name: string; role: string; email: string; phone: string }[] };
21 const deals = async (): Promise<Deal[]> => (await fetch(`${base}/api/deals`, { headers: alice })).json() as Promise<Deal[]>;
22 const page = async (id: number, q = ""): Promise<string> => (await fetch(`${base}/deals/${id}${q}`, { headers: alice })).text();
23
24 test("a person from another deal is offered; one already on this deal is not", async () => {
25 const all = await deals();
26 const alder = all.find((d) => d.address === "1418 Alder Lane")!;
27 const priya = alder.parties.find((p) => p.email !== "" && p.role === "lender")!;
28 const other = all.find((d) => d.id !== alder.id && !d.parties.some((p) => p.email === priya.email))!;
29 const offered = await page(other.id);
30 expect(offered).toContain("Use someone from your other deals");
31 expect(offered).toContain(`href="/deals/${other.id}?use=${encodeURIComponent(priya.email.toLowerCase())}#add-party"`);
32 const here = await page(alder.id);
33 expect(here).not.toContain(`?use=${encodeURIComponent(priya.email.toLowerCase())}`);
34 });
35
36 test("using a person prefills the form, and adding creates a party with their email and phone", async () => {
37 forgetRationing();
38 const all = await deals();
outdated

The assertion uses the raw who.name in value="..." without escape(); it passes only because the sample names have no special characters. Compare against the escaped form. Also assert the prefilled role option is selected, since box 2 promises the most recent role.

39 const from = all.find((d) => d.parties.some((p) => p.email !== "" && p.phone !== ""))!;
40 const who = from.parties.find((p) => p.email !== "" && p.phone !== "")!;
41 const to = all.find((d) => d.id !== from.id && !d.parties.some((p) => p.email === who.email))!;
42 const html = await page(to.id, `?use=${encodeURIComponent(who.email.toLowerCase())}`);
43 expect(html).toContain(`name="name" required maxlength="100" value="${escape(who.name)}"`);
44 expect(html).toContain(`<option value="${who.role}" selected>`);
45 expect(html).toContain(`value="${who.email}"`);
46 expect(html).toContain(`value="${who.phone}"`);
47 const body = new FormData();
48 body.set("role", who.role);
49 body.set("name", who.name);
50 body.set("email", who.email);
51 body.set("phone", who.phone);
52 const posted = await fetch(`${base}/deals/${to.id}/parties`, { method: "POST", body, headers: alice, redirect: "manual" });
53 expect(posted.status).toBe(303);
54 const after = (await deals()).find((d) => d.id === to.id)!;
55 expect(after.parties.some((p) => p.email === who.email && p.phone === who.phone)).toBe(true);
56 expect(await page(to.id)).not.toContain(`?use=${encodeURIComponent(who.email.toLowerCase())}`);
57 });
58
59 test("a name containing a script tag is escaped in the choice", async () => {
60 forgetRationing();
61 const all = await deals();
62 const [a, b] = all;
63 const body = new FormData();
64 body.set("role", "lender");
65 body.set("name", "<script>alert(1)</script>");
66 body.set("email", "[email protected]");
67 body.set("phone", "");
68 const posted = await fetch(`${base}/deals/${a!.id}/parties`, { method: "POST", body, headers: alice, redirect: "manual" });
69 expect(posted.status).toBe(303);
70 const html = await page(b!.id, "?use=evil%40x.example");
71 expect(html).not.toContain("<script>alert(1)");
72 expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
73 });
74
75 test("Find reaches a person the cap would hide, and says how many are shown", async () => {
76 forgetRationing();
77 const [a, b] = await deals();
78 for (let i = 0; i < 35; i++) {
79 forgetRationing();
80 const body = new FormData();
81 body.set("role", "title");
82 body.set("name", `Closer ${i}`);
83 body.set("email", `closer${i}@t.example`);
84 await fetch(`${base}/deals/${a!.id}/parties`, { method: "POST", body, headers: alice, redirect: "manual" });
85 }
86 const all = await page(b!.id);
87 expect(all).toContain("Showing 30 of");
88 expect(all).not.toContain("closer0%40t.example");
89 const found = await page(b!.id, "?find=closer0%40T.EX");
90 expect(found).toContain("?use=closer0%40t.example");
91 expect(found).not.toContain("Showing");
92 });
93
94 let n = 0;
95 const row = (deal_id: number, role: Party["role"], name: string, email: string, phone: string): Party => ({ id: ++n, deal_id, role, name, contact: email || phone, email, phone });
96
97 test("knownPeople: rows sharing only a phone are one person", () => {
98 const got = knownPeople([row(1, "lender", "Pri", "", "555-0100"), row(2, "lender", "Priya", "[email protected]", "555-0100")], 3);
99 expect(got).toHaveLength(1);
100 expect(got[0]).toMatchObject({ name: "Priya", email: "[email protected]", phone: "555-0100" });
101 });
102
103 test("knownPeople: the newest row gives the role, roles lists every one held", () => {
104 const got = knownPeople([row(1, "lender", "Sam", "[email protected]", ""), row(2, "title", "Sam", "[email protected]", "")], 3);
105 expect(got[0]!.role).toBe("title");
106 expect(got[0]!.roles).toEqual(["Lender", "Title company"]);
107 });
108
109 test("knownPeople: an older row fills the contact the newest lacks", () => {
110 const got = knownPeople([row(1, "lender", "Lee", "[email protected]", "555-0111"), row(2, "lender", "Lee", "[email protected]", "")], 3);
111 expect(got[0]).toMatchObject({ email: "[email protected]", phone: "555-0111" });
112 });
113
114 test("knownPeople: when two rows for one person differ, the newer email and phone win", () => {
115 const byPhone = knownPeople([row(1, "lender", "Lee", "[email protected]", "555-0133"), row(2, "title", "Lee", "[email protected]", "555-0133")], 3);
116 expect(byPhone).toHaveLength(1);
117 expect(byPhone[0]).toMatchObject({ email: "[email protected]", phone: "555-0133", roles: ["Lender", "Title company"] });
118 const byEmail = knownPeople([row(1, "lender", "Lee", "[email protected]", "555-0144"), row(2, "lender", "Lee", "[email protected]", "555-0155")], 3);
119 expect(byEmail[0]).toMatchObject({ phone: "555-0155" });
120 });
121
122 test("knownPeople: someone on this deal by phone alone is left out", () => {
123 const got = knownPeople([row(1, "lender", "Kay", "[email protected]", "555-0122"), row(2, "lender", "Kay", "", "555-0122"), row(1, "buyer", "Other", "[email protected]", "")], 2);
124 expect(got.map((k) => k.name)).toEqual(["Other"]);
125 });
126
127 test("matchKnown looks at name, roles, email and phone, ignoring case", () => {
128 const k = knownPeople([row(1, "lender", "Priya", "[email protected]", "555-0100")], 2);
129 expect(matchKnown(k, "PRIYA")).toHaveLength(1);
130 expect(matchKnown(k, "lender")).toHaveLength(1);
131 expect(matchKnown(k, "0100")).toHaveLength(1);
132 expect(matchKnown(k, "nobody")).toHaveLength(0);
133 });
src/pages/deal.ts +35 −2
@@ -6,6 +6,7 @@
66
77 import { addDays, relative, short, spoken } from "../dates.ts";
88 import { canChange, canRemove, closedOn, EMAIL_MAX, fellOn, PHONE_MAX, REASON_MAX, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
9 import { matchKnown, type Known } from "../people.ts";
910 import { agent as defaults, standard } from "../env.ts";
1011 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1112 import { escape } from "../http.ts";
@@ -24,6 +25,9 @@ const roleOptions = (selected?: string): string =>
2425 (r) => `<option value="${r}"${r === selected ? " selected" : ""}>${escape(PARTY_LABEL[r])}</option>`,
2526 ).join("");
2627
28 /** The most people the add-party form lists at once; Find reaches the rest. */
29 const KNOWN_SHOWN = 30;

KNOWN_SHOWN = 30 silently hides the older people, with no search and no 'more' link. With a real book (200 deals) a lender used long ago cannot be picked, which defeats 'picked, not retyped' and 'one per person'. Fix: drop the cap, or keep it and add a no-JS GET filter (?find=text matching name/role/contact, rendered server-side) so anyone is reachable. Keep the 200-deal speed test green.

30
2731 const count = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
2832
2933 /** A party form refused: whose it was (a party's id, or "new"), what was typed and why it was refused. */
@@ -156,6 +160,11 @@ export function dealPage(input: {
156160 figures?: FiguresProblem | undefined;
157161 /** A party added or corrected and refused: what was typed and why, so the form keeps it. */
158162 party?: PartyProblem | undefined;
163 /** People from other deals the add-party form offers, and the one picked to prefill it. */
164 known?: readonly Known[] | undefined;
165 /** What the agent typed to narrow the choice. */
166 find?: string | undefined;
167 use?: Known | undefined;
159168 }): string {
160169 const { who, agent, deal, on, notice, problem } = input;
161170 const opened = input.open === undefined ? undefined : deal.sent.find((m) => m.id === input.open);
@@ -195,7 +204,30 @@ export function dealPage(input: {
195204 </li>`,
196205 )
197206 .join("");
198 const add = input.party?.id === "new" ? input.party : undefined;
207 const refused = input.party?.id === "new" ? input.party : undefined;
208 const use = input.use;
209 const add = refused ?? (use === undefined ? undefined : { role: use.role as string, name: use.name, email: use.email, phone: use.phone, message: undefined });
210 const find = input.find ?? "";
211 const matching = matchKnown(input.known ?? [], find);
212 const known = matching.slice(0, KNOWN_SHOWN);
213 const pick =
214 (input.known ?? []).length === 0
215 ? ""
216 : `<details class="party-edit"${use === undefined && find === "" ? "" : " open"}>
217 <summary class="button button-quiet button-small">Use someone from your other deals</summary>
218 <form class="stack" method="get" action="${path}#add-party" role="search">
219 <label>Find <span class="muted">(name, role, email or phone)</span><input class="input" type="search" name="find" maxlength="100" autocomplete="off" value="${escape(find)}"></label>
220 <button class="button button-quiet">Find</button>
221 </form>
222 ${known.length === 0 ? `<p class="muted">Nobody on your other deals matches.</p>` : ""}
223 <ul class="parties">${known
224 .map(
225 (k) =>
226 `<li><span class="muted">${escape(k.roles.join(", "))}</span><b>${escape(k.name)}</b>${[k.email, k.phone].filter((v) => v !== "").map((v) => `<span class="mono">${escape(v)}</span>`).join("")}<a class="button button-quiet button-small" href="${path}?use=${encodeURIComponent(k.key)}#add-party" rel="nofollow">Use</a></li>`,
227 )
228 .join("")}</ul>
229 ${matching.length > known.length ? `<p class="muted small">Showing ${known.length} of ${matching.length}; type part of a name above to find the rest.</p>` : ""}
230 </details>`;
199231 const parties =
200232 deal.parties.length === 0
201233 ? `<p class="muted">No parties yet.</p>`
@@ -220,7 +252,8 @@ export function dealPage(input: {
220252 </form>
221253 </section>
222254 <section class="card">
223 <h2>Add a party</h2>
255 <h2 id="add-party">Add a party</h2>
256 ${pick}
224257 <form class="stack" method="post" action="${path}/parties">
225258 <div class="pair">
226259 <label>Role<select class="input" name="role">${roleOptions(add?.role ?? "lender")}</select></label>
src/people.ts +54 −1
@@ -5,7 +5,7 @@
55 */
66
77 import { urgency, type Urgency } from "./dates.ts";
8 import type { DealView } from "./deals.ts";
8 import type { DealView, Party } from "./deals.ts";
99 import { isOpen, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
1010
1111 export interface Owed {
@@ -107,3 +107,56 @@ export function people(deals: readonly DealView[], on: string): Person[] {
107107 return (a.owes[0]?.due ?? "").localeCompare(b.owes[0]?.due ?? "") || a.name.localeCompare(b.name);
108108 });
109109 }
110
111 /** A person already known from other deals, ready to prefill the add-party form. */
112 export interface Known {
113 /** The first of their `personKeys`: what a "use" link names them by. */
114 readonly key: string;
115 readonly name: string;
116 readonly role: PartyRole;
117 /** Every role they have held, as words. */
118 readonly roles: readonly string[];
119 readonly email: string;
120 readonly phone: string;
121 }
122
123 /** The people among these parties who are not yet on deal `dealId`, each once (parties sharing an email or phone are one), newest first. */
124 export function knownPeople(parties: readonly Party[], dealId: number): Known[] {
125 // Union-find over parties: two rows that share any key are one person.
126 const root = parties.map((_, i) => i);
127 const find = (i: number): number => (root[i] === i ? i : (root[i] = find(root[i]!)));
128 const owner = new Map<string, number>();
129 parties.forEach((party, i) => {
130 for (const key of personKeys(party)) {
131 const other = owner.get(key);
132 if (other === undefined) owner.set(key, i);
133 else root[find(i)] = find(other);
134 }
135 });
outdated

The union-merge loop (group/merged/one) is hard to follow and has no direct test. Add tests in src/known.test.ts or src/people.test.ts for: two rows sharing only a phone become one person; role is the newest row's role while roles lists every role held; an older row's email/phone fills a gap in the newest; someone matching on this deal by phone only is excluded. A simpler union-find over personKeys would also be easier to review.

136 const rows = new Map<number, Party[]>();
137 parties.forEach((party, i) => rows.set(find(i), [...(rows.get(find(i)) ?? []), party]));
138 const known: (Known & { id: number })[] = [];
139 for (const group of rows.values()) {
140 if (group.some((r) => r.deal_id === dealId)) continue;
141 const newestFirst = [...group].sort((x, y) => y.id - x.id);
142 const newest = newestFirst[0]!;
143 // The newest row names them; an older row fills a contact the newest lacks.
144 const contact = (get: (r: Party) => string): string => newestFirst.map((r) => get(r).trim()).find((v) => v !== "") ?? "";
145 known.push({
146 id: newest.id,
147 key: personKeys(newest)[0]!,
148 name: newest.name,
149 role: newest.role,
150 roles: [...new Set([...newestFirst].reverse().map((r) => PARTY_LABEL[r.role]))],
outdated

newestFirst.reverse() reverses the array in place, so the email and phone on the next lines are picked oldest-first. Use [...newestFirst].reverse() here and add a test with two different emails where the newer one must win.

151 email: contact((r) => r.email),
152 phone: contact((r) => r.phone),
153 });
154 }
155 return known.sort((a, b) => b.id - a.id).map(({ id: _, ...k }) => k);
156 }
157
158 /** The people whose name, roles, email or phone contain `text`, ignoring case; all of them when it is blank. */
159 export function matchKnown(known: readonly Known[], text: string): Known[] {
160 const t = text.trim().toLowerCase();
161 return t === "" ? [...known] : known.filter((k) => [k.name, ...k.roles, k.email, k.phone].some((v) => v.toLowerCase().includes(t)));
162 }
src/routes.ts +8 −2
@@ -50,7 +50,9 @@ import {
5050 markFellThrough,
5151 getDeal,
5252 withConflicts,
53 canChange,
5354 listDeals,
55 listParties,
5456 markDone,
5557 waiveDate,
5658 mayOpen,
@@ -91,7 +93,7 @@ import { dealSheets } from "./pages/sheet.ts";
9193 import { dealPage, newDealPage } from "./pages/deal.ts";
9294 import { missingPage } from "./pages/missing.ts";
9395 import { refusedPage } from "./pages/refused.ts";
94 import { people } from "./people.ts";
96 import { knownPeople, people } from "./people.ts";
9597 import { reviewHref, reviewPage, type ReviewError, type ReviewField } from "./pages/review.ts";
9698 import { peoplePage } from "./pages/people.ts";
9799 import { activityPage } from "./pages/activity.ts";
@@ -753,7 +755,11 @@ export const routes: readonly Route[] = [
753755 STATUS[found.error],
754756 );
755757 const { notice, open, clear } = readNotice(c.request);
756 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice, open }), 200, clear);
758 const all = canChange(c.who, found.value) ? listParties(c.db, c.who) : undefined;
759 const known = all?.ok ? knownPeople(all.value, found.value.id) : undefined;
760 const wanted = (c.url.searchParams.get("use") ?? "").trim().toLowerCase();
761 const use = wanted === "" ? undefined : known?.find((k) => k.key === wanted);
762 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice, open, known, use, find: (c.url.searchParams.get("find") ?? "").slice(0, 100) }), 200, clear);
757763 },
758764 },
759765 {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs