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

The sample deals stay sensible when the app boots across a month or year end, pinned by a test #256

Merged opened this

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

Merged

mason/deal-clock:mason/254-the-sample-deals-stay-sensible-when-the → main 2 commits fork 3 threads · 3 unresolved

  • Merged. mason/254-the-sample-deals-stay-sensible-when-the was merged into main as 71e8e15.

Review

Sign in to review this change.
9 files changed +131 −21
README.md +5 −3
@@ -9,10 +9,12 @@ Whoever builds or runs the app will find the rest in
99
1010 ## A five-minute tour on the sample deals
1111
12 Seven sample deals are already in, so the first screen is never empty. Four
12 Eight sample deals are already in, so the first screen is never empty. Four
1313 are open: 1418 Alder Lane, 77 Harbor View Dr (Unit 4B), 9 Orchard Row and 2210
1414 Juniper Court. Three closed earlier this year: 35 Mill Pond Road, 602 Cedar
15 Heights Blvd and 14 Saltmarsh Lane. The samples stay current: every time the
15 Heights Blvd and 14 Saltmarsh Lane. One, 58 Larkspur Way, closed a year ago
16 today, so its home anniversary note waits in Review. No sample date falls on a
17 weekend or a federal holiday. The samples stay current: every time the
1618 app starts, the ones nobody has touched move forward so the screen always
1719 looks like today.
1820
@@ -188,7 +190,7 @@ is not brought back. A file with a mistake in any deal brings nothing, and says
188190 which deal and field. In the terminal, press `E` to write your file, and `O` to bring deals back from a file in the exports folder (enter alone takes the newest).
189191
190192 **Put the samples back.** After the tour, an admin taps **Sample deals** below
191 the clock, then **Restore the sample deals** and confirms: the seven samples
193 the clock, then **Restore the sample deals** and confirms: the eight samples
192194 return as they were, dated from today, and the deals you opened are left alone.
193195
194196 ## What is real, and what is not yet
docs/TECHNICAL.md +2 −2
@@ -190,7 +190,7 @@ tools at `POST /mcp` (`list_deals`, `get_deal`, `client_timeline`, `reminders_to
190190 `remove_date` — custom dates only — `remove_deal` — its author or an admin —
191191 `mark_done` — with `done: false` to
192192 reopen a date — `waive_date` — with `waived: false` to un-waive it — `move_date`, `set_reminder_lead`, `amend_deal` (several dates, one reason), `send_reminder`, `restore_samples` — admin only: puts the
193 seven sample deals back and leaves every other deal alone). `send_reminder` takes an
193 eight sample deals back and leaves every other deal alone). `send_reminder` takes an
194194 optional `subject` and `body` to send edited words; without them the draft
195195 goes as it is.
196196
@@ -245,7 +245,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
245245 | `src/export.ts` | the all-my-deals JSON file: deal views shaped to plain data |
246246 | `src/csv.ts` | the spreadsheet file: rows shaped to CSV, formula guard |
247247 | `src/outbox.ts` | a sent reminder's mailto:/sms: link |
248 | `src/sample.ts` | the seven sample deals a new database starts with |
248 | `src/sample.ts` | the eight sample deals a new database starts with |
249249 | `src/result.ts` | what an action answers, and the audit habit they share |
250250 | `src/actions.ts` | the audit trail, read |
251251 | `contract.json` | who may do what: roles, and the least role each verb needs |
src/actions.ts +1 −1
@@ -91,7 +91,7 @@ export const mayRestore = (who: Who): Result<null> =>
9191 : refuse(who, "Sign in to restore the sample deals.", "Only an admin may restore the sample deals.");
9292
9393 /**
94 * Put the seven sample deals back as the README describes them, anchored to
94 * Put the eight sample deals back as the README describes them, anchored to
9595 * today, for the next demo. Only deals the sample identity wrote are removed;
9696 * every deal a person made is left as it is. Audited as a delete: the
9797 * samples are removed and written again.
src/dates.ts +7
@@ -97,6 +97,13 @@ export const isHoliday = (date: string): boolean => holidaysOf(+date.slice(0, 4)
9797 /** Not a weekend and not a US federal holiday. */
9898 export const isBusinessDay = (date: string): boolean => !isWeekend(date) && !isHoliday(date);
9999
100 /** `date` itself when it is a business day, else the last one before it. */
101 export function previousBusinessDay(date: string): string {
102 let at = date;
103 while (!isBusinessDay(at)) at = addDays(at, -1);
104 return at;
105 }
106
100107 /** `date` itself when it is a business day, else the next one after it. */
101108 export function nextBusinessDay(date: string): string {
102109 let at = date;
src/db.test.ts +9 −4
@@ -1,6 +1,7 @@
11 import { Database } from "bun:sqlite";
22 import { expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
4 import { onBusinessDay } from "./sample.ts";

Non-blocking: a second import from ./sample.ts; merge it with the seed import on the next line.

45 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
56 import { seed } from "./sample.ts";
67 import { tmpdir } from "node:os";
@@ -55,12 +56,16 @@ test("sample deals boot looking like today, and a changed one is left alone", ()
5556 again.query<{ due: string }, [string, string]>(
5657 "SELECT d.due FROM deadline d JOIN deal ON deal.id = d.deal_id WHERE deal.address = ?1 AND d.kind = ?2",
5758 ).get(address, kind)!.due;
58 expect(after("1418 Alder Lane", "closing")).toBe(addDays(today(DEFAULT_ZONE), 4));
59 expect(after("1418 Alder Lane", "inspection")).toBe(addDays(today(DEFAULT_ZONE), -26 + 10));
60 expect(after("9 Orchard Row", "appraisal")).toBe(addDays(today(DEFAULT_ZONE), 2));
59 // Each date was held on a business day when seeded, then carried 30 days and held on one again.
60 const now = today(DEFAULT_ZONE);
outdated

This used to pin the appraisal exactly. Expect the exact business-day-adjusted date, not a ±3 range.

61 const held = (days: number, closing = false) =>
62 onBusinessDay(addDays(onBusinessDay(addDays(then, days), then, closing), 30), now, closing);
63 expect(after("1418 Alder Lane", "closing")).toBe(held(4, true));
64 expect(after("1418 Alder Lane", "inspection")).toBe(held(-26 + 10));
65 expect(after("9 Orchard Row", "appraisal")).toBe(held(2));
6166 expect(after("2210 Juniper Court", "closing")).toBe(juniper);
6267 const move = again.query<{ to_due: string }, []>("SELECT to_due FROM deadline_move").get()!;
63 expect(move.to_due).toBe(addDays(today(DEFAULT_ZONE), 2));
68 expect(move.to_due).toBe(held(2));
6469 expect(again.query("SELECT value FROM app_meta WHERE key = 'sample_anchor'").get()).toEqual({ value: today(DEFAULT_ZONE) });
6570 });
6671
src/mcp.ts +1 −1
@@ -554,7 +554,7 @@ export const tools: readonly Tool[] = [
554554 },
555555 {
556556 name: "restore_samples",
557 description: "Put the seven sample deals back as the README describes them, anchored to today; deals people made are untouched.",
557 description: "Put the eight sample deals back as the README describes them, anchored to today; deals people made are untouched.",
558558 inputSchema: { type: "object", properties: {} },
559559 run: (db, who) => restoreSamples(db, who),
560560 },
src/sample.test.ts +59 −1
@@ -10,7 +10,7 @@ import { dollars } from "./money.ts";
1010 import { clock } from "./pages/clock.ts";
1111 import { people } from "./people.ts";
1212 import { thisWeek } from "./week.ts";
13 import { addDays, today, spoken, DEFAULT_ZONE } from "./dates.ts";
13 import { addDays, daysBetween, isBusinessDay, today, spoken, DEFAULT_ZONE } from "./dates.ts";
1414 import { createDeal, listDeals, markDone } from "./deals.ts";
1515 import { drafts, todaysDrafts, unsent } from "./reminders.ts";
1616 import { serve } from "./server.ts";
@@ -266,3 +266,61 @@ test("on a fresh boot the first reminder for today is for a date already late or
266266 expect(first).toBeDefined();
267267 expect(first.moment === "late" || first.due <= day).toBe(true);
268268 });
269
270 // The samples are written relative to the day of the boot; the tour in the README must read the same across a month or year end.
271 for (const on of ["2026-12-28", "2027-01-31", "2027-02-28", "2028-02-29", "2027-12-31"]) {
272 test(`samples booted on ${on}: business days, the four open ones are open, the four old ones closed`, () => {
273 const db = openDb(mkdtempSync(join(tmpdir(), "app-sample-edge-")));
274 restore(db, on);
275 const listed = listDeals(db, { role: "user", id: "u1", name: "alice" });
276 if (!listed.ok) throw new Error(listed.message);
277 const deals = listed.value.filter((d) => d.author_id === "sample");
278 expect(deals.length).toBe(8);
279 for (const d of deals) {
280 expect(isBusinessDay(d.contract_date)).toBe(true);
281 expect(isBusinessDay(d.closing)).toBe(true);
282 for (const x of d.deadlines) expect(isBusinessDay(x.due)).toBe(true);
283 }
284 const open = deals.filter((d) => !d.closed);
285 expect(open.map((d) => d.address).sort()).toEqual(["1418 Alder Lane", "2210 Juniper Court", "77 Harbor View Dr, Unit 4B", "9 Orchard Row"]);
286 // The ones expected closed: Mill Pond, Cedar Heights and Saltmarsh (this year) and Larkspur (a year ago).
287 // Each is finished, closed before the day, and only the first three close in the book's year.
288 const closed = deals.filter((x) => x.closed);
289 expect(closed.map((d) => d.address).sort()).toEqual(["14 Saltmarsh Lane", "35 Mill Pond Road", "58 Larkspur Way", "602 Cedar Heights Blvd"]);
outdated

Both branches assert d.closing < on, so the if/else is redundant. Collapse it, and keep the year check only where it applies.

290 for (const d of closed) {
291 expect(d.deadlines.every((x) => x.done_at !== null || x.waived_at !== null)).toBe(true);
292 expect(d.closing < on).toBe(true);
293 if (d.address !== "58 Larkspur Way") expect(d.closing.slice(0, 4)).toBe(on.slice(0, 4));
294 }
295 // Exactly one open date is overdue: the Harbor View inspection.
296 const late = open.flatMap((d) => d.deadlines.filter((x) => x.done_at === null && x.waived_at === null && x.due < on).map((x) => `${d.address}:${x.kind}`));
297 expect(late).toEqual(["77 Harbor View Dr, Unit 4B:inspection"]);
298 // Alder Lane still closes within the week; the book still counts three closed this year.
299 const alder = open.find((d) => d.address === "1418 Alder Lane")!;
300 expect(daysBetween(on, alder.closing)).toBeGreaterThan(0);
301 expect(daysBetween(on, alder.closing)).toBeLessThanOrEqual(7);
302 expect(tally(listed.value, on).closedThisYear).toBe(3);
303 });
304 }
305
306 test("samples refreshed day after day across weekends and holidays keep every date on a business day", () => {
307 const db = openDb(mkdtempSync(join(tmpdir(), "app-sample-refresh-")));
308 let on = "2026-11-04";
309 restore(db, on);
310 const read = () => db.query<{ due: string; done_at: string | null }, []>("SELECT due, done_at FROM deadline").all();
311 const finished = read().filter((d) => d.done_at !== null).length;
312 const contracts = () => db.query<{ contract_date: string }, []>("SELECT contract_date FROM deal").all();
313 for (let i = 0; i < 40; i++) {
314 on = addDays(on, 1);
315 refresh(db, on);
316 for (const d of read()) expect(isBusinessDay(d.due)).toBe(true);
317 for (const c of contracts()) expect(isBusinessDay(c.contract_date)).toBe(true);
318 // What was finished stays finished.
319 expect(read().filter((d) => d.done_at !== null).length).toBe(finished);
320 }
321 const moved = db.query<{ from_due: string; to_due: string }, []>("SELECT from_due, to_due FROM deadline_move").get()!;
322 expect(isBusinessDay(moved.from_due) && isBusinessDay(moved.to_due)).toBe(true);
323 const listed = listDeals(db, { role: "user", id: "u1", name: "alice" });
324 if (!listed.ok) throw new Error(listed.message);
325 expect(listed.value.filter((d) => d.closed).length).toBe(4);
326 });
src/sample.ts +46 −9
@@ -5,11 +5,11 @@
55 * year, so the book line and the Closed list show a year of sales, and one
66 * closed a year ago today, so its home anniversary note waits in Review. Dates are
77 * set relative to the day the database is created, so a fresh preview always
8 * looks like today.
8 * looks like today. None falls on a weekend or a federal holiday.
99 */
1010
1111 import type { Database } from "bun:sqlite";
12 import { addDays, daysBetween, today } from "./dates.ts";
12 import { addDays, daysBetween, isBusinessDay, nextBusinessDay, previousBusinessDay, today } from "./dates.ts";
1313 import { zoneOf } from "./profile.ts";
1414 import { type PartyRole } from "./deadlines.ts";
1515 import { BRIEF_LENGTHS, validEmail } from "./env.ts";
@@ -215,6 +215,26 @@ function placed(s: Sample, on: string): { contract: number; closing: number } {
215215 return { contract: closing - (s.closing - s.contract), closing };
216216 }
217217
218 /**
219 * `date` moved onto a business day without crossing `on`, so what was overdue
220 * stays overdue and what is ahead stays ahead. A day already past steps back,
221 * unless that carries it into the year before, where a deal closed this year
222 * would leave it. A day ahead steps back too (so it stays before the closing
223 * it precedes) when that does not reach `on`; a closing, or a day that would
224 * step back to a day gone, steps forward.
225 */
226 export function onBusinessDay(date: string, on: string, closing = false): string {
227 if (isBusinessDay(date)) return date;
228 if (date < on) {
229 const back = previousBusinessDay(date);
230 if (back.slice(0, 4) === date.slice(0, 4)) return back;
231 const forward = nextBusinessDay(date);
232 return forward < on ? forward : back;
233 }
234 const back = previousBusinessDay(date);
235 return closing || back < on ? nextBusinessDay(date) : back;
236 }
237
218238 /** The time of day a sample's finished dates carry: what tells them from a person's click. */
219239 const DONE_TIME = "T17:00:00.000Z";
220240
@@ -342,13 +362,23 @@ export function refresh(db: Database, on = today(zoneOf(db))): void {
342362 // A database seeded before the fix stamped every finished date the day before the anchor: restamp it against its own due day.
343363 const legacy = `${addDays(anchor, -1)}${DONE_TIME}`;
344364 const restamped = shifted.deadlines.map((d, i) => (deadlines[i]!.done_at === legacy ? { ...d, doneAt: doneStamp(d.due, on) } : d));
345 db.query("UPDATE deal SET contract_date = ?1 WHERE id = ?2").run(shifted.contractDate, deal.id);
346 for (const d of restamped) db.query("UPDATE deadline SET due = ?1, done_at = ?2, waived_at = ?3 WHERE id = ?4").run(d.due, d.doneAt, d.waivedAt, d.id);
347 for (const m of shifted.moves) db.query("UPDATE deadline_move SET from_due = ?1, to_due = ?2 WHERE id = ?3").run(m.fromDue, m.toDue, m.id);
365 // Whole days carry a date onto a weekend or holiday; each lands on a business day again, as at the first boot.
366 const anniversary = SAMPLES.find((x) => x.address === deal.sample)?.anniversary !== undefined;
367 const rolled = (due: string, closing = false) => (anniversary ? previousBusinessDay(due) : onBusinessDay(due, on, closing));
368 const kindOf = new Map(deadlines.map((d) => [d.id, d.kind]));
369 db.query("UPDATE deal SET contract_date = ?1 WHERE id = ?2").run(rolled(shifted.contractDate), deal.id);
370 for (const d of restamped) {
371 const due = rolled(d.due, kindOf.get(d.id) === "closing");
372 // A finished date is stamped against its own due day, so rolling the day never leaves it late (the anniversary sample's closing keeps its day).
373 const doneAt = d.doneAt !== null && !(anniversary && kindOf.get(d.id) === "closing") && d.doneAt.endsWith(DONE_TIME) ? doneStamp(due, on) : d.doneAt;
374 db.query("UPDATE deadline SET due = ?1, done_at = ?2, waived_at = ?3 WHERE id = ?4").run(due, doneAt, d.waivedAt, d.id);
375 }
376 for (const m of shifted.moves) db.query("UPDATE deadline_move SET from_due = ?1, to_due = ?2 WHERE id = ?3").run(rolled(m.fromDue), rolled(m.toDue), m.id);
348377 // The sample's sent reminder follows its date, so it stays "yesterday's".
349378 const days = `+${daysBetween(anchor, on)} days`;
350379 db.query("UPDATE deadline_move SET at = strftime('%Y-%m-%dT%H:%M:%fZ', at, ?1) WHERE deadline_id IN (SELECT id FROM deadline WHERE deal_id = ?2)").run(days, deal.id);
351380 db.query("UPDATE reminder SET due = date(due, ?1), sent_at = strftime('%Y-%m-%dT%H:%M:%fZ', sent_at, ?1) WHERE deal_id = ?2 AND sample = 1").run(days, deal.id);
381 db.query("UPDATE reminder SET due = (SELECT due FROM deadline WHERE id = reminder.deadline_id) WHERE deal_id = ?1 AND sample = 1 AND moment <> 'checkin'").run(deal.id);
352382 }
353383 db.query("UPDATE app_meta SET value = ?1 WHERE key = 'sample_anchor'").run(on);
354384 }).immediate();
@@ -371,7 +401,7 @@ function writeSamples(db: Database, on: string): void {
371401 buyer: s.buyer,
372402 seller: s.seller,
373403 contractDate: addDays(on, at.contract),
374 closingDate: addDays(on, at.closing),
404 closingDate: onBusinessDay(addDays(on, at.closing), on),
375405 lengths: { ...BRIEF_LENGTHS, ...s.lengths },
376406 businessDays: false,
377407 salePrice: s.price,
@@ -385,6 +415,11 @@ function writeSamples(db: Database, on: string): void {
385415 if (s.done?.includes(kind) || s.waived?.includes(kind)) continue;
386416 db.query("UPDATE deadline SET time = ?1, place = ?2 WHERE deal_id = ?3 AND kind = ?4").run(appointmentSlot(s.address, kind), s.address, deal.id, kind);
387417 }
418 // The deadlines were counted in calendar days from the contract; none of them, nor the contract, falls on a weekend or holiday.
419 db.query("UPDATE deal SET contract_date = ?1 WHERE id = ?2").run(onBusinessDay(addDays(on, at.contract), on), deal.id);
420 // The anniversary sample always steps back, so it stays closed in last year, as the book counts it.
421 for (const d of db.query<{ id: number; kind: string; due: string }, [number]>("SELECT id, kind, due FROM deadline WHERE deal_id = ?1").all(deal.id))
422 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(s.anniversary === undefined ? onBusinessDay(d.due, on, d.kind === "closing") : previousBusinessDay(d.kind === "closing" ? addDays(on, at.closing) : d.due), d.id);
388423 db.query("INSERT INTO sample_deal (deal_id, sample) VALUES (?1, ?2)").run(deal.id, s.address);
389424 if (s.anniversary !== undefined)
390425 db.query("UPDATE party SET email = ?1, contact = ?1 WHERE deal_id = ?2 AND role = 'buyer'").run(s.anniversary, deal.id);
@@ -393,14 +428,16 @@ function writeSamples(db: Database, on: string): void {
393428 const phone = second ?? (email === "" ? first : "");
394429 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);
395430 }
431 // The anniversary sample was finished on the day a year back, whichever business day its due falls on.
432 const finished = s.anniversary === undefined ? addDays(on, -1) : addDays(addDays(on, at.closing), -1);
396433 for (const kind of s.done ?? [])
397 db.query("UPDATE deadline SET done_at = min(date(due, '-1 day'), ?1) || ?2 WHERE deal_id = ?3 AND kind = ?4").run(addDays(on, -1), DONE_TIME, deal.id, kind);
434 db.query("UPDATE deadline SET done_at = min(date(due, '-1 day'), ?1) || ?2 WHERE deal_id = ?3 AND kind = ?4").run(finished, DONE_TIME, deal.id, kind);
398435 for (const kind of s.waived ?? [])
399436 db.query("UPDATE deadline SET waived_at = ?1, waived_by = ?2 WHERE deal_id = ?3 AND kind = ?4").run(`${addDays(on, -1)}${DONE_TIME}`, SAMPLE.name, deal.id, kind);
400437 for (const [kind, note] of s.notes ?? [])
401438 db.query("UPDATE deadline SET note = ?1 WHERE deal_id = ?2 AND kind = ?3").run(note, deal.id, kind);
402439 for (const [label, days, owes, what] of s.custom ?? [])
403 db.query("INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5)").run(deal.id, label, addDays(on, days), owes, what);
440 db.query("INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5)").run(deal.id, label, onBusinessDay(addDays(on, days), on), owes, what);
404441 if (s.sent !== undefined) {
405442 const [kind, role, moment, subject, body] = s.sent;
406443 const d = db.query<{ id: number; label: string; due: string }, [number, string]>("SELECT id, label, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!;
@@ -418,7 +455,7 @@ function writeSamples(db: Database, on: string): void {
418455 if (s.moved !== undefined) {
419456 const [kind, days, reason] = s.moved;
420457 const d = db.query<{ id: number; due: string }, [number, string]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = ?2").get(deal.id, kind)!;
421 const to = addDays(on, days);
458 const to = onBusinessDay(addDays(on, days), on);
422459 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(to, d.id);
423460 db.query("INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, at, notify) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1)").run(d.id, d.due, to, reason, SAMPLE.name, `${on}T08:00:00.000Z`);
424461 }
src/waiting.test.ts +1
@@ -43,6 +43,7 @@ test("a page other than the clock carries the count the review page walks throug
4343 test("approving or declining every message leaves the next page with none", async () => {
4444 const before = headerCount(await get("/people"))!;
4545 for (let left = before; left > 0; left--) {
46 forgetRationing(); // one send per waiting message; how many wait depends on the day, and this test is not about the limit
4647 const page = await get("/reminders/today");
4748 const hidden = (name: string) => new RegExp(`name="${name}" value="([^"]*)"`).exec(page)![1]!;
4849 const keys = { deadline: hidden("deadline"), party: hidden("party"), moment: hidden("moment"), at: "0", done: "0", q: "" };

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs