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

New deal shows every computed date before it is opened, and a refused form keeps what was typed #22

Merged opened this

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

Merged

mason/deal-clock:mason/12-new-deal-shows-every-computed-date-befor → main 3 commits fork 3 threads · 3 unresolved

  • Merged. mason/12-new-deal-shows-every-computed-date-befor was merged into main as 6c86e19.

Review

Sign in to review this change.
11 files changed +257 −28
README.md +5 −1
@@ -60,7 +60,11 @@ since they were last set, so the screen always looks like today.
6060 buyer, seller, contract date and closing date. The standard lengths are
6161 already filled in (inspection 10 days, appraisal 21, financing 30, title 14,
6262 final walkthrough the day before closing) and you can change them; tick
63 Count business days to skip weekends. Tap Open deal. You land on the new
63 Count business days to skip weekends. Tap Check the dates to see every
64 date the deal would get (label, weekday and date, who owes it) without
65 saving anything; a refused form comes back with what you typed and the
66 reason beside its field. In the terminal, press c instead of n for the same
67 list. Tap Open deal. You land on the new
6468 deal's page with every date worked out, and it has its own lane on the clock.
6569 11. **Download the calendar file.** On a deal's page, tap Add to calendar.
6670 You get a calendar file with every date of the deal and an alarm three days
docs/TECHNICAL.md +2 −1
@@ -36,7 +36,8 @@ goes as it is.
3636
3737 The terminal does the page's work too. It opens on every open date, soonest
3838 first: `n` opens a new deal (address, buyer, seller, contract date, closing
39 date; the standard lengths do the rest), `x` marks the date under the cursor
39 date; the standard lengths do the rest; `c` asks the same five questions and
40 lists every date `n` would create, writing nothing), `x` marks the date under the cursor
4041 done, `u` reopens it, `m` moves it (the new date, then the reason), `o` opens
4142 its deal — where `a` adds a date,
4243 `p` adds a party, `e` edits the party under the cursor (the cursor walks the
docs/design/areas/new-deal.md added +6
@@ -0,0 +1,6 @@
1 # New deal
2
3 New classes on `/deals/new`:
4
5 - `.actions` — the form's buttons side by side, wrapping at 360px.
6 - `.field-error` — a refusal's reason beside the field it concerns, in the overdue colour, 14px, bold.
src/deals.ts +25 −6
@@ -258,23 +258,31 @@ export interface Plan {
258258 export function plan(input: NewDeal): Result<Plan> {
259259 const address = line(input.address, 3, 200);
260260 if (address === undefined)
261 return fail("invalid", "The address is 3 to 200 characters.");
261 return fail("invalid", "The address is 3 to 200 characters.", "address");
262262 const buyer = line(input.buyer, 1, 100);
263263 const seller = line(input.seller, 1, 100);
264264 if (buyer === undefined || seller === undefined)
265 return fail("invalid", "Name the buyer and the seller (up to 100 characters each).");
265 return fail(
266 "invalid",
267 "Name the buyer and the seller (up to 100 characters each).",
268 buyer === undefined ? "buyer" : "seller",
269 );
266270 const { contractDate, closingDate } = input;
267271 if (!isDate(contractDate) || !isDate(closingDate))
268 return fail("invalid", "The contract and closing dates are dates (YYYY-MM-DD).");
272 return fail(
273 "invalid",
274 "The contract and closing dates are dates (YYYY-MM-DD).",
275 isDate(contractDate) ? "closing_date" : "contract_date",
276 );
269277 if (closingDate <= contractDate)
270 return fail("invalid", "Closing comes after the contract date.");
278 return fail("invalid", "Closing comes after the contract date.", "closing_date");
271279 const lengths = { ...DEFAULT_LENGTHS };
272280 for (const key of Object.keys(DEFAULT_LENGTHS) as (keyof Lengths)[]) {
273281 const raw = input.lengths?.[key];
274282 if (raw === undefined || raw === "") continue;
275283 const n = Number(raw);
276284 if (!Number.isInteger(n) || n < 0 || n > LENGTH_MAX)
277 return fail("invalid", `The ${key} length is a whole number of days, 0 to ${LENGTH_MAX}.`);
285 return fail("invalid", `The ${key} length is a whole number of days, 0 to ${LENGTH_MAX}.`, key);
278286 lengths[key] = n;
279287 }
280288 const businessDays =
@@ -282,6 +290,17 @@ export function plan(input: NewDeal): Result<Plan> {
282290 return ok({ address, buyer, seller, contractDate, closingDate, lengths, businessDays });
283291 }
284292
293 /** A date a plan would create, as `insertDeal` writes it. */
294 export interface PlannedDate {
295 readonly label: string;
296 readonly due: string;
297 readonly owes: PartyRole;
298 }
299
300 /** Every date `insertDeal` would create for this plan, in order — and nothing written. */
301 export const plannedDates = (p: Plan): PlannedDate[] =>
302 schedule(p).map(({ kind, due }) => ({ label: KIND[kind].label, due, owes: KIND[kind].owes }));
303

plannedDates is only reachable from the page; give the terminal's new-deal flow the same preview so both doors can do it.

285304 /** Write a planned deal: the deal, its buyer and seller, and the standard dates. */
286305 export function insertDeal(
287306 db: Database,
@@ -352,7 +371,7 @@ function update(
352371 if (!found.ok) return found;
353372 const address = line(input.address, 3, 200);
354373 if (address === undefined)
355 return fail("invalid", "The address is 3 to 200 characters.");
374 return fail("invalid", "The address is 3 to 200 characters.", "address");
356375 db.query("UPDATE deal SET address = ?1 WHERE id = ?2").run(address, found.value.id);
357376 emit("deal.changed", { id: found.value.id });
358377 return ok(view(db, { ...found.value, address }));
src/pages/deal.ts +57 −12
@@ -5,7 +5,7 @@
55 */
66
77 import { addDays, relative, spoken } from "../dates.ts";
8 import { canChange, canRemove, type DealView, type Party } from "../deals.ts";
8 import { canChange, canRemove, type DealView, type Party, type Plan, type PlannedDate } from "../deals.ts";
99 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1010 import { escape } from "../http.ts";
1111 import type { Who } from "../who.ts";
@@ -115,10 +115,50 @@ export function dealPage(input: {
115115 return layout({ body, who, path, heading: deal.address, notice });
116116 }
117117
118 export function newDealPage(input: { who: Who; on: string; notice?: string | undefined }): string {
119 const { who, on, notice } = input;
118 /** What the form was last sent with, what was wrong with it, and the dates it would make. */
119 export interface NewDealState {
120 readonly values: Readonly<Record<string, string>>;
121 readonly problem?: { readonly field?: string | undefined; readonly message: string } | undefined;
122 readonly preview?: { readonly plan: Plan; readonly dates: readonly PlannedDate[] } | undefined;
123 }
124
125 const previewList = ({ plan, dates }: NonNullable<NewDealState["preview"]>): string => {
126 const who = (d: PlannedDate): string =>
127 d.owes === "buyer" ? plan.buyer : d.owes === "seller" ? plan.seller : PARTY_LABEL[d.owes];
128 return `<section class="card narrow" id="preview" aria-labelledby="preview-h">
129 <h2 id="preview-h">The dates this deal would get</h2>
130 <p class="muted small">Nothing is saved yet. <b>Open deal</b> creates exactly these.</p>
131 <ol class="dates">${dates
132 .map(
133 (d) => `<li class="date-row"><div><p><b>${escape(d.label)}</b></p><p class="muted small">${escape(spoken(d.due))} · ${escape(who(d))}</p></div></li>`,
134 )
135 .join("")}</ol>
136 </section>`;
137 };
138
139 export function newDealPage(input: {
140 who: Who;
141 on: string;
142 notice?: string | undefined;
143 state?: NewDealState | undefined;
144 }): string {
145 const { who, on, notice, state } = input;
146 const values = state?.values ?? {};
147 const problem = state?.problem;
148 const val = (name: string, fallback: string): string => escape(values[name] ?? fallback);
149 const why = (name: string): string =>
150 problem?.field === name
151 ? `<span class="field-error" id="${name}-why" role="alert">${escape(problem.message)}</span>`
152 : "";
153 const bad = (name: string): string =>
154 problem?.field === name ? ` aria-invalid="true" aria-describedby="${name}-why"` : "";
155 const general =
156 problem !== undefined && problem.field === undefined
157 ? `<p class="field-error" role="alert">${escape(problem.message)}</p>`
158 : "";
120159 const length = (name: keyof typeof DEFAULT_LENGTHS, label: string) =>
121 `<label>${label}<input class="input" type="number" inputmode="numeric" name="${name}" min="0" max="180" value="${DEFAULT_LENGTHS[name]}" required></label>`;
160 `<label>${label}<input class="input" type="number" inputmode="numeric" name="${name}" min="0" max="180" value="${val(name, String(DEFAULT_LENGTHS[name]))}" required${bad(name)}>${why(name)}</label>`;
161 const ticked = values.business_days !== undefined;
122162 const body =
123163 who.role === "anon"
124164 ? `<p class="crumb"><a href="/">← The clock</a></p><section class="card"><h1>New deal</h1><p><a href="/__forge/signin?to=/deals/new">Sign in</a> to open a deal.</p></section>`
@@ -127,14 +167,15 @@ export function newDealPage(input: { who: Who; on: string; notice?: string | und
127167 <h1>New deal</h1>
128168 <p class="muted">The contract and closing dates, and the contingency lengths, set every date. You can move any of them after.</p>
129169 <form class="stack" method="post" action="/deals">
130 <label>Property address<input class="input" name="address" required minlength="3" maxlength="200" autocomplete="off" placeholder="1418 Alder Lane"></label>
170 ${general}
171 <label>Property address<input class="input" name="address" required minlength="3" maxlength="200" autocomplete="off" placeholder="1418 Alder Lane" value="${val("address", "")}"${bad("address")}>${why("address")}</label>
131172 <div class="pair">
132 <label>Buyer<input class="input" name="buyer" required maxlength="100"></label>
133 <label>Seller<input class="input" name="seller" required maxlength="100"></label>
173 <label>Buyer<input class="input" name="buyer" required maxlength="100" value="${val("buyer", "")}"${bad("buyer")}>${why("buyer")}</label>
174 <label>Seller<input class="input" name="seller" required maxlength="100" value="${val("seller", "")}"${bad("seller")}>${why("seller")}</label>
134175 </div>
135176 <div class="pair">
136 <label>Contract date<input class="input" type="date" name="contract_date" required value="${escape(on)}"></label>
137 <label>Closing date<input class="input" type="date" name="closing_date" required value="${escape(addDays(on, 35))}"></label>
177 <label>Contract date<input class="input" type="date" name="contract_date" required value="${val("contract_date", on)}"${bad("contract_date")}>${why("contract_date")}</label>
178 <label>Closing date<input class="input" type="date" name="closing_date" required value="${val("closing_date", addDays(on, 35))}"${bad("closing_date")}>${why("closing_date")}</label>
138179 </div>
139180 <fieldset>
140181 <legend>Contingency lengths, in days from the contract date</legend>
@@ -145,11 +186,15 @@ export function newDealPage(input: { who: Who; on: string; notice?: string | und
145186 ${length("title", "Title")}
146187 ${length("walkthrough", "Walkthrough, days before closing")}
147188 </div>
148 <label class="check"><input type="checkbox" name="business_days"> Count business days (skip weekends)</label>
189 <label class="check"><input type="checkbox" name="business_days"${ticked ? " checked" : ""}> Count business days (skip weekends)</label>
149190 </fieldset>
150 <button class="button">Open deal</button>
191 <div class="actions">
192 <button class="button">Open deal</button>
193 <button class="button button-quiet" formaction="/deals/check">Check the dates</button>
194 </div>
151195 </form>
152196 <p class="muted small">Reading these from the contract PDF is phase two.</p>
153 </section>`;
197 </section>
198 ${state?.preview === undefined ? "" : previewList(state.preview)}`;
154199 return layout({ body, who, path: "/deals/new", heading: "New deal", notice });
155200 }
src/result.ts +4 −2
@@ -12,12 +12,14 @@ import type { Who } from "./who.ts";
1212 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
1313 export type Result<T> =
1414 | { ok: true; value: T }
15 | { ok: false; error: Failure; message: string };
15 | { ok: false; error: Failure; message: string; field?: string };
1616 export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
17 export const fail = <T>(error: Failure, message: string): Result<T> => ({
17 /** `field` names the input a form should put the message beside. */
18 export const fail = <T>(error: Failure, message: string, field?: string): Result<T> => ({
1819 ok: false,
1920 error,
2021 message,
22 ...(field === undefined ? {} : { field }),
2123 });
2224
2325 /** The refusal for a "no": who is not signed in is asked to; who is, is told. */
src/routes.ts +22 −1
@@ -44,6 +44,9 @@ import {
4444 getDeal,
4545 listDeals,
4646 markDone,
47 mayOpen,
48 plan,
49 plannedDates,
4750 moveDeadline,
4851 removeDeadline,
4952 removeParty,
@@ -347,7 +350,25 @@ export const routes: readonly Route[] = [
347350 const f = await form(c);
348351 if (f instanceof Response) return f;
349352 const made = createDeal(c.db, c.who, newDeal(f));
350 return made.ok ? back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`) : back(made.message, "/deals/new");
353 if (made.ok) return back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`);
354 if (made.error !== "invalid") return back(made.message, "/deals/new");
355 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: made } }), 422);
356 },
357 },
358 {
359 // The same fields and the same checks as opening a deal; writes nothing.
360 method: "POST",
361 path: "/deals/check",
362 handle: async (c) => {

Add a test that an anon caller gets the sign-in redirect here and nothing is rendered or written.

363 const f = await form(c);
364 if (f instanceof Response) return f;
365 const may = mayOpen(c.who);
366 if (!may.ok) return back(may.message, "/deals/new");
367 const planned = plan(newDeal(f));
368 if (!planned.ok)
369 return html(newDealPage({ who: c.who, on: today(), state: { values: f, problem: planned } }), 422);
370 const preview = { plan: planned.value, dates: plannedDates(planned.value) };
371 return html(newDealPage({ who: c.who, on: today(), state: { values: f, preview } }));
351372 },
352373 },
353374 {
src/server.test.ts +83
@@ -608,3 +608,86 @@ test("a party is corrected and removed from the page and the API; a custom date
608608 expect((await post(`/deadlines/${hoa.id}/remove`, { to: `/deals/${deal.id}` })).status).toBe(303);
609609 expect((await api(`/api/deals/${deal.id}/deadlines/${hoa.id}`, { method: "DELETE" }, mia)).status).toBe(404);
610610 });
611
612 test("Check the dates lists what Open deal would create, and writes nothing", async () => {
613 const dana = as("u7", "dana");
614 const count = async () => ((await (await api("/api/deals", {}, dana)).json()) as unknown[]).length;
615 const before = await count();
616 const send = (extra: Record<string, string>) => {
617 const f = new FormData();
618 for (const [k, v] of Object.entries({
619 address: "7 Preview <b>Row</b>",
620 buyer: "Pat",
621 seller: "Lee",
622 contract_date: "2026-10-02", // a Friday
623 closing_date: "2026-11-20",
624 ...extra,
625 }))
626 f.set(k, v);
627 return api("/deals/check", { method: "POST", body: f }, dana);
628 };
629 const calendar = await (await send({})).text();
630 expect(calendar).toContain("Inspection period ends");
631 expect(calendar).toContain("Mon, Oct 12"); // 10 calendar days after Oct 2
632 expect(calendar).toContain("7 Preview &lt;b&gt;Row&lt;/b&gt;");
633 expect(calendar).not.toContain("<b>Row</b>");
634 const business = await (await send({ business_days: "on", inspection: "3" })).text();
635 expect(business).toContain("Wed, Oct 7"); // 3 business days after a Friday
636 expect(business).toContain('name="business_days" checked');
637 expect(calendar).not.toContain('name="business_days" checked');
outdated

Weak: "checked" matches other markup. Assert name="business_days" checked.

638 expect(await count()).toBe(before);
639 });
640
641 const erin = as("u8", "erin");
642
643 test("a refused form comes back with what was typed, escaped, and the reason by its field", async () => {
644 const f = new FormData();
645 for (const [k, v] of Object.entries({
646 address: `8 "Quote" <i>Lane`,
647 buyer: "Pat",
648 seller: "Lee",
649 contract_date: "2026-10-10",
650 closing_date: "2026-10-01",
651 }))
652 f.set(k, v);
653 for (const path of ["/deals", "/deals/check"]) {
654 const res = await api(path, { method: "POST", body: f, redirect: "manual" }, erin);
655 expect(res.status).toBe(422);
656 const page = await res.text();
657 expect(page).toContain("8 &quot;Quote&quot; &lt;i&gt;Lane");
658 expect(page).not.toContain("<i>Lane");
659 expect(page).toContain('id="closing_date-why"');
660 expect(page).toContain("Closing comes after the contract date.");
661 }
662 });
663
664 test("Check the dates refuses a guest and writes nothing; a refusal with no field shows its message", async () => {
665 const f = new FormData();
666 for (const [k, v] of Object.entries({
667 address: "10 Guest Road",
668 buyer: "Pat",
669 seller: "Lee",
670 contract_date: "2026-10-02",
671 closing_date: "2026-11-20",
672 }))
673 f.set(k, v);
674 const guest = await api("/deals/check", { method: "POST", body: f, redirect: "manual" });
675 expect(guest.status).toBe(303);
676 expect(guest.headers.get("location")).toBe("/deals/new");
677 expect(guest.headers.get("set-cookie")).toContain("notice=");
678 expect(await guest.text()).not.toContain("10 Guest Road");
679 const frank = as("u9", "frank");
680 const listed = (await (await api("/api/deals", {}, frank)).json()) as { address: string }[];
681 expect(listed.some((d) => d.address === "10 Guest Road")).toBe(false);
682 // A refusal that names no field renders its message above the form, escaped.
683 // (plan() names a field for every refusal today; the page still has to cope.)
684 const { newDealPage } = await import("./pages/deal.ts");
685 const page = newDealPage({
686 who: { role: "user", id: "u9", name: "frank" },
687 on: "2026-10-01",
688 state: { values: { address: "<u>x" }, problem: { message: "Try <again>." } },
689 });
690 expect(page).toContain('<p class="field-error" role="alert">Try &lt;again&gt;.</p>');
691 expect(page).toContain("&lt;u&gt;x");
692 expect(page).not.toContain("-why");
693 });
src/terminal.test.ts +21
@@ -161,6 +161,27 @@ test("n opens a deal from five answers, and shows it", () => {
161161 expect(lines(t).join("\n")).toContain("The address is 3 to 200 characters.");
162162 });
163163
164 test("c lists the dates n would create and writes nothing; a guest is asked to sign in", () => {
165 const before = listDeals(db, alice);
166 if (!before.ok) throw new Error(before.message);
167 const t = terminal(db, alice, context);
168 press(t, "c", "44 Cedar Way\r", "Kim Buyer\r", "Lou Seller\r", "2026-10-02\r", "2026-11-20\r");
169 const shown = lines(t).join("\n");
170 expect(shown).toContain("Dates for 44 Cedar Way");
171 expect(shown).toContain("Mon, Oct 12");
172 expect(shown).toContain("Inspection period ends");
173 expect(shown).toContain("Kim Buyer");
174 const after = listDeals(db, alice);
175 if (!after.ok) throw new Error(after.message);
176 expect(after.value.length).toBe(before.value.length);
177 press(t, "c", "x\r", "A\r", "B\r", "soon\r", "later\r");
178 expect(lines(t).join("\n")).toContain("The address is 3 to 200 characters.");
179 const guest = terminal(db, { role: "anon" }, context);
180 guest.press("c");
181 expect(lines(guest).join("\n")).toContain("Sign in to open a deal.");
182 expect(lines(guest).join("\n")).not.toContain("Property address");
183 });
184
164185 test("a guest sees no deals, and is asked to sign in before anything — n included", () => {
165186 const t = terminal(db, { role: "anon" }, context);
166187 expect(lines(t).join("\n")).toContain("Sign in to see deals.");
src/terminal.ts +22 −5
@@ -27,6 +27,9 @@ import {
2727 listDeals,
2828 markDone,
2929 mayOpen,
30 plan,
31 plannedDates,
32 type NewDeal,
3033 moveDeadline,
3134 removeDeadline,
3235 removeParty,
@@ -34,7 +37,7 @@ import {
3437 type DealView,
3538 type DeadlineView,
3639 } from "./deals.ts";
37 import { PARTY_LABEL, PARTY_ROLES } from "./deadlines.ts";
40 import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
3841 import { drafts, MOMENT_LABEL, type Agent, type Draft } from "./reminders.ts";
3942 import type { Result } from "./result.ts";
4043 import type { Who } from "./who.ts";
@@ -275,6 +278,18 @@ export function terminal(
275278 }
276279 }
277280
281 /** The dates `n` would create for these answers, one per line; nothing is written. */
282 function previewDates(input: NewDeal): string {
283 const planned = plan(input);
284 if (!planned.ok) return planned.message;
285 const p = planned.value;
286 const owner = (role: PartyRole): string => (role === "buyer" ? p.buyer : role === "seller" ? p.seller : PARTY_LABEL[role]);
287 return [
288 `Dates for ${p.address} (nothing saved; n opens it):`,
289 ...plannedDates(p).map((d) => ` ${spoken(d.due).padEnd(12)} ${d.label} — ${owner(d.owes)}`),
290 ].join("\n");
291 }
292
278293 function press(chunk: string): void {
279294 if (prompt !== undefined) return typing(chunk);
280295 // Keys typed fast, or pasted, arrive together: each is its own press, and
@@ -298,7 +313,7 @@ export function terminal(
298313 view = "reminders";
299314 cursor = 0;
300315 reading = undefined;
301 } else if (key === "n") {
316 } else if (key === "n" || key === "c") {
302317 const may = mayOpen(me);
303318 if (!may.ok) said = may.message;
304319 else
@@ -307,7 +322,9 @@ export function terminal(
307322 answers: [],
308323 text: "",
309324 finish: ([address, buyer, seller, contractDate, closingDate]) => {
310 const made = createDeal(db, me, { address, buyer, seller, contractDate, closingDate });
325 const input = { address, buyer, seller, contractDate, closingDate };
326 if (key === "c") return previewDates(input);
327 const made = createDeal(db, me, input);
311328 if (!made.ok) return made.message;
312329 view = "deal";
313330 dealId = made.value.id;
@@ -376,13 +393,13 @@ export function terminal(
376393 if (prompt !== undefined)
377394 lines.push(`${prompt.steps[prompt.answers.length]}: ${prompt.text}${esc}7m ${esc}0m`, dim("enter to go on · esc to cancel"));
378395 else {
379 if (said !== "") lines.push(said);
396 if (said !== "") lines.push(...said.split("\n"));
380397 const keys =
381398 view === "reminders"
382399 ? "j/k move · enter read · e edit · s send · d dates · q quit"
383400 : view === "deal"
384401 ? "j/k move · x done · u reopen · m move · a add date · p add party · e edit party · X remove date/party · D remove deal · b back · q quit"
385 : `j/k move · x done · u reopen · m move · o open deal · n new deal · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;
402 : `j/k move · x done · u reopen · m move · o open deal · n new deal · c check dates · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;
386403 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
387404 }
388405 return lines;
static/app.css +10
@@ -666,6 +666,16 @@ footer code {
666666 .stack .button {
667667 justify-self: start;
668668 }
669 .actions {
670 display: flex;
671 flex-wrap: wrap;
672 gap: var(--space-3);
673 }
674 .field-error {
675 color: var(--color-overdue);
676 font-size: var(--text-sm);
677 font-weight: 600;
678 }
669679 .pair,
670680 .lengths {
671681 display: grid;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs