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

Merged opened this

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

Merged

mason/deal-clock:mason/80-an-admin-reads-who-approved-declined-or → main 2 commits fork 1 thread · 1 unresolved

  • Merged. mason/80-an-admin-reads-who-approved-declined-or was merged into main as be8a61d.

Review

Sign in to review this change.
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
146146 the deal-clock mark sits beside the app's name, and it opens full screen
147147 like any app. The same mark is the browser tab's icon.
148148
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
149161 ## Make it yours
150162
151163 The app ships with a sample agent. To carry your own, open **Profile** in the
contract/openapi.json +6
@@ -1801,6 +1801,12 @@
18011801 },
18021802 "outcome": {
18031803 "type": "string"
1804 },
1805 "what": {
1806 "type": [
1807 "string",
1808 "null"
1809 ]
18041810 }
18051811 },
18061812 "required": [
docs/TECHNICAL.md +9 −1
@@ -153,6 +153,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
153153 | `src/contract.ts`, `src/can.ts` | the table, read at boot; the forge's evaluator, verbatim |
154154 | `src/security.ts` | the door: rationing, same origin, the table before the body |
155155 | `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 |
156157 | `src/who.ts` | who is asking, from the forge's signed headers |
157158 | `src/db.ts` | SQLite under `FORGE_APP_DATA`, WAL, forward-only migrations |
158159 | `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.
176177 else. The action still decides about the real row.
177178 - **The audit trail.** Every change, and every change refused, is a row:
178179 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
180188 is a log line, never a failed request.
181189 - **The API, described.** `GET /openapi.json` is `contract/openapi.json`,
182190 written from the routes by `bun run contract:emit`; each operation names
src/actions.ts +9 −4
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import type { AuditRow } from "./audit.ts";
10 import { MESSAGE_WHATS, type AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
1212 import { emit } from "./live.ts";
1313 import { audited, fail, ok, refuse, type Result } from "./result.ts";
@@ -18,14 +18,15 @@ export type { Failure, Result } from "./result.ts";
1818
1919 /**
2020 * 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
2223 * no author, so a cell that gave `list` to a row's role would find nothing
2324 * of its own: anything but "yes" is a refusal here.
2425 */
2526 export function listAudit(
2627 db: Database,
2728 who: Who,
28 input: { limit?: number; before?: number } = {},
29 input: { limit?: number; before?: number; only?: "messages" } = {},
2930 ): Result<AuditRow[]> {
3031 if (permit(who, "audit", "list") !== "yes")
3132 return refuse(
@@ -40,12 +41,16 @@ export function listAudit(
4041 const before = Number.isInteger(input.before)
4142 ? input.before!
4243 : Number.MAX_SAFE_INTEGER;
44 const kept =
45 input.only === "messages"
46 ? ` AND what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")})`
47 : "";
4348 return ok(
4449 db
4550 .query<
4651 AuditRow,
4752 [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`)
4954 .all(before, limit),
5055 );
5156 }
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 &lt;b&gt;");
47 expect(page).not.toContain("alice <b>");
48 expect(page).toContain(`<a href="/deals/${dealId}">9 &lt;i&gt;Audit&lt;/i&gt; 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 {
2828 readonly allowed: 0 | 1;
2929 /** `ok`, or the failure: `signin_required`, `forbidden`, `invalid`, `not_found`, `cross_site`. */
3030 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;
3133 }
3234
3335 export interface Attempt {
@@ -36,8 +38,12 @@ export interface Attempt {
3638 readonly verb: string;
3739 readonly target?: string | number | undefined;
3840 readonly outcome: string;
41 readonly what?: string | undefined;
3942 }
4043
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
4147 /** The newest rows kept; older ones go as new ones come. */
4248 export const KEEP = 50_000;
4349
@@ -48,7 +54,7 @@ export const allowed = (outcome: string): boolean =>
4854 outcome !== "cross_site";
4955
5056 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;
5258 const row = {
5359 who_id: who.role === "anon" ? null : who.id,
5460 who_name: who.role === "anon" ? null : who.name,
@@ -58,11 +64,12 @@ export function record(db: Database, attempt: Attempt): void {
5864 target: target === undefined ? null : String(target),
5965 allowed: allowed(outcome) ? 1 : 0,
6066 outcome,
67 what: what ?? null,
6168 };
6269 try {
6370 const { lastInsertRowid } = db
6471 .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)",
6673 )
6774 .run(
6875 row.who_id,
@@ -73,6 +80,7 @@ export function record(db: Database, attempt: Attempt): void {
7380 row.target,
7481 row.allowed,
7582 row.outcome,
83 row.what,
7684 );
7785 db.query("DELETE FROM audit WHERE id <= ?1").run(
7886 Number(lastInsertRowid) - KEEP,
src/db.ts +2
@@ -323,6 +323,8 @@ export const migrations: string[] = [
323323 email TEXT NOT NULL,
324324 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
325325 )`,
326 // Which change inside a row an audit row was ("reminder.send"), for the Activity page.
327 `ALTER TABLE audit ADD COLUMN what TEXT`,
326328 ];
327329
328330 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
549549
550550 // ---- a deal's dates, parties and reminders: each an update of the deal ----
551551
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). */
553553 function within<T extends { readonly id: number }>(
554554 db: Database,
555555 who: Who,
556 what: string,
556557 dealId: number | undefined,
557558 result: Result<T>,
558559 ): Result<T> {
559 const out = audited(db, who, "deal", "update", dealId, result);
560 const out = audited(db, who, "deal", "update", dealId, result, what);
560561 if (out.ok && dealId !== undefined) emit("deal.changed", { id: dealId });
561562 return out;
562563 }
@@ -594,11 +595,11 @@ export function markDone(
594595 input: { id: number; done: boolean },
595596 ): Result<Deadline> {
596597 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);
598599 db.query(
599600 "UPDATE deadline SET done_at = ?1 WHERE id = ?2",
600601 ).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)));
602603 }
603604
604605 /** Whether `value` is a lead time: a whole number of days, 1 to 30. */
@@ -616,13 +617,13 @@ export function setReminderLead(
616617 input: { id: number; dealId?: number; leadDays: unknown },
617618 ): Result<Deadline> {
618619 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);
620621 // A form or a terminal sends text: a whole number written out is a whole number.
621622 const days = typeof input.leadDays === "string" && /^\s*\d{1,3}\s*$/.test(input.leadDays) ? Number(input.leadDays) : input.leadDays;
622623 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"));
624625 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)));
626627 }
627628
628629 /** Move one date, and only that one; the reason is kept beside it. */
@@ -632,22 +633,22 @@ export function moveDeadline(
632633 input: { id: number; due: unknown; reason: unknown },
633634 ): Result<Deadline> {
634635 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);
636637 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)."));
638639 const reason = line(input.reason, 1, 200);
639640 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)."));
641642 const { deadline } = found.value;
642643 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."));
644645 db.transaction(() => {
645646 db.query("UPDATE deadline SET due = ?1 WHERE id = ?2").run(input.due as string, deadline.id);
646647 db.query(
647648 "INSERT INTO deadline_move (deadline_id, from_due, to_due, reason, by_name, notify) VALUES (?1, ?2, ?3, ?4, ?5, 1)",
648649 ).run(deadline.id, deadline.due, input.due as string, reason, authorOf(who).name);
649650 })();
650 return within(db, who, dealId, ok(reread(db, deadline.id)));
651 return within(db, who, "date.move", dealId, ok(reread(db, deadline.id)));
651652 }
652653
653654 /** One amendment, checked: the moves it makes, or the field that was wrong and why. */
@@ -691,10 +692,10 @@ export function amendDeal(
691692 input: { dealId: number; dates: unknown; reason: unknown },
692693 ): Result<DealView> {
693694 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);
695696 const seen = view(db, found.value);
696697 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));
698699 const name = authorOf(who).name;
699700 db.transaction(() => {
700701 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(
705706 ).run(deadline.id, deadline.due, to, plan.reason, name, number);
706707 }
707708 })();
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)));
709710 }
710711
711712 export function addDeadline(
@@ -715,23 +716,23 @@ export function addDeadline(
715716 ): Result<Deadline> {
716717 const deal = dealFor(db, who, "update", input.dealId);
717718 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);
719720 const label = line(input.label, 1, 100);
720721 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)."));
722723 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)."));
724725 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."));
726727 const what = input.what === undefined || input.what === "" ? "" : line(input.what, 1, 200);
727728 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."));
729730 const made = db
730731 .query<Deadline, [number, string, string, string, string]>(
731732 "INSERT INTO deadline (deal_id, kind, label, due, owes, what) VALUES (?1, 'custom', ?2, ?3, ?4, ?5) RETURNING *",
732733 )
733734 .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));
735736 }
736737
737738 /** A party's name and contact, checked: the same rules to add one and to correct one. */
@@ -751,17 +752,17 @@ export function addParty(
751752 ): Result<Party> {
752753 const deal = dealFor(db, who, "update", input.dealId);
753754 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);
755756 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."));
757758 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);
759760 const made = db
760761 .query<Party, [number, string, string, string]>(
761762 "INSERT INTO party (deal_id, role, name, contact) VALUES (?1, ?2, ?3, ?4) RETURNING *",
762763 )
763764 .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));
765766 }
766767
767768 /** The party and its deal, when `who` may change the deal. */
@@ -794,15 +795,15 @@ export function editParty(
794795 input: { id: number; dealId?: number; name: unknown; contact?: unknown },
795796 ): Result<Party> {
796797 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);
798799 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);
800801 const made = db
801802 .query<Party, [string, string, number]>(
802803 "UPDATE party SET name = ?1, contact = ?2 WHERE id = ?3 RETURNING *",
803804 )
804805 .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));
806807 }
807808
808809 /**
@@ -815,9 +816,9 @@ export function removeParty(
815816 input: { id: number; dealId?: number },
816817 ): Result<{ id: number }> {
817818 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);
819820 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 }));
821822 }
822823
823824 /** What a party or a date is called, for a notice saying it was removed. */
@@ -843,16 +844,17 @@ export function removeDeadline(
843844 input: { id: number; dealId?: number },
844845 ): Result<{ id: number }> {
845846 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);
847848 if (found.value.deadline.kind !== "custom")
848849 return within(
849850 db,
850851 who,
852 "date.remove",
851853 dealId,
852854 fail("invalid", "A standard contract date cannot be removed; move it or mark it done."),
853855 );
854856 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 }));
856858 }
857859
858860 /**
@@ -866,16 +868,16 @@ export function sendReminder(
866868 input: { deadlineId: number; partyId: number; moment: unknown; subject?: unknown; body?: unknown; agent?: Agent },
867869 ): Result<Sent> {
868870 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);
870872 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."));
872874 const party = Number.isInteger(input.partyId)
873875 ? db
874876 .query<Party, [number, number]>("SELECT * FROM party WHERE id = ?1 AND deal_id = ?2")
875877 .get(input.partyId, found.value.deal.id)
876878 : null;
877879 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."));
879881 const { deadline } = found.value;
880882 const seen = view(db, found.value.deal);
881883 const draft = draftsFor(
@@ -884,23 +886,23 @@ export function sendReminder(
884886 input.agent ?? agentOf(db),
885887 ).find((r) => r.party_id === party.id && r.moment === input.moment);
886888 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."));
888890 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."));
890892 const subject =
891893 input.subject === undefined ? draft?.subject : line(input.subject, 1, SUBJECT_MAX);
892894 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.`));
894896 const body = input.body === undefined ? draft?.body : message(input.body, 1, BODY_MAX);
895897 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.`));
897899 const sent = db
898900 .query<SentRow, [number, number, number, string, string, string, string, string, number, string, string, string]>(
899901 `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)
900902 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
901903 )
902904 .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])));
904906 }
905907
906908 /** The draft one decline or undo names, on a date `who` may change. */
@@ -939,20 +941,20 @@ export function declineReminder(
939941 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; reason: unknown; agent?: Agent },
940942 ): Result<Declined> {
941943 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);
943945 const reason = line(input.reason, 1, REASON_MAX);
944946 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.`));
946948 const { draft, deal } = found.value;
947949 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."));
949951 const declined = db
950952 .query<Declined, [number, number, number, string, string, string, string, number, string, string]>(
951953 `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)
952954 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 *`,
953955 )
954956 .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));
956958 }
957959
958960 /** Take back a decline: the reminder is a draft again. */
@@ -962,7 +964,7 @@ export function undoDecline(
962964 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent },
963965 ): Result<{ id: number }> {
964966 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);
966968 const { draft } = found.value;
967969 const gone = db
968970 .query<{ id: number }, [number, number, string, string, number]>(
@@ -970,6 +972,6 @@ export function undoDecline(
970972 )
971973 .get(draft.deadline_id, draft.party_id, draft.moment, draft.due, draft.move_id);
972974 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 }));
975977 }
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 ? "&amp;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";
2020 import { contactLinks } from "./contact.ts";
2121 import { token, tokensHref } from "../tokens.ts";
2222 import type { Agent } from "../reminders.ts";
23 import { permit } from "../contract.ts";
2324 import type { Who } from "../who.ts";
2425
2526 const iconHref = asset("icon.svg");
@@ -84,7 +85,7 @@ ${plain || input.live === false ? "" : `<script type="module" src="${asset("live
8485 ? ""
8586 : `<nav class="row">
8687 ${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>` : ""}`}
8889 ${door}
8990 </nav>`
9091 }
src/result.ts +2
@@ -39,6 +39,7 @@ export const audited = <T extends { readonly id: number }>(
3939 verb: "create" | "update" | "delete",
4040 target: number | undefined,
4141 result: Result<T>,
42 what?: string,
4243 ): Result<T> => {
4344 record(db, {
4445 who,
@@ -46,6 +47,7 @@ export const audited = <T extends { readonly id: number }>(
4647 verb,
4748 target: target ?? (result.ok ? result.value.id : undefined),
4849 outcome: result.ok ? "ok" : result.error,
50 ...(what === undefined ? {} : { what }),
4951 });
5052 return result;
5153 };
src/routes.ts +23
@@ -79,6 +79,8 @@ import { refusedPage } from "./pages/refused.ts";
7979 import { people } from "./people.ts";
8080 import { reviewHref, reviewPage, type ReviewField } from "./pages/review.ts";
8181 import { peoplePage } from "./pages/people.ts";
82 import { activityPage } from "./pages/activity.ts";
83 import { ACTIVITY_PAGE } from "./activity.ts";
8284 import { timelinePage } from "./pages/timeline.ts";
8385 import { welcomePage } from "./pages/welcome.ts";
8486 import { dueOn, remindsLine, todaysDrafts, unsent, type Draft } from "./reminders.ts";
@@ -131,6 +133,7 @@ export const AUDIT_ROW: Schema = {
131133 target: { type: ["string", "null"] },
132134 allowed: { enum: [0, 1] },
133135 outcome: { type: "string" },
136 what: { type: ["string", "null"] },
134137 },
135138 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
136139 };
@@ -500,6 +503,26 @@ export const routes: readonly Route[] = [
500503 return html(peoplePage({ who: c.who, agent: agentOf(c.db), people: people(deals.value, today()), on: today() }));
501504 },
502505 },
outdated

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().

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 },
503526 {
504527 method: "GET",
505528 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
652652 press(t, "M", ...open.flatMap(() => ["\r"]), ..."x", "\r");
653653 expect(lines(t).join("\n")).toContain("Nothing changed");
654654 });
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 @@
88 * reminders what goes out today; enter reads a draft, e edits its words, s sends it
99 * people each person on the deals with every open date they owe (P)
1010 * 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
1112 * profile your name, brokerage, phone and email (I); e edits them, U goes back to the defaults
1213 * 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
1314 *
@@ -58,18 +59,23 @@ import { PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
5859 import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts";
5960 import { permit } from "./contract.ts";
6061 import { drafts, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
62 import type { AuditRow } from "./audit.ts";
6163 import type { Result } from "./result.ts";
6264 import type { Who } from "./who.ts";
6365 import { people } from "./people.ts";
66 import { addresses, refusal, when, wording } from "./activity.ts";
67 import { listAudit } from "./actions.ts";
6468 import { owner, thisWeek } from "./week.ts";
6569
6670 const esc = "\x1b[";
6771 const dim = (s: string): string => `${esc}2m${s}${esc}0m`;
6872 const bold = (s: string): string => `${esc}1m${s}${esc}0m`;
73 /** Audit rows to a screen. */
74 const ACTIVITY_ROWS = 20;
6975 const COLOUR: Readonly<Record<Urgency, string>> = { overdue: "31", soon: "33", later: "36", done: "2" };
7076 const tint = (u: Urgency, s: string): string => `${esc}${COLOUR[u]}m${s}${esc}0m`;
7177
72 type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline" | "profile";
78 type View = "dates" | "week" | "people" | "reminders" | "deal" | "messages" | "timeline" | "profile" | "activity";
7379 interface Row {
7480 readonly deal: DealView;
7581 readonly date: DeadlineView;
@@ -111,6 +117,9 @@ export function terminal(
111117 /** What `/` narrowed the deals to; empty is all of them. */
112118 let found = "";
113119 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[] = [];
114123
115124 const deals = (): DealView[] => {
116125 const listed = listDeals(db, me);
@@ -321,6 +330,32 @@ export function terminal(
321330 return true;
322331 }
323332
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
324359 function onProfile(key: string): void {
325360 if (key !== "e" && key !== "U") return;
326361 if (permit(me, "profile", "update") !== "yes") {
@@ -436,6 +471,11 @@ export function terminal(
436471 } else if (key === "I") {
437472 view = "profile";
438473 cursor = 0;
474 } else if (key === "L") {
475 view = "activity";
476 cursor = 0;
477 onlyMessages = false;
478 trail = [];
439479 } else if (key === "r") {
440480 view = "reminders";
441481 cursor = 0;
@@ -493,6 +533,7 @@ export function terminal(
493533 cursor = 0;
494534 } else if (view === "reminders") onReminder(key);
495535 else if (view === "profile") onProfile(key);
536 else if (view === "activity") onActivity(key);
496537 else if (view === "messages" || view === "timeline") return;
497538 else if (!(view === "deal" && onDeal(key))) onDate(key);
498539 cursor = Math.min(cursor, Math.max(0, rowCount() - 1));
@@ -560,6 +601,21 @@ export function terminal(
560601 lines.push(` ${tint(o.urgency, `${spoken(o.due).padEnd(12)} ${relative(o.due, day).padEnd(12)}`)} ${o.label} — ${o.address}`);
561602 }
562603 }
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 }
563619 } else if (view === "profile") {
564620 const got = getProfile(db, me);
565621 if (!got.ok) lines.push(got.message);
@@ -633,7 +689,9 @@ export function terminal(
633689 else {
634690 if (said !== "") lines.push(...said.split("\n"));
635691 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"
637695 ? permit(me, "profile", "update") === "yes"
638696 ? "e edit · U use defaults · d dates · q quit"
639697 : "d dates · q quit (only an admin changes the profile)"
@@ -647,7 +705,7 @@ export function terminal(
647705 ? "b back to the deal · d dates · q quit"
648706 : view === "deal"
649707 ? "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`;
651709 lines.push(dim(me.role === "anon" ? `${keys} · sign in with a key the forge knows to change anything` : keys));
652710 }
653711 return lines;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs