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

"Today" is the agent's day in their own time zone, set on the Profile, so at 6 pm Eastern the clock does not already show tomorrow #171

Merged opened this

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

Merged

mason/deal-clock:mason/163-today-is-the-agent-s-day-in-their-own-ti → main 2 commits fork 1 thread · 1 unresolved

  • Merged. mason/163-today-is-the-agent-s-day-in-their-own-ti was merged into main as 40db2b2.

Review

Sign in to review this change.
43 files changed +486 −250
README.md +2 −1
@@ -138,7 +138,8 @@ includes closed deals.
138138 The app ships with a sample agent; the Profile in step 10 replaces it. Each
139139 deal sets how many days before a date its reminder goes (1 to 30), and your
140140 Profile may add one line of your own to the end of every message ("Text me
141 anytime, I answer within the hour"). Whoever runs the app can set your usual
141 anytime, I answer within the hour"). Set your time zone on the Profile so
142 "today" is your day, not the server's. Whoever runs the app can set your usual
142143 contract lengths once; see the technical page. On your phone, choose Add to
143144 Home Screen: the deal-clock mark sits beside the name and it opens full screen.
144145
contract/openapi.json +20
@@ -36,6 +36,11 @@
3636 "type": "string",
3737 "maxLength": 254
3838 },
39 "zone": {
40 "type": "string",
41 "maxLength": 64,
42 "description": "The agent's IANA time zone, such as America/New_York: the day \"today\" is told in. Leaving it out on a save keeps the saved zone; a name this runtime does not know is a 422 naming zone."
43 },
3944 "line": {
4045 "type": "string",
4146 "maxLength": 200,
@@ -101,6 +106,11 @@
101106 "type": "string",
102107 "maxLength": 254
103108 },
109 "zone": {
110 "type": "string",
111 "maxLength": 64,
112 "description": "The agent's IANA time zone, such as America/New_York: the day \"today\" is told in. Leaving it out on a save keeps the saved zone; a name this runtime does not know is a 422 naming zone."
113 },
104114 "line": {
105115 "type": "string",
106116 "maxLength": 200,
@@ -147,6 +157,11 @@
147157 "type": "string",
148158 "maxLength": 254
149159 },
160 "zone": {
161 "type": "string",
162 "maxLength": 64,
163 "description": "The agent's IANA time zone, such as America/New_York: the day \"today\" is told in. Leaving it out on a save keeps the saved zone; a name this runtime does not know is a 422 naming zone."
164 },
150165 "line": {
151166 "type": "string",
152167 "maxLength": 200,
@@ -213,6 +228,11 @@
213228 "type": "string",
214229 "maxLength": 254
215230 },
231 "zone": {
232 "type": "string",
233 "maxLength": 64,
234 "description": "The agent's IANA time zone, such as America/New_York: the day \"today\" is told in. Leaving it out on a save keeps the saved zone; a name this runtime does not know is a 422 naming zone."
235 },
216236 "line": {
217237 "type": "string",
218238 "maxLength": 200,
docs/TECHNICAL.md +1 −1
@@ -11,7 +11,7 @@ is the saved Profile (one `profile` row in sqlite). Until one is saved, four
1111 settings (Settings → App → Environment) are the defaults: `DEAL_CLOCK_AGENT`,
1212 `DEAL_CLOCK_BROKERAGE`, `DEAL_CLOCK_PHONE` (digits, spaces, `+ ( ) - .`, at
1313 most 30 characters) and `DEAL_CLOCK_EMAIL` (one `@`, at most 254). A bad phone
14 or email falls back to the sample with one line in the log. Dates follow the server's time zone (`TZ`).
14 or email falls back to the sample with one line in the log. "Today" is the agent's day in the IANA time zone saved on the Profile (default `America/New_York`; `TZ` is not read). Every caller passes the zone to `today(zone)` in `src/dates.ts`, and stored moments (done, sent, waived, fell through) are shown as days in that zone. Dates themselves stay plain `YYYY-MM-DD` strings.
1515
1616 ## Running it, the API, MCP and the terminal
1717
src/activitycsv.test.ts +2 −2
@@ -3,7 +3,7 @@ import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { today } from "./dates.ts";
6 import { today, DEFAULT_ZONE } from "./dates.ts";
77 import { createDeal, sendReminder } from "./deals.ts";
88 import { openDb } from "./db.ts";
99 import { forgetRationing } from "./security.ts";
@@ -38,7 +38,7 @@ test("an admin gets the file, with the header, a guarded address and the wording
3838 const res = await get("/activity.csv", root);
3939 expect(res.status).toBe(200);
4040 expect(res.headers.get("content-type")).toBe("text/csv; charset=utf-8");
41 expect(res.headers.get("content-disposition")).toBe(`attachment; filename="deal-clock-activity-${today()}.csv"`);
41 expect(res.headers.get("content-disposition")).toBe(`attachment; filename="deal-clock-activity-${today(DEFAULT_ZONE)}.csv"`);
4242 const body = await res.text();
4343 expect(body.startsWith("when,who,what,deal,outcome\r\n")).toBe(true);
4444 expect(body).toContain("'=1+1 Formula Way");
src/book.closed.test.ts +3 −3
@@ -4,7 +4,7 @@ import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { bookLine, tally } from "./book.ts";
7 import { spoken, today } from "./dates.ts";
7 import { spoken, today, DEFAULT_ZONE } from "./dates.ts";
88 import { createDeal, getDeal, listDeals, markDone } from "./deals.ts";
99 import { openDb } from "./db.ts";
1010 import { forgetRationing } from "./security.ts";
@@ -15,7 +15,7 @@ import { sign, type Who } from "./who.ts";
1515 const KEY = "a-key-only-the-forge-holds";
1616 const dir = mkdtempSync(join(tmpdir(), "app-bookclosed-"));
1717 const alice: Who = { role: "user", id: "u1", name: "alice" };
18 const year = today().slice(0, 4);
18 const year = today(DEFAULT_ZONE).slice(0, 4);
1919
2020 const db = openDb(dir);
2121 function closedDeal(address: string, closingDate: string, salePrice: number | undefined): void {
@@ -52,7 +52,7 @@ test("the Closed card shows the price beside the closing day, and nothing for a
5252 test("the terminal's clock view opens with the same book line", () => {
5353 const listed = listDeals(openDb(dir), alice);
5454 if (!listed.ok) throw new Error(listed.message);
55 const want = bookLine(tally(listed.value, today()), today());
55 const want = bookLine(tally(listed.value, today(DEFAULT_ZONE)), today(DEFAULT_ZONE));
5656 const t = terminal(openDb(dir), alice, { title: "deal-clock", where: "test", agent: { name: "Dana", brokerage: "HP", phone: "555", email: "[email protected]" } });
5757 const screen = t.screen().map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
5858 expect(screen).toContain(want);
src/csv.ts +7 −9
@@ -6,7 +6,7 @@
66
77 import { wording } from "./activity.ts";
88 import type { AuditRow } from "./audit.ts";
9 import { today } from "./dates.ts";
9 import { timeOf, today } from "./dates.ts";
1010 import { PARTY_LABEL } from "./deadlines.ts";
1111 import type { DealView } from "./deals.ts";
1212
@@ -34,7 +34,7 @@ export function sheet(deals: readonly DealView[]): string {
3434 nameOf(deal, "seller"),
3535 d.label,
3636 d.due,
37 d.done_at === null ? "" : today(new Date(d.done_at)),
37 d.done_at === null ? "" : today(deal.zone, new Date(d.done_at)),
3838 PARTY_LABEL[d.owes],
3939 nameOf(deal, d.owes),
4040 d.moves.length > 0 ? "yes" : "no",
@@ -44,21 +44,19 @@ export function sheet(deals: readonly DealView[]): string {
4444
4545 export const ACTIVITY_COLUMNS = ["when", "who", "what", "deal", "outcome"] as const;
4646
47 const pad = (n: number): string => String(n).padStart(2, "0");
48
49 /** "2026-11-08 14:05" in this process's zone; the stored text itself if it does not read. */
50 const localTime = (at: string): string => {
47 /** "2026-11-08 14:05" in the agent's zone; the stored text itself if it does not read. */
48 const localTime = (at: string, zone: string): string => {
5149 const d = new Date(at);
52 return Number.isNaN(d.getTime()) ? at : `${today(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
50 return Number.isNaN(d.getTime()) ? at : `${today(zone, d)} ${timeOf(zone, d)}`;
5351 };
5452
5553 /** The audit rows as a file, header first, in the order given: when, who, what, deal address, outcome. */
56 export function activitySheet(rows: readonly AuditRow[], addresses: ReadonlyMap<string, string>): string {
54 export function activitySheet(rows: readonly AuditRow[], addresses: ReadonlyMap<string, string>, zone: string): string {
5755 const out: string[][] = [[...ACTIVITY_COLUMNS]];
5856 for (const r of rows) {
5957 const named = r.resource === "deal" && r.target !== null;
6058 out.push([
61 localTime(r.at),
59 localTime(r.at, zone),
6260 r.who_name ?? "someone not signed in",
6361 wording(r),
6462 named ? (addresses.get(r.target!) ?? "no longer here") : "",
src/dates.ts +58 −7
@@ -2,7 +2,8 @@
22 * Calendar dates as plain `YYYY-MM-DD` strings: what a contract speaks in.
33 * No times and no zones inside — a date is a day, computed in UTC so that
44 * adding days never trips over daylight saving. `today` is the one place a
5 * clock is read, in the zone the process runs in (`TZ`).
5 * clock is read, and it reads it in the agent's zone (set on the Profile),
6 * which every caller passes in: the process's own zone (`TZ`) is never used.
67 */
78
89 const ISO = /^(\d{4})-(\d{2})-(\d{2})$/;
@@ -114,14 +115,64 @@ export function addBusinessDays(date: string, days: number): string {
114115 return at;
115116 }
116117
117 /** The date in this process's zone, now. */
118 export function today(now = new Date()): string {
119 const y = now.getFullYear();
120 const m = String(now.getMonth() + 1).padStart(2, "0");
121 const d = String(now.getDate()).padStart(2, "0");
122 return `${y}-${m}-${d}`;
118 /** The zone a profile starts with, and the one the samples are told in. */
119 export const DEFAULT_ZONE = "America/New_York";
120
121 /** The US zones the Profile page offers, with the name a person knows them by. */
122 export const US_ZONES: readonly (readonly [string, string])[] = [
123 ["America/New_York", "Eastern"],
124 ["America/Chicago", "Central"],
125 ["America/Denver", "Mountain"],
126 ["America/Los_Angeles", "Pacific"],
127 ["America/Anchorage", "Alaska"],
128 ["Pacific/Honolulu", "Hawaii"],
129 ];
130
131 let known: Set<string> | undefined;
132 /** Is this an IANA time zone name this runtime knows (`America/New_York`, `UTC`)? */
133 export function isZone(value: unknown): value is string {
134 if (typeof value !== "string" || value.length > 64) return false;
135 known ??= new Set([...Intl.supportedValuesOf("timeZone"), "UTC"]);
136 return known.has(value);
123137 }
124138
139 // One formatter per zone, made on first use: `en-CA` writes `YYYY-MM-DD`.
140 const clocks = new Map<string, Intl.DateTimeFormat>();
141 const clockOf = (zone: string): Intl.DateTimeFormat => {
142 let f = clocks.get(zone);
143 if (f === undefined) {
144 f = new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" });
145 clocks.set(zone, f);
146 }
147 return f;
148 };
149
150 /** The calendar date in `zone` at the instant `now` (the present when left out). */
151 export function today(zone: string, now: Date = new Date()): string {
152 return clockOf(zone).format(now);

Drop the = DEFAULT_ZONE default here and make zone required. A caller that forgets it silently gets Eastern, which is the bug this issue exists to remove.

153 }
154
155 const minutes = new Map<string, Intl.DateTimeFormat>();
156 /** "14:05": the time of day in `zone` at `at`. */
157 export function timeOf(zone: string, at: Date): string {
158 let f = minutes.get(zone);
159 if (f === undefined) {
160 f = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
161 minutes.set(zone, f);
162 }
163 return f.format(at);
164 }
165
166 /** The day in `zone` of a stored moment (an ISO timestamp); its first ten characters if it does not read. */
167 export function dayOfStamp(zone: string, at: string): string {
168 const d = new Date(at);
169 return Number.isNaN(d.getTime()) ? at.slice(0, 10) : today(zone, d);
170 }
171
172 /** The date in the zone of whoever `agent` is (`DEFAULT_ZONE` when none is set), at `now`. */
173 export const dayOf = (agent: { readonly zone?: string | undefined }, now?: Date): string =>
174 today(agent.zone ?? DEFAULT_ZONE, now);
175
125176 // Formatters are costly to make and cheap to use: made once.
126177 const SPOKEN = new Intl.DateTimeFormat("en-US", {
127178 weekday: "short",
src/db.test.ts +8 −8
@@ -1,7 +1,7 @@
11 import { Database } from "bun:sqlite";
22 import { expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
4 import { addDays, today } from "./dates.ts";
4 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
55 import { seed } from "./sample.ts";
66 import { tmpdir } from "node:os";
77 import { join } from "node:path";
@@ -36,7 +36,7 @@ test("the sample deals are written once, however many processes open a new file"
3636
3737 test("sample deals boot looking like today, and a changed one is left alone", () => {
3838 const dir = mkdtempSync(join(tmpdir(), "app-refresh-"));
39 const then = addDays(today(), -30);
39 const then = addDays(today(DEFAULT_ZONE), -30);
4040 // A database seeded 30 days ago: open a new one, then replace its samples.
4141 const db = openDb(dir);
4242 db.exec("DELETE FROM deal; DELETE FROM app_meta");
@@ -55,20 +55,20 @@ test("sample deals boot looking like today, and a changed one is left alone", ()
5555 again.query<{ due: string }, [string, string]>(
5656 "SELECT d.due FROM deadline d JOIN deal ON deal.id = d.deal_id WHERE deal.address = ?1 AND d.kind = ?2",
5757 ).get(address, kind)!.due;
58 expect(after("1418 Alder Lane", "closing")).toBe(addDays(today(), 4));
59 expect(after("1418 Alder Lane", "inspection")).toBe(addDays(today(), -26 + 10));
60 expect(after("9 Orchard Row", "appraisal")).toBe(addDays(today(), 2));
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));
6161 expect(after("2210 Juniper Court", "closing")).toBe(juniper);
6262 const move = again.query<{ to_due: string }, []>("SELECT to_due FROM deadline_move").get()!;
63 expect(move.to_due).toBe(addDays(today(), 2));
64 expect(again.query("SELECT value FROM app_meta WHERE key = 'sample_anchor'").get()).toEqual({ value: today() });
63 expect(move.to_due).toBe(addDays(today(DEFAULT_ZONE), 2));
64 expect(again.query("SELECT value FROM app_meta WHERE key = 'sample_anchor'").get()).toEqual({ value: today(DEFAULT_ZONE) });
6565 });
6666
6767 test("a reminder sent under the name Sample data does not pass as the sample's own", () => {
6868 const dir = mkdtempSync(join(tmpdir(), "app-spoof-"));
6969 const db = openDb(dir);
7070 db.exec("DELETE FROM deal; DELETE FROM app_meta");
71 seed(db, addDays(today(), -30));
71 seed(db, addDays(today(DEFAULT_ZONE), -30));
7272 const orchard = db.query<{ id: number }, []>("SELECT id FROM deal WHERE address = '9 Orchard Row'").get()!.id;
7373 const d = db.query<{ id: number; due: string }, [number]>("SELECT id, due FROM deadline WHERE deal_id = ?1 AND kind = 'closing'").get(orchard)!;
7474 const p = db.query<{ id: number }, [number]>("SELECT id FROM party WHERE deal_id = ?1").get(orchard)!;
src/db.ts +2
@@ -499,6 +499,8 @@ export const migrations: string[] = [
499499 DROP TABLE reminder_hold;
500500 ALTER TABLE reminder_hold_new RENAME TO reminder_hold;
501501 CREATE INDEX reminder_hold_deal ON reminder_hold (deal_id)`,
502 // The agent's own time zone: "today" is their day, not the server's (src/dates.ts).
503 `ALTER TABLE profile ADD COLUMN zone TEXT NOT NULL DEFAULT 'America/New_York' CHECK (length(zone) BETWEEN 1 AND 64)`,
502504 ];
503505
504506 export function openDb(dir = dataDir): Database {
src/deals.test.ts +17 −17
@@ -7,7 +7,7 @@ import { expect, test } from "bun:test";
77 import { mkdtempSync } from "node:fs";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { addDays, spoken, today } from "./dates.ts";
10 import { addDays, spoken, today, DEFAULT_ZONE } from "./dates.ts";
1111 import {
1212 addDeadline,
1313 addParty,
@@ -65,7 +65,7 @@ test("a new database carries four sample deals: one overdue, one closing this we
6565 if (!all.ok) throw new Error(all.message);
6666 const samples = all.value.filter((d) => d.author_id === "sample");
6767 expect(samples.length).toBe(7);
68 const on = today();
68 const on = today(DEFAULT_ZONE);
6969 expect(
7070 samples.some((d) => d.deadlines.some((x) => x.done_at === null && x.due < on)),
7171 ).toBe(true);
@@ -197,12 +197,12 @@ test("a party and a custom date join the deal; reminders follow who is on it", (
197197 });
198198
199199 test("reminders: three days before and the morning of, drafted in words, marked sent once", () => {
200 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
200 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30), lengths: { inspection: "8" } });
201201 const inspection = due(deal, "inspection"); // due in three days
202202 const mine = drafts(deal, agent).filter((r) => r.deadline_id === inspection.id);
203203 expect(mine.map((r) => [r.party_name, r.moment, r.on])).toEqual([
204 ["Ann Buyer", "before", today()],
205 ["Sam Seller", "before", today()],
204 ["Ann Buyer", "before", today(DEFAULT_ZONE)],
205 ["Sam Seller", "before", today(DEFAULT_ZONE)],
206206 ["Ann Buyer", "day_of", inspection.due],
207207 ["Sam Seller", "day_of", inspection.due],
208208 ["Ann Buyer", "late", addDays(inspection.due, 1)],
@@ -214,7 +214,7 @@ test("reminders: three days before and the morning of, drafted in words, marked
214214 expect(buyer.body).toContain("Dana Whitfield, Harbor & Pine Realty");
215215 expect(mine[1]!.body).toContain("Ann Buyer (buyer) is on it");
216216
217 const tick = () => dueOn([fresh(deal.id)], today(), agent).filter((r) => r.deadline_id === inspection.id);
217 const tick = () => dueOn([fresh(deal.id)], today(DEFAULT_ZONE), agent).filter((r) => r.deadline_id === inspection.id);
218218 expect(tick().length).toBe(2);
219219 const sent = sendReminder(db, alice, { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" });
220220 expect(sent.ok).toBe(true);
@@ -234,7 +234,7 @@ test("reminders: three days before and the morning of, drafted in words, marked
234234 });
235235
236236 test("an edited send stores the edited words; an empty body is refused; a sent reminder keeps its words", () => {
237 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
237 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30), lengths: { inspection: "8" } });
238238 const inspection = due(deal, "inspection");
239239 const buyer = drafts(deal, agent).find((r) => r.deadline_id === inspection.id && r.moment === "before")!;
240240 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
@@ -356,8 +356,8 @@ test("an edited contact shows in the next draft; a removed party gets none", ()
356356 });
357357
358358 test("the record keeps the party's role and the date's label after both are removed, newest first", () => {
359 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30) });
360 const hoa = addDeadline(db, alice, { dealId: deal.id, label: "HOA review", due: addDays(today(), 9), owes: "buyer" });
359 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30) });
360 const hoa = addDeadline(db, alice, { dealId: deal.id, label: "HOA review", due: addDays(today(DEFAULT_ZONE), 9), owes: "buyer" });
361361 expect(hoa.ok).toBe(true);
362362 const id = hoa.ok ? hoa.value.id : 0;
363363 const buyer = deal.parties.find((p) => p.role === "buyer")!;
@@ -413,9 +413,9 @@ test("correcting and removing are updates of the deal: audited, and refused to a
413413 });
414414
415415 test("a declined reminder leaves the unsent count and /tick, keeps its reason, and undo brings it back", () => {
416 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
416 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30), lengths: { inspection: "8" } });
417417 const inspection = due(deal, "inspection");
418 const tick = () => dueOn([fresh(deal.id)], today(), agent).filter((r) => r.deadline_id === inspection.id);
418 const tick = () => dueOn([fresh(deal.id)], today(DEFAULT_ZONE), agent).filter((r) => r.deadline_id === inspection.id);
419419 const buyer = tick().find((r) => r.moment === "before")!;
420420 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
421421 const before = tick().length;
@@ -437,7 +437,7 @@ test("a declined reminder leaves the unsent count and /tick, keeps its reason, a
437437 });
438438
439439 test("a decline needs a reason of 1 to 200 characters, a real unsent reminder, and someone signed in", () => {
440 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30) });
440 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30) });
441441 const inspection = due(deal, "inspection");
442442 const buyer = drafts(deal, agent).find((r) => r.deadline_id === inspection.id && r.moment === "before")!;
443443 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
@@ -479,7 +479,7 @@ test("a deal is closed when its Closing date is marked done, and open again when
479479 });
480480
481481 test("an overdue follow-up: the morning after, to whoever owes the date alone, until it is done or moved", () => {
482 const deal = open({ contractDate: addDays(today(), -10), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
482 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -10), closingDate: addDays(today(DEFAULT_ZONE), 30), lengths: { inspection: "8" } });
483483 const inspection = due(deal, "inspection"); // due two days ago
484484 const lates = (d: DealView) => drafts(d, agent).filter((r) => r.deadline_id === inspection.id && r.moment === "late");
485485 expect(lates(deal).map((r) => [r.party_name, r.on, r.sent_at])).toEqual([["Ann Buyer", addDays(inspection.due, 1), null]]);
@@ -497,7 +497,7 @@ test("an overdue follow-up: the morning after, to whoever owes the date alone, u
497497 expect(db.query("SELECT moment FROM reminder WHERE deadline_id = ?1").all(inspection.id)).toEqual([{ moment: "late" }]);
498498
499499 // Moving the date makes a fresh follow-up for the new date; a done date drafts none.
500 const to = addDays(today(), -1);
500 const to = addDays(today(DEFAULT_ZONE), -1);
501501 expect(moveDeadline(db, alice, { id: inspection.id, due: to, reason: "Needs more time" }).ok).toBe(true);
502502 const moved = lates(fresh(deal.id));
503503 expect(moved.map((r) => [r.due, r.sent_at])).toEqual([[to, null]]);
@@ -508,7 +508,7 @@ test("an overdue follow-up: the morning after, to whoever owes the date alone, u
508508 });
509509
510510 test("pending: an overdue follow-up stays listed while unsent; the earlier moments drop once the date passes", () => {
511 const deal = open({ contractDate: addDays(today(), -10), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
511 const deal = open({ contractDate: addDays(today(DEFAULT_ZONE), -10), closingDate: addDays(today(DEFAULT_ZONE), 30), lengths: { inspection: "8" } });
512512 const inspection = due(deal, "inspection"); // due two days ago
513513 const mine = (d: DealView) => drafts(d, agent).filter((r) => r.deadline_id === inspection.id);
514514 const day = addDays(inspection.due, 3);
@@ -565,14 +565,14 @@ test("moving a date drafts a Date changed notice to the parties a day-of reminde
565565 expect(notes.map((n) => n.party_id).sort()).toEqual(day.map((n) => n.party_id).sort());
566566 expect(notes.length).toBeGreaterThan(0);
567567 const n = notes[0]!;
568 expect(n.on).toBe(today());
568 expect(n.on).toBe(today(DEFAULT_ZONE));
569569 expect(n.body).toContain("5 Moved Ln");
570570 expect(n.body).toContain(spoken(from));
571571 expect(n.body).toContain(spoken("2026-11-20"));
572572 expect(n.body).toContain(signOff(agent));
573573 expect(n.body).not.toContain("Inspector sick");
574574 expect(n.sent_at).toBeNull();
575 expect(pending(n, today())).toBe(true);
575 expect(pending(n, today(DEFAULT_ZONE))).toBe(true);
576576 });
577577
578578 test("a second move replaces the unsent notice and leaves a sent one as sent", () => {
src/deals.ts +25 −16
@@ -8,7 +8,7 @@
88
99 import type { Database } from "bun:sqlite";
1010 import { permit } from "./contract.ts";
11 import { addDays, isBusinessDay, isDate, nextBusinessDay, spoken, today } from "./dates.ts";
11 import { addDays, dayOfStamp, isBusinessDay, isDate, nextBusinessDay, spoken, today } from "./dates.ts";
1212 import {
1313 DEFAULT_LENGTHS,
1414 isClosed,
@@ -27,7 +27,7 @@ import {
2727 type PartyRole,
2828 } from "./deadlines.ts";
2929 import { LENGTH_MAX, standard, validEmail, validPhone } from "./env.ts";
30 import { agentOf } from "./profile.ts";
30 import { agentOf, zoneOf } from "./profile.ts";
3131 import { emit } from "./live.ts";
3232 import { closingPlace, closingTime } from "./closing.ts";
3333 import { amount, rate } from "./money.ts";
@@ -136,6 +136,8 @@ export interface Sent {
136136 readonly move_id: number;
137137 readonly by_name: string;
138138 readonly sent_at: string;
139 /** The day it was sent, in the agent's zone. */
140 readonly sent_on: string;
139141 /** The words that went out, as approved; '' on a reminder sent before they were kept. */
140142 readonly subject: string;
141143 readonly body: string;
@@ -144,7 +146,7 @@ export interface Sent {
144146 /** Every such link: Mail for the party's email, Messages for their phone. `href` is the first. */
145147 readonly hrefs: readonly string[];
146148 }
147 type SentRow = Omit<Sent, "href" | "hrefs">;
149 type SentRow = Omit<Sent, "href" | "hrefs" | "sent_on">;
148150 export interface Deadline {
149151 readonly id: number;
150152 readonly deal_id: number;
@@ -169,6 +171,8 @@ export interface Deadline {
169171 export interface DeadlineView extends Omit<Deadline, "owes_from" | "owes_by" | "owes_on"> {
170172 /** The day it was marked done, by the app's own calendar (`today()`); null while open or after a reopen. */
171173 readonly done_on: string | null;
174 /** The day it was waived, in the agent's zone; null while it stands. */
175 readonly waived_on: string | null;
172176 /** The latest change of who owes this date; null when it was never changed. */
173177 readonly owes_changed: { readonly from: PartyRole; readonly by: string; readonly on: string } | null;
174178 readonly moves: readonly Move[];
@@ -176,13 +180,15 @@ export interface DeadlineView extends Omit<Deadline, "owes_from" | "owes_by" | "
176180 readonly nonBusinessDay: { readonly next: string } | null;
177181 }
178182 /** The day the Closing date was marked done, by the app's own calendar (the one `today()` keeps). */
179 export const closedOn = (deal: { deadlines: readonly { kind: Kind; done_at: string | null }[]; closing: string }): string => {
183 export const closedOn = (deal: { zone: string; deadlines: readonly { kind: Kind; done_at: string | null }[]; closing: string }): string => {
180184 const at = deal.deadlines.find((d) => d.kind === "closing")?.done_at;
181 return at == null ? deal.closing : today(new Date(at));
185 return at == null ? deal.closing : today(deal.zone, new Date(at));
182186 };
183187
184188 /** A deal with everything hanging off it: what every page and door shows. */
185189 export interface DealView extends Deal {
190 /** The agent's time zone: the one that turns a stored moment into a day (`done_on`, `closedOn`, `fellOn`). */
191 readonly zone: string;
186192 /** The `closing` deadline's date, wherever it has moved. */
187193 readonly closing: string;
188194 /** Its Closing date is marked done: the deal has stepped off the clock. */
@@ -266,17 +272,18 @@ interface Children {
266272 }
267273
268274 /** A sent reminder with the link for the party's contact as it stands now; none once the party is gone. */
269 function withHref(m: SentRow, parties: readonly Party[]): Sent {
275 function withHref(m: SentRow, parties: readonly Party[], zone: string): Sent {
270276 const party = parties.find((p) => p.id === m.party_id);
271277 const hrefs = party === undefined || m.subject === "" ? [] : outboxes(party, m.subject, m.body).map((o) => o.href);
272 return { ...m, href: hrefs[0] ?? null, hrefs };
278 return { ...m, sent_on: dayOfStamp(zone, m.sent_at), href: hrefs[0] ?? null, hrefs };
273279 }
274280
275281 /** One deal assembled from its rows. */
276 function assemble(deal: Deal, rows: Children): DealView {
282 function assemble(deal: Deal, rows: Children, zone: string): DealView {
277283 const moves = rows.moves;
278284 return {
279285 ...deal,
286 zone,
280287 closing:
281288 rows.deadlines.find((d) => d.kind === "closing")?.due ?? deal.contract_date,
282289 closed: isClosed(rows.deadlines),
@@ -284,12 +291,13 @@ function assemble(deal: Deal, rows: Children): DealView {
284291 parties: rows.parties,
285292 deadlines: rows.deadlines.map(({ owes_from, owes_by, owes_on, ...d }) => ({
286293 ...d,
287 done_on: d.done_at === null ? null : today(new Date(d.done_at)),
294 done_on: d.done_at === null ? null : today(zone, new Date(d.done_at)),
295 waived_on: d.waived_at === null ? null : dayOfStamp(zone, d.waived_at),
288296 owes_changed: owes_from === null || owes_by === null || owes_on === null ? null : { from: owes_from, by: owes_by, on: owes_on },
289297 moves: moves.filter((m) => m.deadline_id === d.id),
290298 nonBusinessDay: isOpen(d) && !isBusinessDay(d.due) ? { next: nextBusinessDay(d.due) } : null,
291299 })),
292 sent: rows.sent.map((m) => withHref(m, rows.parties)),
300 sent: rows.sent.map((m) => withHref(m, rows.parties, zone)),
293301 declined: rows.declined,
294302 held: rows.held,
295303 conflicts: conflicts(rows.deadlines),
@@ -324,7 +332,7 @@ function view(db: Database, deal: Deal): DealView {
324332 )
325333 .all(deal.id),
326334 held: db.query<Held, [number]>("SELECT * FROM reminder_hold WHERE deal_id = ?1 ORDER BY id").all(deal.id),
327 });
335 }, zoneOf(db));
328336 }
329337
330338 /** Rows grouped by the deal they hang off, in the order read. */
@@ -382,6 +390,7 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] {
382390 db.query<Held, string[]>(`SELECT * FROM reminder_hold WHERE ${of} ORDER BY id`).all(...params),
383391 (r) => r.deal_id,
384392 );
393 const zone = zoneOf(db);
385394 return deals.map((deal) =>
386395 assemble(deal, {
387396 deadlines: deadlines.get(deal.id) ?? [],
@@ -390,7 +399,7 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] {
390399 sent: sent.get(deal.id) ?? [],
391400 declined: declined.get(deal.id) ?? [],
392401 held: held.get(deal.id) ?? [],
393 }),
402 }, zone),
394403 );
395404 }
396405
@@ -747,7 +756,7 @@ export function markFellThrough(
747756 }
748757
749758 /** The day a deal fell through, by the app's own calendar. */
750 export const fellOn = (deal: { fell_at: string | null }): string => today(new Date(deal.fell_at ?? Date.now()));
759 export const fellOn = (deal: { zone: string; fell_at: string | null }): string => today(deal.zone, new Date(deal.fell_at ?? Date.now()));
751760
752761 export const deleteDeal = (
753762 db: Database,
@@ -877,7 +886,7 @@ export function setOwes(
877886 return within(db, who, OWES_WHAT, dealId, fail("invalid", `${PARTY_LABEL[input.owes]} already owes it.`, "owes"));
878887 const told = [input.owes, ...KIND[deadline.kind].notify];
879888 db.transaction(() => {
880 db.query("UPDATE deadline SET owes = ?1, owes_from = ?2, owes_by = ?3, owes_on = ?4 WHERE id = ?5").run(input.owes as string, deadline.owes, authorOf(who).name, today(), deadline.id);
889 db.query("UPDATE deadline SET owes = ?1, owes_from = ?2, owes_by = ?3, owes_on = ?4 WHERE id = ?5").run(input.owes as string, deadline.owes, authorOf(who).name, today(zoneOf(db)), deadline.id);
881890 for (const h of db.query<{ id: number; moment: string; role: string }, [number]>(
882891 "SELECT h.id, h.moment, p.role FROM reminder_hold h JOIN party p ON p.id = h.party_id WHERE h.deadline_id = ?1",
883892 ).all(deadline.id))
@@ -1249,7 +1258,7 @@ export function sendReminder(
12491258 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
12501259 )
12511260 .get(found.value.deal.id, deadline.id, party.id, draft?.label ?? deadline.label, party.name, party.role, input.moment, draft?.due ?? deadline.due, moveId, authorOf(who).name, subject, body)!;
1252 return within(db, who, "reminder.send", dealId, ok(withHref(sent, [party])));
1261 return within(db, who, "reminder.send", dealId, ok(withHref(sent, [party], zoneOf(db))));
12531262 }
12541263
12551264 /** The draft one decline or undo names, on a date `who` may change. */
@@ -1318,7 +1327,7 @@ export function holdReminder(
13181327 return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was already sent."));
13191328 if (draft.declined !== null)
13201329 return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was declined; undo that first to hold it."));
1321 const day = input.on ?? today();
1330 const day = input.on ?? today(zoneOf(db));
13221331 if (draft.on > day)
13231332 return within(db, who, "reminder.hold", dealId, fail("invalid", `This reminder goes out on ${spoken(draft.on)}; it can be held from that morning.`));
13241333 const subject = input.subject === undefined ? undefined : line(input.subject, 1, SUBJECT_MAX);
src/env.ts +2
@@ -5,6 +5,7 @@
55 */
66
77 import pkg from "../package.json";
8 import { DEFAULT_ZONE } from "./dates.ts";
89
910 export const title: string = pkg.name;
1011 /** The app's own version (package.json): what `/healthz` and `/openapi.json` say. */
@@ -51,6 +52,7 @@ export const agent = {
5152 brokerage: process.env.DEAL_CLOCK_BROKERAGE || "Harbor & Pine Realty",
5253 phone: setting("DEAL_CLOCK_PHONE", "(555) 010-0142", validPhone),
5354 email: setting("DEAL_CLOCK_EMAIL", "[email protected]", validEmail),
55 zone: DEFAULT_ZONE,
5456 } as const;
5557
5658 /** The brief's contingency lengths, in days: what a new deal starts from unless the agent says otherwise. */
src/fell.test.ts +6 −6
@@ -3,9 +3,9 @@ import { afterAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { openDb } from "./db.ts";
8 import { createDeal, getDeal, listDeals, markFellThrough, REASON_MAX, type DealView } from "./deals.ts";
8 import { createDeal, fellOn, getDeal, listDeals, markFellThrough, REASON_MAX, type DealView } from "./deals.ts";
99 import { agent } from "./env.ts";
1010 import { book } from "./ics.ts";
1111 import { people } from "./people.ts";
@@ -25,8 +25,8 @@ const made = createDeal(db, alice, {
2525 address: "5 Fallen Fir Ln",
2626 buyer: "Ann Buyer",
2727 seller: "Sam Seller",
28 contractDate: addDays(today(), -10),
29 closingDate: addDays(today(), 3),
28 contractDate: addDays(today(DEFAULT_ZONE), -10),
29 closingDate: addDays(today(DEFAULT_ZONE), 3),
3030 });
3131 if (!made.ok) throw new Error(made.message);
3232 db.query("UPDATE party SET contact = '[email protected]' WHERE deal_id = ?1").run(made.value.id);
@@ -53,7 +53,7 @@ test("a refused reason, an empty one and a visitor change nothing", () => {
5353 });
5454
5555 test("it leaves the clock, the week, people, reminders and the calendar, and drafts nothing", () => {
56 const day = today();
56 const day = today(DEFAULT_ZONE);
5757 expect(here(thisWeek(all(), day).map((i) => i.deal)).length).toBeGreaterThan(0);
5858 expect(drafts(deal(), agent).length).toBeGreaterThan(0);
5959 expect(statusDrafts(deal(), agent).length).toBeGreaterThan(0);
@@ -63,7 +63,7 @@ test("it leaves the clock, the week, people, reminders and the calendar, and dra
6363 const fell = markFellThrough(db, alice, { id: made.value.id, fell: true, reason: " Buyer's loan\nfell through " });
6464 expect(fell.ok).toBe(true);
6565 expect(deal()).toMatchObject({ fell_through: true, closed: false, fell_reason: "Buyer's loan fell through", fell_by: "alice" });
66 expect(deal().fell_at).toStartWith(day);
66 expect(fellOn(deal())).toBe(day);
6767 expect(markFellThrough(db, alice, { id: made.value.id, fell: true, reason: "again" }).ok).toBe(false);
6868
6969 expect(here(thisWeek(all(), day).map((i) => i.deal))).toEqual([]);
src/hold.test.ts +2 −2
@@ -4,7 +4,7 @@ import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { listAudit, restoreSamples } from "./actions.ts";
7 import { addDays, today } from "./dates.ts";
7 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
88 import { openDb } from "./db.ts";
99 import { createDeal, getDeal, holdReminder, sendReminder, declineReminder, type DealView } from "./deals.ts";
1010 import { drafts, dueOn, todaysDrafts, waitingCount, type Draft } from "./reminders.ts";
@@ -20,7 +20,7 @@ const admin: Who = { role: "admin", id: "a1", name: "root" };
2020 const anon: Who = { role: "anon" };
2121 const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty", phone: "(555) 010-0142", email: "[email protected]" };
2222
23 const now = today();
23 const now = today(DEFAULT_ZONE);
2424 const deal = ((): DealView => {
2525 const made = createDeal(db, alice, { openAnyway: true, address: "7 Hold Ln", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(now, -5), closingDate: addDays(now, 40), lengths: { inspection: "8" } });
2626 if (!made.ok) throw new Error(made.message);
src/lastsent.test.ts +5 −5
@@ -3,7 +3,7 @@ import { expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { openDb } from "./db.ts";
88 import { createDeal, declineReminder, getDeal, listDeals, sendReminder } from "./deals.ts";
99 import { agent } from "./env.ts";
@@ -14,14 +14,14 @@ import type { Who } from "./who.ts";
1414
1515 const db = openDb(mkdtempSync(join(tmpdir(), "app-lastsent-")));
1616 const alice: Who = { role: "user", id: "u1", name: "alice" };
17 const made = createDeal(db, alice, { openAnyway: true, address: "12 Oak Lane", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(today(), -10), closingDate: addDays(today(), 30) });
17 const made = createDeal(db, alice, { openAnyway: true, address: "12 Oak Lane", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(today(DEFAULT_ZONE), -10), closingDate: addDays(today(DEFAULT_ZONE), 30) });
1818 if (!made.ok) throw new Error(made.message);
1919 db.query("UPDATE party SET contact = '[email protected]', email = '[email protected]' WHERE deal_id = ?1 AND role = 'buyer'").run(made.value.id);
2020 db.query("UPDATE party SET contact = '[email protected]', email = '[email protected]' WHERE deal_id = ?1 AND role = 'seller'").run(made.value.id);
2121 const deal = () => { const g = getDeal(db, alice, { id: made.value.id }); if (!g.ok) throw new Error(g.message); return g.value; };
22 const everyone = () => { const l = listDeals(db, alice); if (!l.ok) throw new Error(l.message); return people(l.value, today()); };
22 const everyone = () => { const l = listDeals(db, alice); if (!l.ok) throw new Error(l.message); return people(l.value, today(DEFAULT_ZONE)); };
2323 const ann = () => everyone().find((p) => p.email === "[email protected]")!;
24 const page = () => peoplePage({ who: alice, people: everyone(), on: today() });
24 const page = () => peoplePage({ who: alice, people: everyone(), on: today(DEFAULT_ZONE) });
2525
2626 test("nothing sent yet, then a declined draft still counts for nothing, then a sent one shows", () => {
2727 expect(ann().last_sent).toBeNull();
@@ -31,7 +31,7 @@ test("nothing sent yet, then a declined draft still counts for nothing, then a s
3131 expect(declineReminder(db, alice, { deadlineId: first!.deadline_id, partyId: first!.party_id, moment: first!.moment, reason: "called them" }).ok).toBe(true);
3232 expect(ann().last_sent).toBeNull();
3333 expect(sendReminder(db, alice, { deadlineId: second!.deadline_id, partyId: second!.party_id, moment: second!.moment, agent }).ok).toBe(true);
34 expect(ann().last_sent).toEqual({ sent_on: today(), deal_id: made.value.id, address: "12 Oak Lane", label: second!.label });
34 expect(ann().last_sent).toEqual({ sent_on: today(DEFAULT_ZONE), deal_id: made.value.id, address: "12 Oak Lane", label: second!.label });
3535 expect(page()).toContain(`Last heard`);
3636 expect(page()).toContain(`12 Oak Lane`);
3737 expect(everyone().find((p) => p.email === "[email protected]")!.last_sent).toBeNull();
src/lead.test.ts +2 −2
@@ -7,7 +7,7 @@ import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { Database } from "bun:sqlite";
10 import { addDays, today } from "./dates.ts";
10 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
1111 import { openDb } from "./db.ts";
1212 import { createDeal, getDeal, sendReminder, setReminderLead, type DealView } from "./deals.ts";
1313 import { calendar } from "./ics.ts";
@@ -192,7 +192,7 @@ test("MCP set_reminder_lead sets it and refuses a bad one", async () => {
192192 });
193193
194194 test("the terminal shows the lead and sets it with l; a bad one is refused", () => {
195 const made = createDeal(db, alice, { openAnyway: true, address: "7 Tty Row", buyer: "A", seller: "B", contractDate: today(), closingDate: addDays(today(), 45) });
195 const made = createDeal(db, alice, { openAnyway: true, address: "7 Tty Row", buyer: "A", seller: "B", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 45) });
196196 if (!made.ok) throw new Error(made.message);
197197 const t = terminal(db, alice, { title: "deal-clock", where: "test", agent });
198198 const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "");
src/line.test.ts +2 −2
@@ -3,7 +3,7 @@ import { afterAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { createDeal, getDeal, holdReminder, moveDeadline, sendReminder } from "./deals.ts";
88 import { openDb } from "./db.ts";
99 import { agentOf, setProfile } from "./profile.ts";
@@ -27,7 +27,7 @@ const LINE = "Text me anytime, I answer within the hour";
2727
2828 const db = openDb(mkdtempSync(join(tmpdir(), "app-line-db-")));
2929 const admin: Who = { role: "admin", id: "u0", name: "root" };
30 const made = createDeal(db, admin, { openAnyway: true, address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(), closingDate: addDays(today(), 40) });
30 const made = createDeal(db, admin, { openAnyway: true, address: "1 Oak", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 40) });
3131 if (!made.ok) throw new Error(made.message);
3232 for (const p of made.value.parties) db.query("UPDATE party SET contact = ?1 WHERE id = ?2").run(`${p.name.split(" ")[0]!.toLowerCase()}@example.com`, p.id);
3333 const view = () => {
src/mcp.ts +5 −5
@@ -45,7 +45,7 @@ import { dueOn } from "./reminders.ts";
4545 import { FIND_REFUSAL, find, query } from "./find.ts";
4646 import { SIDES, SIDE_REFUSAL, onSide, sideFilter } from "./side.ts";
4747 import { fields } from "./http.ts";
48 import { agentOf, getProfile, setProfile } from "./profile.ts";
48 import { agentOf, getProfile, setProfile, zoneOf } from "./profile.ts";
4949 import { people } from "./people.ts";
5050 import { timelineRows } from "./timeline.ts";
5151 import { owner, thisWeek } from "./week.ts";
@@ -89,7 +89,7 @@ export const tools: readonly Tool[] = [
8989 run: (db, who, args) => {
9090 const got = getDeal(db, who, { id: Number(args.id) });
9191 if (!got.ok) return got;
92 const dates = timelineRows(got.value, today()).map(({ label, due, role, name, status, todo }) => ({ label, due, owed_by: { role, name: name ?? null }, status, todo: todo.map((g) => (g.label === "" ? g.line : `${g.label}: ${g.line}`)) }));
92 const dates = timelineRows(got.value, today(zoneOf(db))).map(({ label, due, role, name, status, todo }) => ({ label, due, owed_by: { role, name: name ?? null }, status, todo: todo.map((g) => (g.label === "" ? g.line : `${g.label}: ${g.line}`)) }));
9393 return { ok: true, value: { address: got.value.address, sale_price: got.value.sale_price, earnest_amount: got.value.earnest_amount, closing_time: got.value.closing_time, closing_place: got.value.closing_place, agent: agentOf(db), dates } };
9494 },
9595 },
@@ -99,7 +99,7 @@ export const tools: readonly Tool[] = [
9999 inputSchema: { type: "object", properties: {} },
100100 run: (db, who) => {
101101 const deals = listDeals(db, who);
102 return deals.ok ? { ok: true, value: dueOn(deals.value, today(), agentOf(db)) } : deals;
102 return deals.ok ? { ok: true, value: dueOn(deals.value, today(zoneOf(db)), agentOf(db)) } : deals;
103103 },
104104 },
105105 {
@@ -111,7 +111,7 @@ export const tools: readonly Tool[] = [
111111 return deals.ok
112112 ? {
113113 ok: true,
114 value: thisWeek(deals.value, today()).map(({ deal, deadline }) => ({
114 value: thisWeek(deals.value, today(zoneOf(db))).map(({ deal, deadline }) => ({
115115 deal_id: deal.id,
116116 address: deal.address,
117117 owner: owner(deal, deadline),
@@ -128,7 +128,7 @@ export const tools: readonly Tool[] = [
128128 inputSchema: { type: "object", properties: {} },
129129 run: (db, who) => {
130130 const deals = listDeals(db, who);
131 return deals.ok ? { ok: true, value: people(deals.value, today()) } : deals;
131 return deals.ok ? { ok: true, value: people(deals.value, today(zoneOf(db))) } : deals;
132132 },
133133 },
134134 {
src/migrations.pin.json +2 −1
@@ -52,5 +52,6 @@
5252 "fd1b67b66fb8ff34326ca5cb86ab04678619dfea420f21d8f85b2d05c999907f",
5353 "f836a1da11c1f51a255301c4ee62c441612baada0345c1310f4149e5d5ccf5b9",
5454 "72f67a8e8f06f9b9fcac58ff22eb3f4222c77a0968da5981d4e7dce8d4b8ce7d",
55 "166c5e5ec18272d556b87786396c5c3a17da8b56185643e8efeeb83742cc2b5b"
55 "166c5e5ec18272d556b87786396c5c3a17da8b56185643e8efeeb83742cc2b5b",
56 "3fbd9e1851d9bc86a3a4c5adfc9f2300712c450b66a87d253cfcb91586cbbe25"
5657 ]
src/migrations.test.ts +1 −1
@@ -13,7 +13,7 @@ test("every migration is pinned by position; a pull may only append", () => {
1313 });
1414
1515 test("a database made before the Profile line gets the column and reads the agent", () => {
16 const before = migrations.filter((m) => !/profile ADD COLUMN line|commission_rate/.test(m));
16 const before = migrations.filter((m) => !/profile ADD COLUMN line|commission_rate|profile ADD COLUMN zone/.test(m));
1717 const db = new Database(":memory:");
1818 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
1919 before.forEach((sql, i) => {
src/note.test.ts +3 −3
@@ -3,7 +3,7 @@ import { afterAll, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { sheet as csv } from "./csv.ts";
88 import { calendar } from "./ics.ts";
99 import { agent } from "./env.ts";
@@ -32,7 +32,7 @@ async function fresh() {
3232 const made = await fetch(base + "/api/deals", {
3333 method: "POST",
3434 headers: json,
35 body: JSON.stringify({ address: "3 Note Way", open_anyway: true, buyer: "B Buyer", seller: "S Seller", contract_date: addDays(today(), -20), closing_date: addDays(today(), 3) }),
35 body: JSON.stringify({ address: "3 Note Way", open_anyway: true, buyer: "B Buyer", seller: "S Seller", contract_date: addDays(today(DEFAULT_ZONE), -20), closing_date: addDays(today(DEFAULT_ZONE), 3) }),
3636 });
3737 const deal = (await made.json()) as DealView;
3838 const d = deal.deadlines.find((x) => x.kind === "closing")!;
@@ -101,7 +101,7 @@ test("the note shows on the deal page, This week and the printed week, and nowhe
101101 expect(await get("/week")).toContain(SECRET);
102102
103103 const full = await read(deal.id);
104 expect(timelinePage({ who: { role: "user", id: "u", name: "alice" }, deal: full, on: today() })).not.toContain(SECRET);
104 expect(timelinePage({ who: { role: "user", id: "u", name: "alice" }, deal: full, on: today(DEFAULT_ZONE) })).not.toContain(SECRET);
105105 expect(await get(`/deals/${deal.id}/timeline`)).not.toContain(SECRET);
106106 expect(csv([full])).not.toContain(SECRET);
107107 expect(calendar(full, "x.example")).not.toContain(SECRET);
src/owes.test.ts +7 −7
@@ -3,7 +3,7 @@ import { afterAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { openDb } from "./db.ts";
88 import { createDeal, getDeal, markDone, setOwes, waiveDate, type DealView } from "./deals.ts";
99 import { agent } from "./env.ts";
@@ -23,8 +23,8 @@ const made = createDeal(db, alice, {
2323 address: "5 Hand Over Hill",
2424 buyer: "Ann Buyer",
2525 seller: "Sam Seller",
26 contractDate: addDays(today(), -10),
27 closingDate: addDays(today(), 30),
26 contractDate: addDays(today(DEFAULT_ZONE), -10),
27 closingDate: addDays(today(DEFAULT_ZONE), 30),
2828 });
2929 if (!made.ok) throw new Error(made.message);
3030 const deal = (): DealView => {
@@ -35,7 +35,7 @@ const deal = (): DealView => {
3535 const date = (kind: string) => deal().deadlines.find((d) => d.kind === kind)!;
3636 db.query("UPDATE party SET contact = '[email protected]' WHERE deal_id = ?1 AND role = 'buyer'").run(made.value.id);
3737 db.query("UPDATE party SET contact = '[email protected]' WHERE deal_id = ?1 AND role = 'seller'").run(made.value.id);
38 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(today(), date("earnest").id);
38 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(today(DEFAULT_ZONE), date("earnest").id);
3939 const roleOf = (kind: string, moment: string) => drafts(deal(), agent).filter((r) => r.deadline_id === date(kind).id && r.moment === moment).map((r) => r.party_role);
4040
4141 test("a change moves today's draft to the new party and the People page follows", () => {
@@ -43,7 +43,7 @@ test("a change moves today's draft to the new party and the People page follows"
4343 const handed = setOwes(db, alice, { id: date("earnest").id, owes: "seller" });
4444 expect(handed).toMatchObject({ ok: true, value: { owes: "seller" } });
4545 expect(roleOf("earnest", "day_of")).toContain("seller");
46 const list = people([deal()], today());
46 const list = people([deal()], today(DEFAULT_ZONE));
4747 const sam = list.find((p) => p.name === "Sam Seller")!;
4848 const ann = list.find((p) => p.name === "Ann Buyer")!;
4949 expect(sam.owes.map((o) => o.deadline_id)).toContain(date("earnest").id);
@@ -70,7 +70,7 @@ test("an anonymous visitor is refused and nothing changes", () => {
7070 test("a hold on the old party's reminder is dropped with the change", () => {
7171 const id = date("walkthrough").id;
7272 const buyer = deal().parties.find((p) => p.role === "buyer")!;
73 db.query("INSERT INTO reminder_hold (deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name) VALUES (?1, ?2, ?3, 'late', ?4, 0, ?5, ?4, 'alice')").run(made.value.id, id, buyer.id, date("walkthrough").due, addDays(today(), 1));
73 db.query("INSERT INTO reminder_hold (deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name) VALUES (?1, ?2, ?3, 'late', ?4, 0, ?5, ?4, 'alice')").run(made.value.id, id, buyer.id, date("walkthrough").due, addDays(today(DEFAULT_ZONE), 1));
7474 setOwes(db, alice, { id, owes: "seller" });
7575 expect(db.query("SELECT count(*) AS n FROM reminder_hold WHERE deadline_id = ?1").get(id)).toEqual({ n: 0 });
7676 });
@@ -138,7 +138,7 @@ test("the deal page and sheet say who handed a date to whom and when; only the l
138138 const read = async () => ((await (await fetch(`${base}/api/deals/${d.id}`, { headers: me })).json()) as DealView).deadlines;
139139 expect((await page()).includes("Owed by changed")).toBe(false);
140140 expect((await hand("Bob <b>", "seller")).status).toBe(200);
141 expect((await read()).find((x) => x.id === insp.id)!.owes_changed).toEqual({ from: "buyer", by: "Bob <b>", on: today() });
141 expect((await read()).find((x) => x.id === insp.id)!.owes_changed).toEqual({ from: "buyer", by: "Bob <b>", on: today(DEFAULT_ZONE) });
142142 expect((await hand("alice", "lender")).status).toBe(200);
143143 const text = await page();
144144 expect(text.split("Owed by changed from").length - 1).toBe(2); // the date's row and its sheet
src/pages/deal.ts +1 −1
@@ -125,7 +125,7 @@ function messages(deal: DealView, may: boolean, agent: Agent, to: string): strin
125125 m.subject === ""
126126 ? `<p class="muted">The words were not kept for this one.</p>`
127127 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.hrefs, may)}`;
128 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>`;
128 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_on))}</span></summary>${words}</details></li>`;
129129 };
130130 return `${waiting}<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
131131 }
src/pages/file.ts +5 −5
@@ -8,7 +8,7 @@
88 * this page and the terminal print from.
99 */
1010
11 import { doneLine, short, spoken } from "../dates.ts";
11 import { dayOfStamp, doneLine, short, spoken } from "../dates.ts";
1212 import { closedOn, fellOn, type DealView, type Party } from "../deals.ts";
1313 import { PARTY_LABEL } from "../deadlines.ts";
1414 import { closingLine } from "../closing.ts";
@@ -28,7 +28,7 @@ const contactOf = (p: Party): string => {
2828 /** Where one date stands, in words: done on (and how early or late), waived, or open. */
2929 export function fileState(d: DealView["deadlines"][number]): string {
3030 if (d.waived_at !== null)
31 return `Waived ${spoken(d.waived_at.slice(0, 10))}${d.waived_by === null ? "" : ` by ${d.waived_by}`}`;
31 return `Waived ${spoken(d.waived_on ?? d.waived_at.slice(0, 10))}${d.waived_by === null ? "" : ` by ${d.waived_by}`}`;
3232 if (d.done_at !== null) return d.done_on === null ? "Done" : doneLine(d.due, d.done_on);
3333 return "Open";
3434 }
@@ -52,7 +52,7 @@ export function fileRecord(deal: DealView): FileRecord {
5252 const live = new Set(deal.deadlines.map((d) => d.id));
5353 const live_dates = deal.deadlines.map((d) => ({
5454 line: `${d.label} · due ${spoken(d.due)} · ${fileState(d)}`,
55 moves: d.moves.map((m) => `Moved ${short(m.from_due)} → ${short(m.to_due)}: ${m.reason} (${m.by_name}, ${short(m.at.slice(0, 10))})`),
55 moves: d.moves.map((m) => `Moved ${short(m.from_due)} → ${short(m.to_due)}: ${m.reason} (${m.by_name}, ${short(dayOfStamp(deal.zone, m.at))})`),
5656 }));
5757 // A removed date leaves no row of its own; what remains of it is in the messages sent or declined about it.
5858 const gone = new Map<number, { label: string; due: string }>();
@@ -76,12 +76,12 @@ export function fileRecord(deal: DealView): FileRecord {
7676 parties: deal.parties.map((p) => `${PARTY_LABEL[p.role]} · ${p.name}${contactOf(p) === "" ? "" : ` · ${contactOf(p)}`}`),
7777 dates: [...live_dates, ...removed],
7878 sent: deal.sent.map((m) => ({
79 head: `${m.party_name}${m.party_role === "" ? "" : ` · ${PARTY_LABEL[m.party_role]}`} · ${m.label}${live.has(m.deadline_id) ? "" : " (date removed)"}, due ${short(m.due)} · ${sentLabel(m.moment)} · approved by ${m.by_name} on ${spoken(m.sent_at.slice(0, 10))}`,
79 head: `${m.party_name}${m.party_role === "" ? "" : ` · ${PARTY_LABEL[m.party_role]}`} · ${m.label}${live.has(m.deadline_id) ? "" : " (date removed)"}, due ${short(m.due)} · ${sentLabel(m.moment)} · approved by ${m.by_name} on ${spoken(m.sent_on)}`,
8080 subject: m.subject,
8181 body: m.body,
8282 })),
8383 declined: deal.declined.map(
84 (m) => `${m.party_name} · ${m.label}${live.has(m.deadline_id) ? "" : " (date removed)"}, due ${short(m.due)} · ${sentLabel(m.moment)} · declined by ${m.by_name} on ${spoken(m.at.slice(0, 10))}: ${m.reason}`,
84 (m) => `${m.party_name} · ${m.label}${live.has(m.deadline_id) ? "" : " (date removed)"}, due ${short(m.due)} · ${sentLabel(m.moment)} · declined by ${m.by_name} on ${spoken(dayOfStamp(deal.zone, m.at))}: ${m.reason}`,
8585 ),
8686 };
8787 }
src/pages/profile.ts +8 −1
@@ -4,6 +4,7 @@
44 * field, as New deal does. Whoever may not change it sees the details only.
55 */
66
7 import { DEFAULT_ZONE, US_ZONES } from "../dates.ts";
78 import { escape } from "../http.ts";
89 import type { Profile } from "../profile.ts";
910 import type { Agent } from "../reminders.ts";
@@ -36,6 +37,10 @@ export function profilePage(input: {
3637 : "";
3738 const bad = (name: string): string =>
3839 problem?.field === name ? ` aria-invalid="true" aria-describedby="${name}-why"` : "";
40 // The US zones, and the stored one as well when it is none of them.
41 const zone = values.zone ?? agent.zone ?? DEFAULT_ZONE;
42 const zones = US_ZONES.some(([name]) => name === zone) ? US_ZONES : [...US_ZONES, [zone, zone] as const];
43 const zoneName = zones.find(([name]) => name === zone)?.[1] ?? zone;
3944 const general =
4045 problem !== undefined && problem.field === undefined
4146 ? `<p class="field-error" role="alert">${escape(problem.message)}</p>`
@@ -47,6 +52,7 @@ export function profilePage(input: {
4752 <label>Phone<input class="input" type="tel" name="phone" required maxlength="30" autocomplete="tel" value="${val("phone")}"${bad("phone")}>${why("phone")}</label>
4853 <label>Email<input class="input" type="email" name="email" required maxlength="254" autocomplete="email" value="${val("email")}"${bad("email")}>${why("email")}</label>
4954 <label>A line of your own at the end of every message<input class="input" name="line" maxlength="200" value="${val("line")}"${bad("line")}>${why("line")}</label>
55 <label>Your time zone<select class="input" name="zone"${bad("zone")}>${zones.map(([name, label]) => `<option value="${escape(name)}"${name === zone ? " selected" : ""}>${escape(label)}</option>`).join("")}</select>${why("zone")}</label>
5056 <div class="actions">
5157 <button class="button">Save profile</button>
5258 <button class="button button-quiet" formaction="/profile/defaults" formnovalidate>Use defaults</button>
@@ -57,13 +63,14 @@ export function profilePage(input: {
5763 <div><dt class="muted small">Brokerage</dt><dd>${escape(agent.brokerage)}</dd></div>
5864 <div><dt class="muted small">Phone</dt><dd>${escape(agent.phone)}</dd></div>
5965 <div><dt class="muted small">Email</dt><dd>${escape(agent.email)}</dd></div>
66 <div><dt class="muted small">Your time zone</dt><dd>${escape(zoneName)}</dd></div>
6067 <div><dt class="muted small">A line of your own</dt><dd>${escape(agent.line ?? "") || "None"}</dd></div>
6168 </dl>
6269 <p class="muted small">Only an admin can change these.</p>`;
6370 const body = `<p class="crumb"><a href="/">← The clock</a></p>
6471 <section class="card narrow">
6572 <h1>Profile</h1>
66 <p class="muted">${profile.saved ? "Saved by you." : "These are the defaults the app was started with."} The header, the client timeline and the sign-off of every unsent reminder carry them. Reminders already sent keep the words that went out.</p>
73 <p class="muted">${profile.saved ? "Saved by you." : "These are the defaults the app was started with."} The header, the client timeline and the sign-off of every unsent reminder carry them. Reminders already sent keep the words that went out. Your time zone decides which day is today.</p>
6774 ${mayChange ? form : readOnly}
6875 </section>`;
6976 return layout({ body, who, agent, path: "/profile", heading: "Profile", notice, waiting: input.waiting, live: false });
src/pages/sheet.ts +2 −2
@@ -39,7 +39,7 @@ export const URGENCY_LABEL: Readonly<Record<Urgency, string>> = {
3939
4040 /** "Due Thu, Oct 15 · in 3 days", or "Done". */
4141 export function dueLine(d: DeadlineView, on: string): string {
42 if (d.waived_at !== null) return `Waived ${spoken(d.waived_at.slice(0, 10))}${d.waived_by === null ? "" : ` by ${d.waived_by}`} · was due ${spoken(d.due)}`;
42 if (d.waived_at !== null) return `Waived ${spoken(d.waived_on ?? d.waived_at.slice(0, 10))}${d.waived_by === null ? "" : ` by ${d.waived_by}`} · was due ${spoken(d.due)}`;
4343 if (d.done_at !== null) return d.done_on === null ? "Done" : doneLine(d.due, d.done_on);
4444 return `Due ${spoken(d.due)} · ${relative(d.due, on)}`;
4545 }
@@ -144,7 +144,7 @@ const undoForm = (draft: Draft, to: string): string =>
144144 function draftLine(draft: Draft, on: string, withDeal: boolean): string {
145145 const state =
146146 draft.sent_at !== null
147 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
147 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_on ?? draft.sent_at.slice(0, 10)))}</span>`
148148 : draft.declined !== null
149149 ? `<span class="state" data-declined>Not sent: ${escape(draft.declined.reason)} · ${escape(draft.declined.by_name || "someone")}</span>`
150150 : draft.held !== null && draft.held.until > on
src/people.test.ts +1 −1
@@ -45,7 +45,7 @@ test("people who owe nothing open come last; a closed deal's dates are not chase
4545 expect(all.at(-1)!.owes).toEqual([]);
4646 });
4747
48 const sent = (id: number, deal_id: number, party_id: number, label: string, sent_at: string) => ({ id, deal_id, party_id, label, sent_at });
48 const sent = (id: number, deal_id: number, party_id: number, label: string, sent_at: string) => ({ id, deal_id, party_id, label, sent_at, sent_on: sent_at.slice(0, 10) });
4949 const withSent = (d: DealView, ...m: ReturnType<typeof sent>[]): DealView => ({ ...d, sent: m }) as unknown as DealView;
5050
5151 test("last_sent: nothing sent is null; the newest sent message across deals wins; same name, other contact is not them", () => {
src/people.ts +1 −1
@@ -95,7 +95,7 @@ export function people(deals: readonly DealView[], on: string): Person[] {
9595 one.roles.add(party.role);
9696 // Only sent messages are in `deal.sent`; declined and held ones live apart.
9797 for (const m of deal.sent) {
98 if (m.party_id === party.id) one.last = newer(one.last, { sent_on: m.sent_at.slice(0, 10), deal_id: deal.id, address: deal.address, label: m.label, at: m.sent_at, id: m.id });
98 if (m.party_id === party.id) one.last = newer(one.last, { sent_on: m.sent_on, deal_id: deal.id, address: deal.address, label: m.label, at: m.sent_at, id: m.id });
9999 }
100100 // A closed deal is off the clock: nothing on it is chased.
101101 if (deal.closed || deal.fell_through) continue;
src/profile.test.ts +2 −2
@@ -50,7 +50,7 @@ test("the defaults stand until saved, then the saved row; Use defaults restores
5050 expect(agentOf(db)).toEqual(defaults);
5151 expect(getProfile(db, user)).toEqual({ ok: true, value: { ...defaults, id: 1, saved: false } });
5252 expect(setProfile(db, admin, lee).ok).toBe(true);
53 expect(agentOf(db)).toEqual(lee);
53 expect(agentOf(db)).toEqual({ ...lee, zone: "America/New_York" });
5454 const got = getProfile(db, user);
5555 expect(got.ok && got.value.saved).toBe(true);
5656 expect(useDefaults(db, admin).ok).toBe(true);
@@ -160,7 +160,7 @@ test("GET and PUT /api/profile, and the MCP tools, apply the same rules", async
160160 const ok = await put(lee);
161161 expect(ok.status).toBe(200);
162162 const got = await (await fetch(`${base}/api/profile`, { headers: rita })).json();
163 expect(got).toEqual({ ...lee, id: 1, saved: true });
163 expect(got).toEqual({ ...lee, zone: "America/New_York", id: 1, saved: true });
164164 expect((await fetch(`${base}/api/profile`)).status).toBe(401);
165165 const call = (name: string, args: unknown, who: Record<string, string>) =>
166166 fetch(`${base}/mcp`, { method: "POST", headers: { "content-type": "application/json", ...who }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }).then((r) => r.json() as Promise<any>);
src/profile.ts +30 −7
@@ -7,6 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { DEFAULT_ZONE, isZone } from "./dates.ts";
1011 import { agent as defaults, validEmail, validPhone } from "./env.ts";
1112 import type { Agent } from "./reminders.ts";
1213 import { audited, fail, ok, refuse, type Result } from "./result.ts";
@@ -24,14 +25,26 @@ const FIELDS = ["name", "brokerage", "phone", "email"] as const;
2425 /** The agent the page, the drafts and the files name: the saved row, else the defaults. */
2526 export function agentOf(db: Database): Agent {
2627 const row = db
27 .query<Agent, []>("SELECT name, brokerage, phone, email, line FROM profile WHERE id = 1")
28 .query<Agent, []>("SELECT name, brokerage, phone, email, line, zone FROM profile WHERE id = 1")
2829 .get();
2930 if (row === null) return defaults;
3031 const { line, ...rest } = row;
3132 return line ? row : rest;
3233 }
3334
34 /** Five fields as the agent typed them, or the first one that fails and why. */
35 /** The zone the agent's day is told in: the saved one, else the default. Read once per request or per list. */
36 export function zoneOf(db: Database): string {
37 let zone = zones.get(db);
38 if (zone === undefined) {
39 zone = db.query<{ zone: string }, []>("SELECT zone FROM profile WHERE id = 1").get()?.zone ?? defaults.zone;
40 zones.set(db, zone);
41 }
42 return zone;
43 }
44 // Every list of deals asks for the zone: it is read once and forgotten on a save.
45 const zones = new WeakMap<Database, string>();
46
47 /** Six fields as the agent typed them, or the first one that fails and why. */
3548 export function checkProfile(input: Record<string, unknown>): Result<Agent> {
3649 const text = (name: string): string => (typeof input[name] === "string" ? (input[name] as string).trim() : "");
3750 const [name, brokerage, phone, email] = FIELDS.map(text) as [string, string, string, string];
@@ -46,7 +59,10 @@ export function checkProfile(input: Record<string, unknown>): Result<Agent> {
4659 if (line.length > LINE_MAX) return fail("invalid", `Your own line is at most ${LINE_MAX} characters.`, "line");
4760 if (/[\p{Cc}\u2028\u2029]/u.test(line))
4861 return fail("invalid", "Your own line is one line of plain text: no line breaks, tabs or other control characters.", "line");
49 return ok(line ? { name, brokerage, phone, email, line } : { name, brokerage, phone, email });
62 // A client that predates the zone does not send it: the zone stands as it is (`setProfile`).
63 const zone = typeof input.zone === "string" ? input.zone.trim() : DEFAULT_ZONE;
64 if (!isZone(zone)) return fail("invalid", "Your time zone is a name such as America/New_York, one this server knows.", "zone");
65 return ok(line ? { name, brokerage, phone, email, line, zone } : { name, brokerage, phone, email, zone });
5066 }
5167
5268 const may = (who: Who): Result<null> =>
@@ -70,15 +86,21 @@ export function setProfile(db: Database, who: Who, input: Record<string, unknown
7086 else {
7187 // A client that predates the line does not send it, and must not wipe it:
7288 // only an explicit empty string clears.
73 const given = typeof input.line === "string" ? input : { ...input, line: agentOf(db).line ?? "" };
89 const now = agentOf(db);
90 const given = {
91 ...input,
92 ...(typeof input.line === "string" ? {} : { line: now.line ?? "" }),
93 ...(typeof input.zone === "string" ? {} : { zone: now.zone ?? DEFAULT_ZONE }),
94 };
7495 const checked = checkProfile(given);
7596 if (!checked.ok) out = checked;
7697 else {
7798 const a = checked.value;
7899 db.query(
79 `INSERT INTO profile (id, name, brokerage, phone, email, line) VALUES (1, ?1, ?2, ?3, ?4, ?5)
80 ON CONFLICT (id) DO UPDATE SET name = excluded.name, brokerage = excluded.brokerage, phone = excluded.phone, email = excluded.email, line = excluded.line, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`,
81 ).run(a.name, a.brokerage, a.phone, a.email, a.line ?? "");
100 `INSERT INTO profile (id, name, brokerage, phone, email, line, zone) VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6)
101 ON CONFLICT (id) DO UPDATE SET name = excluded.name, brokerage = excluded.brokerage, phone = excluded.phone, email = excluded.email, line = excluded.line, zone = excluded.zone, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`,
102 ).run(a.name, a.brokerage, a.phone, a.email, a.line ?? "", a.zone ?? DEFAULT_ZONE);
103 zones.delete(db);
82104 out = ok({ ...a, id: 1, saved: true });
83105 }
84106 }
@@ -92,6 +114,7 @@ export function useDefaults(db: Database, who: Who): Result<Profile> {
92114 if (!allowed.ok) out = allowed;
93115 else {
94116 db.query("DELETE FROM profile WHERE id = 1").run();
117 zones.delete(db);
95118 out = ok({ ...defaults, id: 1, saved: false });
96119 }
97120 return audited(db, who, "profile", "update", 1, out);
src/release.test.ts +2 −2
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { listAudit } from "./actions.ts";
77 import { wording } from "./activity.ts";
8 import { addDays, today } from "./dates.ts";
8 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
99 import { openDb } from "./db.ts";
1010 import { createDeal, getDeal, holdReminder, releaseReminder, sendReminder, declineReminder, type DealView } from "./deals.ts";
1111 import { todaysDrafts, waitingCount } from "./reminders.ts";
@@ -20,7 +20,7 @@ const admin: Who = { role: "admin", id: "a1", name: "root" };
2020 const anon: Who = { role: "anon" };
2121 const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty", phone: "(555) 010-0142", email: "[email protected]" };
2222
23 const now = today();
23 const now = today(DEFAULT_ZONE);
2424 const made = createDeal(db, alice, { openAnyway: true, address: "9 Release Ln", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(now, -5), closingDate: addDays(now, 40), lengths: { inspection: "8" } });
2525 if (!made.ok) throw new Error(made.message);
2626 const deal: DealView = made.value;
src/reminders.ts +11 −4
@@ -8,7 +8,7 @@
88 * sent one, with the words approved; a sent draft reads back those words.
99 */
1010
11 import { addDays, relative, short, spoken, today, weekday } from "./dates.ts";
11 import { addDays, dayOf, dayOfStamp, relative, short, spoken, today, weekday } from "./dates.ts";
1212 import { closingAfterDate } from "./closing.ts";
1313 import { checkinOn, checkinRoles, checkinWords } from "./checkin.ts";
1414 import { dollars } from "./money.ts";
@@ -23,6 +23,8 @@ export interface Agent {
2323 readonly email: string;
2424 /** One line of the agent's own, above the sign-off; empty or absent for none. */
2525 readonly line?: string | undefined;
26 /** The IANA zone the agent's day is told in; absent reads as `DEFAULT_ZONE`. */
27 readonly zone?: string | undefined;
2628 }
2729
2830 /** How every draft ends: the agent's own line if set, then who to call or write back. */
@@ -52,6 +54,8 @@ export interface Draft {
5254 readonly body: string;
5355 /** When the agent marked it sent, for this date; null while unsent. */
5456 readonly sent_at: string | null;
57 /** The day it was marked sent, in the agent's zone; null while unsent. */
58 readonly sent_on: string | null;
5559 /** Why the agent chose not to send it, and who; null while it stands. */
5660 readonly declined: { readonly reason: string; readonly by_name: string } | null;
5761 /** Held by the agent until a later morning, and who held it; null while it is not (and once sent or declined). */
@@ -237,11 +241,12 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
237241 moment,
238242 lead_days: deadline.lead_days,
239243 move_id: key,
240 on: moment === "moved" ? today(new Date(lastMove(deadline)!.at)) : sendOn(deadline.due, moment, deadline.lead_days),
244 on: moment === "moved" ? today(deal.zone, new Date(lastMove(deadline)!.at)) : sendOn(deadline.due, moment, deadline.lead_days),
241245 // A sent reminder keeps the words it went with, whatever the deal says now.
242246 subject: sent !== undefined && sent.subject !== "" ? sent.subject : held !== undefined && held.subject !== "" ? held.subject : drafted.subject,
243247 body: sent !== undefined && sent.subject !== "" ? sent.body : held !== undefined && held.body !== "" ? held.body : drafted.body,
244248 sent_at: sent?.sent_at ?? null,
249 sent_on: sent === undefined ? null : dayOfStamp(deal.zone, sent.sent_at),
245250 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
246251 held: held === undefined ? null : { until: held.until, from: held.held_on, by_name: held.by_name },
247252 }];
@@ -291,6 +296,7 @@ export function checkinDrafts(deal: DealView, agent: Agent): Draft[] {
291296 subject: sent !== undefined && sent.subject !== "" ? sent.subject : held !== undefined && held.subject !== "" ? held.subject : drafted.subject,
292297 body: sent !== undefined && sent.subject !== "" ? sent.body : held !== undefined && held.body !== "" ? held.body : drafted.body,
293298 sent_at: sent?.sent_at ?? null,
299 sent_on: sent === undefined ? null : dayOfStamp(deal.zone, sent.sent_at),
294300 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
295301 held: held === undefined ? null : { until: held.until, from: held.held_on, by_name: held.by_name },
296302 };
@@ -335,7 +341,7 @@ function statusWords(deal: DealView, party: Party, agent: Agent): { subject: str
335341 const finished = done.length === 0 ? "Nothing is finished yet." : done.map((d) => `• ${d.label}${d.waived_at === null ? "" : " (waived)"}`).join("\n");
336342 return {
337343 subject: `${deal.address} — where things stand`,
338 body: `Hi ${first(party.name)}, here is where things stand on ${deal.address}.\n\nDone:\n${finished}\n\nNext:\n${next.length === 0 ? "Nothing else before closing." : next.join("\n")}${more}\n\nClosing is ${spoken(closing.due)}${closingAfterDate(deal)} (${relative(closing.due, today())}).\n\nLet me know if you have any questions.\n\n${signOff(agent)}`,
344 body: `Hi ${first(party.name)}, here is where things stand on ${deal.address}.\n\nDone:\n${finished}\n\nNext:\n${next.length === 0 ? "Nothing else before closing." : next.join("\n")}${more}\n\nClosing is ${spoken(closing.due)}${closingAfterDate(deal)} (${relative(closing.due, dayOf(agent))}).\n\nLet me know if you have any questions.\n\n${signOff(agent)}`,
339345 };
340346 }
341347
@@ -373,10 +379,11 @@ export function statusDrafts(deal: DealView, agent: Agent): Draft[] {
373379 moment: "status" as const,
374380 lead_days: closing.lead_days,
375381 move_id: stand,
376 on: today(),
382 on: dayOf(agent),
377383 subject: sent !== undefined && sent.subject !== "" ? sent.subject : drafted.subject,
378384 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
379385 sent_at: sent?.sent_at ?? null,
386 sent_on: sent === undefined ? null : dayOfStamp(deal.zone, sent.sent_at),
380387 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
381388 held: null,
382389 };
src/restore.test.ts +2 −2
@@ -3,7 +3,7 @@ import { mkdtempSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { restoreSamples } from "./actions.ts";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { openDb } from "./db.ts";
88 import { addParty, createDeal, listDeals, markDone, moveDeadline, updateDeal, type DealView } from "./deals.ts";
99 import { refresh } from "./sample.ts";
@@ -12,7 +12,7 @@ import type { Who } from "./who.ts";
1212 const db = openDb(mkdtempSync(join(tmpdir(), "app-restore-")));
1313 const alice: Who = { role: "user", id: "u1", name: "alice" };
1414 const root: Who = { role: "admin", id: "u0", name: "root" };
15 const on = today();
15 const on = today(DEFAULT_ZONE);
1616
1717 const all = (): DealView[] => {
1818 const got = listDeals(db, alice);
src/routes.ts +31 −30
@@ -38,7 +38,7 @@ import {
3838 } from "./http.ts";
3939 import type { Verb } from "./can.ts";
4040 import { events } from "./live.ts";
41 import { today } from "./dates.ts";
41 import { DEFAULT_ZONE, dayOf } from "./dates.ts";
4242 import { tally } from "./book.ts";
4343 import { AMOUNT_MAX, RATE_MAX } from "./money.ts";
4444 import { progress } from "./progress.ts";
@@ -148,7 +148,7 @@ function spreadsheet(c: Context): Result<Response> {
148148 value: new Response(sheet(deals.value.filter((deal) => withClosed || !(deal.closed || deal.fell_through))), {
149149 headers: {
150150 "content-type": "text/csv; charset=utf-8",
151 "content-disposition": `attachment; filename="deal-clock-${today()}.csv"`,
151 "content-disposition": `attachment; filename="deal-clock-${dayOf(agentFor(c))}.csv"`,
152152 "cache-control": "no-store",
153153 ...SECURITY,
154154 },
@@ -435,6 +435,7 @@ export const PROFILE: Schema = {
435435 brokerage: { type: "string", minLength: 1, maxLength: 80 },
436436 phone: { type: "string", maxLength: 30 },
437437 email: { type: "string", maxLength: 254 },
438 zone: { type: "string", maxLength: 64, description: "The agent's IANA time zone, such as America/New_York: the day \"today\" is told in. Leaving it out on a save keeps the saved zone; a name this runtime does not know is a 422 naming zone." },
438439 line: { type: "string", maxLength: 200, description: "One line of the agent's own, no line breaks or control characters, above the sign-off of every new draft; empty for none. On a save, leaving it out keeps the saved line; only an empty string clears it." },
439440 saved: { type: "boolean", description: "False while the environment's defaults stand." },
440441 },
@@ -537,7 +538,7 @@ const unconfirmed = (c: Context, path: string): Response =>
537538 function reviewQueue(c: Context, q: string): Result<Draft[]> {
538539 const deals = listDeals(c.db, c.who);
539540 if (!deals.ok) return deals;
540 return { ok: true, value: todaysDrafts(find(deals.value, q), today(), agentFor(c)).filter(unsent) };
541 return { ok: true, value: todaysDrafts(find(deals.value, q), dayOf(agentFor(c)), agentFor(c)).filter(unsent) };
541542 }
542543
543544 /** Whose deals these are, read once per request however many times a page and its header ask. */
@@ -555,7 +556,7 @@ function agentFor(c: Context): Agent {
555556 function waitingIn(db: Database, who: Who, agent: Agent): number {
556557 if (who.role === "anon") return 0;
557558 const deals = listDeals(db, who);
558 return deals.ok ? waitingCount(deals.value, today(), agent) : 0;
559 return deals.ok ? waitingCount(deals.value, dayOf(agent), agent) : 0;
559560 }
560561 const waitingFor = (c: Context): number => waitingIn(c.db, c.who, agentFor(c));
561562
@@ -628,7 +629,7 @@ function partyRefused(c: Context, dealId: number, id: number | "new", f: Record<
628629 const found = getDeal(c.db, c.who, { id: dealId });
629630 if (!found.ok) return back(found.message, `/deals/${dealId}`);
630631 const party = { id, role: f.role ?? "", name: f.name ?? "", email: f.email ?? "", phone: f.phone ?? "", message };
631 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), party }), STATUS.invalid);
632 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), party }), STATUS.invalid);
632633 }
633634
634635 const SENT = "Reminder sent.";
@@ -678,7 +679,7 @@ export const routes: readonly Route[] = [
678679 path: "/",
679680 handle: (c) => {
680681 const { notice, open, clear } = readNotice(c.request);
681 if (c.who.role === "anon") return html(welcomePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today() }), 200, clear);
682 if (c.who.role === "anon") return html(welcomePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)) }), 200, clear);
682683 const deals = listDeals(c.db, c.who);
683684 if (!deals.ok)
684685 return html(
@@ -703,7 +704,7 @@ export const routes: readonly Route[] = [
703704 const side = sideFilter(c.url.searchParams.get("side"));
704705 if (side === undefined)
705706 return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/", heading: "The clock", error: "invalid", message: SIDE_REFUSAL }), 422, clear);
706 return html(clock({ who: c.who, waiting: waitingCount(deals.value, today(), agentFor(c)), agent: agentFor(c), deals: deals.value, on: today(), notice, open, q, side }), 200, clear);
707 return html(clock({ who: c.who, waiting: waitingCount(deals.value, dayOf(agentFor(c)), agentFor(c)), agent: agentFor(c), deals: deals.value, on: dayOf(agentFor(c)), notice, open, q, side }), 200, clear);
707708 },
708709 },
709710 {
@@ -725,7 +726,7 @@ export const routes: readonly Route[] = [
725726 const side = sideFilter(c.url.searchParams.get("side"));
726727 if (side === undefined)
727728 return html(refusedPage({ who: c.who, agent: agentFor(c), path: "/week", heading: "This week", error: "invalid", message: SIDE_REFUSAL }), 422);
728 return html(weekPage({ who: c.who, agent: agentFor(c), deals: onSide(find(deals.value, q), side), on: today(), q, side }));
729 return html(weekPage({ who: c.who, agent: agentFor(c), deals: onSide(find(deals.value, q), side), on: dayOf(agentFor(c)), q, side }));
729730 },
730731 },
731732 {
@@ -738,7 +739,7 @@ export const routes: readonly Route[] = [
738739 refusedPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), path: "/people", heading: "People", error: deals.error, message: deals.message }),
739740 STATUS[deals.error],
740741 );
741 return html(peoplePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), people: people(deals.value, today()), on: today() }));
742 return html(peoplePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), people: people(deals.value, dayOf(agentFor(c))), on: dayOf(agentFor(c)) }));
742743 },
743744 },
744745 {
@@ -778,10 +779,10 @@ export const routes: readonly Route[] = [
778779 if (got.value.length < 500) break;
779780 before = got.value[got.value.length - 1]!.id;
780781 }
781 return new Response(activitySheet(rows, addresses(c.db, rows)), {
782 return new Response(activitySheet(rows, addresses(c.db, rows), agentFor(c).zone ?? DEFAULT_ZONE), {
782783 headers: {
783784 "content-type": "text/csv; charset=utf-8",
784 "content-disposition": `attachment; filename="deal-clock-activity-${today()}.csv"`,
785 "content-disposition": `attachment; filename="deal-clock-activity-${dayOf(agentFor(c))}.csv"`,
785786 "cache-control": "no-store",
786787 ...SECURITY,
787788 },
@@ -818,7 +819,7 @@ export const routes: readonly Route[] = [
818819 path: "/deals/new",
819820 handle: (c) => {
820821 const { notice, clear } = readNotice(c.request);
821 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), notice }), 200, clear);
822 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)), notice }), 200, clear);
822823 },
823824 },
824825 {
@@ -845,7 +846,7 @@ export const routes: readonly Route[] = [
845846 const known = all?.ok ? knownPeople(all.value, found.value.id) : undefined;
846847 const wanted = (c.url.searchParams.get("use") ?? "").trim().toLowerCase();
847848 const use = wanted === "" ? undefined : known?.find((k) => k.key === wanted);
848 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice, open, known, use, find: (c.url.searchParams.get("find") ?? "").slice(0, 100) }), 200, clear);
849 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), notice, open, known, use, find: (c.url.searchParams.get("find") ?? "").slice(0, 100) }), 200, clear);
849850 },
850851 },
851852 {
@@ -856,7 +857,7 @@ export const routes: readonly Route[] = [
856857 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
857858 if (!found.ok && (found.error === "not_found" || found.error === "invalid")) return missingDeal(c);
858859 if (!found.ok) return text(found.message, STATUS[found.error]);
859 return html(dealSheets(found.value, c.who, today(), "/", agentFor(c)));
860 return html(dealSheets(found.value, c.who, dayOf(agentFor(c)), "/", agentFor(c)));
860861 },
861862 },
862863 {
@@ -864,7 +865,7 @@ export const routes: readonly Route[] = [
864865 path: "/deals/:id/timeline",
865866 handle: (c) => {
866867 const found = dealOrRefusal(c);
867 return found instanceof Response ? found : html(timelinePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found, on: today() }));
868 return found instanceof Response ? found : html(timelinePage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found, on: dayOf(agentFor(c)) }));
868869 },
869870 },
870871 {
@@ -902,9 +903,9 @@ export const routes: readonly Route[] = [
902903 const made = createDeal(c.db, c.who, newDeal(fromForm(f)));
903904 if (made.ok) return back("Deal opened. Every date is on the clock.", `/deals/${made.value.id}`);
904905 if (made.error === "conflict")
905 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, existing: openDealAt(c.db, c.who, String(f.address)) } }), 409);
906 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)), state: { values: f, existing: openDealAt(c.db, c.who, String(f.address)) } }), 409);
906907 if (made.error !== "invalid") return back(made.message, "/deals/new");
907 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, problem: made } }), 422);
908 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)), state: { values: f, problem: made } }), 422);
908909 },
909910 },
910911 {
@@ -918,11 +919,11 @@ export const routes: readonly Route[] = [
918919 if (!may.ok) return back(may.message, "/deals/new");
919920 const planned = plan(newDeal(fromForm(f)));
920921 if (!planned.ok)
921 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, problem: planned } }), 422);
922 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)), state: { values: f, problem: planned } }), 422);
922923 const preview = { plan: planned.value, dates: plannedDates(planned.value) };
923924 const there = planFor(c.db, c.who, newDeal(fromForm(f)));
924925 const existing = there.ok ? undefined : openDealAt(c.db, c.who, planned.value.address);
925 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: today(), state: { values: f, preview, existing } }));
926 return html(newDealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), on: dayOf(agentFor(c)), state: { values: f, preview, existing } }));
926927 },
927928 },
928929 {
@@ -1033,7 +1034,7 @@ export const routes: readonly Route[] = [
10331034 if (saved.error !== "invalid" || f.address === undefined) return back(saved.message, `/deals/${id}`);
10341035 const found = getDeal(c.db, c.who, { id });
10351036 if (!found.ok) return back(found.message, `/deals/${id}`);
1036 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), problem: { value: f.address, message: saved.message } }), STATUS.invalid);
1037 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), problem: { value: f.address, message: saved.message } }), STATUS.invalid);
10371038 },
10381039 },
10391040 {
@@ -1048,7 +1049,7 @@ export const routes: readonly Route[] = [
10481049 if (saved.error !== "invalid") return back(saved.message, `/deals/${id}`);
10491050 const found = getDeal(c.db, c.who, { id });
10501051 if (!found.ok) return back(found.message, `/deals/${id}`);
1051 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice: saved.message }), STATUS.invalid);
1052 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), notice: saved.message }), STATUS.invalid);
10521053 },
10531054 },
10541055 {
@@ -1064,7 +1065,7 @@ export const routes: readonly Route[] = [
10641065 const found = getDeal(c.db, c.who, { id });
10651066 if (!found.ok) return back(found.message, `/deals/${id}`);
10661067 const values = { sale_price: String(f.sale_price ?? ""), earnest_amount: String(f.earnest_amount ?? ""), commission_rate: String(f.commission_rate ?? "") };
1067 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), figures: { values, field: saved.field, message: saved.message } }), STATUS.invalid);
1068 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), figures: { values, field: saved.field, message: saved.message } }), STATUS.invalid);
10681069 },
10691070 },
10701071 {
@@ -1080,7 +1081,7 @@ export const routes: readonly Route[] = [
10801081 const found = getDeal(c.db, c.who, { id });
10811082 if (!found.ok) return back(found.message, `/deals/${id}`);
10821083 const values = { closing_time: String(f.closing_time ?? ""), closing_place: String(f.closing_place ?? "") };
1083 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), closing: { values, field: saved.field, message: saved.message } }), STATUS.invalid);
1084 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), closing: { values, field: saved.field, message: saved.message } }), STATUS.invalid);
10841085 },
10851086 },
10861087 {
@@ -1097,7 +1098,7 @@ export const routes: readonly Route[] = [
10971098 if (amended.error !== "invalid" || !found.ok) return back(amended.message, `/deals/${id}`);
10981099 const refused = amendment(found.value, dates, f.reason);
10991100 const problem = refused.ok ? { field: "", message: amended.message } : { field: refused.field, message: refused.message };
1100 return html(dealPage({ who: c.who, deal: found.value, on: today(), amend: { values: f, problem } }), STATUS.invalid);
1101 return html(dealPage({ who: c.who, deal: found.value, on: dayOf(agentFor(c)), amend: { values: f, problem } }), STATUS.invalid);
11011102 },
11021103 },
11031104 {
@@ -1182,7 +1183,7 @@ export const routes: readonly Route[] = [
11821183 const found = deal === undefined ? undefined : getDeal(c.db, c.who, { id: deal });
11831184 // A refusal on a real date comes back as that deal's page, saying why; anything else as before.
11841185 if (found?.ok && (set.error === "invalid" || set.error === "conflict"))
1185 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice: set.message }), STATUS[set.error]);
1186 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), notice: set.message }), STATUS[set.error]);
11861187 return done(set, backTo(f.to));
11871188 },
11881189 },
@@ -1199,7 +1200,7 @@ export const routes: readonly Route[] = [
11991200 const found = deal === undefined ? undefined : getDeal(c.db, c.who, { id: deal });
12001201 // A refused note comes back as that deal's page, saying why, with what was typed in the field.
12011202 if (found?.ok && set.error === "invalid")
1202 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: today(), notice: set.message, typed: { id, note: typeof f.note === "string" ? f.note : "" } }), STATUS[set.error]);
1203 return html(dealPage({ who: c.who, waiting: waitingFor(c), agent: agentFor(c), deal: found.value, on: dayOf(agentFor(c)), notice: set.message, typed: { id, note: typeof f.note === "string" ? f.note : "" } }), STATUS[set.error]);
12031204 return done(set, backTo(f.to));
12041205 },
12051206 },
@@ -1357,7 +1358,7 @@ export const routes: readonly Route[] = [
13571358 handle: (c) => {
13581359 const deals = listDeals(c.db, c.who);
13591360 if (!deals.ok) return answer(deals);
1360 const on = today();
1361 const on = dayOf(agentFor(c));
13611362 return json({ on, reminders: dueOn(deals.value, on, agentFor(c)) });
13621363 },
13631364 api: {
@@ -1411,7 +1412,7 @@ export const routes: readonly Route[] = [
14111412 handle: (c) => {
14121413 const deals = listDeals(c.db, c.who);
14131414 if (!deals.ok) return answer(deals);
1414 const b = tally(deals.value, today());
1415 const b = tally(deals.value, dayOf(agentFor(c)));
14151416 return answer({
14161417 ok: true,
14171418 value: { open: b.open, under_contract: b.underContract, closing_this_month: b.closingThisMonth, closed_this_year: b.closedThisYear, closed_volume: b.closedVolume, without_price: b.withoutPrice, commission_pending: b.commissionPending, commission_earned: b.commissionEarned, without_rate: b.withoutRate },
@@ -1428,7 +1429,7 @@ export const routes: readonly Route[] = [
14281429 path: "/api/people",
14291430 handle: (c) => {
14301431 const deals = listDeals(c.db, c.who);
1431 return answer(deals.ok ? { ok: true, value: people(deals.value, today()) } : deals);
1432 return answer(deals.ok ? { ok: true, value: people(deals.value, dayOf(agentFor(c))) } : deals);
14321433 },
14331434 api: {
14341435 summary:
@@ -1458,7 +1459,7 @@ export const routes: readonly Route[] = [
14581459 path: "/api/deals/:id",
14591460 handle: (c) => {
14601461 const found = getDeal(c.db, c.who, { id: Number(c.params.id) });
1461 return answer(found.ok ? { ok: true, value: { ...found.value, progress: progress(found.value, today()) } } : found);
1462 return answer(found.ok ? { ok: true, value: { ...found.value, progress: progress(found.value, dayOf(agentFor(c))) } } : found);
14621463 },
14631464 api: { summary: "One deal, with its progress: dates done, total, overdue and days to closing.", answer: DEAL_PROGRESS },
14641465 },
src/sample.test.ts +10 −10
@@ -9,7 +9,7 @@ import { dollars } from "./money.ts";
99 import { clock } from "./pages/clock.ts";
1010 import { people } from "./people.ts";
1111 import { thisWeek } from "./week.ts";
12 import { addDays, today } from "./dates.ts";
12 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
1313 import { createDeal, listDeals, markDone } from "./deals.ts";
1414 import { drafts, unsent } from "./reminders.ts";
1515 import type { Who } from "./who.ts";
@@ -84,19 +84,19 @@ test("the samples include three deals closed earlier this year: priced, rated an
8484 for (const d of closed) {
8585 expect(d.sale_price).not.toBeNull();
8686 expect(d.commission_rate).not.toBeNull();
87 expect(d.closing < today()).toBe(true);
88 expect(d.closing.slice(0, 4)).toBe(today().slice(0, 4));
87 expect(d.closing < today(DEFAULT_ZONE)).toBe(true);
88 expect(d.closing.slice(0, 4)).toBe(today(DEFAULT_ZONE).slice(0, 4));
8989 expect(d.deadlines.every((x) => x.done_at !== null || x.waived_at !== null)).toBe(true);
9090 }
9191 // No client party carries a contact, so not even a check-in is drafted.
9292 expect(closed.flatMap((d) => drafts(d, agent))).toEqual([]);
93 const book = tally(listed.value, today());
93 const book = tally(listed.value, today(DEFAULT_ZONE));
9494 expect(book.closedThisYear).toBe(3);
9595 expect(book.closedVolume).toBe(closed.reduce((n, d) => n + (d.sale_price ?? 0), 0));
9696 expect(book.commissionEarned).toBeGreaterThan(0);
9797 // The open samples are the four the clock shows; the closed ones add to neither count.
9898 expect(book.open).toBe(4);
99 expect(bookLine(book, today())).toContain("3 closed this year, $1,375,000");
99 expect(bookLine(book, today(DEFAULT_ZONE))).toContain("3 closed this year, $1,375,000");
100100 });
101101
102102 test("a database seeded on 1 January still reads its closed samples as this year", () => {
@@ -112,7 +112,7 @@ test("a database seeded on 1 January still reads its closed samples as this year
112112 test("restoring the samples brings the closed ones back and leaves a real deal alone", () => {
113113 const db = openDb(mkdtempSync(join(tmpdir(), "app-sample-restore-closed-")));
114114 const alice: Who = { role: "user", id: "u1", name: "alice" };
115 const mine = createDeal(db, alice, { openAnyway: true, address: "12 Elm St", buyer: "A", seller: "S", contractDate: today(), closingDate: addDays(today(), 40) });
115 const mine = createDeal(db, alice, { openAnyway: true, address: "12 Elm St", buyer: "A", seller: "S", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 40) });
116116 if (!mine.ok) throw new Error(mine.message);
117117 const closing = closedSamples(db)[0]!.deadlines.find((d) => d.kind === "closing")!;
118118 markDone(db, alice, { id: closing.id, done: false });
@@ -165,7 +165,7 @@ test("the closed samples are off the clock, This week, People and the calendar,
165165 if (!listed.ok) throw new Error(listed.message);
166166 const closed = listed.value.filter((d) => d.author_id === "sample" && d.closed);
167167 expect(closed.length).toBe(3);
168 const html = clock({ who: alice, deals: listed.value, on: today() });
168 const html = clock({ who: alice, deals: listed.value, on: today(DEFAULT_ZONE) });
169169 const cut = html.indexOf('id="closed"');
170170 expect(cut).toBeGreaterThan(0);
171171 const card = html.slice(cut, html.indexOf("</ul>", cut));
@@ -174,13 +174,13 @@ test("the closed samples are off the clock, This week, People and the calendar,
174174 expect(card).toContain(`${d.address}</a>`);
175175 expect(card).toContain(dollars(d.sale_price!));
176176 expect(rest).not.toContain(d.address);
177 expect(thisWeek(listed.value, today()).some((i) => i.deal.id === d.id)).toBe(false);
178 expect(people(listed.value, today()).some((p) => p.owes.some((o) => o.address === d.address))).toBe(false);
177 expect(thisWeek(listed.value, today(DEFAULT_ZONE)).some((i) => i.deal.id === d.id)).toBe(false);
178 expect(people(listed.value, today(DEFAULT_ZONE)).some((p) => p.owes.some((o) => o.address === d.address))).toBe(false);
179179 expect(book(listed.value, "clock.example")).not.toContain(d.address);
180180 }
181181 // Left open, the same deal would show up in the lanes: the assertions above are not vacuous.
182182 const open = listed.value.filter((d) => d.author_id === "sample" && !d.closed);
183 expect(clock({ who: alice, deals: open, on: today() })).toContain(open[0]!.address);
183 expect(clock({ who: alice, deals: open, on: today(DEFAULT_ZONE) })).toContain(open[0]!.address);
184184 });
185185
186186 test("refresh keeps the closed samples in the past and in this year, across a New Year too", () => {
src/sample.ts +4 −3
@@ -9,6 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { addDays, daysBetween, today } from "./dates.ts";
12 import { zoneOf } from "./profile.ts";
1213 import { type PartyRole } from "./deadlines.ts";
1314 import { BRIEF_LENGTHS, validEmail } from "./env.ts";
1415 import { insertDeal } from "./deals.ts";
@@ -260,7 +261,7 @@ export function isUntouched(state: SampleState, anchor: string): boolean {
260261 * (A reminder the sample itself sent follows its date; any other sent
261262 * reminder makes the deal a changed one.)
262263 */
263 export function refresh(db: Database, on = today()): void {
264 export function refresh(db: Database, on = today(zoneOf(db))): void {
264265 db.transaction(() => {
265266 const row = db.query<{ value: string }, []>("SELECT value FROM app_meta WHERE key = 'sample_anchor'").get();
266267 if (row === null || daysBetween(row.value, on) <= 0) return;
@@ -376,7 +377,7 @@ function writeSamples(db: Database, on: string): void {
376377 }
377378
378379 /** Write the samples into an empty database, once; a database that has had them never gets them again. */
379 export function seed(db: Database, on = today()): void {
380 export function seed(db: Database, on = today(zoneOf(db))): void {
380381 // Asked and written in one write transaction, taken before the question:
381382 // the server and a terminal opening a new file at once seed it once.
382383 db.transaction(() => {
@@ -392,7 +393,7 @@ export function seed(db: Database, on = today()): void {
392393 * transaction, so two restores at once leave seven, not fourteen. Answers the ids
393394 * of the deals written.
394395 */
395 export function restore(db: Database, on = today()): number[] {
396 export function restore(db: Database, on = today(zoneOf(db))): number[] {
396397 return db.transaction(() => {
397398 db.query("DELETE FROM deal WHERE author_id = ?1").run(SAMPLE.id);
398399 writeSamples(db, on);
src/server.test.ts +4 −4
@@ -2,7 +2,7 @@ import { afterAll, beforeEach, expect, test } from "bun:test";
22 import { mkdtempSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import { addDays, spoken, today } from "./dates.ts";
5 import { addDays, spoken, today, DEFAULT_ZONE } from "./dates.ts";
66 import { agent, env } from "./env.ts";
77 import { drafts } from "./reminders.ts";
88 import { serve } from "./server.ts";
@@ -1011,7 +1011,7 @@ test("a deal whose Closing is marked done leaves the lanes for the Closed card,
10111011 // The inspection ends in three days, so a reminder for this deal goes out today.
10121012 const made = await api(
10131013 "/api/deals",
1014 { method: "POST", ...jsonBody({ address: "77 Closing Court", buyer: "B", seller: "S", contract_date: addDays(today(), -7), closing_date: addDays(today(), 25) }) },
1014 { method: "POST", ...jsonBody({ address: "77 Closing Court", buyer: "B", seller: "S", contract_date: addDays(today(DEFAULT_ZONE), -7), closing_date: addDays(today(DEFAULT_ZONE), 25) }) },
10151015 closer,
10161016 );
10171017 expect(made.status).toBe(201);
@@ -1033,7 +1033,7 @@ test("a deal whose Closing is marked done leaves the lanes for the Closed card,
10331033 expect(clock).toContain('id="closed"');
10341034 expect(clock).toContain(`<a href="/deals/${deal.id}">${deal.address}</a> <span class="muted">closed`);
10351035 const page = await (await api(`/deals/${deal.id}`, {}, closer)).text();
1036 expect(page).toContain(`Closed on ${spoken(today())}`);
1036 expect(page).toContain(`Closed on ${spoken(today(DEFAULT_ZONE))}`);
10371037 expect(page).toContain("Inspection period ends");
10381038 const listed = (await (await api("/api/deals", {}, closer)).json()) as { id: number; closed: boolean }[];
10391039 expect(listed.find((d) => d.id === deal.id)!.closed).toBe(true);
@@ -1311,7 +1311,7 @@ test("the spreadsheet: the open deals' dates as CSV, closed ones only on ask, si
13111311 const file = await api("/deals/csv", {}, alice);
13121312 expect(file.status).toBe(200);
13131313 expect(file.headers.get("content-type")).toContain("text/csv");
1314 expect(file.headers.get("content-disposition")).toBe(`attachment; filename="deal-clock-${today()}.csv"`);
1314 expect(file.headers.get("content-disposition")).toBe(`attachment; filename="deal-clock-${today(DEFAULT_ZONE)}.csv"`);
13151315 expect(file.headers.get("x-content-type-options")).toBe("nosniff");
13161316 const body = await file.text();
13171317 expect(body.startsWith("address,buyer,seller,date,due,done,owed_by,party,moved\r\n")).toBe(true);
src/status.test.ts +11 −11
@@ -3,7 +3,7 @@ import { afterAll, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, spoken, today } from "./dates.ts";
6 import { addDays, spoken, today, DEFAULT_ZONE } from "./dates.ts";
77 import {
88 addDeadline, addParty, createDeal, declineReminder, getDeal, markDone, moveDeadline, sendStatusUpdate, statusUpdates, undoDecline, type DealView,
99 } from "./deals.ts";
@@ -21,7 +21,7 @@ const alice: Who = { role: "user", id: "u1", name: "alice" };
2121 const agent = { name: "Dana", brokerage: "Hearth & Porch", phone: "555-0100", email: "[email protected]" };
2222
2323 function open(address: string, closed = false): number {
24 const made = createDeal(db, alice, { address, buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(), closingDate: addDays(today(), 40) });
24 const made = createDeal(db, alice, { address, buyer: "Ann Buyer", seller: "Sam Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 40) });
2525 if (!made.ok) throw new Error(made.message);
2626 const id = made.value.id;
2727 for (const p of made.value.parties) db.query("UPDATE party SET contact = ?1 WHERE id = ?2").run(`${p.name.split(" ")[0]!.toLowerCase()}@example.com`, p.id);
@@ -74,7 +74,7 @@ test("send keeps the edited words, and the Messages record shows them", () => {
7474 const after = updates(id).find((d) => d.party_role === "buyer")!;
7575 expect(after).toMatchObject({ sent_at: expect.any(String), subject: "Quick update", body: "My own words, Ann." });
7676 expect(read(id).sent.map((m) => m.body)).toEqual(["My own words, Ann."]);
77 const page = dealPage({ who: alice, deal: read(id), on: today() });
77 const page = dealPage({ who: alice, deal: read(id), on: today(DEFAULT_ZONE) });
7878 expect(page).toContain("My own words, Ann.");
7979 expect(page).toContain("Status update");
8080 // Nothing is recorded without a send; an empty edit is refused.
@@ -98,10 +98,10 @@ test("a sent or declined update is not offered again until a date changes", () =
9898 expect(updates(id).every((d) => d.sent_at === null && d.declined === null)).toBe(true);
9999 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id, subject: "Second", body: "Second words" }).ok).toBe(true);
100100 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).not.toBeNull();
101 const moved = moveDeadline(db, alice, { id: read(id).deadlines.find((d) => d.kind === "appraisal")!.id, due: addDays(today(), 12), reason: "Lender" });
101 const moved = moveDeadline(db, alice, { id: read(id).deadlines.find((d) => d.kind === "appraisal")!.id, due: addDays(today(DEFAULT_ZONE), 12), reason: "Lender" });
102102 expect(moved.ok).toBe(true);
103103 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).toBeNull();
104 const extra = addDeadline(db, alice, { dealId: id, label: "HOA review", due: addDays(today(), 9), owes: "buyer", what: "" });
104 const extra = addDeadline(db, alice, { dealId: id, label: "HOA review", due: addDays(today(DEFAULT_ZONE), 9), owes: "buyer", what: "" });
105105 if (!extra.ok) throw new Error(extra.message);
106106 expect(sendStatusUpdate(db, alice, { dealId: id, partyId: buyer.party_id }).ok).toBe(true);
107107 expect(updates(id).find((d) => d.party_role === "buyer")!.sent_at).not.toBeNull();
@@ -119,7 +119,7 @@ test("a closed deal drafts none", () => {
119119 const refused = sendStatusUpdate(db, alice, { dealId: id, partyId: read(id).parties[0]!.id });
120120 expect(refused.ok).toBe(false);
121121 expect(read(id).sent).toEqual([]);
122 expect(dealPage({ who: alice, deal: read(id), on: today() })).toContain("nothing to update");
122 expect(dealPage({ who: alice, deal: read(id), on: today(DEFAULT_ZONE) })).toContain("nothing to update");
123123 });
124124
125125 test("the old reminders are untouched: the morning's drafts and /tick never include a status update", () => {
@@ -132,9 +132,9 @@ test("the old reminders are untouched: the morning's drafts and /tick never incl
132132 expect(morning.some((d) => d.moment === "status")).toBe(false);
133133 const inspection = deal.deadlines.find((d) => d.kind === "inspection")!;
134134 expect(dueOn([deal], inspection.due, agent).some((d) => d.moment === "status")).toBe(false);
135 expect(dueOn([deal], today(), agent).some((d) => d.moment === "status")).toBe(false);
135 expect(dueOn([deal], today(DEFAULT_ZONE), agent).some((d) => d.moment === "status")).toBe(false);
136136 expect(deal.sent).toEqual([]);
137 expect(dealPage({ who: alice, deal, on: today() })).toContain('id="status"');
137 expect(dealPage({ who: alice, deal, on: today(DEFAULT_ZONE) })).toContain('id="status"');
138138 });
139139
140140 test("a status update sent again at the same standing keeps every earlier message", () => {
@@ -153,7 +153,7 @@ test("a status update sent again at the same standing keeps every earlier messag
153153 expect(send("Third words")).toBe(true);
154154 expect(read(id).sent.map((m) => m.body).sort()).toEqual(["First words", "Second words", "Third words"]);
155155 expect(updates(id).find((d) => d.party_role === "buyer")).toMatchObject({ body: "Third words" });
156 const page = dealPage({ who: alice, deal: read(id), on: today() });
156 const page = dealPage({ who: alice, deal: read(id), on: today(DEFAULT_ZONE) });
157157 for (const words of ["First words", "Second words", "Third words"]) expect(page).toContain(words);
158158 });
159159
@@ -230,7 +230,7 @@ const rpc = async (name: string, args: unknown, who = editor) =>
230230 (await (await call("/mcp", { method: "POST", body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }, who)).json()) as any;
231231
232232 test("the API, MCP and the page each reach the same action", async () => {
233 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address: "9 Door Way", buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(), closing_date: addDays(today(), 40) }) });
233 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address: "9 Door Way", buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(DEFAULT_ZONE), closing_date: addDays(today(DEFAULT_ZONE), 40) }) });
234234 const deal = (await made.json()) as { id: number; parties: { id: number; name: string }[] };
235235 for (const p of deal.parties) await call(`/api/deals/${deal.id}/parties/${p.id}`, { method: "PATCH", body: JSON.stringify({ name: p.name, contact: "[email protected]" }) });
236236 const drafted = (await (await call(`/api/deals/${deal.id}/status`)).json()) as { moment: string; party_id: number; party_role: string; subject: string }[];
@@ -258,7 +258,7 @@ test("the API, MCP and the page each reach the same action", async () => {
258258
259259 test("the page, the API and MCP each send and decline a status update", async () => {
260260 const make = async (address: string) => {
261 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address, buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(), closing_date: addDays(today(), 40) }) });
261 const made = await call("/api/deals", { method: "POST", body: JSON.stringify({ address, buyer: "Ann Buyer", seller: "Sam Seller", contract_date: today(DEFAULT_ZONE), closing_date: addDays(today(DEFAULT_ZONE), 40) }) });
262262 const deal = (await made.json()) as { id: number; parties: { id: number; name: string }[] };
263263 for (const p of deal.parties) await call(`/api/deals/${deal.id}/parties/${p.id}`, { method: "PATCH", body: JSON.stringify({ name: p.name, contact: "[email protected]" }) });
264264 const drafted = (await (await call(`/api/deals/${deal.id}/status`)).json()) as { party_id: number; deadline_id: number }[];
src/terminal.test.ts +58 −45
@@ -6,7 +6,7 @@ import { expect, test } from "bun:test";
66 import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
9 import { addDays, spoken, today } from "./dates.ts";
9 import { addDays, spoken, today, DEFAULT_ZONE } from "./dates.ts";
1010 import { canChange, shown, addDeadline, addParty, createDeal, editParty, getDeal, listDeals, markDone, moveDeadline, sendReminder, type DealView } from "./deals.ts";
1111 import { openDb } from "./db.ts";
1212 import { terminal, type Terminal } from "./terminal.ts";
@@ -31,8 +31,8 @@ const made = createDeal(db, alice, {
3131 address: "12 Elm St",
3232 buyer: "Ann Buyer",
3333 seller: "Sam Seller",
34 contractDate: today(),
35 closingDate: addDays(today(), 45),
34 contractDate: today(DEFAULT_ZONE),
35 closingDate: addDays(today(DEFAULT_ZONE), 45),
3636 });
3737 if (!made.ok) throw new Error(made.message);
3838 const id = made.value.id;
@@ -64,7 +64,7 @@ test("m moves one date with a reason, and nothing else; esc cancels", () => {
6464 press(t, "m", "2099", "\x1b");
6565 expect(lines(t).join("\n")).toContain("Cancelled.");
6666 expect(date("appraisal").moves.length).toBe(0);
67 const to = addDays(today(), 25);
67 const to = addDays(today(DEFAULT_ZONE), 25);
6868 press(t, "m", to, "\r", "Lender asked for more time", "\r");
6969 const after = deal();
7070 expect(after.deadlines.map((d) => [d.id, d.due]).sort()).toEqual(
@@ -82,7 +82,7 @@ test("o opens a deal; a adds a date, p a party; D removes it after a yes", () =>
8282 goTo(t, "Closing — 12 Elm St");
8383 t.press("o");
8484 expect(lines(t)).toContain("12 Elm St");
85 press(t, "a", "HOA review ends\r", `${addDays(today(), 5)}\r`, "buyer\r", "\r");
85 press(t, "a", "HOA review ends\r", `${addDays(today(DEFAULT_ZONE), 5)}\r`, "buyer\r", "\r");
8686 expect(deal().deadlines.some((d) => d.label === "HOA review ends" && d.kind === "custom")).toBe(true);
8787 press(t, "p", "lender\r", "Lee Lender\r", "[email protected]\r", "(555) 010-0166\r");
8888 expect(deal().parties.some((p) => p.role === "lender" && p.email === "[email protected]" && p.phone === "(555) 010-0166")).toBe(true);
@@ -95,8 +95,8 @@ test("o opens a deal; a adds a date, p a party; D removes it after a yes", () =>
9595 address: "99 Gone Rd",
9696 buyer: "B",
9797 seller: "S",
98 contractDate: today(),
99 closingDate: addDays(today(), 30),
98 contractDate: today(DEFAULT_ZONE),
99 closingDate: addDays(today(DEFAULT_ZONE), 30),
100100 });
101101 if (!other.ok) throw new Error(other.message);
102102 goTo(t, "Closing — 99 Gone Rd");
@@ -151,7 +151,7 @@ test("e with an empty answer keeps that part of the draft; too long a message is
151151
152152 test("n opens a deal from five answers, and shows it", () => {
153153 const t = terminal(db, alice, context);
154 press(t, "n", "31 Birch Row\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "\r");
154 press(t, "n", "31 Birch Row\r", "Kim Buyer\r", "Lou Seller\r", `${today(DEFAULT_ZONE)}\r`, `${addDays(today(DEFAULT_ZONE), 40)}\r`, "\r");
155155 const listed = listDeals(db, alice);
156156 if (!listed.ok) throw new Error(listed.message);
157157 const made = listed.value.find((d) => d.address === "31 Birch Row");
@@ -205,12 +205,12 @@ test("e edits the party under the cursor; X removes a party or a custom date aft
205205 address: "7 Cedar Ct",
206206 buyer: "Bea Buyer",
207207 seller: "Sid Seller",
208 contractDate: today(),
209 closingDate: addDays(today(), 30),
208 contractDate: today(DEFAULT_ZONE),
209 closingDate: addDays(today(DEFAULT_ZONE), 30),
210210 });
211211 if (!own.ok) throw new Error(own.message);
212212 const lender = addParty(db, alice, { dealId: own.value.id, role: "lender", name: "Lee Lender", contact: "[email protected]" });
213 const hoa = addDeadline(db, alice, { dealId: own.value.id, label: "HOA review", due: addDays(today(), 9), owes: "buyer" });
213 const hoa = addDeadline(db, alice, { dealId: own.value.id, label: "HOA review", due: addDays(today(DEFAULT_ZONE), 9), owes: "buyer" });
214214 if (!lender.ok || !hoa.ok) throw new Error("setup");
215215 const read = () => {
216216 const got = getDeal(db, alice, { id: own.value.id });
@@ -316,8 +316,8 @@ test("a closed deal's dates leave the date list and reminders, it is listed unde
316316 address: "88 Shut Ave",
317317 buyer: "B",
318318 seller: "S",
319 contractDate: addDays(today(), -7),
320 closingDate: addDays(today(), 20),
319 contractDate: addDays(today(DEFAULT_ZONE), -7),
320 closingDate: addDays(today(DEFAULT_ZONE), 20),
321321 });
322322 if (!other.ok) throw new Error(other.message);
323323 const closing = other.value.deadlines.find((d) => d.kind === "closing")!;
@@ -333,7 +333,7 @@ test("a closed deal's dates leave the date list and reminders, it is listed unde
333333 const dates = lines(t).join("\n");
334334 expect(dates).not.toContain("Inspection period ends — 88 Shut Ave");
335335 expect(dates).toContain("Closed (4)");
336 expect(dates).toContain(`88 Shut Ave — closed ${spoken(today())}`);
336 expect(dates).toContain(`88 Shut Ave — closed ${spoken(today(DEFAULT_ZONE))}`);
337337 t.press("r");
338338 expect(lines(t).join("\n")).not.toContain("88 Shut Ave");
339339 t.press("d");
@@ -348,7 +348,7 @@ test("a closed deal's dates leave the date list and reminders, it is listed unde
348348 });
349349
350350 test("w lists the dates overdue or due within seven days, by day, with who owes each; x works there", () => {
351 const soon = addDeadline(db, alice, { dealId: id, label: "Week check", due: addDays(today(), 2), owes: "buyer" });
351 const soon = addDeadline(db, alice, { dealId: id, label: "Week check", due: addDays(today(DEFAULT_ZONE), 2), owes: "buyer" });
352352 if (!soon.ok) throw new Error(soon.message);
353353 const t = terminal(db, alice, context);
354354 t.press("w");
@@ -381,7 +381,7 @@ test("s on a deal lists what was sent, newest first, with the words; b comes bac
381381 const screen = lines(t).join("\n");
382382 expect(screen).toContain("Messages — 12 Elm St");
383383 expect(screen.indexOf(seller!.name)).toBeLessThan(screen.indexOf(buyer!.name));
384 expect(screen).toContain("sent " + today());
384 expect(screen).toContain("sent " + today(DEFAULT_ZONE));
385385 expect(screen).not.toContain("Later one");
386386 press(t, "j", "\r");
387387 expect(lines(t).join("\n")).toContain("First <b>words</b>");
@@ -400,11 +400,11 @@ test("r lists an overdue follow-up as late, as the clock page does, until it is
400400 address: "5 Late Ln",
401401 buyer: "Lena Buyer",
402402 seller: "Sid Seller",
403 contractDate: addDays(today(), -20),
404 closingDate: addDays(today(), 30),
403 contractDate: addDays(today(DEFAULT_ZONE), -20),
404 closingDate: addDays(today(DEFAULT_ZONE), 30),
405405 });
406406 if (!slipped.ok) throw new Error(slipped.message);
407 const missed = addDeadline(db, alice, { dealId: slipped.value.id, label: "Appraisal back", due: addDays(today(), -3), owes: "buyer" });
407 const missed = addDeadline(db, alice, { dealId: slipped.value.id, label: "Appraisal back", due: addDays(today(DEFAULT_ZONE), -3), owes: "buyer" });
408408 if (!missed.ok) throw new Error(missed.message);
409409 const t = terminal(db, alice, context);
410410 t.press("r");
@@ -444,12 +444,12 @@ test("/ finds a deal and narrows dates, week and reminders to it; / then enter c
444444 address: "9 Oak Ln",
445445 buyer: "Zed Zimmer",
446446 seller: "Yan Yates",
447 contractDate: today(),
448 closingDate: addDays(today(), 45),
447 contractDate: today(DEFAULT_ZONE),
448 closingDate: addDays(today(DEFAULT_ZONE), 45),
449449 });
450450 if (!other.ok) throw new Error(other.message);
451451 for (const dealId of [id, other.value.id]) {
452 const added = addDeadline(db, alice, { dealId, label: "Find check", due: addDays(today(), 1), owes: "buyer" });
452 const added = addDeadline(db, alice, { dealId, label: "Find check", due: addDays(today(DEFAULT_ZONE), 1), owes: "buyer" });
453453 if (!added.ok) throw new Error(added.message);
454454 }
455455 const t = terminal(db, alice, context);
@@ -483,7 +483,7 @@ test("/ finds a deal and narrows dates, week and reminders to it; / then enter c
483483 });
484484
485485 test("A corrects the address of the open deal; a too-short one is refused and nothing changes", () => {
486 const own = createDeal(db, alice, { openAnyway: true, address: "3 Oak St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 30) });
486 const own = createDeal(db, alice, { openAnyway: true, address: "3 Oak St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 30) });
487487 if (!own.ok) throw new Error(own.message);
488488 const read = () => {
489489 const got = getDeal(db, alice, { id: own.value.id });
@@ -510,7 +510,7 @@ test("a signed-out terminal is not asked for an address", () => {
510510 test("P lists each person once with the dates they owe across deals; a guest is refused", () => {
511511 const own = openDb(mkdtempSync(join(tmpdir(), "app-terminal-people-")));
512512 const open = (address: string) => {
513 const made = createDeal(own, alice, { openAnyway: true, address, buyer: "B", seller: "S", contractDate: today(), closingDate: addDays(today(), 30) });
513 const made = createDeal(own, alice, { openAnyway: true, address, buyer: "B", seller: "S", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 30) });
514514 if (!made.ok) throw new Error(made.message);
515515 addParty(own, alice, { dealId: made.value.id, role: "lender", name: "Lena Lender", contact: "[email protected]" });
516516 };
@@ -531,7 +531,7 @@ test("P lists each person once with the dates they owe across deals; a guest is
531531
532532 test("P shows when each person last got a sent message, and about what", () => {
533533 const own = openDb(mkdtempSync(join(tmpdir(), "app-terminal-lastsent-")));
534 const made = createDeal(own, alice, { openAnyway: true, address: "9 Heard Way", buyer: "Bea Buyer", seller: "Sol Seller", contractDate: addDays(today(), -5), closingDate: addDays(today(), 30) });
534 const made = createDeal(own, alice, { openAnyway: true, address: "9 Heard Way", buyer: "Bea Buyer", seller: "Sol Seller", contractDate: addDays(today(DEFAULT_ZONE), -5), closingDate: addDays(today(DEFAULT_ZONE), 30) });
535535 if (!made.ok) throw new Error(made.message);
536536 const got = getDeal(own, alice, { id: made.value.id });
537537 if (!got.ok) throw new Error(got.message);
@@ -542,7 +542,7 @@ test("P shows when each person last got a sent message, and about what", () => {
542542 const t = terminal(own, alice, context);
543543 t.press("P");
544544 const screen = lines(t).join("\n");
545 expect(screen).toContain(`Last heard ${spoken(today())} · ${date.label}, 9 Heard Way`);
545 expect(screen).toContain(`Last heard ${spoken(today(DEFAULT_ZONE))} · ${date.label}, 9 Heard Way`);
546546 expect(screen).toContain("Nothing sent yet");
547547 });
548548
@@ -552,11 +552,11 @@ test("the deal view lists a date that falls after closing, in words", () => {
552552 address: "3 Fig Ct",
553553 buyer: "B",
554554 seller: "S",
555 contractDate: today(),
556 closingDate: addDays(today(), 30),
555 contractDate: today(DEFAULT_ZONE),
556 closingDate: addDays(today(DEFAULT_ZONE), 30),
557557 });
558558 if (!other.ok) throw new Error(other.message);
559 const late = addDeadline(db, alice, { dealId: other.value.id, label: "Rate lock", due: addDays(today(), 35), owes: "buyer" });
559 const late = addDeadline(db, alice, { dealId: other.value.id, label: "Rate lock", due: addDays(today(DEFAULT_ZONE), 35), owes: "buyer" });
560560 expect(late.ok).toBe(true);
561561 const t = terminal(db, alice, context);
562562 goTo(t, "Rate lock — 3 Fig Ct");
@@ -571,13 +571,13 @@ test("m past closing moves the date and the status line names the conflict; a is
571571 address: "5 Gum Rd",
572572 buyer: "B",
573573 seller: "S",
574 contractDate: today(),
575 closingDate: addDays(today(), 30),
574 contractDate: today(DEFAULT_ZONE),
575 closingDate: addDays(today(DEFAULT_ZONE), 30),
576576 });
577577 if (!other.ok) throw new Error(other.message);
578578 const t = terminal(db, alice, context);
579579 goTo(t, "Financing contingency ends — 5 Gum Rd");
580 const past = addDays(today(), 33);
580 const past = addDays(today(DEFAULT_ZONE), 33);
581581 press(t, "m", `${past}\r`, "Lender slow\r");
582582 const moved = lines(t).join("\n");
583583 expect(moved).toContain("Moved Financing contingency ends");
@@ -590,7 +590,7 @@ test("m past closing moves the date and the status line names the conflict; a is
590590 });
591591
592592 test("a moved date's Date changed notice is on the reminders list; s sends it and the sent list reads its date", () => {
593 const made2 = createDeal(db, alice, { openAnyway: true, address: "31 Moved Way", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 45) });
593 const made2 = createDeal(db, alice, { openAnyway: true, address: "31 Moved Way", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 45) });
594594 if (!made2.ok) throw new Error(made2.message);
595595 const insp = made2.value.deadlines.find((d) => d.kind === "inspection")!;
596596 const to = addDays(insp.due, 5);
@@ -616,7 +616,7 @@ test("a moved date's Date changed notice is on the reminders list; s sends it an
616616 });
617617
618618 test("n declines a Date changed notice with a reason and u undoes it", () => {
619 const made3 = createDeal(db, alice, { openAnyway: true, address: "32 Moved Way", buyer: "Cy Buyer", seller: "Sol Seller", contractDate: today(), closingDate: addDays(today(), 45) });
619 const made3 = createDeal(db, alice, { openAnyway: true, address: "32 Moved Way", buyer: "Cy Buyer", seller: "Sol Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 45) });
620620 if (!made3.ok) throw new Error(made3.message);
621621 const insp = made3.value.deadlines.find((d) => d.kind === "inspection")!;
622622 moveDeadline(db, alice, { id: insp.id, due: addDays(insp.due, 5), reason: "x" });
@@ -636,15 +636,15 @@ test("I shows the profile; an admin edits it and goes back to the defaults, and
636636 const t = terminal(db, root, { title: "deal-clock", where: "test" });
637637 press(t, "I");
638638 expect(lines(t).join("\n")).toContain("Not saved");
639 press(t, "e", "Riley Agent\r", "\r", "555 0199\r", "\r", "Text me anytime\r");
639 press(t, "e", "Riley Agent\r", "\r", "555 0199\r", "\r", "Text me anytime\r", "\r");
640640 const saved = lines(t).join("\n");
641641 expect(saved).toContain("Profile saved.");
642642 expect(saved).toContain("Name Riley Agent");
643643 expect(saved).toContain("Phone 555 0199");
644644 expect(saved).toContain("Own line Text me anytime");
645 press(t, "e", "\r", "\r", "\r", "\r", "\r");
645 press(t, "e", "\r", "\r", "\r", "\r", "\r", "\r");
646646 expect(lines(t).join("\n")).toContain("Own line Text me anytime");
647 press(t, "e", "\r", "\r", "\r", "\r", "-\r");
647 press(t, "e", "\r", "\r", "\r", "\r", "-\r", "\r");
648648 expect(lines(t).join("\n")).toContain("Own line none");
649649 expect(lines(t)[0]).toContain("Riley Agent");
650650 press(t, "U", "yes\r");
@@ -652,6 +652,19 @@ test("I shows the profile; an admin edits it and goes back to the defaults, and
652652 expect(lines(t).join("\n")).toContain("Not saved");
653653 });
654654
655 test("the profile editor has a time zone step: it is saved, shown, refused when unknown, and the terminal's today follows it", () => {
656 const root: Who = { role: "admin", id: "u0", name: "root" };
657 const t = terminal(db, root, { title: "deal-clock", where: "test" });
658 press(t, "I", "e", "\r", "\r", "\r", "\r", "\r", "Nowhere/Land\r");
659 expect(lines(t).join("\n")).not.toContain("Time zone Nowhere/Land");
660 press(t, "I", "e", "\r", "\r", "\r", "\r", "\r", "Pacific/Kiritimati\r");
661 const screen = lines(t).join("\n");
662 expect(screen).toContain("Time zone Pacific/Kiritimati");
663 expect(screen).toContain(spoken(today("Pacific/Kiritimati")) + " ·");
664 press(t, "e", "\r", "\r", "\r", "\r", "\r", "America/New_York\r");
665 expect(lines(t).join("\n")).toContain(spoken(today("America/New_York")) + " ·");
666 });
667
655668 test("the profile is read-only to a user and shows nothing to a guest", () => {
656669 const user = terminal(db, alice, context);
657670 press(user, "I", "e");
@@ -706,7 +719,7 @@ test("a reader who may not change a deal sees no contact and no link", () => {
706719 });
707720
708721 test("M amends the contract: a blank answer keeps a date, the rest move together with one reason", () => {
709 const own = createDeal(db, alice, { openAnyway: true, address: "8 Amend Rd", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 60) });
722 const own = createDeal(db, alice, { openAnyway: true, address: "8 Amend Rd", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 60) });
710723 if (!own.ok) throw new Error(own.message);
711724 const read = () => {
712725 const got = getDeal(db, alice, { id: own.value.id });
@@ -730,12 +743,12 @@ test("L reads the audit trail in words for an admin, filters to messages and pag
730743 const root: Who = { role: "admin", id: "u0", name: "root" };
731744 // A book of its own, so the newest rows are these.
732745 const db = openDb(mkdtempSync(join(tmpdir(), "app-terminal-activity-")));
733 const mine = createDeal(db, alice, { openAnyway: true, address: "7 Trail Row", buyer: "Ann", seller: "Sam", contractDate: today(), closingDate: addDays(today(), 45) });
746 const mine = createDeal(db, alice, { openAnyway: true, address: "7 Trail Row", buyer: "Ann", seller: "Sam", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 45) });
734747 if (!mine.ok) throw new Error(mine.message);
735748 const inspection = mine.value.deadlines.find((d) => d.kind === "inspection")!;
736749 const party = db.query<{ id: number }, [number]>("SELECT id FROM party WHERE deal_id = ?1 LIMIT 1").get(mine.value.id)!;
737750 expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: party.id, moment: "before" }).ok).toBe(true);
738 expect(moveDeadline(db, alice, { id: inspection.id, due: addDays(today(), 20), reason: "Seller asked" }).ok).toBe(true);
751 expect(moveDeadline(db, alice, { id: inspection.id, due: addDays(today(DEFAULT_ZONE), 20), reason: "Seller asked" }).ok).toBe(true);
739752 const t = terminal(db, root, context);
740753 press(t, "L");
741754 let screen = lines(t).join("\n");
@@ -771,7 +784,7 @@ test("L reads the audit trail in words for an admin, filters to messages and pag
771784 });
772785
773786 test("a date on a weekend shows its next business day, and N rolls it there with the reason", () => {
774 let saturday = addDays(today(), 400);
787 let saturday = addDays(today(DEFAULT_ZONE), 400);
775788 while (new Date(`${saturday}T00:00:00Z`).getUTCDay() !== 6) saturday = addDays(saturday, 1);
776789 const monday = addDays(saturday, 2);
777790 const added = addDeadline(db, alice, { dealId: id, label: "Rate lock ends", due: saturday, owes: "buyer", what: "" });
@@ -800,7 +813,7 @@ test("T sets and clears a date's note, shown beside the date, through setNote",
800813 });
801814
802815 test("C sets the closing time and place of the open deal, a bad time is refused, and the deal view says the closing", () => {
803 const own = createDeal(db, alice, { openAnyway: true, address: "4 Pine St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(), closingDate: addDays(today(), 30) });
816 const own = createDeal(db, alice, { openAnyway: true, address: "4 Pine St", buyer: "Bea Buyer", seller: "Sid Seller", contractDate: today(DEFAULT_ZONE), closingDate: addDays(today(DEFAULT_ZONE), 30) });
804817 if (!own.ok) throw new Error(own.message);
805818 const read = () => {
806819 const got = getDeal(db, alice, { id: own.value.id });
@@ -831,15 +844,15 @@ test("a signed-out terminal is not asked for a closing time", () => {
831844
832845 test("n asks which side, defaults to Buyer's agent, and refuses an unknown word", () => {
833846 const t = terminal(db, alice, context);
834 press(t, "n", "51 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "Listing agent\r");
847 press(t, "n", "51 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today(DEFAULT_ZONE)}\r`, `${addDays(today(DEFAULT_ZONE), 40)}\r`, "Listing agent\r");
835848 const listed = listDeals(db, alice);
836849 if (!listed.ok) throw new Error(listed.message);
837850 expect(listed.value.find((d) => d.address === "51 Side St")?.side).toBe("listing");
838 press(t, "d", "n", "52 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "\r");
851 press(t, "d", "n", "52 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today(DEFAULT_ZONE)}\r`, `${addDays(today(DEFAULT_ZONE), 40)}\r`, "\r");
839852 const again = listDeals(db, alice);
840853 if (!again.ok) throw new Error(again.message);
841854 expect(again.value.find((d) => d.address === "52 Side St")?.side).toBe("buyer");
842 press(t, "d", "n", "53 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today()}\r`, `${addDays(today(), 40)}\r`, "seller\r");
855 press(t, "d", "n", "53 Side St\r", "Kim Buyer\r", "Lou Seller\r", `${today(DEFAULT_ZONE)}\r`, `${addDays(today(DEFAULT_ZONE), 40)}\r`, "seller\r");
843856 expect(lines(t).join("\n")).toContain("Side is buyer, listing or both.");
844857 const last = listDeals(db, alice);
845858 if (!last.ok) throw new Error(last.message);
src/terminal.ts +9 −6
@@ -10,7 +10,7 @@
1010 * timeline a deal's dates as a client would get them (t on a deal)
1111 * file a deal's broker file: figures, parties, every date and message (f on a deal)
1212 * activity who approved, declined or changed what, newest first (L, admins); m only messages, o older, y newer
13 * profile your name, brokerage, phone, email and own line (I); e edits them, U goes back to the defaults
13 * profile your name, brokerage, phone, email, own line and time zone (I); e edits them, U goes back to the defaults
1414 * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, C sets the closing time and place, M amends the contract, S drafts a status update for the party under the cursor, D removes it, F marks it fell through (or brings it back), Y changes the side (buyer, listing or both)
1515 *
1616 * On a date (dates or deal view): x marks it done, W waives it (the buyer gave it up), u reopens it or un-waives it, m moves it
@@ -25,7 +25,7 @@ import { bookLine, tally } from "./book.ts";
2525 import { closingLine } from "./closing.ts";
2626 import { timelineRows } from "./timeline.ts";
2727 import { fileRecord } from "./pages/file.ts";
28 import { isDate, relative, spoken, today, urgencyOf, type Urgency } from "./dates.ts";
28 import { DEFAULT_ZONE, isDate, relative, spoken, today, urgencyOf, type Urgency } from "./dates.ts";
2929 import {
3030 addDeadline,
3131 addParty,
@@ -69,7 +69,7 @@ import { find, FIND_MAX, query } from "./find.ts";
6969 import { mayRestore, restoreSamples } from "./actions.ts";
7070 import { conflictLine } from "./order.ts";
7171 import { isOpen, PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
72 import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts";
72 import { agentOf, getProfile, setProfile, useDefaults, zoneOf } from "./profile.ts";
7373 import { permit } from "./contract.ts";
7474 import { drafts, heldFrom, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
7575 import type { AuditRow } from "./audit.ts";
@@ -117,7 +117,7 @@ export function terminal(
117117 me: Who,
118118 context: { title: string; where: string; ssh?: string | undefined; agent?: Agent; on?: () => string },
119119 ): Terminal {
120 const on = context.on ?? today;
120 const on = context.on ?? ((): string => today(zoneOf(db)));
121121 /** The saved profile unless a caller fixed one: read when drawn, so a save elsewhere shows at once. */
122122 const agentNow = (): Agent => context.agent ?? agentOf(db);
123123 let view: View = "dates";
@@ -486,10 +486,11 @@ export function terminal(
486486 `Phone (enter keeps ${now.phone})`,
487487 `Email (enter keeps ${now.email})`,
488488 `A line of your own above the sign-off (enter keeps ${now.line ? `"${now.line}"` : "none"}, - clears it)`,
489 `Your time zone (enter keeps ${now.zone ?? DEFAULT_ZONE}; a name such as America/Chicago)`,
489490 ],
490491 answers: [],
491492 text: "",
492 finish: ([name, brokerage, phone, email, line]) =>
493 finish: ([name, brokerage, phone, email, line, zone]) =>
493494 report(
494495 setProfile(db, me, {
495496 name: name || now.name,
@@ -497,6 +498,7 @@ export function terminal(
497498 phone: phone || now.phone,
498499 email: email || now.email,
499500 line: line === "-" ? "" : line || (now.line ?? ""),
501 zone: zone || now.zone || DEFAULT_ZONE,
500502 }),
501503 "Profile saved.",
502504 ),
@@ -783,6 +785,7 @@ export function terminal(
783785 ` Phone ${a.phone}`,
784786 ` Email ${a.email}`,
785787 ` Own line ${a.line ?? dim("none")}`,
788 ` Time zone ${a.zone ?? DEFAULT_ZONE}`,
786789 );
787790 }
788791 } else if (view === "messages") {
@@ -794,7 +797,7 @@ export function terminal(
794797 deal.sent.forEach((m, i) => {
795798 const role = m.party_role === "" ? "" : ` (${PARTY_LABEL[m.party_role].toLowerCase()})`;
796799 const text = `${m.party_name}${role} · ${m.label}, ${spoken(m.due)} · ${sentLabel(m.moment).toLowerCase()}`;
797 lines.push(`${i === cursor ? "▸" : " "} ${dim(`sent ${m.sent_at.slice(0, 10)}`.padEnd(16))} ${i === cursor ? bold(text) : text}`);
800 lines.push(`${i === cursor ? "▸" : " "} ${dim(`sent ${m.sent_on}`.padEnd(16))} ${i === cursor ? bold(text) : text}`);
798801 if (reading === i && canChange(me, deal)) {
799802 const found = deal.parties.find((p) => p.id === m.party_id);
800803 const to = found === undefined ? "" : reachedAt(found);
src/timezone.test.ts added +97
@@ -0,0 +1,97 @@
1 /** "Today" is the agent's day in the zone set on the Profile, not the server's. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { Database } from "bun:sqlite";
4 import { mkdtempSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { dayOf, dayOfStamp, DEFAULT_ZONE, isZone, today } from "./dates.ts";
8 import { migrate, migrations } from "./db.ts";
9 import { agentOf, setProfile, zoneOf } from "./profile.ts";
10 import { forgetRationing } from "./security.ts";
11 import { serve } from "./server.ts";
12 import { sign } from "./who.ts";
13
14 // 7:30 pm on Sunday, Nov 8 in New York (daylight saving ended that morning); already Monday in UTC.
15 const evening = new Date("2026-11-09T00:30:00Z");
16
17 test("at 00:30 UTC the agent in New York is still on Nov 8, and a date due then is not overdue", async () => {
18 const { urgency } = await import("./dates.ts");
19 const profileDay = today("America/New_York", evening);
20 expect(profileDay).toBe("2026-11-08");
21 expect(urgency("2026-11-08", profileDay, false)).not.toBe("overdue");
22 expect(today("UTC", evening)).toBe("2026-11-09");
23 expect(urgency("2026-11-08", today("UTC", evening), false)).toBe("overdue");
24 expect(dayOf({ zone: "America/Los_Angeles" }, evening)).toBe("2026-11-08");
25 expect(dayOf({}, evening)).toBe("2026-11-08");
26 expect(dayOfStamp("America/New_York", "2026-11-09T00:30:00.000Z")).toBe("2026-11-08");
27 });
28
29 test("only a zone this runtime knows is a zone", () => {
30 for (const ok of ["America/New_York", "Pacific/Honolulu", "UTC", "Europe/Paris"]) expect(isZone(ok)).toBe(true);
31 for (const bad of ["", "Eastern", "EST5EDT; DROP", "America/Nowhere", 5, null, "x".repeat(100)]) expect(isZone(bad)).toBe(false);
32 });
33
34 const KEY = "a-key-only-the-forge-holds";
35 const dir = mkdtempSync(join(tmpdir(), "app-zone-"));
36 const server = serve({ port: 0, dataDir: dir, identityKey: KEY });
37 const base = `http://${server.hostname}:${server.port}`;
38 afterAll(() => server.stop(true));
39 beforeEach(forgetRationing);
40 const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => {
41 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
42 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
43 };
44 const root = as("u0", "root", "admin");
45 const rita = as("u-rita", "rita", "user");
46 const lee = { name: "Lee Park", brokerage: "Bay Homes", phone: "+1 555 0199", email: "[email protected]" };
47 const put = (body: unknown, who = root) =>
48 fetch(`${base}/api/profile`, { method: "PUT", headers: { "content-type": "application/json", ...who }, body: JSON.stringify(body) });
49
50 test("the Profile offers the US zones as a select, and keeps a stored zone that is none of them", async () => {
51 const html = await (await fetch(`${base}/profile`, { headers: root })).text();
52 expect(html).toContain('<select class="input" name="zone">');
53 for (const name of ["Eastern", "Central", "Mountain", "Pacific", "Alaska", "Hawaii"]) expect(html).toContain(`>${name}</option>`);
54 expect(html).toContain('<option value="America/New_York" selected>');
55 expect((await put({ ...lee, zone: "Europe/Paris" })).status).toBe(200);
56 const kept = await (await fetch(`${base}/profile`, { headers: root })).text();
57 expect(kept).toContain('<option value="Europe/Paris" selected>Europe/Paris</option>');
58 });
59
60 test("a zone that is not an IANA name is a 422 naming the field; only an admin saves one", async () => {
61 const bad = await put({ ...lee, zone: "Mars/Olympus" });
62 expect(bad.status).toBe(422);
63 expect(await bad.json()).toMatchObject({ error: "invalid", message: expect.stringContaining("time zone") });
64 expect((await put({ ...lee, zone: "Pacific/Honolulu" }, rita)).status).toBe(403);
65 const form = await fetch(`${base}/profile`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", ...root }, body: new URLSearchParams({ ...lee, zone: "nope" }) });
66 expect(form.status).toBe(422);
67 expect(await form.text()).toContain('aria-describedby="zone-why"');
68 });
69
70 test("the saved zone sets the day /tick and the clock speak in; leaving it out of a save keeps it", async () => {
71 expect((await put({ ...lee, zone: "Pacific/Auckland" })).status).toBe(200);
72 expect((await put(lee)).status).toBe(200);
73 const got = await (await fetch(`${base}/api/profile`, { headers: root })).json();
74 expect(got).toMatchObject({ zone: "Pacific/Auckland" });
75 const tick = await (await fetch(`${base}/tick`, { method: "POST", headers: { ...rita } })).json();
76 expect(tick.on).toBe(today("Pacific/Auckland"));
77 });
78
79 test("a database from before the zone boots with the default, and a save changes what is read", () => {
80 const db = new Database(":memory:");
81 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
82 const before = migrations.slice(0, -1);
83 before.forEach((sql, i) => {
84 try {
85 db.exec(sql);
86 } catch (error) {
87 if (!String(error).includes("duplicate column name")) throw error;
88 }
89 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1);
90 });
91 db.exec("INSERT INTO profile (id, name, brokerage, phone, email) VALUES (1, 'Ana', 'B', '555', '[email protected]')");
92 expect(migrate(db)).toBe(migrations.length);
93 expect(agentOf(db).zone).toBe(DEFAULT_ZONE);
94 expect(zoneOf(db)).toBe(DEFAULT_ZONE);
95 expect(setProfile(db, { role: "admin", id: "u0", name: "root" }, { name: "Ana", brokerage: "B", phone: "555", email: "[email protected]", zone: "America/Chicago" }).ok).toBe(true);
96 expect(zoneOf(db)).toBe("America/Chicago");
97 });
src/waive.test.ts +13 −13
@@ -3,7 +3,7 @@ import { afterAll, beforeEach, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays, today } from "./dates.ts";
6 import { addDays, today, DEFAULT_ZONE } from "./dates.ts";
77 import { openDb } from "./db.ts";
88 import { createDeal, getDeal, markDone, moveDeadline, waiveDate, type DealView } from "./deals.ts";
99 import { agent } from "./env.ts";
@@ -25,8 +25,8 @@ const made = createDeal(db, alice, {
2525 address: "3 Waiver Way",
2626 buyer: "Ann Buyer",
2727 seller: "Sam Seller",
28 contractDate: addDays(today(), -10),
29 closingDate: addDays(today(), 30),
28 contractDate: addDays(today(DEFAULT_ZONE), -10),
29 closingDate: addDays(today(DEFAULT_ZONE), 30),
3030 });
3131 if (!made.ok) throw new Error(made.message);
3232 const deal = (): DealView => {
@@ -45,7 +45,7 @@ test("waiving records the day and who, and stops the reminders; un-waiving bring
4545 const waived = waiveDate(db, alice, { id: date("financing").id, waived: true });
4646 expect(waived.ok).toBe(true);
4747 expect(date("financing")).toMatchObject({ waived_by: "alice", done_at: null });
48 expect(date("financing").waived_at).toStartWith(today());
48 expect(date("financing").waived_on).toBe(today(DEFAULT_ZONE));
4949 expect(remindersOn("financing")).toEqual([]);
5050 expect(date("financing").nonBusinessDay).toBeNull();
5151 expect(waiveDate(db, alice, { id: date("financing").id, waived: true }).ok).toBe(false);
@@ -56,31 +56,31 @@ test("waiving records the day and who, and stops the reminders; un-waiving bring
5656 });
5757
5858 test("waiving leaves the review and the header count, and an overdue follow-up", () => {
59 moveDeadline(db, alice, { id: date("inspection").id, due: addDays(today(), -3), reason: "Slipped" });
59 moveDeadline(db, alice, { id: date("inspection").id, due: addDays(today(DEFAULT_ZONE), -3), reason: "Slipped" });
6060 expect(remindersOn("inspection").some((r) => r.moment === "late")).toBe(true);
61 const before = waitingCount([deal()], today(), agent);
61 const before = waitingCount([deal()], today(DEFAULT_ZONE), agent);
6262 expect(before).toBeGreaterThan(0);
6363 waiveDate(db, alice, { id: date("inspection").id, waived: true });
6464 expect(remindersOn("inspection")).toEqual([]);
65 expect(waitingCount([deal()], today(), agent)).toBeLessThan(before);
65 expect(waitingCount([deal()], today(DEFAULT_ZONE), agent)).toBeLessThan(before);
6666 waiveDate(db, alice, { id: date("inspection").id, waived: false });
67 moveDeadline(db, alice, { id: date("inspection").id, due: addDays(today(), 5), reason: "Back" });
67 moveDeadline(db, alice, { id: date("inspection").id, due: addDays(today(DEFAULT_ZONE), 5), reason: "Back" });
6868 });
6969
7070 test("progress counts a waived date as settled, and the timeline says Waived", () => {
71 const before = progress(deal(), today());
71 const before = progress(deal(), today(DEFAULT_ZONE));
7272 waiveDate(db, alice, { id: date("inspection").id, waived: true });
73 const after = progress(deal(), today());
73 const after = progress(deal(), today(DEFAULT_ZONE));
7474 expect(after.done).toBe(before.done + 1);
7575 expect(after.total).toBe(before.total);
76 const row = timelineRows(deal(), today()).find((r) => r.label === date("inspection").label)!;
76 const row = timelineRows(deal(), today(DEFAULT_ZONE)).find((r) => r.label === date("inspection").label)!;
7777 expect(row).toMatchObject({ status: "Waived", urgency: "waived" });
7878 expect(row.mark).not.toBe("✓");
7979 waiveDate(db, alice, { id: date("inspection").id, waived: false });
8080 });
8181
8282 test("a waived date past closing is no conflict, and it changes the status update's standing", () => {
83 moveDeadline(db, alice, { id: date("financing").id, due: addDays(today(), 40), reason: "Lender" });
83 moveDeadline(db, alice, { id: date("financing").id, due: addDays(today(DEFAULT_ZONE), 40), reason: "Lender" });
8484 expect(deal().conflicts.length).toBe(1);
8585 const before = standing(deal());
8686 waiveDate(db, alice, { id: date("financing").id, waived: true });
@@ -107,7 +107,7 @@ test("someone who may not update the deal is refused, and the refusal is audited
107107 });
108108
109109 test("the sheet offers Waive beside Mark done, but never on Closing, and Un-waive on a waived date", () => {
110 const html = (kind: string) => sheet(deal(), date(kind), alice, today(), "/");
110 const html = (kind: string) => sheet(deal(), date(kind), alice, today(DEFAULT_ZONE), "/");
111111 expect(html("inspection")).toContain("Mark done");
112112 expect(html("inspection")).toContain(`action="/deadlines/${date("inspection").id}/waive"`);
113113 expect(html("inspection")).toContain("Yes, waive");
src/week.page.test.ts +2 −2
@@ -3,7 +3,7 @@ import { afterAll, expect, test } from "bun:test";
33 import { mkdtempSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { addDays } from "./dates.ts";
6 import { addDays, DEFAULT_ZONE } from "./dates.ts";
77 import { forgetRationing } from "./security.ts";
88 import { serve } from "./server.ts";
99 import { sign } from "./who.ts";
@@ -87,7 +87,7 @@ test("a place with markup in it is escaped on the sheet", async () => {
8787 const { today } = await import("./dates.ts");
8888 const db = openDb(dir);
8989 const me = { role: "user" as const, id: "u1", name: "alice" };
90 const made = createDeal(db, me, { address: "9 Escape Way", buyer: "A B", seller: "C D", contractDate: addDays(today(), -20), closingDate: addDays(today(), 1), openAnyway: true });
90 const made = createDeal(db, me, { address: "9 Escape Way", buyer: "A B", seller: "C D", contractDate: addDays(today(DEFAULT_ZONE), -20), closingDate: addDays(today(DEFAULT_ZONE), 1), openAnyway: true });
9191 if (!made.ok) throw new Error(made.message);
9292 const set = updateDeal(db, me, { id: made.value.id, closingTime: "08:00", closingPlace: "<b>Title</b> & Co" });
9393 if (!set.ok) throw new Error(set.message);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs