Public: anyone can read this; the crew can change it.
An admin reads who approved, declined or changed what on an Activity page, so "a human approves every message" can be shown, not just said #82
Check · Review · Land · Live done — Landed and live in production.
mason/deal-clock:mason/80-an-admin-reads-who-approved-declined-or → main 2 commits fork 1 thread · 1 unresolved
15 files
changed +463
−58
README.md +12
| @@ -146,6 +146,18 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture | ||
| 146 | 146 | the deal-clock mark sits beside the app's name, and it opens full screen |
| 147 | 147 | like any app. The same mark is the browser tab's icon. |
| 148 | 148 | |
| 149 | ## Activity: who approved what | |
| 150 | ||
| 151 | An admin sees **Activity** in the header: the newest hundred things anyone | |
| 152 | tried to change, one plain line each — who (or "someone not signed in"), what | |
| 153 | ("sent a reminder", "declined a reminder", "moved a date", "saved the | |
| 154 | profile"), on which deal (linked while it exists), when, and, if it was | |
| 155 | refused, why. **Messages** narrows it to sends, declines and undos, so the | |
| 156 | sales meeting can show that every message that went out was approved by a | |
| 157 | named person at a stated time; **Older** pages back. In the terminal press L, | |
| 158 | then m for only messages, o for older and y for newer. A signed-in user who is | |
| 159 | not an admin is told no; a stranger is asked to sign in. | |
| 160 | ||
| 149 | 161 | ## Make it yours |
| 150 | 162 | |
| 151 | 163 | The app ships with a sample agent. To carry your own, open **Profile** in the |
contract/openapi.json +6
| @@ -1801,6 +1801,12 @@ | ||
| 1801 | 1801 | }, |
| 1802 | 1802 | "outcome": { |
| 1803 | 1803 | "type": "string" |
| 1804 | }, | |
| 1805 | "what": { | |
| 1806 | "type": [ | |
| 1807 | "string", | |
| 1808 | "null" | |
| 1809 | ] | |
| 1804 | 1810 | } |
| 1805 | 1811 | }, |
| 1806 | 1812 | "required": [ |
docs/TECHNICAL.md +9 −1
| @@ -153,6 +153,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it. | ||
| 153 | 153 | | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim | |
| 154 | 154 | | `src/security.ts` | the door: rationing, same origin, the table before the body | |
| 155 | 155 | | `src/audit.ts` | every change and every refused one, as a row | |
| 156 | | `src/activity.ts` | the audit trail in words, for the page and the terminal | | |
| 156 | 157 | | `src/who.ts` | who is asking, from the forge's signed headers | |
| 157 | 158 | | `src/db.ts` | SQLite under `FORGE_APP_DATA`, WAL, forward-only migrations | |
| 158 | 159 | | `src/live.ts` | the in-process bus and `GET /events` | |
| @@ -176,7 +177,14 @@ decide nothing themselves. `AGENTS.md` says how to add to it. | ||
| 176 | 177 | else. The action still decides about the real row. |
| 177 | 178 | - **The audit trail.** Every change, and every change refused, is a row: |
| 178 | 179 | who, which resource and verb, which row, when, and whether they were |
| 179 | let. Admins read it at `GET /api/audit`. A row that cannot be written | |
| 180 | let. Admins read it at `GET /api/audit` and, in words, at `GET /activity` | |
| 181 | (`src/pages/activity.ts`) and with L in the terminal; the words, times and | |
| 182 | deal addresses are shared in `src/activity.ts`. `?before=<id>` pages, | |
| 183 | `?only=messages` keeps sends, declines and undos, a bad value is a 400 page; | |
| 184 | `permit(who, "audit", "list")` decides at every door, no cell changed. | |
| 185 | Changes inside a deal share `deal update`, so the row's `what` column | |
| 186 | (`reminder.send`, `date.move`, …) says which; an unknown pair is worded | |
| 187 | `resource verb`. A row that cannot be written | |
| 180 | 188 | is a log line, never a failed request. |
| 181 | 189 | - **The API, described.** `GET /openapi.json` is `contract/openapi.json`, |
| 182 | 190 | written from the routes by `bun run contract:emit`; each operation names |
src/actions.ts +9 −4
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import type { AuditRow } from "./audit.ts"; | |
| 10 | import { MESSAGE_WHATS, type AuditRow } from "./audit.ts"; | |
| 11 | 11 | import { permit } from "./contract.ts"; |
| 12 | 12 | import { emit } from "./live.ts"; |
| 13 | 13 | import { audited, fail, ok, refuse, type Result } from "./result.ts"; |
| @@ -18,14 +18,15 @@ export type { Failure, Result } from "./result.ts"; | ||
| 18 | 18 | |
| 19 | 19 | /** |
| 20 | 20 | * The audit trail, newest first, for whoever the table lets read it (an |
| 21 | * admin, as the scaffold has it). `before` pages back by id. Audit rows name | |
| 21 | * admin, as the scaffold has it). `before` pages back by id; `only: | |
| 22 | * "messages"` keeps reminder sends, declines and undos. Audit rows name | |
| 22 | 23 | * no author, so a cell that gave `list` to a row's role would find nothing |
| 23 | 24 | * of its own: anything but "yes" is a refusal here. |
| 24 | 25 | */ |
| 25 | 26 | export function listAudit( |
| 26 | 27 | db: Database, |
| 27 | 28 | who: Who, |
| 28 | input: { limit?: number; before?: number } = {}, | |
| 29 | input: { limit?: number; before?: number; only?: "messages" } = {}, | |
| 29 | 30 | ): Result<AuditRow[]> { |
| 30 | 31 | if (permit(who, "audit", "list") !== "yes") |
| 31 | 32 | return refuse( |
| @@ -40,12 +41,16 @@ export function listAudit( | ||
| 40 | 41 | const before = Number.isInteger(input.before) |
| 41 | 42 | ? input.before! |
| 42 | 43 | : Number.MAX_SAFE_INTEGER; |
| 44 | const kept = | |
| 45 | input.only === "messages" | |
| 46 | ? ` AND what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")})` | |
| 47 | : ""; | |
| 43 | 48 | return ok( |
| 44 | 49 | db |
| 45 | 50 | .query< |
| 46 | 51 | AuditRow, |
| 47 | 52 | [number, number] |
| 48 | >("SELECT * FROM audit WHERE id < ?1 ORDER BY id DESC LIMIT ?2") | |
| 53 | >(`SELECT * FROM audit WHERE id < ?1${kept} ORDER BY id DESC LIMIT ?2`) | |
| 49 | 54 | .all(before, limit), |
| 50 | 55 | ); |
| 51 | 56 | } |
src/activity.test.ts added +109
| @@ -0,0 +1,109 @@ | ||
| 1 | /** Activity: the audit trail in plain English, for an admin only, paged, filtered and quick. */ | |
| 2 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; | |
| 3 | import { mkdtempSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { wording } from "./activity.ts"; | |
| 7 | import { createDeal, moveDeadline, sendReminder } from "./deals.ts"; | |
| 8 | import { openDb } from "./db.ts"; | |
| 9 | import { forgetRationing } from "./security.ts"; | |
| 10 | import { serve } from "./server.ts"; | |
| 11 | import { sign, type Who } from "./who.ts"; | |
| 12 | ||
| 13 | const KEY = "a-key-only-the-forge-holds"; | |
| 14 | const dir = mkdtempSync(join(tmpdir(), "app-activity-")); | |
| 15 | const db = openDb(dir); | |
| 16 | const alice: Who = { role: "user", id: "u1", name: "alice <b>" }; | |
| 17 | const server = serve({ port: 0, dataDir: dir, identityKey: KEY }); | |
| 18 | const base = `http://${server.hostname}:${server.port}`; | |
| 19 | afterAll(() => server.stop(true)); | |
| 20 | beforeEach(forgetRationing); | |
| 21 | ||
| 22 | const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => { | |
| 23 | const identity = `${id}|${name}|${role}|${Date.now() + 600_000}`; | |
| 24 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 25 | }; | |
| 26 | const root = as("u0", "root", "admin"); | |
| 27 | const user = as("u1", "alice", "user"); | |
| 28 | const get = (path: string, who: Record<string, string> = {}) => fetch(base + path, { headers: who }); | |
| 29 | ||
| 30 | let dealId = 0; | |
| 31 | beforeAll(() => { | |
| 32 | const made = createDeal(db, alice, { address: "9 <i>Audit</i> Row", buyer: "Ann", seller: "Sam", contractDate: "2026-10-01", closingDate: "2026-11-06" }); | |
| 33 | if (!made.ok) throw new Error(made.message); | |
| 34 | dealId = made.value.id; | |
| 35 | const inspection = made.value.deadlines.find((d) => d.kind === "inspection")!; | |
| 36 | const party = db.query<{ id: number }, [number]>("SELECT id FROM party WHERE deal_id = ?1 LIMIT 1").get(dealId)!; | |
| 37 | expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: party.id, moment: "before" }).ok).toBe(true); | |
| 38 | expect(moveDeadline(db, alice, { id: inspection.id, due: "2026-10-20", reason: "Seller asked" }).ok).toBe(true); | |
| 39 | }); | |
| 40 | ||
| 41 | test("an admin sees a send with the sender's name, the deal linked, and everything escaped", async () => { | |
| 42 | const res = await get("/activity", root); | |
| 43 | expect(res.status).toBe(200); | |
| 44 | const page = await res.text(); | |
| 45 | expect(page).toContain("sent a reminder"); | |
| 46 | expect(page).toContain("alice <b>"); | |
| 47 | expect(page).not.toContain("alice <b>"); | |
| 48 | expect(page).toContain(`<a href="/deals/${dealId}">9 <i>Audit</i> Row</a>`); | |
| 49 | expect(page).toContain("moved a date"); | |
| 50 | expect(page).toContain('href="/activity"'); | |
| 51 | }); | |
| 52 | ||
| 53 | test("a user is refused, a stranger is asked to sign in, and only the allowed see the link", async () => { | |
| 54 | expect((await get("/activity", user)).status).toBe(403); | |
| 55 | const stranger = await get("/activity"); | |
| 56 | expect(stranger.status).toBe(401); | |
| 57 | expect(await stranger.text()).toContain("Sign in"); | |
| 58 | expect(await (await get("/", user)).text()).not.toContain('href="/activity"'); | |
| 59 | expect(await (await get("/", root)).text()).toContain('href="/activity"'); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a before that is not a whole number, or an unknown filter, is a 400 page", async () => { | |
| 63 | for (const q of ["before=abc", "before=-1", "before=1.5", "only=everything"]) { | |
| 64 | const res = await get(`/activity?${q}`, root); | |
| 65 | expect(res.status).toBe(400); | |
| 66 | expect(res.headers.get("content-type")).toContain("text/html"); | |
| 67 | } | |
| 68 | }); | |
| 69 | ||
| 70 | test("only=messages keeps sends and drops a date move", async () => { | |
| 71 | const page = await (await get("/activity?only=messages", root)).text(); | |
| 72 | expect(page).toContain("sent a reminder"); | |
| 73 | expect(page).not.toContain("moved a date"); | |
| 74 | }); | |
| 75 | ||
| 76 | test("a refused attempt says so in words, and an unknown pair falls back to resource verb", async () => { | |
| 77 | await fetch(`${base}/api/deals`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); | |
| 78 | const page = await (await get("/activity", root)).text(); | |
| 79 | expect(page).toContain("someone not signed in"); | |
| 80 | expect(page).toContain("Refused"); | |
| 81 | expect(page).toContain("they were not signed in"); | |
| 82 | expect(wording({ resource: "gizmo", verb: "poke", what: null })).toBe("gizmo poke"); | |
| 83 | }); | |
| 84 | ||
| 85 | test("Older pages back by id and keeps the filter", async () => { | |
| 86 | const insert = db.query("INSERT INTO audit (role, resource, verb, allowed, outcome, what) VALUES ('user','deal','update',1,'ok','reminder.send')"); | |
| 87 | for (let i = 0; i < 120; i++) insert.run(); | |
| 88 | const first = await (await get("/activity", root)).text(); | |
| 89 | const older = first.match(/href="\/activity\?before=(\d+)"/); | |
| 90 | expect(older).not.toBeNull(); | |
| 91 | const next = await get(`/activity?before=${older![1]}&only=messages`, root); | |
| 92 | expect(next.status).toBe(200); | |
| 93 | expect((await next.text()).match(/<li>/g)!.length).toBeGreaterThan(0); | |
| 94 | }); | |
| 95 | ||
| 96 | test("the page answers in under 50 ms with 1,000 audit rows", async () => { | |
| 97 | const insert = db.query("INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome, what) VALUES ('u1','alice','user','deal','update',?1,1,'ok','reminder.send')"); | |
| 98 | for (let i = 0; i < 1000; i++) insert.run(String(dealId)); | |
| 99 | await get("/activity", root); | |
| 100 | const times: number[] = []; | |
| 101 | for (let i = 0; i < 15; i++) { | |
| 102 | const start = performance.now(); | |
| 103 | const res = await get("/activity", root); | |
| 104 | times.push(performance.now() - start); | |
| 105 | expect(res.status).toBe(200); | |
| 106 | await res.arrayBuffer(); | |
| 107 | } | |
| 108 | expect(times.sort((a, b) => a - b)[7]!).toBeLessThan(50); | |
| 109 | }); |
src/activity.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | /** | |
| 2 | * Activity in words, shared by its two doors (the page and the terminal): | |
| 3 | * what each audited change is called, why a refusal was one, when it was, | |
| 4 | * and which deals the rows name. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import type { AuditRow } from "./audit.ts"; | |
| 9 | ||
| 10 | /** Rows to a page; a door asks for one more to know whether there is an older page. */ | |
| 11 | export const ACTIVITY_PAGE = 100; | |
| 12 | ||
| 13 | /** What each audited change is called, by `what` when a row has one, else `resource verb`. */ | |
| 14 | const WORDS: Readonly<Record<string, string>> = { | |
| 15 | "reminder.send": "sent a reminder", | |
| 16 | "reminder.decline": "declined a reminder", | |
| 17 | "reminder.undo": "undid a declined reminder", | |
| 18 | "date.move": "moved a date", | |
| 19 | "date.done": "marked a date done", | |
| 20 | "date.lead": "changed when a date's reminder goes out", | |
| 21 | "date.add": "added a date", | |
| 22 | "date.remove": "removed a date", | |
| 23 | "deal.amend": "amended the contract dates", | |
| 24 | "party.add": "added a party", | |
| 25 | "party.edit": "changed a party", | |
| 26 | "party.remove": "removed a party", | |
| 27 | "deal create": "added a deal", | |
| 28 | "deal update": "changed a deal", | |
| 29 | "deal delete": "removed a deal", | |
| 30 | "profile update": "saved the profile", | |
| 31 | }; | |
| 32 | ||
| 33 | const REFUSALS: Readonly<Record<string, string>> = { | |
| 34 | signin_required: "they were not signed in", | |
| 35 | forbidden: "they may not do that", | |
| 36 | invalid: "what they sent was not valid", | |
| 37 | not_found: "it was not there", | |
| 38 | cross_site: "it came from another site", | |
| 39 | }; | |
| 40 | ||
| 41 | const AT = new Intl.DateTimeFormat("en-US", { | |
| 42 | weekday: "short", | |
| 43 | month: "short", | |
| 44 | day: "numeric", | |
| 45 | hour: "numeric", | |
| 46 | minute: "2-digit", | |
| 47 | timeZone: "UTC", | |
| 48 | timeZoneName: "short", | |
| 49 | }); | |
| 50 | ||
| 51 | export const wording = (row: Pick<AuditRow, "resource" | "verb" | "what">): string => | |
| 52 | (row.what !== null && WORDS[row.what]) || WORDS[`${row.resource} ${row.verb}`] || `${row.resource} ${row.verb}`; | |
| 53 | ||
| 54 | /** "Fri, Oct 16, 3:04 PM UTC" from the stored ISO time; the text itself if it does not read. */ | |
| 55 | export const when = (at: string): string => { | |
| 56 | const ms = Date.parse(at); | |
| 57 | return Number.isNaN(ms) ? at : AT.format(ms); | |
| 58 | }; | |
| 59 | ||
| 60 | /** The addresses of the deals the rows name, by id: one query for the page. */ | |
| 61 | export function addresses(db: Database, rows: readonly AuditRow[]): Map<string, string> { | |
| 62 | const ids = [ | |
| 63 | ...new Set(rows.filter((r) => r.resource === "deal" && r.target !== null && /^\d+$/.test(r.target)).map((r) => Number(r.target))), | |
| 64 | ]; | |
| 65 | if (ids.length === 0) return new Map(); | |
| 66 | return new Map( | |
| 67 | db | |
| 68 | .query<{ id: number; address: string }, number[]>(`SELECT id, address FROM deal WHERE id IN (${ids.map(() => "?").join(",")})`) | |
| 69 | .all(...ids) | |
| 70 | .map((d) => [String(d.id), d.address]), | |
| 71 | ); | |
| 72 | } | |
| 73 | ||
| 74 | /** Why a row was refused, in words; an unknown outcome is said as it is. */ | |
| 75 | export const refusal = (outcome: string): string => REFUSALS[outcome] ?? outcome; |
src/audit.ts +10 −2
| @@ -28,6 +28,8 @@ export interface AuditRow { | ||
| 28 | 28 | readonly allowed: 0 | 1; |
| 29 | 29 | /** `ok`, or the failure: `signin_required`, `forbidden`, `invalid`, `not_found`, `cross_site`. */ |
| 30 | 30 | readonly outcome: string; |
| 31 | /** Which change inside a row, when the resource and verb alone do not say (`reminder.send`); null for older rows. */ | |
| 32 | readonly what: string | null; | |
| 31 | 33 | } |
| 32 | 34 | |
| 33 | 35 | export interface Attempt { |
| @@ -36,8 +38,12 @@ export interface Attempt { | ||
| 36 | 38 | readonly verb: string; |
| 37 | 39 | readonly target?: string | number | undefined; |
| 38 | 40 | readonly outcome: string; |
| 41 | readonly what?: string | undefined; | |
| 39 | 42 | } |
| 40 | 43 | |
| 44 | /** The changes that are a message's life: sent, declined, undone. The Activity page's `only=messages`. */ | |
| 45 | export const MESSAGE_WHATS = ["reminder.send", "reminder.decline", "reminder.undo"] as const; | |
| 46 | ||
| 41 | 47 | /** The newest rows kept; older ones go as new ones come. */ |
| 42 | 48 | export const KEEP = 50_000; |
| 43 | 49 | |
| @@ -48,7 +54,7 @@ export const allowed = (outcome: string): boolean => | ||
| 48 | 54 | outcome !== "cross_site"; |
| 49 | 55 | |
| 50 | 56 | export function record(db: Database, attempt: Attempt): void { |
| 51 | const { who, resource, verb, target, outcome } = attempt; | |
| 57 | const { who, resource, verb, target, outcome, what } = attempt; | |
| 52 | 58 | const row = { |
| 53 | 59 | who_id: who.role === "anon" ? null : who.id, |
| 54 | 60 | who_name: who.role === "anon" ? null : who.name, |
| @@ -58,11 +64,12 @@ export function record(db: Database, attempt: Attempt): void { | ||
| 58 | 64 | target: target === undefined ? null : String(target), |
| 59 | 65 | allowed: allowed(outcome) ? 1 : 0, |
| 60 | 66 | outcome, |
| 67 | what: what ?? null, | |
| 61 | 68 | }; |
| 62 | 69 | try { |
| 63 | 70 | const { lastInsertRowid } = db |
| 64 | 71 | .query( |
| 65 | "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | |
| 72 | "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome, what) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | |
| 66 | 73 | ) |
| 67 | 74 | .run( |
| 68 | 75 | row.who_id, |
| @@ -73,6 +80,7 @@ export function record(db: Database, attempt: Attempt): void { | ||
| 73 | 80 | row.target, |
| 74 | 81 | row.allowed, |
| 75 | 82 | row.outcome, |
| 83 | row.what, | |
| 76 | 84 | ); |
| 77 | 85 | db.query("DELETE FROM audit WHERE id <= ?1").run( |
| 78 | 86 | Number(lastInsertRowid) - KEEP, |
src/db.ts +2
| @@ -323,6 +323,8 @@ export const migrations: string[] = [ | ||
| 323 | 323 | email TEXT NOT NULL, |
| 324 | 324 | updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) |
| 325 | 325 | )`, |
| 326 | // Which change inside a row an audit row was ("reminder.send"), for the Activity page. | |
| 327 | `ALTER TABLE audit ADD COLUMN what TEXT`, | |
| 326 | 328 | ]; |
| 327 | 329 | |
| 328 | 330 | export function openDb(dir = dataDir): Database { |
src/deals.ts +49 −47
| @@ -549,14 +549,15 @@ function remove(db: Database, who: Who, input: { id: number }): Result<{ id: num | ||
| 549 | 549 | |
| 550 | 550 | // ---- a deal's dates, parties and reminders: each an update of the deal ---- |
| 551 | 551 | |
| 552 | /** A change inside deal `dealId`, audited as an update of that deal. */ | |
| 552 | /** A change inside deal `dealId`, audited as an update of that deal; `what` names which change (src/pages/activity.ts words it). */ | |
| 553 | 553 | function within<T extends { readonly id: number }>( |
| 554 | 554 | db: Database, |
| 555 | 555 | who: Who, |
| 556 | what: string, | |
| 556 | 557 | dealId: number | undefined, |
| 557 | 558 | result: Result<T>, |
| 558 | 559 | ): Result<T> { |
| 559 | const out = audited(db, who, "deal", "update", dealId, result); | |
| 560 | const out = audited(db, who, "deal", "update", dealId, result, what); | |
| 560 | 561 | if (out.ok && dealId !== undefined) emit("deal.changed", { id: dealId }); |
| 561 | 562 | return out; |
| 562 | 563 | } |
| @@ -594,11 +595,11 @@ export function markDone( | ||
| 594 | 595 | input: { id: number; done: boolean }, |
| 595 | 596 | ): Result<Deadline> { |
| 596 | 597 | const { dealId, found } = deadlineFor(db, who, input.id); |
| 597 | if (!found.ok) return within(db, who, dealId, found); | |
| 598 | if (!found.ok) return within(db, who, "date.done", dealId, found); | |
| 598 | 599 | db.query( |
| 599 | 600 | "UPDATE deadline SET done_at = ?1 WHERE id = ?2", |
| 600 | 601 | ).run(input.done ? new Date().toISOString() : null, input.id); |
| 601 | return within(db, who, dealId, ok(reread(db, input.id))); | |
| 602 | return within(db, who, "date.done", dealId, ok(reread(db, input.id))); | |
| 602 | 603 | } |
| 603 | 604 | |
| 604 | 605 | /** Whether `value` is a lead time: a whole number of days, 1 to 30. */ |
| @@ -616,13 +617,13 @@ export function setReminderLead( | ||
| 616 | 617 | input: { id: number; dealId?: number; leadDays: unknown }, |
| 617 | 618 | ): Result<Deadline> { |
| 618 | 619 | const { dealId, found } = deadlineFor(db, who, input.id, input.dealId); |
| 619 | if (!found.ok) return within(db, who, dealId, found); | |
| 620 | if (!found.ok) return within(db, who, "date.lead", dealId, found); | |
| 620 | 621 | // A form or a terminal sends text: a whole number written out is a whole number. |
| 621 | 622 | const days = typeof input.leadDays === "string" && /^\s*\d{1,3}\s*$/.test(input.leadDays) ? Number(input.leadDays) : input.leadDays; |
| 622 | 623 | if (!isLead(days)) |
| 623 | return within(db, who, dealId, fail("invalid", `Days before is a whole number from ${LEAD_MIN} to ${LEAD_MAX}.`, "lead_days")); | |
| 624 | return within(db, who, "date.lead", dealId, fail("invalid", `Days before is a whole number from ${LEAD_MIN} to ${LEAD_MAX}.`, "lead_days")); | |
| 624 | 625 | db.query("UPDATE deadline SET lead_days = ?1 WHERE id = ?2").run(days, input.id); |
| 625 | return within(db, who, dealId, ok(reread(db, input.id))); | |
| 626 | return within(db, who, "date.lead", dealId, ok(reread(db, input.id))); | |
| 626 | 627 | } |
| 627 | 628 | |
| 628 | 629 | /** Move one date, and only that one; the reason is kept beside it. */ |
| @@ -632,22 +633,22 @@ export function moveDeadline( | ||
| 632 | 633 | input: { id: number; due: unknown; reason: unknown }, |
| 633 | 634 | ): Result<Deadline> { |
| 634 | 635 | const { dealId, found } = deadlineFor(db, who, input.id); |
| 635 | if (!found.ok) return within(db, who, dealId, found); | |
| 636 | if (!found.ok) return within(db, who, "date.move", dealId, found); | |
| 636 | 637 | if (!isDate(input.due)) |
| 637 | return within(db, who, dealId, fail("invalid", "The new date is a date (YYYY-MM-DD).")); | |
| 638 | return within(db, who, "date.move", dealId, fail("invalid", "The new date is a date (YYYY-MM-DD).")); | |
| 638 | 639 | const reason = line(input.reason, 1, 200); |
| 639 | 640 | if (reason === undefined) |
| 640 | return within(db, who, dealId, fail("invalid", "Say why the date moved (up to 200 characters).")); | |
| 641 | return within(db, who, "date.move", dealId, fail("invalid", "Say why the date moved (up to 200 characters).")); | |
| 641 | 642 | const { deadline } = found.value; |
| 642 | 643 | if (input.due === deadline.due) |
| 643 | return within(db, who, dealId, fail("invalid", "That is already its date.")); | |
| 644 | return within(db, who, "date.move", dealId, fail("invalid", "That is already its date.")); | |
| 644 | 645 | db.transaction(() => { |
| 645 | 646 | db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(input.due as string, deadline.id); |
| 646 | 647 | db.query( |
| 647 | 648 | "INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, notify) VALUES (?1, ?2, ?3, ?4, ?5, 1)", |
| 648 | 649 | ).run(deadline.id, deadline.due, input.due as string, reason, authorOf(who).name); |
| 649 | 650 | })(); |
| 650 | return within(db, who, dealId, ok(reread(db, deadline.id))); | |
| 651 | return within(db, who, "date.move", dealId, ok(reread(db, deadline.id))); | |
| 651 | 652 | } |
| 652 | 653 | |
| 653 | 654 | /** One amendment, checked: the moves it makes, or the field that was wrong and why. */ |
| @@ -691,10 +692,10 @@ export function amendDeal( | ||
| 691 | 692 | input: { dealId: number; dates: unknown; reason: unknown }, |
| 692 | 693 | ): Result<DealView> { |
| 693 | 694 | const found = dealFor(db, who, "update", input.dealId); |
| 694 | if (!found.ok) return within(db, who, undefined, found); | |
| 695 | if (!found.ok) return within(db, who, "deal.amend", undefined, found); | |
| 695 | 696 | const seen = view(db, found.value); |
| 696 | 697 | const plan = amendment(seen, input.dates, input.reason); |
| 697 | if (!plan.ok) return within(db, who, found.value.id, fail("invalid", plan.message)); | |
| 698 | if (!plan.ok) return within(db, who, "deal.amend", found.value.id, fail("invalid", plan.message)); | |
| 698 | 699 | const name = authorOf(who).name; |
| 699 | 700 | db.transaction(() => { |
| 700 | 701 | const number = db.query<{ n: number }, []>("SELECT coalesce(max(amendment), 0) + 1 AS n FROM deadline_move").get()!.n; |
| @@ -705,7 +706,7 @@ export function amendDeal( | ||
| 705 | 706 | ).run(deadline.id, deadline.due, to, plan.reason, name, number); |
| 706 | 707 | } |
| 707 | 708 | })(); |
| 708 | return within(db, who, found.value.id, ok(view(db, found.value))); | |
| 709 | return within(db, who, "deal.amend", found.value.id, ok(view(db, found.value))); | |
| 709 | 710 | } |
| 710 | 711 | |
| 711 | 712 | export function addDeadline( |
| @@ -715,23 +716,23 @@ export function addDeadline( | ||
| 715 | 716 | ): Result<Deadline> { |
| 716 | 717 | const deal = dealFor(db, who, "update", input.dealId); |
| 717 | 718 | const dealId = deal.ok ? deal.value.id : undefined; |
| 718 | if (!deal.ok) return within(db, who, Number.isInteger(input.dealId) ? input.dealId : undefined, deal); | |
| 719 | if (!deal.ok) return within(db, who, "date.add", Number.isInteger(input.dealId) ? input.dealId : undefined, deal); | |
| 719 | 720 | const label = line(input.label, 1, 100); |
| 720 | 721 | if (label === undefined) |
| 721 | return within(db, who, dealId, fail("invalid", "Name the date (up to 100 characters).")); | |
| 722 | return within(db, who, "date.add", dealId, fail("invalid", "Name the date (up to 100 characters).")); | |
| 722 | 723 | if (!isDate(input.due)) |
| 723 | return within(db, who, dealId, fail("invalid", "The date is a date (YYYY-MM-DD).")); | |
| 724 | return within(db, who, "date.add", dealId, fail("invalid", "The date is a date (YYYY-MM-DD).")); | |
| 724 | 725 | if (!isPartyRole(input.owes)) |
| 725 | return within(db, who, dealId, fail("invalid", "Say which party owes it.")); | |
| 726 | return within(db, who, "date.add", dealId, fail("invalid", "Say which party owes it.")); | |
| 726 | 727 | const what = input.what === undefined || input.what === "" ? "" : line(input.what, 1, 200); |
| 727 | 728 | if (what === undefined) |
| 728 | return within(db, who, dealId, fail("invalid", "What is owed is up to 200 characters.")); | |
| 729 | return within(db, who, "date.add", dealId, fail("invalid", "What is owed is up to 200 characters.")); | |
| 729 | 730 | const made = db |
| 730 | 731 | .query<Deadline, [number, string, string, string, string]>( |
| 731 | 732 | "INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5) RETURNING *", |
| 732 | 733 | ) |
| 733 | 734 | .get(deal.value.id, label, input.due, input.owes, what)!; |
| 734 | return within(db, who, dealId, ok(made)); | |
| 735 | return within(db, who, "date.add", dealId, ok(made)); | |
| 735 | 736 | } |
| 736 | 737 | |
| 737 | 738 | /** A party's name and contact, checked: the same rules to add one and to correct one. */ |
| @@ -751,17 +752,17 @@ export function addParty( | ||
| 751 | 752 | ): Result<Party> { |
| 752 | 753 | const deal = dealFor(db, who, "update", input.dealId); |
| 753 | 754 | const dealId = deal.ok ? deal.value.id : undefined; |
| 754 | if (!deal.ok) return within(db, who, Number.isInteger(input.dealId) ? input.dealId : undefined, deal); | |
| 755 | if (!deal.ok) return within(db, who, "party.add", Number.isInteger(input.dealId) ? input.dealId : undefined, deal); | |
| 755 | 756 | if (!isPartyRole(input.role)) |
| 756 | return within(db, who, dealId, fail("invalid", "A party is a buyer, seller, lender, title company or the other agent.")); | |
| 757 | return within(db, who, "party.add", dealId, fail("invalid", "A party is a buyer, seller, lender, title company or the other agent.")); | |
| 757 | 758 | const text = partyText(input); |
| 758 | if (!text.ok) return within(db, who, dealId, text); | |
| 759 | if (!text.ok) return within(db, who, "party.add", dealId, text); | |
| 759 | 760 | const made = db |
| 760 | 761 | .query<Party, [number, string, string, string]>( |
| 761 | 762 | "INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4) RETURNING *", |
| 762 | 763 | ) |
| 763 | 764 | .get(deal.value.id, input.role, text.value.name, text.value.contact)!; |
| 764 | return within(db, who, dealId, ok(made)); | |
| 765 | return within(db, who, "party.add", dealId, ok(made)); | |
| 765 | 766 | } |
| 766 | 767 | |
| 767 | 768 | /** The party and its deal, when `who` may change the deal. */ |
| @@ -794,15 +795,15 @@ export function editParty( | ||
| 794 | 795 | input: { id: number; dealId?: number; name: unknown; contact?: unknown }, |
| 795 | 796 | ): Result<Party> { |
| 796 | 797 | const { dealId, found } = partyFor(db, who, input.id, input.dealId); |
| 797 | if (!found.ok) return within(db, who, dealId, found); | |
| 798 | if (!found.ok) return within(db, who, "party.edit", dealId, found); | |
| 798 | 799 | const text = partyText(input); |
| 799 | if (!text.ok) return within(db, who, dealId, text); | |
| 800 | if (!text.ok) return within(db, who, "party.edit", dealId, text); | |
| 800 | 801 | const made = db |
| 801 | 802 | .query<Party, [string, string, number]>( |
| 802 | 803 | "UPDATE party SET name = ?1, contact = ?2 WHERE id = ?3 RETURNING *", |
| 803 | 804 | ) |
| 804 | 805 | .get(text.value.name, text.value.contact, input.id)!; |
| 805 | return within(db, who, dealId, ok(made)); | |
| 806 | return within(db, who, "party.edit", dealId, ok(made)); | |
| 806 | 807 | } |
| 807 | 808 | |
| 808 | 809 | /** |
| @@ -815,9 +816,9 @@ export function removeParty( | ||
| 815 | 816 | input: { id: number; dealId?: number }, |
| 816 | 817 | ): Result<{ id: number }> { |
| 817 | 818 | const { dealId, found } = partyFor(db, who, input.id, input.dealId); |
| 818 | if (!found.ok) return within(db, who, dealId, found); | |
| 819 | if (!found.ok) return within(db, who, "party.remove", dealId, found); | |
| 819 | 820 | db.query("DELETE FROM party WHERE id = ?1").run(input.id); |
| 820 | return within(db, who, dealId, ok({ id: input.id })); | |
| 821 | return within(db, who, "party.remove", dealId, ok({ id: input.id })); | |
| 821 | 822 | } |
| 822 | 823 | |
| 823 | 824 | /** What a party or a date is called, for a notice saying it was removed. */ |
| @@ -843,16 +844,17 @@ export function removeDeadline( | ||
| 843 | 844 | input: { id: number; dealId?: number }, |
| 844 | 845 | ): Result<{ id: number }> { |
| 845 | 846 | const { dealId, found } = deadlineFor(db, who, input.id, input.dealId); |
| 846 | if (!found.ok) return within(db, who, dealId, found); | |
| 847 | if (!found.ok) return within(db, who, "date.remove", dealId, found); | |
| 847 | 848 | if (found.value.deadline.kind !== "custom") |
| 848 | 849 | return within( |
| 849 | 850 | db, |
| 850 | 851 | who, |
| 852 | "date.remove", | |
| 851 | 853 | dealId, |
| 852 | 854 | fail("invalid", "A standard contract date cannot be removed; move it or mark it done."), |
| 853 | 855 | ); |
| 854 | 856 | db.query("DELETE FROM deadline WHERE id = ?1").run(input.id); |
| 855 | return within(db, who, dealId, ok({ id: input.id })); | |
| 857 | return within(db, who, "date.remove", dealId, ok({ id: input.id })); | |
| 856 | 858 | } |
| 857 | 859 | |
| 858 | 860 | /** |
| @@ -866,16 +868,16 @@ export function sendReminder( | ||
| 866 | 868 | input: { deadlineId: number; partyId: number; moment: unknown; subject?: unknown; body?: unknown; agent?: Agent }, |
| 867 | 869 | ): Result<Sent> { |
| 868 | 870 | const { dealId, found } = deadlineFor(db, who, input.deadlineId); |
| 869 | if (!found.ok) return within(db, who, dealId, found); | |
| 871 | if (!found.ok) return within(db, who, "reminder.send", dealId, found); | |
| 870 | 872 | if (!isMoment(input.moment)) |
| 871 | return within(db, who, dealId, fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed.")); | |
| 873 | return within(db, who, "reminder.send", dealId, fail("invalid", "A reminder is for three days before, the day of, the day after (overdue), or a date that changed.")); | |
| 872 | 874 | const party = Number.isInteger(input.partyId) |
| 873 | 875 | ? db |
| 874 | 876 | .query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2") |
| 875 | 877 | .get(input.partyId, found.value.deal.id) |
| 876 | 878 | : null; |
| 877 | 879 | if (party === null) |
| 878 | return within(db, who, dealId, fail("not_found", "No such party on this deal.")); | |
| 880 | return within(db, who, "reminder.send", dealId, fail("not_found", "No such party on this deal.")); | |
| 879 | 881 | const { deadline } = found.value; |
| 880 | 882 | const seen = view(db, found.value.deal); |
| 881 | 883 | const draft = draftsFor( |
| @@ -884,23 +886,23 @@ export function sendReminder( | ||
| 884 | 886 | input.agent ?? agentOf(db), |
| 885 | 887 | ).find((r) => r.party_id === party.id && r.moment === input.moment); |
| 886 | 888 | if (draft === undefined && input.moment === "moved") |
| 887 | return within(db, who, dealId, fail("not_found", "No such reminder on this date.")); | |
| 889 | return within(db, who, "reminder.send", dealId, fail("not_found", "No such reminder on this date.")); | |
| 888 | 890 | if (draft?.declined != null) |
| 889 | return within(db, who, dealId, fail("invalid", "This reminder was declined; undo that first to send it.")); | |
| 891 | return within(db, who, "reminder.send", dealId, fail("invalid", "This reminder was declined; undo that first to send it.")); | |
| 890 | 892 | const subject = |
| 891 | 893 | input.subject === undefined ? draft?.subject : line(input.subject, 1, SUBJECT_MAX); |
| 892 | 894 | if (subject === undefined) |
| 893 | return within(db, who, dealId, fail("invalid", `The subject is 1 to ${SUBJECT_MAX} characters.`)); | |
| 895 | return within(db, who, "reminder.send", dealId, fail("invalid", `The subject is 1 to ${SUBJECT_MAX} characters.`)); | |
| 894 | 896 | const body = input.body === undefined ? draft?.body : message(input.body, 1, BODY_MAX); |
| 895 | 897 | if (body === undefined) |
| 896 | return within(db, who, dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`)); | |
| 898 | return within(db, who, "reminder.send", dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`)); | |
| 897 | 899 | const sent = db |
| 898 | 900 | .query<SentRow, [number, number, number, string, string, string, string, string, number, string, string, string]>( |
| 899 | 901 | `INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, move_id, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) |
| 900 | 902 | ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`, |
| 901 | 903 | ) |
| 902 | 904 | .get(found.value.deal.id, deadline.id, party.id, draft?.label ?? deadline.label, party.name, party.role, input.moment, draft?.due ?? deadline.due, draft?.move_id ?? 0, authorOf(who).name, subject, body)!; |
| 903 | return within(db, who, dealId, ok(withHref(sent, [party]))); | |
| 905 | return within(db, who, "reminder.send", dealId, ok(withHref(sent, [party]))); | |
| 904 | 906 | } |
| 905 | 907 | |
| 906 | 908 | /** The draft one decline or undo names, on a date `who` may change. */ |
| @@ -939,20 +941,20 @@ export function declineReminder( | ||
| 939 | 941 | input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; reason: unknown; agent?: Agent }, |
| 940 | 942 | ): Result<Declined> { |
| 941 | 943 | const { dealId, found } = draftOf(db, who, input); |
| 942 | if (!found.ok) return within(db, who, dealId, found); | |
| 944 | if (!found.ok) return within(db, who, "reminder.decline", dealId, found); | |
| 943 | 945 | const reason = line(input.reason, 1, REASON_MAX); |
| 944 | 946 | if (reason === undefined) |
| 945 | return within(db, who, dealId, fail("invalid", `Say why in 1 to ${REASON_MAX} characters.`)); | |
| 947 | return within(db, who, "reminder.decline", dealId, fail("invalid", `Say why in 1 to ${REASON_MAX} characters.`)); | |
| 946 | 948 | const { draft, deal } = found.value; |
| 947 | 949 | if (draft.sent_at !== null) |
| 948 | return within(db, who, dealId, fail("invalid", "This reminder was already sent.")); | |
| 950 | return within(db, who, "reminder.decline", dealId, fail("invalid", "This reminder was already sent.")); | |
| 949 | 951 | const declined = db |
| 950 | 952 | .query<Declined, [number, number, number, string, string, string, string, number, string, string]>( |
| 951 | 953 | `INSERT INTO reminder_declined (deal_id, deadline_id, party_id, label, party_name, moment, due, move_id, reason, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) |
| 952 | 954 | ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET reason = excluded.reason, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`, |
| 953 | 955 | ) |
| 954 | 956 | .get(deal.id, draft.deadline_id, draft.party_id, draft.label, draft.party_name, draft.moment, draft.due, draft.move_id, reason, authorOf(who).name)!; |
| 955 | return within(db, who, dealId, ok(declined)); | |
| 957 | return within(db, who, "reminder.decline", dealId, ok(declined)); | |
| 956 | 958 | } |
| 957 | 959 | |
| 958 | 960 | /** Take back a decline: the reminder is a draft again. */ |
| @@ -962,7 +964,7 @@ export function undoDecline( | ||
| 962 | 964 | input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent }, |
| 963 | 965 | ): Result<{ id: number }> { |
| 964 | 966 | const { dealId, found } = draftOf(db, who, input); |
| 965 | if (!found.ok) return within(db, who, dealId, found); | |
| 967 | if (!found.ok) return within(db, who, "reminder.undo", dealId, found); | |
| 966 | 968 | const { draft } = found.value; |
| 967 | 969 | const gone = db |
| 968 | 970 | .query<{ id: number }, [number, number, string, string, number]>( |
| @@ -970,6 +972,6 @@ export function undoDecline( | ||
| 970 | 972 | ) |
| 971 | 973 | .get(draft.deadline_id, draft.party_id, draft.moment, draft.due, draft.move_id); |
| 972 | 974 | if (gone === null) |
| 973 | return within(db, who, dealId, fail("invalid", "This reminder was not declined.")); | |
| 974 | return within(db, who, dealId, ok({ id: gone.id })); | |
| 975 | return within(db, who, "reminder.undo", dealId, fail("invalid", "This reminder was not declined.")); | |
| 976 | return within(db, who, "reminder.undo", dealId, ok({ id: gone.id })); | |
| 975 | 977 | } |
src/pages/activity.ts added +50
| @@ -0,0 +1,50 @@ | ||
| 1 | /** | |
| 2 | * Activity at `/activity`: the audit trail as plain-English lines, newest | |
| 3 | * first — who, what, on which deal, when, and whether it was refused — so | |
| 4 | * "a human approves every message" can be shown. Only for whoever the table | |
| 5 | * lets list the audit (`permit`), a hundred rows to a page. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import type { AuditRow } from "../audit.ts"; | |
| 10 | import { ACTIVITY_PAGE, addresses, refusal, when, wording } from "../activity.ts"; | |
| 11 | import { escape } from "../http.ts"; | |
| 12 | import type { Agent } from "../reminders.ts"; | |
| 13 | import type { Who } from "../who.ts"; | |
| 14 | import { layout } from "./layout.ts"; | |
| 15 | ||
| 16 | export function activityPage(input: { | |
| 17 | who: Who; | |
| 18 | agent?: Agent | undefined; | |
| 19 | db: Database; | |
| 20 | /** Up to one more than a page: the extra says there are older rows. */ | |
| 21 | rows: readonly AuditRow[]; | |
| 22 | only: boolean; | |
| 23 | }): string { | |
| 24 | const { who, agent, db, only } = input; | |
| 25 | const rows = input.rows.slice(0, ACTIVITY_PAGE); | |
| 26 | const older = input.rows.length > ACTIVITY_PAGE; | |
| 27 | const deals = addresses(db, rows); | |
| 28 | const line = (r: AuditRow): string => { | |
| 29 | const address = r.resource === "deal" && r.target !== null ? deals.get(r.target) : undefined; | |
| 30 | const on = | |
| 31 | address !== undefined | |
| 32 | ? ` on <a href="/deals/${escape(r.target!)}">${escape(address)}</a>` | |
| 33 | : r.resource === "deal" && r.target !== null | |
| 34 | ? ` on deal ${escape(r.target)} (no longer here)` | |
| 35 | : ""; | |
| 36 | const refused = r.outcome === "ok" ? "" : ` · <b class="u-overdue">Refused</b>: ${escape(refusal(r.outcome))}`; | |
| 37 | return `<li><b>${r.who_name === null ? "someone not signed in" : escape(r.who_name)}</b> ${escape(wording(r))}${on} <span class="muted">· ${escape(when(r.at))}</span>${refused}</li>`; | |
| 38 | }; | |
| 39 | const filter = only | |
| 40 | ? `<a href="/activity">Everything</a> · <b>Messages</b>` | |
| 41 | : `<b>Everything</b> · <a href="/activity?only=messages">Messages</a>`; | |
| 42 | const next = older | |
| 43 | ? `<p><a class="button button-quiet" href="/activity?before=${rows[rows.length - 1]!.id}${only ? "&only=messages" : ""}">Older</a></p>` | |
| 44 | : ""; | |
| 45 | const body = `<h1>Activity</h1> | |
| 46 | <p class="summary">Who approved, declined or changed what, newest first. ${filter}</p> | |
| 47 | ${rows.length === 0 ? `<p class="muted">Nothing yet.</p>` : `<ul class="stack">${rows.map(line).join("")}</ul>`} | |
| 48 | ${next}`; | |
| 49 | return layout({ body, who, agent, path: "/activity", heading: "Activity", live: false }); | |
| 50 | } |
src/pages/layout.ts +2 −1
| @@ -20,6 +20,7 @@ import { labelOf, NO_CONTACT } from "../outbox.ts"; | ||
| 20 | 20 | import { contactLinks } from "./contact.ts"; |
| 21 | 21 | import { token, tokensHref } from "../tokens.ts"; |
| 22 | 22 | import type { Agent } from "../reminders.ts"; |
| 23 | import { permit } from "../contract.ts"; | |
| 23 | 24 | import type { Who } from "../who.ts"; |
| 24 | 25 | |
| 25 | 26 | const iconHref = asset("icon.svg"); |
| @@ -84,7 +85,7 @@ ${plain || input.live === false ? "" : `<script type="module" src="${asset("live | ||
| 84 | 85 | ? "" |
| 85 | 86 | : `<nav class="row"> |
| 86 | 87 | ${env === "production" ? "" : `<span class="pill" data-env="${escape(env)}">${escape(where)}</span>`} |
| 87 | ${who.role === "anon" ? "" : `<a class="button button-quiet" href="/">Clock</a> <a class="button button-quiet" href="/people">People</a> <a class="button button-quiet" href="/profile">Profile</a>`} | |
| 88 | ${who.role === "anon" ? "" : `<a class="button button-quiet" href="/">Clock</a> <a class="button button-quiet" href="/people">People</a> <a class="button button-quiet" href="/profile">Profile</a>${permit(who, "audit", "list") === "yes" ? ` <a class="button button-quiet" href="/activity">Activity</a>` : ""}`} | |
| 88 | 89 | ${door} |
| 89 | 90 | </nav>` |
| 90 | 91 | } |
src/result.ts +2
| @@ -39,6 +39,7 @@ export const audited = <T extends { readonly id: number }>( | ||
| 39 | 39 | verb: "create" | "update" | "delete", |
| 40 | 40 | target: number | undefined, |
| 41 | 41 | result: Result<T>, |
| 42 | what?: string, | |
| 42 | 43 | ): Result<T> => { |
| 43 | 44 | record(db, { |
| 44 | 45 | who, |
| @@ -46,6 +47,7 @@ export const audited = <T extends { readonly id: number }>( | ||
| 46 | 47 | verb, |
| 47 | 48 | target: target ?? (result.ok ? result.value.id : undefined), |
| 48 | 49 | outcome: result.ok ? "ok" : result.error, |
| 50 | ...(what === undefined ? {} : { what }), | |
| 49 | 51 | }); |
| 50 | 52 | return result; |
| 51 | 53 | }; |
src/routes.ts +23
| @@ -79,6 +79,8 @@ import { refusedPage } from "./pages/refused.ts"; | ||
| 79 | 79 | import { people } from "./people.ts"; |
| 80 | 80 | import { reviewHref, reviewPage, type ReviewField } from "./pages/review.ts"; |
| 81 | 81 | import { peoplePage } from "./pages/people.ts"; |
| 82 | import { activityPage } from "./pages/activity.ts"; | |
| 83 | import { ACTIVITY_PAGE } from "./activity.ts"; | |
| 82 | 84 | import { timelinePage } from "./pages/timeline.ts"; |
| 83 | 85 | import { welcomePage } from "./pages/welcome.ts"; |
| 84 | 86 | import { dueOn, remindsLine, todaysDrafts, unsent, type Draft } from "./reminders.ts"; |
| @@ -131,6 +133,7 @@ export const AUDIT_ROW: Schema = { | ||
| 131 | 133 | target: { type: ["string", "null"] }, |
| 132 | 134 | allowed: { enum: [0, 1] }, |
| 133 | 135 | outcome: { type: "string" }, |
| 136 | what: { type: ["string", "null"] }, | |
| 134 | 137 | }, |
| 135 | 138 | required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"], |
| 136 | 139 | }; |
| @@ -500,6 +503,26 @@ export const routes: readonly Route[] = [ | ||
| 500 | 503 | return html(peoplePage({ who: c.who, agent: agentOf(c.db), people: people(deals.value, today()), on: today() })); |
| 501 | 504 | }, |
| 502 | 505 | }, |
| 506 | { | |
| 507 | method: "GET", | |
| 508 | path: "/activity", | |
| 509 | handle: (c) => { | |
| 510 | const before = c.url.searchParams.get("before"); | |
| 511 | const only = c.url.searchParams.get("only"); | |
| 512 | const bad = (before !== null && whole(before) === undefined) || (only !== null && only !== "messages"); | |
| 513 | const got = listAudit(c.db, c.who, { | |
| 514 | limit: ACTIVITY_PAGE + 1, | |
| 515 | ...(bad || before === null ? {} : { before: whole(before)! }), | |
| 516 | ...(!bad && only === "messages" ? { only } : {}), | |
| 517 | }); | |
| 518 | const path = "/activity"; | |
| 519 | if (!got.ok) | |
| 520 | return html(refusedPage({ who: c.who, agent: agentOf(c.db), path, heading: "Activity", error: got.error, message: got.message }), STATUS[got.error]); | |
| 521 | if (bad) | |
| 522 | return html(refusedPage({ who: c.who, agent: agentOf(c.db), path, heading: "Activity", error: "invalid", message: "Older is a whole number, and the only filter is messages." }), 400); | |
| 523 | return html(activityPage({ who: c.who, agent: agentOf(c.db), db: c.db, rows: got.value, only: only === "messages" })); | |
| 524 | }, | |
| 525 | }, | |
| 503 | 526 | { |
| 504 | 527 | method: "GET", |
| 505 | 528 | path: "/deals/ics", |
src/terminal.test.ts +44
| @@ -652,3 +652,47 @@ test("M amends the contract: a blank answer keeps a date, the rest move together | ||
| 652 | 652 | press(t, "M", ...open.flatMap(() => ["\r"]), ..."x", "\r"); |
| 653 | 653 | expect(lines(t).join("\n")).toContain("Nothing changed"); |
| 654 | 654 | }); |
| 655 | ||
| 656 | test("L reads the audit trail in words for an admin, filters to messages and pages; a user and a guest are refused", () => { | |
| 657 | const root: Who = { role: "admin", id: "u0", name: "root" }; | |
| 658 | // A book of its own, so the newest rows are these. | |
| 659 | const db = openDb(mkdtempSync(join(tmpdir(), "app-terminal-activity-"))); | |
| 660 | const mine = createDeal(db, alice, { address: "7 Trail Row", buyer: "Ann", seller: "Sam", contractDate: today(), closingDate: addDays(today(), 45) }); | |
| 661 | if (!mine.ok) throw new Error(mine.message); | |
| 662 | const inspection = mine.value.deadlines.find((d) => d.kind === "inspection")!; | |
| 663 | const party = db.query<{ id: number }, [number]>("SELECT id FROM party WHERE deal_id = ?1 LIMIT 1").get(mine.value.id)!; | |
| 664 | expect(sendReminder(db, alice, { deadlineId: inspection.id, partyId: party.id, moment: "before" }).ok).toBe(true); | |
| 665 | expect(moveDeadline(db, alice, { id: inspection.id, due: addDays(today(), 20), reason: "Seller asked" }).ok).toBe(true); | |
| 666 | const t = terminal(db, root, context); | |
| 667 | press(t, "L"); | |
| 668 | let screen = lines(t).join("\n"); | |
| 669 | expect(screen).toContain("Activity"); | |
| 670 | expect(screen).toContain("alice sent a reminder on 7 Trail Row"); | |
| 671 | expect(screen).toContain("alice moved a date on 7 Trail Row"); | |
| 672 | press(t, "m"); | |
| 673 | screen = lines(t).join("\n"); | |
| 674 | expect(screen).toContain("Activity — messages"); | |
| 675 | expect(screen).toContain("sent a reminder"); | |
| 676 | expect(screen).not.toContain("moved a date"); | |
| 677 | press(t, "m"); | |
| 678 | const insert = db.query("INSERT INTO audit (who_id, who_name, role, resource, verb, allowed, outcome, what) VALUES ('u1','pager','user','profile','update',1,'ok',NULL)"); | |
| 679 | for (let i = 0; i < 25; i++) insert.run(); | |
| 680 | press(t, "L"); | |
| 681 | expect(lines(t).join("\n")).toContain("pager saved the profile"); | |
| 682 | press(t, "o"); | |
| 683 | expect(lines(t).join("\n")).toContain("pager saved the profile"); | |
| 684 | press(t, "o"); | |
| 685 | expect(lines(t).join("\n")).toContain("alice sent a reminder"); | |
| 686 | press(t, "y", "y"); | |
| 687 | expect(lines(t).join("\n")).toContain("pager saved the profile"); | |
| 688 | press(t, "y"); | |
| 689 | expect(lines(t).join("\n")).toContain("This is the newest."); | |
| 690 | ||
| 691 | const user = terminal(db, alice, context); | |
| 692 | press(user, "L"); | |
| 693 | expect(lines(user).join("\n")).toContain("Only an admin can read the audit trail."); | |
| 694 | expect(lines(user).join("\n")).not.toContain("sent a reminder"); | |
| 695 | const guest = terminal(db, { role: "anon" } as Who, context); | |
| 696 | press(guest, "L"); | |
| 697 | expect(lines(guest).join("\n")).toContain("Sign in to read the audit trail."); | |
| 698 | }); |
src/terminal.ts +61 −3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * reminders what goes out today; enter reads a draft, e edits its words, s sends it |
| 9 | 9 | * people each person on the deals with every open date they owe (P) |
| 10 | 10 | * timeline a deal's dates as a client would get them (t on a deal) |
| 11 | * activity who approved, declined or changed what, newest first (L, admins); m only messages, o older, y newer | |
| 11 | 12 | * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults |
| 12 | 13 | * deal one deal's dates and parties; a adds a date, p a party, A corrects the address, M amends the contract, D removes it |
| 13 | 14 | * |
| @@ -58,18 +59,23 @@ import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts"; | ||
| 58 | 59 | import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts"; |
| 59 | 60 | import { permit } from "./contract.ts"; |
| 60 | 61 | import { drafts, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts"; |
| 62 | import type { AuditRow } from "./audit.ts"; | |
| 61 | 63 | import type { Result } from "./result.ts"; |
| 62 | 64 | import type { Who } from "./who.ts"; |
| 63 | 65 | import { people } from "./people.ts"; |
| 66 | import { addresses, refusal, when, wording } from "./activity.ts"; | |
| 67 | import { listAudit } from "./actions.ts"; | |
| 64 | 68 | import { owner, thisWeek } from "./week.ts"; |
| 65 | 69 | |
| 66 | 70 | const esc = "\x1b["; |
| 67 | 71 | const dim = (s: string): string => `${esc}2m${s}${esc}0m`; |
| 68 | 72 | const bold = (s: string): string => `${esc}1m${s}${esc}0m`; |
| 73 | /** Audit rows to a screen. */ | |
| 74 | const ACTIVITY_ROWS = 20; | |
| 69 | 75 | const COLOUR: Readonly<Record<Urgency, string>> = { overdue: "31", soon: "33", later: "36", done: "2" }; |
| 70 | 76 | const tint = (u: Urgency, s: string): string => `${esc}${COLOUR[u]}m${s}${esc}0m`; |
| 71 | 77 | |
| 72 | type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline" | "profile"; | |
| 78 | type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline" | "profile" | "activity"; | |
| 73 | 79 | interface Row { |
| 74 | 80 | readonly deal: DealView; |
| 75 | 81 | readonly date: DeadlineView; |
| @@ -111,6 +117,9 @@ export function terminal( | ||
| 111 | 117 | /** What `/` narrowed the deals to; empty is all of them. */ |
| 112 | 118 | let found = ""; |
| 113 | 119 | let done = false; |
| 120 | /** Activity: only messages, and the `before` ids of the pages already passed (the last is the page shown). */ | |
| 121 | let onlyMessages = false; | |
| 122 | let trail: number[] = []; | |
| 114 | 123 | |
| 115 | 124 | const deals = (): DealView[] => { |
| 116 | 125 | const listed = listDeals(db, me); |
| @@ -321,6 +330,32 @@ export function terminal( | ||
| 321 | 330 | return true; |
| 322 | 331 | } |
| 323 | 332 | |
| 333 | /** The page of the audit trail now shown: up to a screenful and whether older rows wait. */ | |
| 334 | function activityRows(): Result<{ rows: AuditRow[]; older: boolean }> { | |
| 335 | const before = trail[trail.length - 1]; | |
| 336 | const got = listAudit(db, me, { | |
| 337 | limit: ACTIVITY_ROWS + 1, | |
| 338 | ...(before === undefined ? {} : { before }), | |
| 339 | ...(onlyMessages ? { only: "messages" as const } : {}), | |
| 340 | }); | |
| 341 | return got.ok ? { ok: true, value: { rows: got.value.slice(0, ACTIVITY_ROWS), older: got.value.length > ACTIVITY_ROWS } } : got; | |
| 342 | } | |
| 343 | ||
| 344 | function onActivity(key: string): void { | |
| 345 | if (key === "m") { | |
| 346 | onlyMessages = !onlyMessages; | |
| 347 | trail = []; | |
| 348 | } else if (key === "o") { | |
| 349 | const page = activityRows(); | |
| 350 | const last = page.ok && page.value.older ? page.value.rows[page.value.rows.length - 1] : undefined; | |
| 351 | if (last !== undefined) trail.push(last.id); | |
| 352 | else said = "No older activity."; | |
| 353 | } else if (key === "y") { | |
| 354 | if (trail.length === 0) said = "This is the newest."; | |
| 355 | else trail.pop(); | |
| 356 | } | |
| 357 | } | |
| 358 | ||
| 324 | 359 | function onProfile(key: string): void { |
| 325 | 360 | if (key !== "e" && key !== "U") return; |
| 326 | 361 | if (permit(me, "profile", "update") !== "yes") { |
| @@ -436,6 +471,11 @@ export function terminal( | ||
| 436 | 471 | } else if (key === "I") { |
| 437 | 472 | view = "profile"; |
| 438 | 473 | cursor = 0; |
| 474 | } else if (key === "L") { | |
| 475 | view = "activity"; | |
| 476 | cursor = 0; | |
| 477 | onlyMessages = false; | |
| 478 | trail = []; | |
| 439 | 479 | } else if (key === "r") { |
| 440 | 480 | view = "reminders"; |
| 441 | 481 | cursor = 0; |
| @@ -493,6 +533,7 @@ export function terminal( | ||
| 493 | 533 | cursor = 0; |
| 494 | 534 | } else if (view === "reminders") onReminder(key); |
| 495 | 535 | else if (view === "profile") onProfile(key); |
| 536 | else if (view === "activity") onActivity(key); | |
| 496 | 537 | else if (view === "messages" || view === "timeline") return; |
| 497 | 538 | else if (!(view === "deal" && onDeal(key))) onDate(key); |
| 498 | 539 | cursor = Math.min(cursor, Math.max(0, rowCount() - 1)); |
| @@ -560,6 +601,21 @@ export function terminal( | ||
| 560 | 601 | lines.push(` ${tint(o.urgency, `${spoken(o.due).padEnd(12)} ${relative(o.due, day).padEnd(12)}`)} ${o.label} — ${o.address}`); |
| 561 | 602 | } |
| 562 | 603 | } |
| 604 | } else if (view === "activity") { | |
| 605 | const page = activityRows(); | |
| 606 | if (!page.ok) lines.push(page.message); | |
| 607 | else { | |
| 608 | const names = addresses(db, page.value.rows); | |
| 609 | lines.push(bold(onlyMessages ? "Activity — messages" : "Activity"), dim("Who approved, declined or changed what, newest first."), ""); | |
| 610 | if (page.value.rows.length === 0) lines.push(dim("Nothing yet.")); | |
| 611 | for (const r of page.value.rows) { | |
| 612 | const address = r.resource === "deal" && r.target !== null ? names.get(r.target) : undefined; | |
| 613 | const on = address !== undefined ? ` on ${address}` : r.resource === "deal" && r.target !== null ? ` on deal ${r.target} (no longer here)` : ""; | |
| 614 | lines.push( | |
| 615 | ` ${bold(r.who_name ?? "someone not signed in")} ${wording(r)}${on} ${dim(`· ${when(r.at)}`)}${r.outcome === "ok" ? "" : ` ${tint("overdue", `Refused: ${refusal(r.outcome)}`)}`}`, | |
| 616 | ); | |
| 617 | } | |
| 618 | } | |
| 563 | 619 | } else if (view === "profile") { |
| 564 | 620 | const got = getProfile(db, me); |
| 565 | 621 | if (!got.ok) lines.push(got.message); |
| @@ -633,7 +689,9 @@ export function terminal( | ||
| 633 | 689 | else { |
| 634 | 690 | if (said !== "") lines.push(...said.split("\n")); |
| 635 | 691 | const keys = |
| 636 | view === "profile" | |
| 692 | view === "activity" | |
| 693 | ? `m ${onlyMessages ? "everything" : "only messages"} · o older · y newer · d dates · q quit` | |
| 694 | : view === "profile" | |
| 637 | 695 | ? permit(me, "profile", "update") === "yes" |
| 638 | 696 | ? "e edit · U use defaults · d dates · q quit" |
| 639 | 697 | : "d dates · q quit (only an admin changes the profile)" |
| @@ -647,7 +705,7 @@ export function terminal( | ||
| 647 | 705 | ? "b back to the deal · d dates · q quit" |
| 648 | 706 | : view === "deal" |
| 649 | 707 | ? "j/k move · t client timeline · s messages · x done · u reopen · m move · l remind lead · a add date · p add party · e edit party · A edit address · M amend the contract · X remove date/party · D remove deal · b back · q quit" |
| 650 | : `j/k move · x done · u reopen · m move · l lead · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · q quit`; | |
| 708 | : `j/k move · x done · u reopen · m move · l lead · o open deal · n new deal · c check dates · / find · R restore samples · h ${showDone ? "hide" : "show"} done · w this week · r reminders · P people · I profile · L activity · q quit`; | |
| 651 | 709 | lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys)); |
| 652 | 710 | } |
| 653 | 711 | return lines; |
new above
offline
This is the only door to Activity. src/tty.ts has no matching command, so the terminal cannot read the audit trail. Add one that calls listAudit and uses wording().