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

A party keeps both a phone and an email, and Send on a reminder offers Open in Mail and Open in Messages so the agent picks how it reaches them #123

Merged opened this

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

Merged

mason/deal-clock:mason/120-a-party-keeps-both-a-phone-and-an-email → main 2 commits fork

  • Merged. mason/120-a-party-keeps-both-a-phone-and-an-email was merged into main as f920885.

Review

Sign in to review this change.
25 files changed +600 −134
README.md +6 −4
@@ -62,12 +62,14 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
6262 see the words it would send, in a subject field and a message field,
6363 already filled in. Change the message; the subject can run to 150
6464 characters and the message to 2000. On the review page, a party with no
65 email or phone shows an **Email or phone** field and a **Save contact**
65 email or phone shows **Email** and **Phone** fields and a **Save contact**
6666 button; save it and you land back on the same draft with the contact
67 shown and your edited words kept. Send without a contact still records
67 shown and your edited words kept. A party can keep both: a lender is
68 emailed and a buyer is texted from the same deal. Send without a contact still records
6869 your approval, and your Mail then opens with no recipient.
69 4. **Send it.** Tap Send. Send records your approval and opens your own
70 Mail or Messages with the words: nothing is sent by the app itself. A
70 4. **Send it.** Tap Send. Send records your approval and offers **Open in
71 Mail** and **Open in Messages** (both when the party has an email and a
72 phone, one otherwise), each opening your own app with the words: nothing is sent by the app itself. A
7173 short notice at the top of the page reads "Reminder sent." with one link,
7274 **Open in Mail** (an email on file) or **Open in Messages** (a phone), that
7375 you tap to send from your own app; with neither on file it says "No email
contract/openapi.json +86 −10
@@ -545,9 +545,17 @@
545545 "name": {
546546 "type": "string"
547547 },
548 "contact": {
548 "email": {
549549 "type": "string"
550550 },
551 "phone": {
552 "type": "string"
553 },
554 "contact": {
555 "type": "string",
556 "deprecated": true,
557 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release."
558 },
551559 "roles": {
552560 "type": "array",
553561 "items": {
@@ -729,8 +737,18 @@
729737 "name": {
730738 "type": "string"
731739 },
740 "email": {
741 "type": "string",
742 "maxLength": 200
743 },
744 "phone": {
745 "type": "string",
746 "maxLength": 30
747 },
732748 "contact": {
733 "type": "string"
749 "type": "string",
750 "deprecated": true,
751 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release."
734752 }
735753 }
736754 }
@@ -973,7 +991,14 @@
973991 "string",
974992 "null"
975993 ],
976 "description": "A mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone."
994 "description": "The first of hrefs: a mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone."
995 },
996 "hrefs": {
997 "type": "array",
998 "items": {
999 "type": "string"
1000 },
1001 "description": "Every link these words can go by: mailto: for the party's email, then sms: for their phone; empty when the party has neither, or is gone."
9771002 }
9781003 }
9791004 }
@@ -1161,7 +1186,7 @@
11611186 },
11621187 "/api/deals/{id}/parties/{party}": {
11631188 "patch": {
1164 "summary": "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
1189 "summary": "Correct a party's name, email and phone (all are rewritten; a missing email or phone clears it; 422 for an email that is not [email protected] up to 200 characters, or a phone of digits, spaces and + - ( ) . up to 30). The deprecated contact is still read when neither email nor phone is sent. Their role stays.",
11651190 "operationId": "patchApiDealsIdPartiesParty",
11661191 "parameters": [
11671192 {
@@ -1193,9 +1218,19 @@
11931218 "minLength": 1,
11941219 "maxLength": 100
11951220 },
1221 "email": {
1222 "type": "string",
1223 "maxLength": 200
1224 },
1225 "phone": {
1226 "type": "string",
1227 "maxLength": 30
1228 },
11961229 "contact": {
11971230 "type": "string",
1198 "maxLength": 120
1231 "deprecated": true,
1232 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release.",
1233 "maxLength": 200
11991234 }
12001235 },
12011236 "required": [
@@ -1207,7 +1242,7 @@
12071242 },
12081243 "responses": {
12091244 "200": {
1210 "description": "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
1245 "description": "Correct a party's name, email and phone (all are rewritten; a missing email or phone clears it; 422 for an email that is not [email protected] up to 200 characters, or a phone of digits, spaces and + - ( ) . up to 30). The deprecated contact is still read when neither email nor phone is sent. Their role stays.",
12111246 "content": {
12121247 "application/json": {
12131248 "schema": {
@@ -1228,8 +1263,18 @@
12281263 "name": {
12291264 "type": "string"
12301265 },
1266 "email": {
1267 "type": "string",
1268 "maxLength": 200
1269 },
1270 "phone": {
1271 "type": "string",
1272 "maxLength": 30
1273 },
12311274 "contact": {
1232 "type": "string"
1275 "type": "string",
1276 "deprecated": true,
1277 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release."
12331278 }
12341279 }
12351280 }
@@ -1421,6 +1466,12 @@
14211466 "string",
14221467 "null"
14231468 ]
1469 },
1470 "hrefs": {
1471 "type": "array",
1472 "items": {
1473 "type": "string"
1474 }
14241475 }
14251476 },
14261477 "required": [
@@ -2600,8 +2651,18 @@
26002651 "name": {
26012652 "type": "string"
26022653 },
2654 "email": {
2655 "type": "string",
2656 "maxLength": 200
2657 },
2658 "phone": {
2659 "type": "string",
2660 "maxLength": 30
2661 },
26032662 "contact": {
2604 "type": "string"
2663 "type": "string",
2664 "deprecated": true,
2665 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release."
26052666 }
26062667 }
26072668 }
@@ -2844,7 +2905,14 @@
28442905 "string",
28452906 "null"
28462907 ],
2847 "description": "A mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone."
2908 "description": "The first of hrefs: a mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone."
2909 },
2910 "hrefs": {
2911 "type": "array",
2912 "items": {
2913 "type": "string"
2914 },
2915 "description": "Every link these words can go by: mailto: for the party's email, then sms: for their phone; empty when the party has neither, or is gone."
28482916 }
28492917 }
28502918 }
@@ -2894,9 +2962,17 @@
28942962 "other_agent"
28952963 ]
28962964 },
2897 "contact": {
2965 "email": {
28982966 "type": "string"
28992967 },
2968 "phone": {
2969 "type": "string"
2970 },
2971 "contact": {
2972 "type": "string",
2973 "deprecated": true,
2974 "description": "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release."
2975 },
29002976 "moment": {
29012977 "enum": [
29022978 "before",
docs/TECHNICAL.md +11 −5
@@ -101,12 +101,18 @@ no place to edit a paragraph, so to change the words use the page, API or MCP. A
101101
102102 *Send* records the agent's approval and the words approved with it; the app
103103 itself sends nothing and has no mail server. `src/outbox.ts` turns a sent
104 reminder and its party's contact into one link: `mailto:` (subject and body
105 percent-encoded) for an email, `sms:` for a phone, none otherwise ("No email
106 or phone on file"). The page shows it as **Open in Mail** / **Open in Messages**
104 reminder and its party's email and phone into links (`outboxes`): `mailto:`
105 (subject and body percent-encoded) for an email, then `sms:` for a phone, none
106 otherwise ("No email or phone on file"). The approval is recorded once whatever
107 the number of links. A party has an optional `email` (up to 200 characters) and
108 an optional `phone` (digits, spaces and `+ - ( ) .`, up to 30), each checked at
109 the boundary (422 otherwise). `contact` is **deprecated**: it still reads, as the
110 email else the phone, and is still accepted when neither new field is sent (sorted
111 into whichever it looks like); it goes in the next release. The migration split
112 existing contacts the same way. The page shows it as **Open in Mail** / **Open in Messages**
107113 in the notice after Send, on the sheet and in **Messages**; it is never opened
108 by script. `sent[].href` (and `send_reminder`'s answer) carries it, `null` when
109 there is no link; the terminal shows the address and says to send from the phone. The record is shown on the
114 by script. `sent[].hrefs` (and `send_reminder`'s answer) carries every link, `href` the first of them (`null` when
115 there is none); the terminal shows the address and says to send from the phone. The record is shown on the
110116 page (the **Messages** section of `/deals/:id`, newest first, each entry
111117 opening to the approved words), in `/api/deals/:id` and the MCP `get_deal` as
112118 `sent`, and in the terminal (open a deal with `o`, then `s`: the sent reminders,
src/db.ts +9
@@ -407,6 +407,15 @@ export const migrations: string[] = [
407407 // The two figures a deal is about, in whole dollars; null while none is set.
408408 `ALTER TABLE deal ADD COLUMN sale_price INTEGER CHECK (sale_price IS NULL OR sale_price BETWEEN 0 AND 100000000)`,
409409 `ALTER TABLE deal ADD COLUMN earnest_amount INTEGER CHECK (earnest_amount IS NULL OR earnest_amount BETWEEN 0 AND 100000000)`,
410 // A party keeps an email and a phone apart. `contact` stays as the first of them
411 // (the deprecated single field); the one that was there moves into whichever it looks like.
412 `ALTER TABLE party ADD COLUMN email TEXT NOT NULL DEFAULT ''`,
413 `ALTER TABLE party ADD COLUMN phone TEXT NOT NULL DEFAULT ''`,
414 `UPDATE party SET email = trim(contact)
415 WHERE trim(contact) GLOB '[A-Za-z0-9._+-]*@[A-Za-z0-9.-]*' AND trim(contact) NOT GLOB '*[^A-Za-z0-9._+@-]*'
416 AND length(trim(contact)) - length(replace(trim(contact), '@', '')) = 1 AND length(trim(contact)) <= 200`,
417 `UPDATE party SET phone = trim(contact)
418 WHERE email = '' AND trim(contact) NOT GLOB '*[^0-9 +().-]*' AND trim(contact) GLOB '*[0-9]*' AND length(trim(contact)) <= 30`,
410419 ];
411420
412421 export function openDb(dir = dataDir): Database {
src/deals.ts +58 −22
@@ -25,11 +25,11 @@ import {
2525 type Lengths,
2626 type PartyRole,
2727 } from "./deadlines.ts";
28 import { LENGTH_MAX, standard } from "./env.ts";
28 import { LENGTH_MAX, standard, validEmail, validPhone } from "./env.ts";
2929 import { agentOf } from "./profile.ts";
3030 import { emit } from "./live.ts";
3131 import { amount } from "./money.ts";
32 import { outbox } from "./outbox.ts";
32 import { outboxes } from "./outbox.ts";
3333 import { conflictLine, conflicts, type Conflict } from "./order.ts";
3434 import { SEND_SPAN, draftOfMoment, statusDrafts, type Agent, type Draft } from "./reminders.ts";
3535 import { audited, conflict, fail, ok, refuse, type Result } from "./result.ts";
@@ -56,7 +56,12 @@ export interface Party {
5656 readonly deal_id: number;
5757 readonly role: PartyRole;
5858 readonly name: string;
59 /** Deprecated: the email, or else the phone; kept one release for readers of the old single field. */
5960 readonly contact: string;
61 /** Up to 200 characters; '' when none. */
62 readonly email: string;
63 /** Up to 30 digits, spaces and + - ( ) . ; '' when none. */
64 readonly phone: string;
6065 }
6166 export interface Declined {
6267 readonly id: number;
@@ -126,8 +131,10 @@ export interface Sent {
126131 readonly body: string;
127132 /** A link that opens the party's own Mail or Messages with these words (`outbox.ts`); null when there is none to offer. */
128133 readonly href: string | null;
134 /** Every such link: Mail for the party's email, Messages for their phone. `href` is the first. */
135 readonly hrefs: readonly string[];
129136 }
130 type SentRow = Omit<Sent, "href">;
137 type SentRow = Omit<Sent, "href" | "hrefs">;
131138 export interface Deadline {
132139 readonly id: number;
133140 readonly deal_id: number;
@@ -205,8 +212,12 @@ export function message(value: unknown, min: number, max: number): string | unde
205212 }
206213
207214 export const SUBJECT_MAX = 150;
208 /** The longest a party's contact may be. */
209 export const CONTACT_MAX = 120;
215 /** The longest a party's email may be. */
216 export const EMAIL_MAX = 200;
217 /** The longest free-text contact an old row may keep. */
218 const CONTACT_MAX = 120;
219 /** The longest a party's phone may be. */
220 export const PHONE_MAX = 30;
210221 export const REASON_MAX = 200;
211222 /** The longest working note on a date. */
212223 export const NOTE_MAX = 200;
@@ -228,7 +239,7 @@ const authorOf = (who: Who): { id: string; name: string } =>
228239 export const shown = (who: Who, deal: DealView): DealView =>
229240 canChange(who, deal)
230241 ? deal
231 : { ...deal, parties: deal.parties.map((p) => ({ ...p, contact: "" })), sent: deal.sent.map((m) => ({ ...m, href: null })) };
242 : { ...deal, parties: deal.parties.map((p) => ({ ...p, contact: "", email: "", phone: "" })), sent: deal.sent.map((m) => ({ ...m, href: null, hrefs: [] })) };
232243
233244 // ---- reading ----
234245
@@ -245,7 +256,8 @@ interface Children {
245256 /** A sent reminder with the link for the party's contact as it stands now; none once the party is gone. */
246257 function withHref(m: SentRow, parties: readonly Party[]): Sent {
247258 const party = parties.find((p) => p.id === m.party_id);
248 return { ...m, href: party === undefined || m.subject === "" ? null : (outbox(party.contact, m.subject, m.body)?.href ?? null) };
259 const hrefs = party === undefined || m.subject === "" ? [] : outboxes(party, m.subject, m.body).map((o) => o.href);
260 return { ...m, href: hrefs[0] ?? null, hrefs };
249261 }
250262
251263 /** One deal assembled from its rows. */
@@ -975,20 +987,44 @@ export function addDeadline(
975987 return within(db, who, "date.add", dealId, ok(made));
976988 }
977989
978 /** A party's name and contact, checked: the same rules to add one and to correct one. */
979 function partyText(input: { name: unknown; contact?: unknown }): Result<{ name: string; contact: string }> {
990 /**
991 * A party's name, email and phone, checked: the same rules to add one and to
992 * correct one. `contact` is the deprecated single field: it stands in for an
993 * email or phone only when neither is given, and is sorted into whichever it
994 * looks like.
995 */
996 function partyText(input: { name: unknown; email?: unknown; phone?: unknown; contact?: unknown }): Result<{ name: string; email: string; phone: string; contact: string }> {
980997 const name = line(input.name, 1, 100);
981998 if (name === undefined) return fail("invalid", "A name is 1 to 100 characters.");
982 const contact =
983 input.contact === undefined || input.contact === "" ? "" : line(input.contact, 1, CONTACT_MAX);
984 if (contact === undefined) return fail("invalid", "A contact is up to 120 characters.");
985 return ok({ name, contact });
999 const given = (v: unknown): v is string => v !== undefined && v !== null && v !== "";
1000 let email = "";
1001 let phone = "";
1002 if (!given(input.email) && !given(input.phone) && given(input.contact)) {
1003 const old = line(input.contact, 1, EMAIL_MAX);
1004 if (old === undefined) return fail("invalid", "A contact is up to 200 characters.");
1005 if (validEmail(old)) email = old;
1006 else if (validPhone(old)) phone = old;
1007 else if (old.length > CONTACT_MAX) return fail("invalid", "A contact is up to 120 characters.");
1008 else return ok({ name, email: "", phone: "", contact: old }); // an old free-text contact is kept as it was
1009 } else {
1010 if (given(input.email)) {
1011 const v = line(input.email, 1, EMAIL_MAX);
1012 if (v === undefined || !validEmail(v)) return fail("invalid", "An email looks like [email protected], up to 200 characters.");
1013 email = v;
1014 }
1015 if (given(input.phone)) {
1016 const v = line(input.phone, 1, PHONE_MAX);
1017 if (v === undefined || !validPhone(v)) return fail("invalid", "A phone is digits, spaces and + - ( ) . up to 30 characters.");
1018 phone = v;
1019 }
1020 }
1021 return ok({ name, email, phone, contact: email || phone });
9861022 }
9871023
9881024 export function addParty(
9891025 db: Database,
9901026 who: Who,
991 input: { dealId: number; role: unknown; name: unknown; contact?: unknown },
1027 input: { dealId: number; role: unknown; name: unknown; email?: unknown; phone?: unknown; contact?: unknown },
9921028 ): Result<Party> {
9931029 const deal = dealFor(db, who, "update", input.dealId);
9941030 const dealId = deal.ok ? deal.value.id : undefined;
@@ -998,10 +1034,10 @@ export function addParty(
9981034 const text = partyText(input);
9991035 if (!text.ok) return within(db, who, "party.add", dealId, text);
10001036 const made = db
1001 .query<Party, [number, string, string, string]>(
1002 "INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4) RETURNING *",
1037 .query<Party, [number, string, string, string, string, string]>(
1038 "INSERT INTO party (deal_id, role, name, contact, email, phone) VALUES (?1, ?2, ?3, ?4, ?5, ?6) RETURNING *",
10031039 )
1004 .get(deal.value.id, input.role, text.value.name, text.value.contact)!;
1040 .get(deal.value.id, input.role, text.value.name, text.value.contact, text.value.email, text.value.phone)!;
10051041 return within(db, who, "party.add", dealId, ok(made));
10061042 }
10071043
@@ -1028,21 +1064,21 @@ function partyFor(
10281064 return { dealId: deal.value.id, found: ok({ deal: deal.value, party }) };
10291065 }
10301066
1031 /** Correct a party's name and contact. Their role stays: it decides which dates they are told about. */
1067 /** Correct a party's name, email and phone. Their role stays: it decides which dates they are told about. */
10321068 export function editParty(
10331069 db: Database,
10341070 who: Who,
1035 input: { id: number; dealId?: number; name: unknown; contact?: unknown },
1071 input: { id: number; dealId?: number; name: unknown; email?: unknown; phone?: unknown; contact?: unknown },
10361072 ): Result<Party> {
10371073 const { dealId, found } = partyFor(db, who, input.id, input.dealId);
10381074 if (!found.ok) return within(db, who, "party.edit", dealId, found);
10391075 const text = partyText(input);
10401076 if (!text.ok) return within(db, who, "party.edit", dealId, text);
10411077 const made = db
1042 .query<Party, [string, string, number]>(
1043 "UPDATE party SET name = ?1, contact = ?2 WHERE id = ?3 RETURNING *",
1078 .query<Party, [string, string, string, string, number]>(
1079 "UPDATE party SET name = ?1, contact = ?2, email = ?3, phone = ?4 WHERE id = ?5 RETURNING *",
10441080 )
1045 .get(text.value.name, text.value.contact, input.id)!;
1081 .get(text.value.name, text.value.contact, text.value.email, text.value.phone, input.id)!;
10461082 return within(db, who, "party.edit", dealId, ok(made));
10471083 }
10481084
src/find.ts +1 −1
@@ -12,7 +12,7 @@ export const FIND_REFUSAL = `Find takes up to ${FIND_MAX} characters, with no co
1212
1313 /** The text a deal is found by: address, every party (buyer and seller included)'s name and contact. */
1414 const haystack = (deal: DealView): string =>
15 [deal.address, ...deal.parties.flatMap((p) => [p.name, p.contact])]
15 [deal.address, ...deal.parties.flatMap((p) => [p.name, p.contact, p.email, p.phone])]
1616 .join("\n")
1717 .toLowerCase();
1818
src/mcp.ts +10 −6
@@ -415,28 +415,32 @@ export const tools: readonly Tool[] = [
415415 deal_id: { type: "integer" },
416416 role: { enum: [...PARTY_ROLES] },
417417 name: { type: "string", maxLength: 100 },
418 contact: { type: "string", maxLength: 120 },
418 email: { type: "string", maxLength: 200 },
419 phone: { type: "string", maxLength: 30, description: "Digits, spaces and + - ( ) . only." },
420 contact: { type: "string", maxLength: 200, description: "Deprecated: use email and phone. Read as whichever it looks like when neither is given." },
419421 },
420422 required: ["deal_id", "role", "name"],
421423 },
422424 run: (db, who, a) =>
423 addParty(db, who, { dealId: Number(a.deal_id), role: a.role, name: a.name, contact: a.contact }),
425 addParty(db, who, { dealId: Number(a.deal_id), role: a.role, name: a.name, email: a.email, phone: a.phone, contact: a.contact }),
424426 },
425427 {
426428 name: "edit_party",
427 description: "Correct a party's name and contact (their role stays); the next reminder draft uses the new contact. Party ids are in get_deal.",
429 description: "Correct a party's name, email and phone (their role stays; an email or phone left out is cleared); the next reminder draft uses them. Party ids are in get_deal.",
428430 inputSchema: {
429431 type: "object",
430432 properties: {
431433 deal_id: { type: "integer" },
432434 party_id: { type: "integer" },
433435 name: { type: "string", maxLength: 100 },
434 contact: { type: "string", maxLength: 120 },
436 email: { type: "string", maxLength: 200 },
437 phone: { type: "string", maxLength: 30, description: "Digits, spaces and + - ( ) . only." },
438 contact: { type: "string", maxLength: 200, description: "Deprecated: use email and phone. Read as whichever it looks like when neither is given." },
435439 },
436 required: ["deal_id", "party_id", "name", "contact"],
440 required: ["deal_id", "party_id", "name"],
437441 },
438442 run: (db, who, a) =>
439 editParty(db, who, { dealId: Number(a.deal_id), id: Number(a.party_id), name: a.name, contact: a.contact }),
443 editParty(db, who, { dealId: Number(a.deal_id), id: Number(a.party_id), name: a.name, email: a.email, phone: a.phone, contact: a.contact }),
440444 },
441445 {
442446 name: "remove_party",
src/notice.test.ts +4 −4
@@ -23,8 +23,8 @@ test("a malformed notice cookie is shown as text and opens nothing", () => {
2323
2424 test("the link and its absence are for whoever may change the deal alone", () => {
2525 const href = "mailto:[email protected]?subject=s&body=b";
26 expect(outboxLine(href, true)).toContain('href="mailto:[email protected]?subject=s&amp;body=b"');
27 expect(outboxLine(null, true)).toContain("No email or phone on file");
28 expect(outboxLine(href, false)).toBe("");
29 expect(outboxLine(null, false)).toBe("");
26 expect(outboxLine([href], true)).toContain('href="mailto:[email protected]?subject=s&amp;body=b"');
27 expect(outboxLine([], true)).toContain("No email or phone on file");
28 expect(outboxLine([href], false)).toBe("");
29 expect(outboxLine([], false)).toBe("");
3030 });
src/outbox.ts +15
@@ -48,5 +48,20 @@ export function outbox(contact: string, subject: string, body: string): Outbox |
4848 return null;
4949 }
5050
51 /**
52 * Every link these words can go by to this party: Mail for an email, Messages
53 * for a phone, in that order; empty when the party has neither. The party's
54 * deprecated single `contact` stands in for a row that has neither field set.
55 */
56 export function outboxes(party: { email: string; phone: string; contact?: string }, subject: string, body: string): Outbox[] {
57 const set = party.email !== "" || party.phone !== "";
58 const values = set ? [party.email, party.phone] : [party.contact ?? ""];
59 return values.flatMap((v) => outbox(v, subject, body) ?? []);
60 }
61
62 /** Where a party can be reached, in words: their email and phone, or the deprecated contact alone; '' when nowhere. */
63 export const reachedAt = (p: { email: string; phone: string; contact: string }): string =>
64 [p.email, p.phone].filter((v) => v !== "").join(" and ") || p.contact;
65
5166 /** The words on a link `outbox` made, by its scheme. */
5267 export const labelOf = (href: string): string => (href.startsWith("mailto:") ? "Open in Mail" : "Open in Messages");
src/pages/clock.ts +1 −1
@@ -249,5 +249,5 @@ function render(input: {
249249 }
250250 <p class="muted small">Each date reminds its parties a few days before (three unless you set another, per date) and the morning of, and the one who owes a date is asked for an update the morning after it slips. Send records your approval and opens your own Mail or Messages with the words.</p>
251251 </section>`}`;
252 return layout({ body, who, agent, waiting: input.waiting, path: "/", notice, open: opened?.href });
252 return layout({ body, who, agent, waiting: input.waiting, path: "/", notice, open: opened?.hrefs });
253253 }
src/pages/deal.ts +39 −11
@@ -5,7 +5,7 @@
55 */
66
77 import { addDays, relative, short, spoken } from "../dates.ts";
8 import { canChange, canRemove, closedOn, fellOn, REASON_MAX, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
8 import { canChange, canRemove, closedOn, EMAIL_MAX, fellOn, PHONE_MAX, REASON_MAX, type DealView, type Party, type Plan, type PlannedDate, type Sent } from "../deals.ts";
99 import { agent as defaults, standard } from "../env.ts";
1010 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
@@ -26,14 +26,39 @@ const roleOptions = (selected?: string): string =>
2626
2727 const count = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
2828
29 /** A party form refused: whose it was (a party's id, or "new"), what was typed and why it was refused. */
30 export interface PartyProblem {
31 readonly id: number | "new";
32 readonly role: string;
33 readonly name: string;
34 readonly email: string;
35 readonly phone: string;
36 readonly message: string;
37 }
38
39 /** The optional email and phone fields of a party form, with the refusal beside them. */
40 const contactFields = (email: string, phone: string, message?: string): string =>
41 `${message === undefined ? "" : `<p class="conflict" role="alert">${escape(message)}</p>`}
42 <div class="pair">
43 <label>Email <span class="muted">(optional)</span><input class="input" type="email" name="email" maxlength="${EMAIL_MAX}" autocomplete="off" value="${escape(email)}"${message === undefined ? "" : ' aria-invalid="true"'}></label>
44 <label>Phone <span class="muted">(optional)</span><input class="input" type="tel" name="phone" maxlength="${PHONE_MAX}" autocomplete="off" value="${escape(phone)}"${message === undefined ? "" : ' aria-invalid="true"'}></label>
45 </div>`;
46
47 /** A party's email and phone as links, each on its own. */
48 const partyLinks = (p: Party): string => {
49 const both = [p.email, p.phone].filter((v) => v !== "");
50 return both.length > 0 ? both.map((v) => `<span class="mono">${partyContact(v)}</span>`).join("") : p.contact === "" ? "" : `<span class="mono">${partyContact(p.contact)}</span>`;
51 };
52
2953 /** Correct a party or remove them: a plain form each, back to this page. */
30 const partyControls = (p: Party, to: string): string => `<div class="party-controls">
31 <details class="party-edit">
54 const partyControls = (p: Party, to: string, problem?: PartyProblem): string => `<div class="party-controls">
55 <details class="party-edit"${problem === undefined ? "" : " open"}>
3256 <summary class="button button-quiet button-small">Edit</summary>
3357 <form class="stack" method="post" action="/parties/${p.id}/edit">
3458 <input type="hidden" name="to" value="${escape(to)}">
35 <label>Name<input class="input" name="name" required maxlength="100" value="${escape(p.name)}"></label>
36 <label>Email or phone <span class="muted">(optional)</span><input class="input" name="contact" maxlength="120" value="${escape(p.contact)}"></label>
59 <label>Name<input class="input" name="name" required maxlength="100" value="${escape(problem?.name ?? p.name)}"></label>
60 ${contactFields(problem?.email ?? p.email, problem?.phone ?? p.phone, problem?.message)}
61 ${p.email === "" && p.phone === "" && p.contact !== "" ? `<input type="hidden" name="contact" value="${escape(p.contact)}">` : ""}
3762 <button class="button">Save</button>
3863 </form>
3964 </details>
@@ -80,7 +105,7 @@ function messages(deal: DealView, may: boolean, agent: Agent, to: string): strin
80105 const words =
81106 m.subject === ""
82107 ? `<p class="muted">The words were not kept for this one.</p>`
83 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.href, may)}`;
108 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.hrefs, may)}`;
84109 return `<li class="draft"><details><summary><span><b>${escape(m.party_name)}</b> <span class="muted">${role} · ${escape(m.label)}${removed}, ${escape(short(m.due))} · ${escape(sentLabel(m.moment))}</span><br>${escape(m.subject === "" ? "(no subject kept)" : m.subject)}</span><span class="state" data-sent>Sent ${escape(short(m.sent_at.slice(0, 10)))}</span></summary>${words}</details></li>`;
85110 };
86111 return `${waiting}<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
@@ -129,6 +154,8 @@ export function dealPage(input: {
129154 amend?: AmendState | undefined;
130155 /** A sale price or earnest money amount that was refused: what was typed and why. */
131156 figures?: FiguresProblem | undefined;
157 /** A party added or corrected and refused: what was typed and why, so the form keeps it. */
158 party?: PartyProblem | undefined;
132159 }): string {
133160 const { who, agent, deal, on, notice, problem } = input;
134161 const opened = input.open === undefined ? undefined : deal.sent.find((m) => m.id === input.open);
@@ -168,13 +195,14 @@ export function dealPage(input: {
168195 </li>`,
169196 )
170197 .join("");
198 const add = input.party?.id === "new" ? input.party : undefined;
171199 const parties =
172200 deal.parties.length === 0
173201 ? `<p class="muted">No parties yet.</p>`
174202 : `<ul class="parties">${deal.parties
175203 .map(
176204 (p) =>
177 `<li><span class="muted">${escape(PARTY_LABEL[p.role])}</span><b>${escape(p.name)}</b>${p.contact === "" ? "" : `<span class="mono">${partyContact(p.contact)}</span>`}${may ? partyControls(p, path) : ""}</li>`,
205 `<li><span class="muted">${escape(PARTY_LABEL[p.role])}</span><b>${escape(p.name)}</b>${partyLinks(p)}${may ? partyControls(p, path, input.party?.id === p.id ? input.party : undefined) : ""}</li>`,
178206 )
179207 .join("")}</ul>`;
180208 const forms = may
@@ -195,10 +223,10 @@ export function dealPage(input: {
195223 <h2>Add a party</h2>
196224 <form class="stack" method="post" action="${path}/parties">
197225 <div class="pair">
198 <label>Role<select class="input" name="role">${roleOptions("lender")}</select></label>
199 <label>Name<input class="input" name="name" required maxlength="100"></label>
226 <label>Role<select class="input" name="role">${roleOptions(add?.role ?? "lender")}</select></label>
227 <label>Name<input class="input" name="name" required maxlength="100" value="${escape(add?.name ?? "")}"></label>
200228 </div>
201 <label>Email or phone <span class="muted">(optional)</span><input class="input" name="contact" maxlength="120"></label>
229 ${contactFields(add?.email ?? "", add?.phone ?? "", add?.message)}
202230 <button class="button">Add party</button>
203231 </form>
204232 </section>`
@@ -245,7 +273,7 @@ export function dealPage(input: {
245273 })
246274 : ""
247275 }`;
248 return layout({ body, who, agent, waiting: input.waiting, path, heading: deal.address, notice, open: opened?.href });
276 return layout({ body, who, agent, waiting: input.waiting, path, heading: deal.address, notice, open: opened?.hrefs });
249277 }
250278
251279 /** What the form was last sent with, what was wrong with it, and the dates it would make. */
src/pages/layout.ts +3 −3
@@ -39,8 +39,8 @@ export function layout(input: {
3939 path: string;
4040 heading?: string;
4141 notice?: string | undefined;
42 /** The link a notice about a sent reminder offers: the href `outbox` made for it. */
43 open?: string | null | undefined;
42 /** The links a notice about a sent reminder offers: the hrefs `outboxes` made for it; empty when the party has none. */
43 open?: readonly string[] | undefined;
4444 /** How many of today's messages wait for approval; the header's Review link says so, and is left out when the count is not known. */
4545 waiting?: number | undefined;
4646 /** Whether the page keeps its regions live; false for a page with none. */
@@ -108,7 +108,7 @@ ${plain || input.live === false ? "" : `<script type="module" src="${asset("live
108108 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
109109 </footer>`}
110110 </div>
111 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}${open === undefined ? "" : open === null ? ` ${NO_CONTACT}.` : ` <a href="${escape(open)}">${labelOf(open)}</a>`}</p>`}
111 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}${open === undefined ? "" : open.length === 0 ? ` ${NO_CONTACT}.` : open.map((h) => ` <a href="${escape(h)}">${labelOf(h)}</a>`).join("")}</p>`}
112112 </body>
113113 </html>
114114 `;
src/pages/people.ts +1 −1
@@ -18,7 +18,7 @@ const owedRow = (o: Person["owes"][number], on: string): string =>
1818
1919 const person = (p: Person, on: string): string => `<section class="card person">
2020 <h2>${escape(p.name)}</h2>
21 <p class="muted">${escape(p.roles.join(", "))}${p.contact === "" ? "" : ` · ${partyContact(p.contact)}`}</p>
21 <p class="muted">${escape(p.roles.join(", "))}${[p.email, p.phone, ...(p.email === "" && p.phone === "" ? [p.contact] : [])].filter((v) => v !== "").map((v) => ` · ${partyContact(v)}`).join("")}</p>
2222 ${p.owes.length === 0 ? `<p class="muted">Nothing open</p>` : `<ul class="week-list">${p.owes.map((o) => owedRow(o, on)).join("")}</ul>`}
2323 </section>`;
2424
src/pages/review.ts +10 −8
@@ -7,7 +7,7 @@
77 */
88
99 import type { Agent } from "../reminders.ts";
10 import { BODY_MAX, CONTACT_MAX, REASON_MAX, SUBJECT_MAX } from "../deals.ts";
10 import { BODY_MAX, EMAIL_MAX, PHONE_MAX, REASON_MAX, SUBJECT_MAX } from "../deals.ts";
1111 import { spoken } from "../dates.ts";
1212 import { PARTY_LABEL } from "../deadlines.ts";
1313 import { escape } from "../http.ts";
@@ -41,8 +41,9 @@ export interface Typed {
4141 readonly subject: string;
4242 readonly body: string;
4343 readonly reason: string;
44 /** The contact typed into the Save contact field; empty when there was none. */
45 readonly contact?: string | undefined;
44 /** The email and phone typed into the Save contact fields; empty when there was none. */
45 readonly email?: string | undefined;
46 readonly phone?: string | undefined;
4647 }
4748
4849 const FIELD_LABEL: Readonly<Record<ReviewField, string>> = { subject: "Subject", body: "Message", reason: "Why not", contact: "Email or phone" };
@@ -60,7 +61,7 @@ export function reviewPage(input: {
6061 /** How many this round has sent or declined. */
6162 done: number;
6263 notice?: string | undefined;
63 open?: string | null | undefined;
64 open?: readonly string[] | undefined;
6465 error?: ReviewError | undefined;
6566 typed?: Typed | undefined;
6667 }): string {
@@ -81,9 +82,10 @@ export function reviewPage(input: {
8182 * saves the contact; its button posts to the contact action instead of Send. The form opens with a
8283 * hidden Send button so Enter anywhere in it still sends.
8384 */
84 function contactField(value: string, problem: string, invalid: string): string {
85 function contactField(typed: Typed, problem: string, invalid: string): string {
8586 return `${problem}
86 <label>Email or phone<input class="input" name="contact" value="${escape(value)}" maxlength="${CONTACT_MAX}" autocomplete="off"${invalid}></label>
87 <label>Email<input class="input" type="email" name="email" value="${escape(typed.email ?? "")}" maxlength="${EMAIL_MAX}" autocomplete="off"${invalid}></label>
88 <label>Phone<input class="input" type="tel" name="phone" value="${escape(typed.phone ?? "")}" maxlength="${PHONE_MAX}" autocomplete="off"${invalid}></label>
8789 <button class="button button-quiet" formaction="${REVIEW_PATH}/contact">Save contact</button>`;
8890 }
8991
@@ -104,10 +106,10 @@ function form(
104106 <h1>Review today's reminders</h1>
105107 <p><a href="/deals/${draft.deal_id}">${escape(draft.address)}</a></p>
106108 <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(momentLabel(draft.moment, draft.lead_days))}${draft.held === null ? "" : ` · ${escape(heldFrom(draft.held))}`}</span></p>
107 <p>To <b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${draft.contact === "" ? "" : ` · ${escape(draft.contact)}`}</span></p>
109 <p>To <b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${[draft.email, draft.phone].filter((v) => v !== "").map((v) => ` · ${escape(v)}`).join("") || (draft.contact === "" ? "" : ` · ${escape(draft.contact)}`)}</span></p>
108110 <form class="move" method="post" action="${REVIEW_PATH}/send">${hidden(keys)}
109111 ${draft.contact === "" ? '<button class="button" hidden tabindex="-1" aria-hidden="true">Send</button>' : ""}
110 ${draft.contact === "" ? contactField(typed.contact ?? "", problem("contact"), invalid("contact")) : ""}
112 ${draft.contact === "" ? contactField(typed, problem("contact"), invalid("contact")) : ""}
111113 ${problem("subject")}
112114 <label>Subject<input class="input" name="subject" value="${escape(typed.subject)}" maxlength="${SUBJECT_MAX}" required${invalid("subject")}></label>
113115 ${problem("body")}
src/pages/sheet.ts +5 −5
@@ -11,7 +11,7 @@ import { isOpen, isWaivable, LEAD_MAX, LEAD_MIN, PARTY_LABEL, PARTY_ROLES } from
1111 import { escape } from "../http.ts";
1212 import { confirmRemove } from "./confirm.ts";
1313 import { memoizer, print } from "../memo.ts";
14 import { labelOf, NO_CONTACT, outbox } from "../outbox.ts";
14 import { labelOf, NO_CONTACT, outboxes } from "../outbox.ts";
1515 import { conflictLine } from "../order.ts";
1616 import { agent as defaults } from "../env.ts";
1717 import { draftsFor, heldFrom, momentLabel, MOMENTS, remindsLine, type Agent, type Draft } from "../reminders.ts";
@@ -93,9 +93,9 @@ export const hidden = (fields: Record<string, string | number>): string =>
9393 .map(([k, v]) => `<input type="hidden" name="${k}" value="${escape(String(v))}">`)
9494 .join("");
9595
96 /** The one link a sent reminder offers, or why there is none; nothing for a reader who may not see contacts. */
97 export const outboxLine = (href: string | null, may: boolean): string =>
98 !may ? "" : href === null ? `<p class="muted">${NO_CONTACT}</p>` : `<p><a class="button" href="${escape(href)}">${labelOf(href)}</a></p>`;
96 /** The links a sent reminder offers (Mail, Messages, or both), or why there are none; nothing for a reader who may not see contacts. */
97 export const outboxLine = (hrefs: readonly string[], may: boolean): string =>
98 !may ? "" : hrefs.length === 0 ? `<p class="muted">${NO_CONTACT}</p>` : `<p class="row">${hrefs.map((h) => `<a class="button" href="${escape(h)}">${labelOf(h)}</a>`).join(" ")}</p>`;
9999
100100 /** The words of a draft, as the party will read them. */
101101 const draftText = (draft: Draft): string => `<div class="draft-text">
@@ -168,7 +168,7 @@ function draftLine(draft: Draft, on: string, withDeal: boolean): string {
168168 export function draftItem(draft: Draft, on: string, may: boolean, to: string): string {
169169 const inside =
170170 draft.sent_at !== null
171 ? `${draftText(draft)}${outboxLine(outbox(draft.contact, draft.subject, draft.body)?.href ?? null, may)}`
171 ? `${draftText(draft)}${outboxLine(outboxes(draft, draft.subject, draft.body).map((o) => o.href), may)}`
172172 : draft.declined !== null
173173 ? `${draftText(draft)}${may ? undoForm(draft, to) : ""}`
174174 : may
src/partycontact.test.ts +2 −2
@@ -10,12 +10,12 @@ const contacts = ["[email protected]", "(555) 010-0142", "Ask at the front desk
1010
1111 const bare = (h: string) => h.replace(/<p class="agent-contact">.*?<\/p>/, "");
1212 const peopleHtml = (contact: string) => bare(
13 peoplePage({ who, on: "2026-10-10", people: [{ name: "P", roles: ["Lender"], contact, owes: [] } as unknown as Person] }));
13 peoplePage({ who, on: "2026-10-10", people: [{ name: "P", roles: ["Lender"], contact, email: "", phone: "", owes: [] } as unknown as Person] }));
1414 const dealHtml = (contact: string) => bare(
1515 dealPage({
1616 who,
1717 on: "2026-10-10",
18 deal: { id: 1, address: "A", closed: false, contract_date: "2026-10-01", closing: "2026-11-01", business_days: 0, parties: [{ id: 1, deal_id: 1, role: "lender", name: "P", contact }], deadlines: [], conflicts: [], sent: [] } as unknown as DealView,
18 deal: { id: 1, address: "A", closed: false, contract_date: "2026-10-01", closing: "2026-11-01", business_days: 0, parties: [{ id: 1, deal_id: 1, role: "lender", name: "P", contact, email: "", phone: "" }], deadlines: [], conflicts: [], sent: [] } as unknown as DealView,
1919 }));
2020
2121 for (const [page, render] of [["people", peopleHtml], ["deal", dealHtml]] as const) {
src/people.test.ts +1 −1
@@ -8,7 +8,7 @@ const deal = (id: number, address: string, parties: [number, string, string, str
88 id,
99 address,
1010 closed,
11 parties: parties.map(([pid, role, name, contact]) => ({ id: pid, deal_id: id, role, name, contact })),
11 parties: parties.map(([pid, role, name, contact]) => ({ id: pid, deal_id: id, role, name, contact, email: "", phone: "" })),
1212 deadlines: dates.map(([did, owes, label, due, done_at]) => ({ id: did, owes, label, due, done_at, waived_at: null })),
1313 }) as unknown as DealView;
1414
src/people.ts +43 −8
@@ -21,28 +21,61 @@ export interface Owed {
2121 export interface Person {
2222 /** The name on the person's most recently added party row. */
2323 readonly name: string;
24 /** Deprecated: the email, or else the phone. */
2425 readonly contact: string;
26 readonly email: string;
27 readonly phone: string;
2528 /** The roles they hold across deals, as words, in the order first met. */
2629 readonly roles: readonly string[];
2730 /** Open dates they owe, soonest first, then by address. */
2831 readonly owes: readonly Owed[];
2932 }
3033
31 /** Two parties are one person when their contact is the same, ignoring case and outer spaces; with no contact, their name. */
32 export const personKey = (p: { name: string; contact: string }): string =>
33 (p.contact.trim() === "" ? p.name : p.contact).trim().toLowerCase();
34 /** What identifies a party: their email and phone, ignoring case and outer spaces; with neither, their contact, else their name. */
35 export const personKeys = (p: { name: string; contact: string; email?: string; phone?: string }): string[] => {
36 const t = (v: string | undefined) => (v ?? "").trim().toLowerCase();
37 const both = [t(p.email), t(p.phone)].filter((v) => v !== "");
38 return both.length > 0 ? both : [t(p.contact) || t(p.name)];
39 };
3440
41 /** The one key a party is shown under in a sentence: its email, else phone, else contact, else name. */
42 export const personKey = (p: { name: string; contact: string; email?: string; phone?: string }): string => personKeys(p)[0]!;
43
44 interface One { name: string; newest: number; contact: string; email: string; phone: string; roles: Set<PartyRole>; owes: Map<number, Owed> }
45
46 /** Two parties are one person when they share an email or a phone, even if one row has only the phone and another both. */
3547 export function people(deals: readonly DealView[], on: string): Person[] {
36 const byKey = new Map<string, { name: string; newest: number; contact: string; roles: Set<PartyRole>; owes: Map<number, Owed> }>();
48 const byKey = new Map<string, One>();
49 const merge = (into: One, from: One): void => {
50 if (from.newest > into.newest) {
51 into.newest = from.newest;
52 into.name = from.name;
53 into.contact = from.contact;
54 into.email = from.email;
55 into.phone = from.phone;
56 }
57 for (const r of from.roles) into.roles.add(r);
58 for (const [id, o] of from.owes) into.owes.set(id, o);
59 };
3760 for (const deal of deals) {
3861 for (const party of deal.parties) {
39 const key = personKey(party);
40 const one = byKey.get(key) ?? { name: party.name, newest: -1, contact: party.contact.trim(), roles: new Set(), owes: new Map() };
41 byKey.set(key, one);
62 const keys = personKeys(party);
63 let one: One = { name: party.name, newest: -1, contact: party.contact.trim(), email: party.email.trim(), phone: party.phone.trim(), roles: new Set(), owes: new Map() };
64 for (const key of keys) {
65 const found = byKey.get(key);
66 if (found !== undefined && found !== one) {
67 merge(found, one);
68 for (const [k, v] of byKey) if (v === one) byKey.set(k, found);
69 one = found;
70 }
71 }
72 for (const key of keys) byKey.set(key, one);
4273 if (party.id > one.newest) {
4374 one.newest = party.id;
4475 one.name = party.name;
4576 one.contact = party.contact.trim();
77 one.email = party.email.trim();
78 one.phone = party.phone.trim();
4679 }
4780 one.roles.add(party.role);
4881 // A closed deal is off the clock: nothing on it is chased.
@@ -60,10 +93,12 @@ export function people(deals: readonly DealView[], on: string): Person[] {
6093 }
6194 }
6295 }
63 return [...byKey.values()]
96 return [...new Set(byKey.values())]
6497 .map((p) => ({
6598 name: p.name,
6699 contact: p.contact,
100 email: p.email,
101 phone: p.phone,
67102 roles: [...p.roles].map((r) => PARTY_LABEL[r]),
68103 owes: [...p.owes.values()].sort((a, b) => a.due.localeCompare(b.due) || a.address.localeCompare(b.address)),
69104 }))
src/reminders.ts +6
@@ -35,6 +35,8 @@ export interface Draft {
3535 readonly party_name: string;
3636 readonly party_role: PartyRole;
3737 readonly contact: string;
38 readonly email: string;
39 readonly phone: string;
3840 readonly moment: Moment;
3941 /** Days before the due date the "before" reminder goes out: the date's own lead time. */
4042 readonly lead_days: number;
@@ -219,6 +221,8 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
219221 party_name: party.name,
220222 party_role: party.role,
221223 contact: party.contact,
224 email: party.email,
225 phone: party.phone,
222226 moment,
223227 lead_days: deadline.lead_days,
224228 move_id: key,
@@ -305,6 +309,8 @@ export function statusDrafts(deal: DealView, agent: Agent): Draft[] {
305309 party_name: party.name,
306310 party_role: party.role,
307311 contact: party.contact,
312 email: party.email,
313 phone: party.phone,
308314 moment: "status" as const,
309315 lead_days: closing.lead_days,
310316 move_id: stand,
src/review.test.ts +23 −7
@@ -136,7 +136,8 @@ const bareDraft = async (address: string) => {
136136
137137 test("the contact field shows only while the party has no contact", async () => {
138138 const { page } = await bareDraft("31 Bare Contact Rd");
139 expect(page).toContain('name="contact"');
139 expect(page).toContain('name="email"');
140 expect(page).toContain('name="phone"');
140141 expect(page).toContain("Save contact");
141142 expect(page.indexOf("<button class=\"button\" hidden")).toBeGreaterThan(-1);
142143 expect(page.indexOf("<button class=\"button\" hidden")).toBeLessThan(page.indexOf("Save contact"));
@@ -147,7 +148,7 @@ test("the contact field shows only while the party has no contact", async () =>
147148 test("Save contact fills it in, returns to the same draft, and keeps the edited words", async () => {
148149 const { page, at } = await bareDraft("32 Save Contact Rd");
149150 const s = shown(page);
150 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), contact: "[email protected]", subject: "My subject", body: "My words" });
151 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), email: "[email protected]", subject: "My subject", body: "My words" });
151152 expect(res.status).toBe(200);
152153 const after = await res.text();
153154 expect(shown(after).deadline).toBe(s.deadline);
@@ -162,17 +163,17 @@ test("Save contact fills it in, returns to the same draft, and keeps the edited
162163 test("bad contact input is a 422 that keeps what was typed and the edited words", async () => {
163164 const { page, at } = await bareDraft("33 Bad Contact Rd");
164165 const s = shown(page);
165 const long = "x".repeat(121);
166 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), contact: long, subject: "Kept subject", body: "Kept body" });
166 const long = "x".repeat(201);
167 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), email: long, subject: "Kept subject", body: "Kept body" });
167168 expect(res.status).toBe(422);
168169 const bad = await res.text();
169170 expect(bad).toContain("<b>Email or phone:</b>");
170171 expect(bad).toContain(long);
171172 expect(bad).toContain("Kept subject");
172173 expect(bad).toContain("Kept body");
173 const empty = await post("/reminders/today/contact", { ...keys(s), at: String(at), contact: " ", subject: "Kept subject", body: "Kept body" });
174 const empty = await post("/reminders/today/contact", { ...keys(s), at: String(at), email: " ", subject: "Kept subject", body: "Kept body" });
174175 expect(empty.status).toBe(422);
175 const anon = await post("/reminders/today/contact", { ...keys(s), contact: "[email protected]" }, {});
176 const anon = await post("/reminders/today/contact", { ...keys(s), email: "[email protected]" }, {});
176177 expect([401, 403]).toContain(anon.status);
177178 });
178179
@@ -188,7 +189,22 @@ test("Send on a draft with no contact still records the approval", async () => {
188189 test("a stale or tampered name posted with the contact renames no one", async () => {
189190 const { page, at } = await bareDraft("35 Name Rd");
190191 const s = shown(page);
191 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), name: "Mallory", contact: "[email protected]" });
192 const res = await post("/reminders/today/contact", { ...keys(s), at: String(at), name: "Mallory", email: "[email protected]" });
192193 expect(res.status).toBe(200);
193194 expect(await res.text()).not.toContain("Mallory");
194195 });
196
197 test("Save contact takes an email and a phone together, and a bad phone keeps both as typed", async () => {
198 const { page, at } = await bareDraft("36 Both Rd");
199 const s = shown(page);
200 const bad = await post("/reminders/today/contact", { ...keys(s), at: String(at), email: "[email protected]", phone: "call me" });
201 expect(bad.status).toBe(422);
202 const text = await bad.text();
203 expect(text).toContain('value="[email protected]"');
204 expect(text).toContain('value="call me"');
205 const good = await post("/reminders/today/contact", { ...keys(s), at: String(at), email: "[email protected]", phone: "(555) 010-0199" });
206 expect(good.status).toBe(200);
207 const after = await good.text();
208 expect(after).toContain("[email protected]");
209 expect(after).toContain("(555) 010-0199");
210 });
src/routes.ts +41 −14
@@ -177,15 +177,18 @@ export const AUDIT_ROW: Schema = {
177177 };
178178 const DATE: Schema = { type: "string", format: "date" };
179179 const ROLE: Schema = { enum: ["buyer", "seller", "lender", "title", "other_agent"] };
180 const CONTACT: Schema = { type: "string", deprecated: true, description: "Deprecated: the email, else the phone. Read email and phone instead; this reads for one more release." };
180181 const PARTY: Schema = {
181182 type: "object",
182 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, contact: { type: "string" } },
183 properties: { id: { type: "integer" }, role: ROLE, name: { type: "string" }, email: { type: "string", maxLength: 200 }, phone: { type: "string", maxLength: 30 }, contact: CONTACT },
183184 };
184185 export const PERSON: Schema = {
185186 type: "object",
186187 properties: {
187188 name: { type: "string" },
188 contact: { type: "string" },
189 email: { type: "string" },
190 phone: { type: "string" },
191 contact: CONTACT,
189192 roles: { type: "array", items: { type: "string" } },
190193 owes: {
191194 type: "array",
@@ -318,7 +321,12 @@ export const DEAL: Schema = {
318321 body: { type: "string", description: "The message that was sent, as approved." },
319322 href: {
320323 type: ["string", "null"],
321 description: "A mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone.",
324 description: "The first of hrefs: a mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone.",
325 },
326 hrefs: {
327 type: "array",
328 items: { type: "string" },
329 description: "Every link these words can go by: mailto: for the party's email, then sms: for their phone; empty when the party has neither, or is gone.",
322330 },
323331 },
324332 },
@@ -363,7 +371,9 @@ export const DRAFT: Schema = {
363371 party_id: { type: "integer" },
364372 party_name: { type: "string" },
365373 party_role: ROLE,
366 contact: { type: "string" },
374 email: { type: "string" },
375 phone: { type: "string" },
376 contact: CONTACT,
367377 moment: { enum: ["before", "day_of", "late", "moved", "status"] },
368378 on: DATE,
369379 subject: { type: "string" },
@@ -529,7 +539,7 @@ function sameDraft(c: Context, f: Record<string, string>, q: string, settled: nu
529539 ? queue.value.findIndex((d) => d.deadline_id === Number(f.deadline) && d.party_id === Number(f.party) && d.moment === f.moment)
530540 : -1;
531541 if (!queue.ok || same === -1) return undefined;
532 const typed = { subject: f.subject ?? "", body: f.body ?? "", reason: f.reason ?? "", contact: f.contact ?? "" };
542 const typed = { subject: f.subject ?? "", body: f.body ?? "", reason: f.reason ?? "", email: f.email ?? "", phone: f.phone ?? "" };
533543 return reviewPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), queue: queue.value, q, at: same, done: settled, error, typed });
534544 }
535545
@@ -546,9 +556,9 @@ async function reviewedContact(c: Context): Promise<Response> {
546556 const settled = count(f.done);
547557 const party = Number(f.party);
548558 const result: Result<unknown> =
549 (f.contact ?? "").trim() === ""
559 (f.email ?? "").trim() === "" && (f.phone ?? "").trim() === ""
550560 ? { ok: false, error: "invalid", message: "Add an email or phone to save." }
551 : editParty(c.db, c.who, { id: party, name: nameOf(c.db, "party", party), contact: f.contact });
561 : editParty(c.db, c.who, { id: party, name: nameOf(c.db, "party", party), email: f.email, phone: f.phone });
552562 if (!result.ok && (result.error === "signin_required" || result.error === "forbidden"))
553563 return html(refusedPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), path: reviewHref(q, at, settled), heading: "Review today's reminders", error: result.error, message: result.message }), STATUS[result.error]);
554564 const shown = sameDraft(c, f, q, settled, result.ok ? undefined : { field: "contact", message: result.message });
@@ -556,6 +566,18 @@ async function reviewedContact(c: Context): Promise<Response> {
556566 return html(shown, result.ok ? 200 : STATUS.invalid);
557567 }
558568
569 /** The deal a party is on, when they exist. */
570 const dealOfParty = (c: Context, party: number): number | undefined =>
571 c.db.query<{ deal_id: number }, [number]>("SELECT deal_id FROM party WHERE id = ?1").get(party)?.deal_id;
572
573 /** A party form that was refused for what was typed: the deal's page again, saying why, with the fields kept. */
574 function partyRefused(c: Context, dealId: number, id: number | "new", f: Record<string, string>, message: string): Response {
575 const found = getDeal(c.db, c.who, { id: dealId });
576 if (!found.ok) return back(found.message, `/deals/${dealId}`);
577 const party = { id, role: f.role ?? "", name: f.name ?? "", email: f.email ?? "", phone: f.phone ?? "", message };
578 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), party }), STATUS.invalid);
579 }
580
559581 const SENT = "Reminder sent.";
560582 const HELD = "Held until tomorrow.";
561583
@@ -834,7 +856,8 @@ export const routes: readonly Route[] = [
834856 const f = await form(c);
835857 if (f instanceof Response) return f;
836858 const id = Number(c.params.id);
837 return done(addParty(c.db, c.who, { dealId: id, role: f.role, name: f.name, contact: f.contact }), backTo(`/deals/${id}`), "Party added.");
859 const added = addParty(c.db, c.who, { dealId: id, role: f.role, name: f.name, email: f.email, phone: f.phone, contact: f.contact });
860 return added.ok || added.error !== "invalid" ? done(added, backTo(`/deals/${id}`), "Party added.") : partyRefused(c, id, "new", f, added.message);
838861 },
839862 },
840863 {
@@ -1090,7 +1113,11 @@ export const routes: readonly Route[] = [
10901113 handle: async (c) => {
10911114 const f = await form(c);
10921115 if (f instanceof Response) return f;
1093 return done(editParty(c.db, c.who, { id: Number(c.params.id), name: f.name, contact: f.contact }), backTo(f.to), "Party corrected.");
1116 const id = Number(c.params.id);
1117 const edited = editParty(c.db, c.who, { id, name: f.name, email: f.email, phone: f.phone, contact: f.contact });
1118 if (edited.ok || edited.error !== "invalid") return done(edited, backTo(f.to), "Party corrected.");
1119 const deal = dealOfParty(c, id);
1120 return deal === undefined ? back(edited.message, backTo(f.to)) : partyRefused(c, deal, id, f, edited.message);
10941121 },
10951122 },
10961123 {
@@ -1154,7 +1181,7 @@ export const routes: readonly Route[] = [
11541181 clear,
11551182 );
11561183 const sent = open === undefined ? undefined : listDeals(c.db, c.who);
1157 const link = open === undefined || !sent?.ok ? undefined : sent.value.flatMap((d) => d.sent).find((m) => m.id === open)?.href ?? null;
1184 const link = open === undefined || !sent?.ok ? undefined : sent.value.flatMap((d) => d.sent).find((m) => m.id === open)?.hrefs ?? [];
11581185 return html(
11591186 reviewPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), queue: queue.value, q, at: count(c.url.searchParams.get("at")), done: count(c.url.searchParams.get("done")), notice, open: link }),
11601187 200,
@@ -1320,14 +1347,14 @@ export const routes: readonly Route[] = [
13201347 if (body === undefined) return json({ error: "too_large" }, 413);
13211348 const f = fields(body);
13221349 return answer(
1323 editParty(c.db, c.who, { id: Number(c.params.party), dealId: Number(c.params.id), name: f.name, contact: f.contact }),
1350 editParty(c.db, c.who, { id: Number(c.params.party), dealId: Number(c.params.id), name: f.name, email: f.email, phone: f.phone, contact: f.contact }),
13241351 );
13251352 },
13261353 api: {
1327 summary: "Correct a party's name and contact (both are rewritten; a missing contact clears it). Their role stays.",
1354 summary: "Correct a party's name, email and phone (all are rewritten; a missing email or phone clears it; 422 for an email that is not [email protected] up to 200 characters, or a phone of digits, spaces and + - ( ) . up to 30). The deprecated contact is still read when neither email nor phone is sent. Their role stays.",
13281355 body: {
13291356 type: "object",
1330 properties: { name: { type: "string", minLength: 1, maxLength: 100 }, contact: { type: "string", maxLength: 120 } },
1357 properties: { name: { type: "string", minLength: 1, maxLength: 100 }, email: { type: "string", maxLength: 200 }, phone: { type: "string", maxLength: 30 }, contact: { ...CONTACT, maxLength: 200 } },
13311358 required: ["name"],
13321359 },
13331360 answer: PARTY,
@@ -1370,7 +1397,7 @@ export const routes: readonly Route[] = [
13701397 properties: { party_id: { type: "integer" }, subject: { type: "string", minLength: 1, maxLength: 150 }, body: { type: "string", minLength: 1, maxLength: 2000 } },
13711398 required: ["party_id"],
13721399 },
1373 answer: { type: "object", properties: { id: { type: "integer" }, subject: { type: "string" }, body: { type: "string" }, href: { type: ["string", "null"] } }, required: ["id", "subject", "body"] },
1400 answer: { type: "object", properties: { id: { type: "integer" }, subject: { type: "string" }, body: { type: "string" }, href: { type: ["string", "null"] }, hrefs: { type: "array", items: { type: "string" } } }, required: ["id", "subject", "body"] },
13741401 status: 201,
13751402 },
13761403 },
src/sample.ts +10 −6
@@ -8,7 +8,7 @@
88 import type { Database } from "bun:sqlite";
99 import { addDays, daysBetween, today } from "./dates.ts";
1010 import { type PartyRole } from "./deadlines.ts";
11 import { BRIEF_LENGTHS } from "./env.ts";
11 import { BRIEF_LENGTHS, validEmail } from "./env.ts";
1212 import { insertDeal } from "./deals.ts";
1313
1414 export const SAMPLE = { id: "sample", name: "Sample data" };
@@ -24,7 +24,8 @@ interface Sample {
2424 readonly price: number;
2525 readonly earnest: number;
2626 readonly lengths?: Partial<typeof BRIEF_LENGTHS>;
27 readonly parties: readonly [PartyRole, string, string][];
27 /** Role, name, email or phone, and a phone besides when the first is an email. */
28 readonly parties: readonly (readonly [PartyRole, string, string] | readonly [PartyRole, string, string, string])[];
2829 readonly done?: readonly string[];
2930 /** Kinds the buyer waived on purpose. */
3031 readonly waived?: readonly string[];
@@ -47,7 +48,7 @@ const SAMPLES: readonly Sample[] = [
4748 earnest: 12_750,
4849 lengths: { financing: 28 },
4950 parties: [
50 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]"],
51 ["lender", "Priya Nair, Coastline Mortgage", "[email protected]", "(555) 010-0177"],
5152 ["title", "Marcus Lee, Bayside Title", "[email protected]"],
5253 ["other_agent", "Jordan Ellis, Crestline Homes", "(555) 014-2290"],
5354 ],
@@ -69,7 +70,7 @@ const SAMPLES: readonly Sample[] = [
6970 price: 318_500,
7071 earnest: 6_000,
7172 parties: [
72 ["lender", "Owen Brandt, First Keel Bank", "[email protected]"],
73 ["lender", "Owen Brandt, First Keel Bank", "[email protected]", "(555) 010-0188"],
7374 ["title", "Bayside Title", "[email protected]"],
7475 ["other_agent", "Alicia Moreno, Moreno & Co.", "[email protected]"],
7576 ],
@@ -246,8 +247,11 @@ function writeSamples(db: Database, on: string): void {
246247 earnestAmount: s.earnest,
247248 });
248249 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);
249 for (const [role, name, contact] of s.parties)
250 db.query("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4)").run(deal.id, role, name, contact);
250 for (const [role, name, first, second] of s.parties) {
251 const email = validEmail(first) ? first : "";
252 const phone = second ?? (email === "" ? first : "");
253 db.query("INSERT INTO party (deal_id, role, name, contact, email, phone) VALUES (?1, ?2, ?3, ?4, ?5, ?6)").run(deal.id, role, name, email || phone, email, phone);
254 }
251255 for (const kind of s.done ?? [])
252256 db.query("UPDATE deadline SET done_at = ?1 WHERE deal_id = ?2 AND kind = ?3").run(`${addDays(on, -1)}T17:00:00.000Z`, deal.id, kind);
253257 for (const kind of s.waived ?? [])
src/terminal.test.ts +6 −6
@@ -84,8 +84,8 @@ test("o opens a deal; a adds a date, p a party; D removes it after a yes", () =>
8484 expect(lines(t)).toContain("12 Elm St");
8585 press(t, "a", "HOA review ends\r", `${addDays(today(), 5)}\r`, "buyer\r", "\r");
8686 expect(deal().deadlines.some((d) => d.label === "HOA review ends" && d.kind === "custom")).toBe(true);
87 press(t, "p", "lender\r", "Lee Lender\r", "[email protected]\r");
88 expect(deal().parties.some((p) => p.role === "lender" && p.contact === "[email protected]")).toBe(true);
87 press(t, "p", "lender\r", "Lee Lender\r", "[email protected]\r", "(555) 010-0166\r");
88 expect(deal().parties.some((p) => p.role === "lender" && p.email === "[email protected]" && p.phone === "(555) 010-0166")).toBe(true);
8989 expect(lines(t).join("\n")).toContain("[email protected]");
9090 press(t, "D", "no\r");
9191 expect(lines(t).join("\n")).toContain("Kept.");
@@ -226,8 +226,8 @@ test("e edits the party under the cursor; X removes a party or a custom date aft
226226 const rows = read().deadlines.length;
227227 for (let i = 0; i < rows + 2; i++) t.press("j");
228228 expect(under(t)).toContain("Lee Lender");
229 press(t, "e", "Lee Lender\r", "[email protected]\r");
230 expect(read().parties.find((p) => p.id === lender.value.id)?.contact).toBe("[email protected]");
229 press(t, "e", "Lee Lender\r", "[email protected]\r", "\r");
230 expect(read().parties.find((p) => p.id === lender.value.id)?.email).toBe("[email protected]");
231231 expect(under(t)).toContain("[email protected]");
232232 // X asks first; anything but yes keeps it.
233233 press(t, "X", "no\r");
@@ -671,13 +671,13 @@ test("the Messages view shows who a sent message goes to", () => {
671671 });
672672
673673 test("a reader who may not change a deal sees no contact and no link", () => {
674 const view = { ...deal(), parties: deal().parties.map((p) => ({ ...p, contact: "[email protected]" })), sent: [{ ...(sentOf()), href: "mailto:[email protected]?subject=s&body=b" }] };
674 const view = { ...deal(), parties: deal().parties.map((p) => ({ ...p, contact: "[email protected]", email: "[email protected]", phone: "555" })), sent: [{ ...(sentOf()), href: "mailto:[email protected]?subject=s&body=b" }] };
675675 const seen = shown({ role: "user", id: "u-reader", name: "reader" }, view);
676676 expect(canChange({ role: "user", id: "u-reader", name: "reader" }, view)).toBe(true);
677677 // With today's table every reader may work the deal; `shown` is what holds when update narrows.
678678 expect(seen).toBe(view);
679679 const narrowed = shown({ role: "anon" }, view);
680 expect(narrowed.parties.every((p) => p.contact === "")).toBe(true);
680 expect(narrowed.parties.every((p) => p.contact === "" && p.email === "" && p.phone === "")).toBe(true);
681681 expect(narrowed.sent.every((m) => m.href === null)).toBe(true);
682682 });
683683
src/terminal.ts +11 −9
@@ -72,6 +72,7 @@ import type { AuditRow } from "./audit.ts";
7272 import type { Result } from "./result.ts";
7373 import type { Who } from "./who.ts";
7474 import { people } from "./people.ts";
75 import { reachedAt } from "./outbox.ts";
7576 import { addresses, refusal, when, wording } from "./activity.ts";
7677 import { listAudit } from "./actions.ts";
7778 import { owner, thisWeek } from "./week.ts";
@@ -259,7 +260,7 @@ export function terminal(
259260 else
260261 ask(deal, [`Status update to ${party.name}, "${mine.subject}": type send to record it as sent, no and a reason to decline, or enter to cancel`], ([answer]) => {
261262 const text = (answer ?? "").trim();
262 if (text === "send") return report(sendStatusUpdate(db, me, { dealId: deal.id, partyId: party.id, subject: mine.subject, body: mine.body }), `Recorded as sent to ${party.name}. ${party.contact === "" ? "" : `Send it from your phone to ${party.contact}.`}`);
263 if (text === "send") return report(sendStatusUpdate(db, me, { dealId: deal.id, partyId: party.id, subject: mine.subject, body: mine.body }), `Recorded as sent to ${party.name}. ${party.contact === "" ? "" : `Send it from your phone to ${reachedAt(party)}.`}`);
263264 if (/^no\b/.test(text))
264265 return report(declineReminder(db, me, { dealId: deal.id, deadlineId: mine.deadline_id, partyId: party.id, moment: "status", reason: text.slice(2) }), `Not sent to ${party.name}.`);
265266 return "Not sent.";
@@ -290,8 +291,8 @@ export function terminal(
290291 if (key === "e") {
291292 if (party === undefined) said = "Move to a party to edit it.";
292293 else
293 ask(deal, [`Name (now ${party.name})`, `Email or phone (now ${party.contact === "" ? "none" : party.contact}; blank clears)`], ([name, contact]) =>
294 report(editParty(db, me, { id: party.id, name, contact }), `Corrected ${name}.`),
294 ask(deal, [`Name (now ${party.name})`, `Email (now ${party.email === "" ? "none" : party.email}; blank clears)`, `Phone (now ${party.phone === "" ? "none" : party.phone}; blank clears)`], ([name, email, phone]) =>
295 report(editParty(db, me, { id: party.id, name, email, phone }), `Corrected ${name}.`),
295296 );
296297 }
297298 if (key === "X") {
@@ -311,8 +312,8 @@ export function terminal(
311312 report(addDeadline(db, me, { dealId: deal.id, label, due, owes, what }), () => withConflicts(db, me, deal.id, `Added ${label}.`)),
312313 );
313314 if (key === "p")
314 ask(deal, [`Role (${PARTY_ROLES.join(", ")})`, "Name", "Email or phone (optional)"], ([role, name, contact]) =>
315 report(addParty(db, me, { dealId: deal.id, role, name, contact }), `Added ${name}.`),
315 ask(deal, [`Role (${PARTY_ROLES.join(", ")})`, "Name", "Email (optional)", "Phone (optional)"], ([role, name, email, phone]) =>
316 report(addParty(db, me, { dealId: deal.id, role, name, email, phone }), `Added ${name}.`),
316317 );
317318 if (key === "D") {
318319 prompt = {
@@ -421,7 +422,7 @@ export function terminal(
421422 body: draft.body,
422423 });
423424 if (sent.ok) edits.delete(id);
424 said = report(sent, `Recorded as sent to ${draft.party_name}: ${draft.label}, ${draft.address}. ${draft.contact === "" ? "No email or phone on file." : `Send it from your phone to ${draft.contact}.`}`);
425 said = report(sent, `Recorded as sent to ${draft.party_name}: ${draft.label}, ${draft.address}. ${reachedAt(draft) === "" ? "No email or phone on file." : `Send it from your phone to ${reachedAt(draft)}.`}`);
425426 }
426427 return true;
427428 }
@@ -720,7 +721,7 @@ export function terminal(
720721 const all = people(listed.value, day);
721722 if (all.length === 0) lines.push(dim("No one yet: add a deal and its parties."));
722723 for (const p of all) {
723 lines.push(`${bold(p.name)} ${dim(`${p.roles.join(", ")}${p.contact === "" ? "" : ` · ${p.contact}`}`)}`);
724 lines.push(`${bold(p.name)} ${dim(`${p.roles.join(", ")}${reachedAt(p) === "" ? "" : ` · ${reachedAt(p)}`}`)}`);
724725 if (p.owes.length === 0) lines.push(dim(" Nothing open"));
725726 for (const o of p.owes)
726727 lines.push(` ${tint(o.urgency, `${spoken(o.due).padEnd(12)} ${relative(o.due, day).padEnd(12)}`)} ${o.label} — ${o.address}`);
@@ -767,7 +768,8 @@ export function terminal(
767768 const text = `${m.party_name}${role} · ${m.label}, ${spoken(m.due)} · ${sentLabel(m.moment).toLowerCase()}`;
768769 lines.push(`${i === cursor ? "▸" : " "} ${dim(`sent ${m.sent_at.slice(0, 10)}`.padEnd(16))} ${i === cursor ? bold(text) : text}`);
769770 if (reading === i && canChange(me, deal)) {
770 const to = deal.parties.find((p) => p.id === m.party_id)?.contact ?? "";
771 const found = deal.parties.find((p) => p.id === m.party_id);
772 const to = found === undefined ? "" : reachedAt(found);
771773 lines.push("", ` ${dim(to === "" ? "No email or phone on file" : `To ${to}: send it from your phone`)}`);
772774 }
773775 if (reading === i) lines.push("", ` ${bold(m.subject === "" ? "(words not kept)" : m.subject)}`, ...m.body.split("\n").map((l) => ` ${l}`), "");
@@ -792,7 +794,7 @@ export function terminal(
792794 lines.push("", bold("Parties"));
793795 deal.parties.forEach((p, i) => {
794796 const at = deal.deadlines.length + i === cursor;
795 lines.push(`${at ? "▸" : " "} ${PARTY_LABEL[p.role].padEnd(14)} ${at ? bold(p.name) : p.name}${p.contact === "" ? "" : dim(` ${p.contact}`)}`);
797 lines.push(`${at ? "▸" : " "} ${PARTY_LABEL[p.role].padEnd(14)} ${at ? bold(p.name) : p.name}${reachedAt(p) === "" ? "" : dim(` ${reachedAt(p)}`)}`);
796798 });
797799 }
798800 } else {
src/twocontacts.test.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * A party keeps an email and a phone apart: the migration that split the old
3 * single contact, the boundary checks, both Send links from one record, and
4 * the pages and samples that show both.
5 */
6 import { Database } from "bun:sqlite";
7 import { expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { migrate, migrations } from "./db.ts";
12 import { addParty, createDeal, editParty, getDeal, sendReminder } from "./deals.ts";
13 import { openDb } from "./db.ts";
14 import { outboxes } from "./outbox.ts";
15 import { dealPage } from "./pages/deal.ts";
16 import { peoplePage } from "./pages/people.ts";
17 import { people } from "./people.ts";
18 import { listDeals } from "./deals.ts";
19 import type { Who } from "./who.ts";
20
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-two-")));
23 const opened = (db: Database) => {
24 const made = createDeal(db, alice, { openAnyway: true, address: "5 Two Contacts Ln", buyer: "Ann", seller: "Sam", contractDate: "2026-10-01", closingDate: "2026-12-06" });
25 if (!made.ok) throw new Error(made.message);
26 return made.value;
27 };
28
29 test("the migration sorts an existing email and an existing phone into their own fields", () => {
30 const db = new Database(":memory:");
31 const last = migrations.findIndex((m) => m.startsWith("ALTER TABLE party ADD COLUMN email"));
32 expect(last).toBeGreaterThan(0);
33 db.exec("PRAGMA foreign_keys = OFF");
34 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT '')");
35 for (const [i, sql] of migrations.slice(0, last).entries()) {
36 db.exec(sql);
37 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1);
38 }
39 const put = db.query("INSERT INTO party (deal_id, role, name, contact) VALUES (1, 'lender', ?1, ?2)");
40 put.run("E", " [email protected] ");
41 put.run("P", "+1 (555) 010-0142");
42 put.run("T", "Ask at the front desk");
43 put.run("N", "");
44 migrate(db);
45 const rows = db.query<{ name: string; email: string; phone: string; contact: string }, []>("SELECT name, email, phone, contact FROM party ORDER BY id").all();
46 expect(rows[0]).toMatchObject({ email: "[email protected]", phone: "" });
47 expect(rows[1]).toMatchObject({ email: "", phone: "+1 (555) 010-0142" });
48 expect(rows[2]).toMatchObject({ email: "", phone: "", contact: "Ask at the front desk" });
49 expect(rows[3]).toMatchObject({ email: "", phone: "" });
50 });
51
52 test("a bad email or phone is refused as invalid, and nothing is written", () => {
53 const db = fresh();
54 const deal = opened(db);
55 for (const email of ["not an email", `a"[email protected]`, "x".repeat(200) + "@x.co"]) {
56 const r = addParty(db, alice, { dealId: deal.id, role: "lender", name: "L", email });
57 expect(r.ok).toBe(false);
58 if (!r.ok) expect(r.error).toBe("invalid");
59 }
60 for (const phone of ["call me", "1".repeat(31), "abc"]) {
61 const r = addParty(db, alice, { dealId: deal.id, role: "lender", name: "L", phone });
62 expect(r.ok).toBe(false);
63 }
64 expect(getDeal(db, alice, { id: deal.id }).ok && (getDeal(db, alice, { id: deal.id }) as { value: { parties: unknown[] } }).value.parties).toHaveLength(2);
65 });
66
67 test("a party takes both, the old contact field is sorted into whichever it looks like, and editing rewrites both", () => {
68 const db = fresh();
69 const deal = opened(db);
70 const both = addParty(db, alice, { dealId: deal.id, role: "lender", name: "Priya", email: "[email protected]", phone: "(555) 010-0177" });
71 expect(both.ok && both.value).toMatchObject({ email: "[email protected]", phone: "(555) 010-0177", contact: "[email protected]" });
72 const old = addParty(db, alice, { dealId: deal.id, role: "title", name: "Tess", contact: "(555) 010-0100" });
73 expect(old.ok && old.value).toMatchObject({ email: "", phone: "(555) 010-0100" });
74 if (!both.ok) throw new Error();
75 const edited = editParty(db, alice, { id: both.value.id, name: "Priya", email: "", phone: "(555) 010-0177" });
76 expect(edited.ok && edited.value).toMatchObject({ email: "", phone: "(555) 010-0177", contact: "(555) 010-0177" });
77 });
78
79 test("a party with both yields both links, one with only one yields that one", () => {
80 const both = outboxes({ email: "[email protected]", phone: "(555) 010-0177", contact: "[email protected]" }, "Hi", "Words & more");
81 expect(both.map((o) => o.label)).toEqual(["Open in Mail", "Open in Messages"]);
82 expect(both[0]!.href).toBe("mailto:[email protected]?subject=Hi&body=Words%20%26%20more");
83 expect(both[1]!.href).toBe("sms:5550100177?&body=Words%20%26%20more");
84 expect(outboxes({ email: "", phone: "(555) 010-0177", contact: "" }, "s", "b").map((o) => o.kind)).toEqual(["sms"]);
85 expect(outboxes({ email: "", phone: "", contact: "" }, "s", "b")).toEqual([]);
86 });
87
88 test("Send records the approval once and offers both links, now and later", () => {
89 const db = fresh();
90 const deal = opened(db);
91 const party = addParty(db, alice, { dealId: deal.id, role: "lender", name: "Priya", email: "[email protected]", phone: "(555) 010-0177" });
92 if (!party.ok) throw new Error(party.message);
93 const inspection = deal.deadlines.find((d) => d.kind === "inspection")!;
94 const sent = sendReminder(db, alice, { deadlineId: inspection.id, partyId: party.value.id, moment: "before", subject: "Approved", body: "These words" });
95 if (!sent.ok) throw new Error(sent.message);
96 expect(sent.value.hrefs).toHaveLength(2);
97 expect(sent.value.href).toBe(sent.value.hrefs[0]!);
98 expect(sent.value.hrefs[0]).toContain("mailto:[email protected]");
99 expect(sent.value.hrefs[1]).toContain("sms:5550100177");
100 const again = sendReminder(db, alice, { deadlineId: inspection.id, partyId: party.value.id, moment: "before", subject: "Approved", body: "These words" });
101 expect(again.ok && again.value.id).toBe(sent.value.id);
102 expect(db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM reminder WHERE party_id = ?1").get(party.value.id)!.n).toBe(1);
103 const shown = getDeal(db, alice, { id: deal.id });
104 if (!shown.ok) throw new Error();
105 const page = dealPage({ who: alice, deal: shown.value, on: "2026-11-01" });
106 expect(page).toContain("Open in Mail");
107 expect(page).toContain("Open in Messages");
108 expect(page).toContain(`href="tel:5550100177"`);
109 expect(page).toContain(`href="mailto:[email protected]"`);
110 });
111
112 test("the People page shows both as links", () => {
113 const db = fresh();
114 const deal = opened(db);
115 addParty(db, alice, { dealId: deal.id, role: "lender", name: "Priya", email: "[email protected]", phone: "(555) 010-0177" });
116 const all = listDeals(db, alice);
117 if (!all.ok) throw new Error();
118 const page = peoplePage({ who: alice, people: people(all.value, "2026-11-01"), on: "2026-11-01" });
119 expect(page).toContain(`href="mailto:[email protected]"`);
120 expect(page).toContain(`href="tel:5550100177"`);
121 expect(page).toContain(`href="sms:5550100177"`);
122 });
123
124 test("a refused party form on the deal's page comes back 422 keeping what was typed", () => {
125 const db = fresh();
126 const deal = opened(db);
127 const shown = getDeal(db, alice, { id: deal.id });
128 if (!shown.ok) throw new Error();
129 const page = dealPage({ who: alice, deal: shown.value, on: "2026-11-01", party: { id: "new", role: "title", name: "Tess", email: "[email protected]", phone: "call me", message: "A phone is digits" } });
130 expect(page).toContain('value="[email protected]"');
131 expect(page).toContain('value="call me"');
132 expect(page).toContain("A phone is digits");
133 });
134
135 test("the sample deals give at least one party both, and the deprecated contact still reads", () => {
136 const db = fresh();
137 const all = listDeals(db, { role: "user", id: "sample", name: "sample" } as Who);
138 const rows = db.query<{ email: string; phone: string; contact: string }, []>("SELECT email, phone, contact FROM party").all();
139 expect(rows.some((r) => r.email !== "" && r.phone !== "")).toBe(true);
140 expect(rows.every((r) => r.contact === (r.email || r.phone))).toBe(true);
141 void all;
142 });
143
144 // ---- over the wire ----
145
146 import { afterAll } from "bun:test";
147 import { serve } from "./server.ts";
148 import { sign } from "./who.ts";
149
150 const KEY = "a-key-only-the-forge-holds";
151 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-two-http-")), identityKey: KEY });
152 const base = `http://${server.hostname}:${server.port}`;
153 afterAll(() => server.stop(true));
154 const identity = `u1|alice|user|${Date.now() + 600_000}`;
155 const signed = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
156
157 test("the party form refuses a bad email with a 422 that keeps the fields, and the API carries email and phone", async () => {
158 const made = await fetch(base + "/api/deals", { method: "POST", headers: { ...signed, "content-type": "application/json" }, body: JSON.stringify({ address: "8 Wire Rd", buyer: "Ann", seller: "Sam", contract_date: "2026-10-01", closing_date: "2026-12-06" }) });
159 const deal = (await made.json()) as { id: number };
160 const post = (path: string, fields: Record<string, string>) =>
161 fetch(base + path, { method: "POST", body: new URLSearchParams(fields), headers: { ...signed, "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" });
162 const bad = await post(`/deals/${deal.id}/parties`, { role: "lender", name: "Priya", email: "nope", phone: "(555) 010-0177" });
163 expect(bad.status).toBe(422);
164 const html = await bad.text();
165 expect(html).toContain('value="nope"');
166 expect(html).toContain('value="(555) 010-0177"');
167 const good = await post(`/deals/${deal.id}/parties`, { role: "lender", name: "Priya", email: "[email protected]", phone: "(555) 010-0177" });
168 expect(good.status).toBe(303);
169 const read = (await (await fetch(`${base}/api/deals/${deal.id}`, { headers: signed })).json()) as { parties: { name: string; email: string; phone: string; contact: string }[] };
170 expect(read.parties.find((p) => p.name === "Priya")).toMatchObject({ email: "[email protected]", phone: "(555) 010-0177", contact: "[email protected]" });
171 const api = await fetch(`${base}/api/deals/${deal.id}/parties/${(read.parties as unknown as { id: number }[]).at(-1)!.id}`, { method: "PATCH", headers: { ...signed, "content-type": "application/json" }, body: JSON.stringify({ name: "Priya", email: "bad email" }) });
172 expect(api.status).toBe(422);
173 });
174
175 test("an old free-text contact is kept on add and on a rename, and the edit form carries it", () => {
176 const db = fresh();
177 const deal = opened(db);
178 const t = addParty(db, alice, { dealId: deal.id, role: "title", name: "Tess", contact: "Ask at the front desk" });
179 expect(t.ok && t.value).toMatchObject({ email: "", phone: "", contact: "Ask at the front desk" });
180 if (!t.ok) throw new Error();
181 const renamed = editParty(db, alice, { id: t.value.id, name: "Tess T.", contact: "Ask at the front desk" });
182 expect(renamed.ok && renamed.value).toMatchObject({ name: "Tess T.", contact: "Ask at the front desk" });
183 const got = getDeal(db, alice, { id: deal.id });
184 if (!got.ok) throw new Error();
185 expect(dealPage({ who: alice, on: "2026-10-10", deal: got.value } as never)).toContain('<input type="hidden" name="contact" value="Ask at the front desk">');
186 });
187
188 test("a person with only a phone on one deal and both on another is one person", () => {
189 const db = fresh();
190 const a = opened(db);
191 const b = createDeal(db, alice, { openAnyway: true, address: "6 Other Ln", buyer: "Bo", seller: "Si", contractDate: "2026-10-01", closingDate: "2026-12-06" });
192 if (!b.ok) throw new Error();
193 addParty(db, alice, { dealId: a.id, role: "lender", name: "Priya", phone: "(555) 010-0177" });
194 addParty(db, alice, { dealId: b.value.id, role: "lender", name: "Priya N.", email: "[email protected]", phone: "(555) 010-0177" });
195 addParty(db, alice, { dealId: b.value.id, role: "lender", name: "Priya N.", email: "[email protected]" });
196 const all = people((listDeals(db, alice) as { value: never }).value, "2026-10-10");
197 expect(all.filter((p) => p.name.startsWith("Priya"))).toHaveLength(1);
198 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs