@terpjs/react-core 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +35 -14
  2. package/package.json +5 -5
  3. package/src/DashboardPage.tsx +34 -0
  4. package/src/Field.test.tsx +26 -1
  5. package/src/Field.tsx +15 -5
  6. package/src/HubPage.tsx +7 -2
  7. package/src/ModuleNav.test.tsx +29 -1
  8. package/src/ModuleNav.tsx +5 -1
  9. package/src/Page.test.tsx +192 -0
  10. package/src/Page.tsx +141 -55
  11. package/src/PageActions.test.tsx +64 -3
  12. package/src/PageActions.tsx +40 -15
  13. package/src/PageSequence.tsx +114 -0
  14. package/src/Stat.test.tsx +376 -0
  15. package/src/Stat.tsx +316 -0
  16. package/src/Timeline.test.tsx +74 -0
  17. package/src/Timeline.tsx +71 -0
  18. package/src/admin/AdminHub.tsx +233 -78
  19. package/src/admin/AuditLogAdmin.tsx +3 -1
  20. package/src/admin/GroupCreate.tsx +3 -1
  21. package/src/admin/GroupDetail.tsx +72 -67
  22. package/src/admin/GroupsAdmin.tsx +3 -1
  23. package/src/admin/ModuleAccessPanel.tsx +13 -12
  24. package/src/admin/RecordHistory.tsx +88 -0
  25. package/src/admin/UserCreate.tsx +3 -1
  26. package/src/admin/UserDetail.tsx +8 -1
  27. package/src/admin/UsersAdmin.tsx +3 -0
  28. package/src/admin/admin.test.tsx +389 -19
  29. package/src/bootstrap.test.tsx +31 -7
  30. package/src/bootstrap.tsx +30 -4
  31. package/src/charts/BarChart.tsx +74 -0
  32. package/src/charts/ProportionBar.tsx +118 -0
  33. package/src/charts/StatusHistory.tsx +75 -0
  34. package/src/charts/TrendChart.tsx +232 -0
  35. package/src/charts/charts.test.tsx +409 -0
  36. package/src/charts/scale.ts +103 -0
  37. package/src/currentInView.ts +28 -0
  38. package/src/dataview/DataView.test.tsx +303 -1
  39. package/src/dataview/DataView.tsx +53 -3
  40. package/src/dataview/DataViewCardList.tsx +21 -13
  41. package/src/dataview/DataViewTable.tsx +5 -6
  42. package/src/dataview/DataViewToolbar.tsx +4 -1
  43. package/src/dataview/README.md +18 -0
  44. package/src/dataview/index.ts +1 -0
  45. package/src/dataview/internal.tsx +112 -5
  46. package/src/dataview/types.ts +39 -10
  47. package/src/errorMessages.test.tsx +17 -0
  48. package/src/errorMessages.tsx +18 -0
  49. package/src/format.ts +15 -0
  50. package/src/index.ts +24 -1
  51. package/src/layout.manifest.json +2 -9
  52. package/src/layout.manifest.test.ts +4 -2
  53. package/src/layout.test.tsx +74 -6
  54. package/src/layout.tsx +85 -25
  55. package/src/layoutContract.test.tsx +239 -1
  56. package/src/layoutContract.ts +131 -5
  57. package/src/layoutDeclaration.test.ts +31 -10
  58. package/src/layoutDeclaration.ts +9 -4
  59. package/src/locale.tsx +28 -3
  60. package/src/markers.test.ts +70 -2
  61. package/src/router.test.tsx +15 -3
  62. package/src/router.tsx +11 -2
  63. package/src/ssr.test.tsx +18 -0
  64. package/src/styles.test.ts +288 -190
  65. package/src/styles.ts +1379 -361
  66. package/src/theme.test.tsx +44 -18
  67. package/src/theme.themes.test.ts +22 -2
  68. package/src/theme.tsx +22 -14
  69. package/src/themes.ts +39 -4
  70. package/src/tokens.guard.test.ts +13 -15
  71. package/src/typography.tsx +5 -1
  72. package/src/ui/Alert.test.tsx +24 -1
  73. package/src/ui/Alert.tsx +10 -1
  74. package/src/ui/Card.tsx +5 -4
  75. package/src/ui/Tabs.test.tsx +44 -0
  76. package/src/ui/Tabs.tsx +5 -2
  77. package/src/ui/Tooltip.test.tsx +171 -2
  78. package/src/ui/Tooltip.tsx +144 -8
  79. package/src/ui/controlMessages.tsx +20 -7
  80. package/src/uiText.test.tsx +16 -0
  81. package/src/uiText.tsx +105 -7
  82. package/src/viewerTimeZone.ts +15 -0
@@ -0,0 +1,88 @@
1
+ import { useEffect, useState } from "react";
2
+
3
+ import type { components } from "@terpjs/contract";
4
+
5
+ import { Timeline } from "../Timeline";
6
+ import type { TimelineEvent } from "../Timeline";
7
+ import { useTerpClient } from "../TerpProvider";
8
+ import type { BadgeTone } from "../ui/Badge";
9
+ import { Card } from "../ui/Card";
10
+ import { unwrap } from "../unwrap";
11
+ import { useStrings } from "../uiText";
12
+ import type { TerpStrings } from "../uiText";
13
+
14
+ type AuditEventRead = components["schemas"]["AuditEventRead"];
15
+
16
+ /** How many of a record's events its screen shows: its recent history, not its whole trail. */
17
+ const RECENT = 10;
18
+
19
+ const ACTION_WORDS: Record<string, keyof TerpStrings> = {
20
+ created: "auditActionCreated",
21
+ updated: "auditActionUpdated",
22
+ deleted: "auditActionDeleted",
23
+ disclosed: "auditActionDisclosed",
24
+ };
25
+
26
+ const ACTION_TONES: Record<string, BadgeTone | undefined> = {
27
+ created: "success",
28
+ deleted: "danger",
29
+ disclosed: "info",
30
+ };
31
+
32
+ /** The tone an audit action is drawn in: a change is neutral, a deletion danger. */
33
+ export function auditActionTone(action: string): BadgeTone {
34
+ return ACTION_TONES[action] ?? "neutral";
35
+ }
36
+
37
+ /** An audit action in the app's words, or as recorded where it is not one the framework names. */
38
+ export function auditActionWord(strings: TerpStrings, action: string): string {
39
+ const key = ACTION_WORDS[action];
40
+ const word = key === undefined ? undefined : strings[key];
41
+ return typeof word === "string" ? word : action;
42
+ }
43
+
44
+ /**
45
+ * A record's own history, from the audit trail: what happened to it and when, newest first, as
46
+ * a `Timeline` (ADR 0169 §5) — the trail narrowed to the record the screen is about.
47
+ *
48
+ * Context rather than content, so it fails quietly: a trail the caller cannot read, or one with
49
+ * nothing about this record yet, renders no section at all, and the screen around it is whole
50
+ * without it.
51
+ */
52
+ export function RecordHistory({ targetType, targetId }: { targetType: string; targetId: string }) {
53
+ const client = useTerpClient();
54
+ const strings = useStrings();
55
+ const [events, setEvents] = useState<readonly AuditEventRead[] | null>(null);
56
+ useEffect(() => {
57
+ const controller = new AbortController();
58
+ void (async () => {
59
+ try {
60
+ const page = unwrap(
61
+ await client.GET("/api/v1/audit/", {
62
+ params: { query: { target_type: targetType, target_id: targetId, limit: RECENT } },
63
+ signal: controller.signal,
64
+ }),
65
+ );
66
+ setEvents(page.items);
67
+ } catch {
68
+ // The history is context: a screen without it still works.
69
+ }
70
+ })();
71
+ return () => controller.abort();
72
+ }, [client, targetType, targetId]);
73
+ if (events === null || events.length === 0) {
74
+ return null;
75
+ }
76
+ const timeline: TimelineEvent[] = events.map((event) => ({
77
+ label: auditActionWord(strings, event.action),
78
+ when: event.created_at,
79
+ detail:
80
+ event.actor_id === null ? undefined : `${strings.actorColumn}: ${event.actor_id.slice(0, 8)}`,
81
+ tone: ACTION_TONES[event.action],
82
+ }));
83
+ return (
84
+ <Card title={strings.recordHistory}>
85
+ <Timeline label={strings.recordHistory} events={timeline} />
86
+ </Card>
87
+ );
88
+ }
@@ -12,6 +12,7 @@ import { useToast } from "../toast";
12
12
  import { Button } from "../ui/Button";
13
13
  import { Input } from "../ui/Input";
14
14
  import { Select } from "../ui/Select";
15
+ import { useErrorMessage } from "../errorMessages";
15
16
  import { useStrings } from "../uiText";
16
17
  import { unwrap } from "../unwrap";
17
18
 
@@ -30,6 +31,7 @@ export function UserCreate() {
30
31
  const client = useTerpClient();
31
32
  const navigate = useNavigate();
32
33
  const strings = useStrings();
34
+ const messageForCode = useErrorMessage();
33
35
  const toast = useToast();
34
36
  const [email, setEmail] = useState("");
35
37
  const [password, setPassword] = useState("");
@@ -73,7 +75,7 @@ export function UserCreate() {
73
75
  const { shown, leftover } = routeFieldErrors(error, RENDERED_FIELDS);
74
76
  setFieldErrors(shown);
75
77
  if (Object.keys(shown).length === 0 || leftover) {
76
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
78
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
77
79
  }
78
80
  } finally {
79
81
  setCreating(false);
@@ -14,11 +14,13 @@ import { useToast } from "../toast";
14
14
  import { Button } from "../ui/Button";
15
15
  import { Input } from "../ui/Input";
16
16
  import { useFormatDateTime } from "../format";
17
+ import { useErrorMessage } from "../errorMessages";
17
18
  import { useStrings } from "../uiText";
18
19
  import { unwrap } from "../unwrap";
19
20
 
20
21
  import { adminCrumb, renderAdminCrumb } from "./crumbs";
21
22
  import { ModuleAccessPanel } from "./ModuleAccessPanel";
23
+ import { RecordHistory } from "./RecordHistory";
22
24
  import { adminRoleLabel } from "./roles";
23
25
  import { useAccessLadder } from "./useAccessLadder";
24
26
 
@@ -33,6 +35,7 @@ export function UserDetail() {
33
35
  const userId = useDeclaredParam("userId");
34
36
  const client = useTerpClient();
35
37
  const strings = useStrings();
38
+ const messageForCode = useErrorMessage();
36
39
  const formatDateTime = useFormatDateTime();
37
40
  const toast = useToast();
38
41
  const [pendingLifecycle, setPendingLifecycle] = useState<PendingLifecycle | null>(null);
@@ -64,7 +67,7 @@ export function UserDetail() {
64
67
  const record = user.item;
65
68
 
66
69
  function failed(error: unknown): void {
67
- toast.warning(error instanceof Error ? error.message : strings.requestFailed);
70
+ toast.warning(messageForCode(error) ?? (error instanceof Error ? error.message : strings.requestFailed));
68
71
  }
69
72
 
70
73
  async function onConfirmLifecycle() {
@@ -170,7 +173,9 @@ export function UserDetail() {
170
173
  >
171
174
  {record !== null && (
172
175
  <Stack gap={6}>
176
+ {/* The account's facts as a ruled sheet (ADR 0169 §5): short, several, read across. */}
173
177
  <DetailList
178
+ layout="grid"
174
179
  items={[
175
180
  { label: strings.email, value: record.email },
176
181
  { label: strings.role, value: adminRoleLabel(rungs, record.role) },
@@ -184,6 +189,8 @@ export function UserDetail() {
184
189
  {/* The rung is chosen where the person is: this is the only screen that has a
185
190
  subject, and the global role above it is the floor every module strip sits on. */}
186
191
  <ModuleAccessPanel subjectId={record.id} globalRank={record.role} />
192
+ {/* The account's own history from the audit trail, newest first (ADR 0169 §5). */}
193
+ <RecordHistory targetType="User" targetId={record.id} />
187
194
  </Stack>
188
195
  )}
189
196
  <ConfirmDialog
@@ -39,6 +39,9 @@ function buildColumns(
39
39
  id: "is_active",
40
40
  header: strings.statusColumn,
41
41
  accessor: (u) => (u.is_active ? strings.statusActive : strings.statusDeactivated),
42
+ // A dot rather than a pill: most accounts are active, and a pill on every row is noise
43
+ // around the one that is not (ADR 0169 §5). The text stays the word.
44
+ status: (u) => (u.is_active ? "success" : "neutral"),
42
45
  meta: { mobileSlot: "status", width: "sm" },
43
46
  },
44
47
  {
@@ -155,6 +155,33 @@ function LogInOnMount() {
155
155
 
156
156
  const emptyPage = { items: [], total: 0, skip: 0, limit: 1 };
157
157
 
158
+ /** A day of the hub's activity fixture: `offset` days after 5 September 2026. */
159
+ function activityDay(offset: number, count: number) {
160
+ return { date: new Date(Date.UTC(2026, 8, 5 + offset)).toISOString().slice(0, 10), count };
161
+ }
162
+
163
+ /**
164
+ * The trail's activity as the hub reads it: thirty days ending 4 October. The last week sums to
165
+ * 21 and the week before to 16, so the figure reads 21, 5 up. The days before the last week
166
+ * count 1, 2, 3, 4 in turn: with one change on each, any seven of them summed to 7, and a
167
+ * comparison read a day off still printed the right delta.
168
+ */
169
+ const LAST_WEEK = [5, 4, 6, 3, 2, 0, 1];
170
+ const ACTIVITY = {
171
+ time_zone: "Europe/Amsterdam",
172
+ days: Array.from({ length: 30 }, (_, index) =>
173
+ activityDay(index, index >= 23 ? LAST_WEEK[index - 23]! : (index % 4) + 1),
174
+ ),
175
+ previous_days: Array.from({ length: 30 }, (_, index) => activityDay(index - 30, 2)),
176
+ by_action: [
177
+ { action: "updated", count: 30 },
178
+ { action: "created", count: 12 },
179
+ { action: "deleted", count: 2 },
180
+ ],
181
+ by_target_type: [{ target_type: "User", count: 44 }],
182
+ total: 44,
183
+ };
184
+
158
185
  /**
159
186
  * Held open, the access-model response does not land. Set by the one test that needs the
160
187
  * role ladder to still be in flight while it looks at the form, so the window in which the
@@ -275,6 +302,10 @@ function stubAdminFetch() {
275
302
  limit: 20,
276
303
  });
277
304
  }
305
+ // The hub counts its active accounts as a total under the status filter.
306
+ if (url.searchParams.get("is_active") === "true") {
307
+ return jsonResponse({ items: [], total: 5, skip: 0, limit: 1 });
308
+ }
278
309
  return jsonResponse({
279
310
  items: [
280
311
  {
@@ -368,6 +399,9 @@ function stubAdminFetch() {
368
399
  limit: 10,
369
400
  });
370
401
  }
402
+ if (path.endsWith("/api/v1/audit/activity")) {
403
+ return jsonResponse(ACTIVITY);
404
+ }
371
405
  if (path.endsWith("/api/v1/audit/")) {
372
406
  // One row, and it earns its place rather than padding the fixture: the audit screen's
373
407
  // expanded panel is the only place the payload renders, so with an empty page that
@@ -469,6 +503,20 @@ function renderAdminApp(
469
503
  * to wait on. This is that thing, and it is the condition that actually gates the click
470
504
  * rather than a proxy for it.
471
505
  */
506
+ /** A figure on the page, read by its label: its value, caption, delta and whether it leads. */
507
+ function figure(label: string) {
508
+ const stat = [...document.querySelectorAll('[data-terp="stat"]')].find(
509
+ (node) => node.querySelector('[data-terp="stat-label"]')?.textContent === label,
510
+ );
511
+ if (stat === undefined) return undefined;
512
+ return {
513
+ value: stat.querySelector('[data-terp="stat-value"]')?.textContent,
514
+ caption: stat.querySelector('[data-terp="stat-caption"]')?.textContent,
515
+ delta: stat.querySelector('[data-terp="stat-change"]')?.textContent,
516
+ headline: stat.hasAttribute("data-headline"),
517
+ };
518
+ }
519
+
472
520
  async function enabledSubmitControl(): Promise<HTMLElement> {
473
521
  const control = await screen.findByRole("button", { name: "Provision user" });
474
522
  await waitFor(() => expect(control).toBeEnabled());
@@ -476,34 +524,166 @@ async function enabledSubmitControl(): Promise<HTMLElement> {
476
524
  }
477
525
 
478
526
  describe("the packaged admin area", () => {
479
- it("serves the hub at /admin with cards into users, groups and audit", async () => {
480
- renderAdminApp("/admin");
527
+ it("serves the hub at /admin as a dashboard: the figures, the areas, then the trail", async () => {
528
+ const { fetchMock } = renderAdminApp("/admin");
481
529
  await waitFor(() =>
482
530
  expect(screen.getByRole("heading", { level: 1, name: "Admin" })).toBeInTheDocument(),
483
531
  );
484
- expect(screen.getByRole("link", { name: /Users/ })).toBeInTheDocument();
485
- expect(screen.getByRole("link", { name: /Groups/ })).toBeInTheDocument();
486
- expect(screen.getByRole("link", { name: /Audit log/ })).toBeInTheDocument();
487
- // Live totals from the limit=1 probes reach the cards.
488
- await waitFor(() => expect(screen.getByText("7")).toBeInTheDocument());
489
- expect(screen.getByText("3")).toBeInTheDocument();
532
+ for (const area of [/Users/, /Groups/, /Audit log/, /^Access/]) {
533
+ expect(screen.getByRole("link", { name: area })).toBeInTheDocument();
534
+ }
535
+ // The summary band's figures, each read by its label: the active accounts as a total under
536
+ // the status filter, with the rest deactivated; the groups; and the trail's last week
537
+ // against the week before, from one activity read.
538
+ await waitFor(() => expect(figure("Changes, last 7 days")?.value).toBe("21"));
539
+ expect(figure("Active accounts")).toMatchObject({ value: "5", caption: "2 deactivated", headline: true });
540
+ expect(figure("Groups")?.value).toBe("3");
541
+ // 21 against the 16 of the seven days just before. Mutation: those seven read a day off.
542
+ expect(figure("Changes, last 7 days")?.delta).toMatch(/(^|\D)5(\D|$)/);
543
+ // Then the trail per day against the days before, and the kinds of change in the app's words.
544
+ expect(screen.getByText("Changes per day")).toBeInTheDocument();
545
+ expect(screen.getByText("Changes by kind, last 30 days")).toBeInTheDocument();
546
+ expect(screen.getAllByText("Changed").length).toBeGreaterThan(0);
547
+ const reads = fetchMock.mock.calls.map((call) => new URL((call[0] as Request).url));
548
+ const activity = reads.find((url) => url.pathname.endsWith("/api/v1/audit/activity"))!;
549
+ expect(activity.searchParams.get("days")).toBe("30");
550
+ expect(activity.searchParams.get("time_zone")).toBe(
551
+ Intl.DateTimeFormat().resolvedOptions().timeZone,
552
+ );
490
553
  // The sidebar carries the single admin-gated entry.
491
554
  expect(screen.getByRole("link", { name: "Admin" })).toBeInTheDocument();
492
555
  });
493
556
 
494
- it("serves a capability-selective hub: dropped sections lose card, route and stat call", async () => {
495
- const { fetchMock } = renderAdminApp("/admin", 30, { groups: false });
557
+ it("serves a capability-selective hub: dropped sections lose card, figure and read", async () => {
558
+ const { fetchMock } = renderAdminApp("/admin", 30, { groups: false, audit: false });
496
559
  await waitFor(() =>
497
560
  expect(screen.getByRole("heading", { level: 1, name: "Admin" })).toBeInTheDocument(),
498
561
  );
499
562
  expect(screen.getByRole("link", { name: /Users/ })).toBeInTheDocument();
500
- expect(screen.getByRole("link", { name: /Audit log/ })).toBeInTheDocument();
501
563
  expect(screen.queryByRole("link", { name: /Groups/ })).not.toBeInTheDocument();
502
- // The users stat still arrives; the groups endpoint is never probed (its
503
- // capability may not be mounted at all).
504
- await waitFor(() => expect(screen.getByText("7")).toBeInTheDocument());
564
+ expect(screen.queryByRole("link", { name: /Audit log/ })).not.toBeInTheDocument();
565
+ // The users figure still arrives; the groups and the trail are never read (their
566
+ // capabilities may not be mounted at all), and the audit section takes its charts along.
567
+ await waitFor(() => expect(figure("Active accounts")?.value).toBe("5"));
568
+ expect(figure("Groups")).toBeUndefined();
569
+ expect(figure("Changes, last 7 days")).toBeUndefined();
570
+ expect(screen.queryByText("Changes per day")).not.toBeInTheDocument();
505
571
  const probed = fetchMock.mock.calls.map((call) => (call[0] as Request).url);
506
572
  expect(probed.some((url) => url.includes("/api/v1/groups/"))).toBe(false);
573
+ expect(probed.some((url) => url.includes("/api/v1/audit/"))).toBe(false);
574
+ });
575
+
576
+ it("keeps every other figure when one read fails (ADR 0171)", async () => {
577
+ const { fetchMock } = renderAdminApp("/admin");
578
+ const answer = fetchMock.getMockImplementation()!;
579
+ // The failing read lands last, after the others have drawn their figures, so a failure
580
+ // that took the page's other reads down with it shows here rather than being overwritten.
581
+ let fail!: () => void;
582
+ const failing = new Promise<void>((resolve) => (fail = resolve));
583
+ fetchMock.mockImplementation(async (input, init) => {
584
+ if (!new URL((input as Request).url).pathname.endsWith("/api/v1/groups/")) {
585
+ return answer(input, init);
586
+ }
587
+ await failing;
588
+ return jsonResponse({ detail: "unavailable" }, 503);
589
+ });
590
+ await waitFor(() => expect(figure("Changes, last 7 days")?.value).toBe("21"));
591
+ await waitFor(() => expect(figure("Active accounts")?.value).toBe("5"));
592
+ await act(async () => {
593
+ fail();
594
+ await new Promise((resolve) => setTimeout(resolve, 0));
595
+ });
596
+ // Mutation: the reads awaited together behind one catch, so one failure dashed them all.
597
+ expect(figure("Changes, last 7 days")?.value).toBe("21");
598
+ expect(figure("Active accounts")?.value).toBe("5");
599
+ expect(figure("Groups")?.value).toBe("—");
600
+ });
601
+
602
+ it("draws the days before as the comparison, not the last thirty again", async () => {
603
+ renderAdminApp("/admin");
604
+ const chart = await screen.findByRole("figure", { name: "Changes per day" });
605
+ const comparison = within(chart)
606
+ .getAllByRole("row")
607
+ .slice(1)
608
+ .map((row) => within(row).getAllByRole("cell").at(-1)!.textContent);
609
+ // Every day before counts 2 in the fixture; the last thirty never do all at once.
610
+ expect(comparison).toHaveLength(30);
611
+ expect(new Set(comparison)).toEqual(new Set(["2"]));
612
+ });
613
+
614
+ it("counts the trail in the viewer's zone, whatever the host running the test is in", async () => {
615
+ const real = Intl.DateTimeFormat.prototype.resolvedOptions;
616
+ vi.spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions").mockImplementation(function (
617
+ this: Intl.DateTimeFormat,
618
+ ) {
619
+ return { ...real.call(this), timeZone: "Pacific/Chatham" };
620
+ });
621
+ const { fetchMock } = renderAdminApp("/admin");
622
+ await waitFor(() => expect(figure("Changes, last 7 days")?.value).toBe("21"));
623
+ const activity = fetchMock.mock.calls
624
+ .map((call) => new URL((call[0] as Request).url))
625
+ .find((url) => url.pathname.endsWith("/api/v1/audit/activity"))!;
626
+ expect(activity.searchParams.get("time_zone")).toBe("Pacific/Chatham");
627
+ });
628
+
629
+ it("counts in UTC rather than drawing nothing when the server refuses the viewer's zone", async () => {
630
+ const real = Intl.DateTimeFormat.prototype.resolvedOptions;
631
+ vi.spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions").mockImplementation(function (
632
+ this: Intl.DateTimeFormat,
633
+ ) {
634
+ return { ...real.call(this), timeZone: "Etc/Unknown" };
635
+ });
636
+ const { fetchMock } = renderAdminApp("/admin");
637
+ const answer = fetchMock.getMockImplementation()!;
638
+ fetchMock.mockImplementation(async (input, init) => {
639
+ const url = new URL((input as Request).url);
640
+ return url.pathname.endsWith("/api/v1/audit/activity") &&
641
+ url.searchParams.get("time_zone") === "Etc/Unknown"
642
+ ? jsonResponse({ detail: "'Etc/Unknown' is not a time zone this server knows." }, 400)
643
+ : answer(input, init);
644
+ });
645
+ // Mutation: no second read, and the figure keeps its dash with both charts gone.
646
+ await waitFor(() => expect(figure("Changes, last 7 days")?.value).toBe("21"));
647
+ expect(screen.getByRole("figure", { name: "Changes per day" })).toBeInTheDocument();
648
+ const zones = fetchMock.mock.calls
649
+ .map((call) => new URL((call[0] as Request).url))
650
+ .filter((url) => url.pathname.endsWith("/api/v1/audit/activity"))
651
+ .map((url) => url.searchParams.get("time_zone"));
652
+ expect(zones).toEqual(["Etc/Unknown", "UTC"]);
653
+ });
654
+
655
+ it("lays the area cards out on as many tracks as there are cards", async () => {
656
+ // Two cards on a fixed three left a blank third column; one card took a third of the row.
657
+ renderAdminApp("/admin", 30, { groups: false, audit: false });
658
+ const users = await screen.findByRole("link", { name: /Users/ });
659
+ expect(users.closest('[data-terp="grid"]')).toHaveAttribute("data-template", "1:1");
660
+ });
661
+
662
+ it("never counts fewer than no deactivated accounts", async () => {
663
+ // The total and the active count are two reads; an account made between them made -1.
664
+ const { fetchMock } = renderAdminApp("/admin", 30, { groups: false, audit: false });
665
+ const answer = fetchMock.getMockImplementation()!;
666
+ fetchMock.mockImplementation(async (input, init) => {
667
+ const url = new URL((input as Request).url);
668
+ return url.pathname.endsWith("/api/v1/users/") && url.searchParams.get("is_active") === "true"
669
+ ? jsonResponse({ items: [], total: 8, skip: 0, limit: 1 })
670
+ : answer(input, init);
671
+ });
672
+ await waitFor(() => expect(figure("Active accounts")?.value).toBe("8"));
673
+ expect(figure("Active accounts")?.caption).toBe("0 deactivated");
674
+ });
675
+
676
+ it("drops the access card with the access section, the one a full hub always drew", async () => {
677
+ // The selective hub replaced the full one only when users, groups or audit was dropped, so
678
+ // `{ access: false }` alone removed the route and kept the card that leads to it.
679
+ renderAdminApp("/admin", 30, { access: false });
680
+ await waitFor(() =>
681
+ expect(screen.getByRole("heading", { level: 1, name: "Admin" })).toBeInTheDocument(),
682
+ );
683
+ expect(screen.getByRole("link", { name: /Users/ })).toBeInTheDocument();
684
+ expect(screen.getByRole("link", { name: /Groups/ })).toBeInTheDocument();
685
+ expect(screen.getByRole("link", { name: /Audit log/ })).toBeInTheDocument();
686
+ expect(screen.queryByRole("link", { name: /^Access/ })).not.toBeInTheDocument();
507
687
  });
508
688
 
509
689
  it("uses the users overview action and clickable rows for dedicated pages", async () => {
@@ -513,6 +693,13 @@ describe("the packaged admin area", () => {
513
693
  );
514
694
  expect(screen.getByRole("button", { name: "Provision user" })).toBeInTheDocument();
515
695
  await waitFor(() => expect(screen.getByText("jane.doe@example.com")).toBeInTheDocument());
696
+ // The status column is the quiet form (ADR 0169 §5): a dot before its word, toned by the
697
+ // account's state. Mutation: drop `status` from the column, and the dot is gone.
698
+ const active = screen.getAllByText("Active")[0]!.closest('[data-terp="dataview-status"]')!;
699
+ expect(active.querySelector('[data-terp="dataview-status-dot"]')).toHaveAttribute(
700
+ "data-tone",
701
+ "success",
702
+ );
516
703
  expect(screen.getByRole("navigation", { name: "Breadcrumb" })).toHaveTextContent("Admin");
517
704
 
518
705
  fireEvent.click(screen.getByText("jane.doe@example.com"));
@@ -702,6 +889,9 @@ describe("the packaged admin area", () => {
702
889
  renderAdminApp("/admin/groups");
703
890
  await screen.findByRole("heading", { level: 1, name: "Groups" });
704
891
  await screen.findByText("Finance");
892
+ // Group sizes as bars against the largest shown, each still printed (ADR 0169 §5).
893
+ // Mutation: drop `bar` from the column, and no meter is named for it.
894
+ expect(screen.getAllByRole("meter", { name: "Members" }).length).toBeGreaterThan(0);
705
895
 
706
896
  fireEvent.click(screen.getByRole("button", { name: "Create group" }));
707
897
  await screen.findByRole("heading", { level: 1, name: "Create group" });
@@ -819,6 +1009,33 @@ describe("the packaged admin area", () => {
819
1009
  ).toBeInTheDocument();
820
1010
  });
821
1011
 
1012
+ it("words a refusal by its code in the app's language, not in the backend's English", async () => {
1013
+ // The admin screens toasted the backend's detail as written, so a rate-limited create said
1014
+ // "Too many requests; please retry later." on a Dutch screen. Mutation: toast error.message
1015
+ // again, and the English sentence is what appears.
1016
+ const { fetchMock } = renderAdminApp("/admin/groups/new", 30, true, DUTCH);
1017
+ await screen.findByRole("heading", { level: 1, name: "Groep aanmaken" });
1018
+ const passthrough = fetchMock.getMockImplementation()!;
1019
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
1020
+ const request = input as Request;
1021
+ if (request.method === "POST" && request.url.endsWith("/api/v1/groups/")) {
1022
+ return jsonResponse(
1023
+ { code: "rate_limited", detail: "Too many requests; please retry later.", request_id: "-" },
1024
+ 429,
1025
+ );
1026
+ }
1027
+ return passthrough(input, init);
1028
+ });
1029
+
1030
+ fireEvent.change(screen.getByLabelText("Naam"), { target: { value: "Redactie" } });
1031
+ fireEvent.click(screen.getByRole("button", { name: "Groep aanmaken" }));
1032
+
1033
+ expect(
1034
+ await screen.findByText("Te veel verzoeken tegelijk. Wacht even en probeer het opnieuw."),
1035
+ ).toBeInTheDocument();
1036
+ expect(screen.queryByText("Too many requests; please retry later.")).toBeNull();
1037
+ });
1038
+
822
1039
  it("renders its dates through the framework helper, not the built-in", async () => {
823
1040
  // What this gates is the CONVERSION, not the locale channel, and the distinction is worth
824
1041
  // naming: `renderAdminApp` mounts no `LocaleProvider`, so `useFormatDateTime` resolves an
@@ -866,18 +1083,171 @@ describe("the packaged admin area", () => {
866
1083
  renderAdminApp("/admin/groups/g1");
867
1084
  const headings = await waitFor(() => {
868
1085
  const found = document.querySelectorAll('[data-terp="admin-section-title"]');
869
- // Access per module, members, granted permissions. The count is here so the loop below
870
- // cannot pass by finding nothing, and naming them is what keeps it from being a magic
871
- // number the next section silently invalidates.
872
- expect(found.length).toBe(3);
1086
+ // Access per module. The count is here so the loop below cannot pass by finding
1087
+ // nothing; the members and the granted permissions were two more, and are collections
1088
+ // that name themselves now (below).
1089
+ expect(found.length).toBe(1);
873
1090
  return found;
874
1091
  });
875
1092
  for (const heading of headings) {
876
- expect(heading.tagName).toBe("H2");
1093
+ // An h3, the level of the group's two collections beside it and of every Card's title:
1094
+ // as an h2 it put the members and the permissions under "Access per module" in the
1095
+ // page's outline. Mutation: an h2 again, and this fails.
1096
+ expect(heading.tagName).toBe("H3");
877
1097
  expect(heading.getAttribute("style")).toBeNull();
878
1098
  }
879
1099
  });
880
1100
 
1101
+ it("shows an account's facts and a group's as ruled sheets", async () => {
1102
+ // The packaged detail screens are the ruled grid's consumers in the framework (ADR 0169
1103
+ // §5). Mutation: drop layout="grid" from either list, and its layout is "stacked".
1104
+ renderAdminApp("/admin/users/u1");
1105
+ await screen.findByRole("heading", { level: 1, name: "jane.doe@example.com" });
1106
+ await waitFor(() =>
1107
+ expect(document.querySelector('[data-terp="detail-list"]')).toHaveAttribute("data-layout", "grid"),
1108
+ );
1109
+ cleanup();
1110
+ renderAdminApp("/admin/groups/g1");
1111
+ await waitFor(() =>
1112
+ expect(document.querySelector('[data-terp="detail-list"]')).toHaveAttribute("data-layout", "grid"),
1113
+ );
1114
+ });
1115
+
1116
+ it("shows an account's own history from the audit trail, in the app's words", async () => {
1117
+ // The trail narrowed to the record the screen is about (ADR 0169 §5): the request names
1118
+ // the record, and the events read as a timeline, newest first. Mutation: drop the target
1119
+ // from the query, and the request is the whole trail.
1120
+ const { fetchMock } = renderAdminApp("/admin/users/u1");
1121
+ const base = fetchMock.getMockImplementation()!;
1122
+ fetchMock.mockImplementation(async (input) => {
1123
+ const url = new URL((input as Request).url);
1124
+ if (url.pathname.endsWith("/api/v1/audit/") && url.searchParams.get("target_id") === "u1") {
1125
+ return jsonResponse({
1126
+ items: [
1127
+ {
1128
+ id: "e2",
1129
+ created_at: "2026-08-21T09:30:00Z",
1130
+ action: "updated",
1131
+ target_type: "User",
1132
+ target_id: "u1",
1133
+ actor_id: "9f2c1b7e-0000-4000-8000-000000000002",
1134
+ request_id: null,
1135
+ payload: null,
1136
+ },
1137
+ {
1138
+ id: "e1",
1139
+ created_at: "2026-08-20T08:00:00Z",
1140
+ action: "created",
1141
+ target_type: "User",
1142
+ target_id: "u1",
1143
+ actor_id: null,
1144
+ request_id: null,
1145
+ payload: null,
1146
+ },
1147
+ ],
1148
+ total: 2,
1149
+ skip: 0,
1150
+ limit: 10,
1151
+ });
1152
+ }
1153
+ return base(input);
1154
+ });
1155
+ const history = await screen.findByRole("list", { name: "History" });
1156
+ const items = within(history).getAllByRole("listitem");
1157
+ expect(items.map((item) => item.querySelector('[data-terp="timeline-label"]')!.textContent)).toEqual([
1158
+ "Changed",
1159
+ "Created",
1160
+ ]);
1161
+ expect(items[0]!.textContent).toContain("Actor: 9f2c1b7e");
1162
+ const asked = fetchMock.mock.calls
1163
+ .map((call) => new URL((call[0] as Request).url))
1164
+ .find((url) => url.pathname.endsWith("/api/v1/audit/"))!;
1165
+ expect(asked.searchParams.get("target_type")).toBe("User");
1166
+ expect(asked.searchParams.get("target_id")).toBe("u1");
1167
+ });
1168
+
1169
+ it("shows a group's own history, asked for by the group", async () => {
1170
+ // Mutation: ask GroupDetail's history for the wrong record type, and this group's events are
1171
+ // never asked for.
1172
+ const { fetchMock } = renderAdminApp("/admin/groups/g1");
1173
+ const base = fetchMock.getMockImplementation()!;
1174
+ fetchMock.mockImplementation(async (input) => {
1175
+ const url = new URL((input as Request).url);
1176
+ if (
1177
+ url.pathname.endsWith("/api/v1/audit/") &&
1178
+ url.searchParams.get("target_type") === "Group" &&
1179
+ url.searchParams.get("target_id") === "g1"
1180
+ ) {
1181
+ return jsonResponse({
1182
+ items: [
1183
+ {
1184
+ id: "g-e1",
1185
+ created_at: "2026-08-20T08:00:00Z",
1186
+ action: "created",
1187
+ target_type: "Group",
1188
+ target_id: "g1",
1189
+ actor_id: null,
1190
+ request_id: null,
1191
+ payload: null,
1192
+ },
1193
+ ],
1194
+ total: 1,
1195
+ skip: 0,
1196
+ limit: 10,
1197
+ });
1198
+ }
1199
+ return base(input);
1200
+ });
1201
+ const history = await screen.findByRole("list", { name: "History" });
1202
+ expect(within(history).getAllByRole("listitem").map((item) => item.textContent)).toEqual([
1203
+ expect.stringContaining("Created"),
1204
+ ]);
1205
+ });
1206
+
1207
+ it.each([
1208
+ ["a trail the caller may not read", () => jsonResponse({ code: "permission_denied", detail: "No.", request_id: "-" }, 403)],
1209
+ ["a trail with nothing about the record", () => jsonResponse({ items: [], total: 0, skip: 0, limit: 10 })],
1210
+ ])("renders no history section for %s, and nothing in its place", async (_case, answer) => {
1211
+ // The history is context: the screen is whole without it. Mutation: render an error state
1212
+ // when the trail cannot be read, or the card when it is empty, and a section appears here.
1213
+ const { fetchMock } = renderAdminApp("/admin/users/u1");
1214
+ const base = fetchMock.getMockImplementation()!;
1215
+ fetchMock.mockImplementation(async (input) => {
1216
+ const url = new URL((input as Request).url);
1217
+ return url.pathname.endsWith("/api/v1/audit/") ? answer() : base(input);
1218
+ });
1219
+ await screen.findByRole("heading", { level: 1 });
1220
+ await waitFor(() =>
1221
+ expect(
1222
+ fetchMock.mock.calls.some((call) => new URL((call[0] as Request).url).pathname.endsWith("/api/v1/audit/")),
1223
+ ).toBe(true),
1224
+ );
1225
+ // Let the answer land and the component settle before looking for what it must not draw.
1226
+ await act(async () => {
1227
+ await new Promise((resolve) => setTimeout(resolve, 0));
1228
+ });
1229
+ expect(screen.queryByRole("heading", { name: "History" })).toBeNull();
1230
+ expect(screen.queryByRole("list", { name: "History" })).toBeNull();
1231
+ expect(document.querySelector('[data-terp="error-state"]')).toBeNull();
1232
+ });
1233
+
1234
+ it("names each of a group's collections, and counts the one it has read", async () => {
1235
+ // The members and the grants were an h2 the screen placed over an embedded DataView, with
1236
+ // the count nowhere; the collection now carries its own name and count (ADR 0169 §5), and
1237
+ // the way to add to it sits in its toolbar, under the name. The fixture serves one member
1238
+ // and no grants request at all, so only the members heading may claim a number.
1239
+ // Mutation: drop the count from DataView's heading, and "Members 1" is never found.
1240
+ renderAdminApp("/admin/groups/g1");
1241
+ expect(await screen.findByRole("heading", { level: 3, name: "Members 1" })).toBeInTheDocument();
1242
+ const permissions = screen.getByRole("heading", { level: 3, name: /^Permissions/ });
1243
+ expect(permissions.closest('[data-terp="dataview"]')).not.toBeNull();
1244
+ // The add-member form is inside the members collection, after its heading.
1245
+ const members = screen.getByRole("heading", { level: 3, name: "Members 1" });
1246
+ const form = screen.getByRole("button", { name: "Add member" }).closest("form")!;
1247
+ expect(members.closest('[data-terp="dataview"]')!.contains(form)).toBe(true);
1248
+ expect(members.compareDocumentPosition(form) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
1249
+ });
1250
+
881
1251
  it("speaks the app's language on the audit screen, its table and expanded row included", async () => {
882
1252
  // The framework's own screen, under the framework's own Dutch catalog. Its title was Dutch
883
1253
  // and everything its DataView drew was not — the result count, the row controls — because