@terpjs/react-core 0.31.0 → 0.33.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.
@@ -1,126 +1,273 @@
1
1
  import { Link } from "@tanstack/react-router";
2
2
  import { useEffect, useState } from "react";
3
3
 
4
- import { HubCard, HubPage } from "../HubPage";
4
+ import type { components } from "@terpjs/contract";
5
+
6
+ import { ProportionBar } from "../charts/ProportionBar";
7
+ import { TrendChart } from "../charts/TrendChart";
8
+ import type { ChartPoint } from "../charts/TrendChart";
9
+ import { DashboardPage } from "../DashboardPage";
10
+ import { useFormatDate, useFormatNumber } from "../format";
11
+ import { HubCard } from "../HubPage";
5
12
  import type { RenderHubCardLink } from "../HubPage";
6
13
  import type { AdminAreaSections } from "../bootstrap";
7
14
  import { NavIcon } from "../icons";
8
- import { Stat } from "../Stat";
15
+ import { Grid } from "../layout";
16
+ import type { GridTemplate } from "../layout";
17
+ import { Stat, StatGroup } from "../Stat";
9
18
  import { useTerpClient } from "../TerpProvider";
10
19
  import { unwrap } from "../unwrap";
11
- import { useStrings } from "../uiText";
20
+ import { fillPlaceholders, useStrings } from "../uiText";
21
+ import { viewerTimeZone } from "../viewerTimeZone";
22
+ import { auditActionTone, auditActionWord } from "./RecordHistory";
23
+
24
+ type AuditActivityRead = components["schemas"]["AuditActivityRead"];
25
+ type AuditDayCount = components["schemas"]["AuditDayCount"];
12
26
 
13
27
  const renderLink: RenderHubCardLink = ({ to, children }) => <Link to={to}>{children}</Link>;
14
28
 
15
- interface HubStats {
16
- users: number | null;
29
+ /** The days the hub's activity chart draws; the read returns as many days before them too. */
30
+ const ACTIVITY_DAYS = 30;
31
+
32
+ /** The days the activity figure sums, read from the end of the same days. */
33
+ const FIGURE_DAYS = 7;
34
+
35
+ /** The area cards' tracks, one per card; a single card takes the row (`columns={1}`). */
36
+ const CARD_TEMPLATES: Record<number, GridTemplate> = { 2: "1:1", 3: "1:1:1", 4: "1:1:1:1" };
37
+
38
+ interface HubData {
39
+ accounts: number | null;
40
+ activeAccounts: number | null;
17
41
  groups: number | null;
42
+ activity: AuditActivityRead | null;
43
+ }
44
+
45
+ /** A `YYYY-MM-DD` day as that day, wherever the browser is: `new Date(day)` would read UTC. */
46
+ function localDay(isoDate: string): Date {
47
+ const [year, month, day] = isoDate.split("-").map(Number);
48
+ return new Date(year!, month! - 1, day!);
18
49
  }
19
50
 
20
51
  /**
21
- * Live totals for the hub cards (a `limit=1` page carries the exact total).
22
- * A section the app dropped never fires its call — its capability may not be
23
- * mounted at all.
52
+ * The hub's figures and the trail's activity, each read on its own so one that fails leaves the
53
+ * others standing. A section the app dropped never fires its reads: its capability may not be
54
+ * mounted at all. The active accounts are a total under the status filter, and the activity is
55
+ * counted on the server, so nothing is counted from a page in the browser.
24
56
  */
25
- function useHubStats(sections: Required<AdminAreaSections>): HubStats {
57
+ function useHubData(sections: Required<AdminAreaSections>): HubData {
26
58
  const client = useTerpClient();
27
- const [stats, setStats] = useState<HubStats>({ users: null, groups: null });
28
- const { users: wantUsers, groups: wantGroups } = sections;
59
+ const [data, setData] = useState<HubData>({
60
+ accounts: null,
61
+ activeAccounts: null,
62
+ groups: null,
63
+ activity: null,
64
+ });
65
+ const { users: wantUsers, groups: wantGroups, audit: wantAudit } = sections;
29
66
  useEffect(() => {
30
67
  const controller = new AbortController();
31
- void (async () => {
32
- try {
33
- const [users, groups] = await Promise.all([
34
- wantUsers
35
- ? client.GET("/api/v1/users/", {
36
- params: { query: { limit: 1 } },
37
- signal: controller.signal,
38
- })
39
- : null,
40
- wantGroups
41
- ? client.GET("/api/v1/groups/", {
42
- params: { query: { limit: 1 } },
43
- signal: controller.signal,
44
- })
45
- : null,
46
- ]);
47
- setStats({
48
- users: users !== null ? unwrap(users).total : null,
49
- groups: groups !== null ? unwrap(groups).total : null,
50
- });
51
- } catch {
52
- // The cards stay navigable without their stat lines (e.g. offline, races).
53
- }
54
- })();
68
+ const signal = controller.signal;
69
+ const keep = <K extends keyof HubData>(key: K, read: () => Promise<HubData[K]>) => {
70
+ void read().then(
71
+ (value) => {
72
+ if (!signal.aborted) setData((current) => ({ ...current, [key]: value }));
73
+ },
74
+ // The page stays usable without the figure: it keeps its dash (offline, a race).
75
+ () => undefined,
76
+ );
77
+ };
78
+ if (wantUsers) {
79
+ keep("accounts", async () =>
80
+ unwrap(await client.GET("/api/v1/users/", { params: { query: { limit: 1 } }, signal })).total,
81
+ );
82
+ keep("activeAccounts", async () =>
83
+ unwrap(
84
+ await client.GET("/api/v1/users/", {
85
+ params: { query: { is_active: true, limit: 1 } },
86
+ signal,
87
+ }),
88
+ ).total,
89
+ );
90
+ }
91
+ if (wantGroups) {
92
+ keep("groups", async () =>
93
+ unwrap(await client.GET("/api/v1/groups/", { params: { query: { limit: 1 } }, signal })).total,
94
+ );
95
+ }
96
+ if (wantAudit) {
97
+ keep("activity", async () => {
98
+ const read = (time_zone: string) =>
99
+ client.GET("/api/v1/audit/activity", {
100
+ params: { query: { days: ACTIVITY_DAYS, time_zone } },
101
+ signal,
102
+ });
103
+ const zone = viewerTimeZone();
104
+ const answer = await read(zone);
105
+ // A zone the server's database does not know is refused (400). Counted in UTC the
106
+ // trail is a day off at worst; refused, the figure kept its dash and both charts were
107
+ // gone, with nothing on the page to say why.
108
+ if (answer.response.status === 400 && zone !== "UTC") return unwrap(await read("UTC"));
109
+ return unwrap(answer);
110
+ });
111
+ }
55
112
  return () => controller.abort();
56
- }, [client, wantUsers, wantGroups]);
57
- return stats;
113
+ }, [client, wantUsers, wantGroups, wantAudit]);
114
+ return data;
115
+ }
116
+
117
+ function sum(days: readonly AuditDayCount[]): number {
118
+ return days.reduce((total, day) => total + day.count, 0);
58
119
  }
59
120
 
60
121
  /**
61
- * The packaged admin hub (`/admin`): one card per administration area — users,
62
- * groups and the audit log — with live totals where they are cheap to know, each a `Stat`
63
- * so a count reads here as it does on every other page (ADR 0169 §5).
64
- * The sidebar's single "Admin" entry opens this hub; the overviews breadcrumb
65
- * back to it, keeping the hub -> overview -> detail layering every Terp screen
66
- * follows. `sections` (default: all) mirrors the app's `adminArea` selection —
67
- * a dropped section loses its card and its stat call.
122
+ * The packaged admin hub (`/admin`): a dashboard of the administration (ADR 0171). The summary
123
+ * band carries the active accounts — the headline — the groups and the trail's last week; the
124
+ * areas follow as cards, getting to one being the hub's first job; then the trail per day
125
+ * against the days before, and the kinds of change. The sidebar's single "Admin" entry opens
126
+ * it, and the overviews breadcrumb back to it, keeping the hub -> overview -> detail layering
127
+ * every Terp screen follows. `sections` (default: all) mirrors the app's `adminArea` selection:
128
+ * a dropped section loses its card, its figure, its reads and, for the audit log, its charts.
68
129
  */
69
130
  export function AdminHub({ sections }: { sections?: AdminAreaSections } = {}) {
70
131
  const strings = useStrings();
132
+ const formatDate = useFormatDate();
133
+ const formatNumber = useFormatNumber();
71
134
  const selected = {
72
135
  users: sections?.users !== false,
73
136
  groups: sections?.groups !== false,
74
137
  audit: sections?.audit !== false,
75
138
  access: sections?.access !== false,
76
139
  };
77
- const stats = useHubStats(selected);
140
+ const data = useHubData(selected);
141
+ const activity = data.activity;
142
+ const points = (days: readonly AuditDayCount[]): ChartPoint[] =>
143
+ days.map((day) => ({ label: formatDate(localDay(day.date)), value: day.count }));
144
+ const lastWeek = activity === null ? null : activity.days.slice(-FIGURE_DAYS);
145
+ const weekBefore =
146
+ activity === null ? null : activity.days.slice(-2 * FIGURE_DAYS, -FIGURE_DAYS);
147
+ // Two reads that run side by side, so an account made between them could make this -1.
148
+ const deactivated =
149
+ data.accounts === null || data.activeAccounts === null
150
+ ? null
151
+ : Math.max(0, data.accounts - data.activeAccounts);
152
+
153
+ const figures = [
154
+ selected.users && (
155
+ <Stat
156
+ key="accounts"
157
+ headline
158
+ label={strings.adminHubActiveAccounts}
159
+ value={data.activeAccounts}
160
+ caption={
161
+ deactivated === null
162
+ ? undefined
163
+ : fillPlaceholders(strings.adminHubDeactivated, { count: formatNumber(deactivated) })
164
+ }
165
+ />
166
+ ),
167
+ selected.groups && <Stat key="groups" label={strings.adminGroups} value={data.groups} />,
168
+ selected.audit && (
169
+ <Stat
170
+ key="changes"
171
+ label={fillPlaceholders(strings.adminHubChangesWeek, { count: formatNumber(FIGURE_DAYS) })}
172
+ value={lastWeek === null ? null : sum(lastWeek)}
173
+ delta={
174
+ lastWeek === null || weekBefore === null
175
+ ? undefined
176
+ : {
177
+ value: sum(lastWeek) - sum(weekBefore),
178
+ sentiment: "neutral",
179
+ label: strings.adminHubVsWeekBefore,
180
+ }
181
+ }
182
+ trend={lastWeek === null ? undefined : points(lastWeek)}
183
+ />
184
+ ),
185
+ ].filter(Boolean);
186
+
187
+ const cards = [
188
+ selected.users && (
189
+ <HubCard
190
+ key="users"
191
+ to="/admin/users"
192
+ title={strings.adminUsers}
193
+ description={strings.adminUsersDescription}
194
+ icon={<NavIcon name="users" label={strings.adminUsers} />}
195
+ renderLink={renderLink}
196
+ />
197
+ ),
198
+ selected.groups && (
199
+ <HubCard
200
+ key="groups"
201
+ to="/admin/groups"
202
+ title={strings.adminGroups}
203
+ description={strings.adminGroupsDescription}
204
+ icon={<NavIcon name="shield" label={strings.adminGroups} />}
205
+ renderLink={renderLink}
206
+ />
207
+ ),
208
+ selected.audit && (
209
+ <HubCard
210
+ key="audit"
211
+ to="/admin/audit"
212
+ title={strings.adminAudit}
213
+ description={strings.adminAuditDescription}
214
+ icon={<NavIcon name="audit" label={strings.adminAudit} />}
215
+ renderLink={renderLink}
216
+ />
217
+ ),
218
+ selected.access && (
219
+ <HubCard
220
+ key="access"
221
+ to="/admin/access"
222
+ title={strings.adminAccess}
223
+ description={strings.adminAccessDescription}
224
+ icon={<NavIcon name="shield" label={strings.adminAccess} />}
225
+ renderLink={renderLink}
226
+ />
227
+ ),
228
+ ].filter(Boolean);
229
+
78
230
  return (
79
- <HubPage title={strings.admin} parents={[{ label: strings.home, to: "/" }]}>
80
- {selected.users && (
81
- <HubCard
82
- to="/admin/users"
83
- title={strings.adminUsers}
84
- description={strings.adminUsersDescription}
85
- icon={<NavIcon name="users" label={strings.adminUsers} />}
86
- stat={
87
- stats.users !== null ? <Stat label={strings.adminHubTotal} value={stats.users} /> : undefined
88
- }
89
- renderLink={renderLink}
90
- />
91
- )}
92
- {selected.groups && (
93
- <HubCard
94
- to="/admin/groups"
95
- title={strings.adminGroups}
96
- description={strings.adminGroupsDescription}
97
- icon={<NavIcon name="shield" label={strings.adminGroups} />}
98
- stat={
99
- stats.groups !== null ? (
100
- <Stat label={strings.adminHubTotal} value={stats.groups} />
101
- ) : undefined
102
- }
103
- renderLink={renderLink}
104
- />
231
+ <DashboardPage
232
+ title={strings.admin}
233
+ parents={[{ label: strings.home, to: "/" }]}
234
+ summary={figures.length > 0 ? <StatGroup>{figures}</StatGroup> : undefined}
235
+ >
236
+ {/* As many tracks as cards: a fixed three left a blank column beside two cards and gave
237
+ one card a third of the row. */}
238
+ {cards.length > 1 ? (
239
+ <Grid as="ul" template={CARD_TEMPLATES[cards.length]}>
240
+ {cards}
241
+ </Grid>
242
+ ) : (
243
+ <Grid as="ul" columns={1}>
244
+ {cards}
245
+ </Grid>
105
246
  )}
106
- {selected.audit && (
107
- <HubCard
108
- to="/admin/audit"
109
- title={strings.adminAudit}
110
- description={strings.adminAuditDescription}
111
- icon={<NavIcon name="audit" label={strings.adminAudit} />}
112
- renderLink={renderLink}
247
+ {selected.audit && activity !== null && (
248
+ <TrendChart
249
+ label={strings.adminHubChangesPerDay}
250
+ mark="columns"
251
+ series={{
252
+ label: fillPlaceholders(strings.adminHubLastDays, { count: formatNumber(ACTIVITY_DAYS) }),
253
+ points: points(activity.days),
254
+ }}
255
+ comparison={{
256
+ label: fillPlaceholders(strings.adminHubDaysBefore, { count: formatNumber(ACTIVITY_DAYS) }),
257
+ points: points(activity.previous_days),
258
+ }}
113
259
  />
114
260
  )}
115
- {selected.access && (
116
- <HubCard
117
- to="/admin/access"
118
- title={strings.adminAccess}
119
- description={strings.adminAccessDescription}
120
- icon={<NavIcon name="shield" label={strings.adminAccess} />}
121
- renderLink={renderLink}
261
+ {selected.audit && activity !== null && activity.by_action.length > 0 && (
262
+ <ProportionBar
263
+ label={fillPlaceholders(strings.adminHubChangesByKind, { count: formatNumber(ACTIVITY_DAYS) })}
264
+ parts={activity.by_action.map((row) => ({
265
+ label: auditActionWord(strings, row.action),
266
+ value: row.count,
267
+ tone: auditActionTone(row.action),
268
+ }))}
122
269
  />
123
270
  )}
124
- </HubPage>
271
+ </DashboardPage>
125
272
  );
126
273
  }
@@ -346,7 +346,7 @@ export function GroupDetail() {
346
346
  const record = group.item;
347
347
  return (
348
348
  <DetailPage
349
- title={record?.name ?? strings.adminGroups}
349
+ title={record?.name ?? null}
350
350
  parents={[
351
351
  { ...adminCrumb(strings), to: "/admin" },
352
352
  { label: strings.adminGroups, to: "/admin/groups" },
@@ -29,6 +29,11 @@ const ACTION_TONES: Record<string, BadgeTone | undefined> = {
29
29
  disclosed: "info",
30
30
  };
31
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
+
32
37
  /** An audit action in the app's words, or as recorded where it is not one the framework names. */
33
38
  export function auditActionWord(strings: TerpStrings, action: string): string {
34
39
  const key = ACTION_WORDS[action];
@@ -129,7 +129,7 @@ export function UserDetail() {
129
129
 
130
130
  return (
131
131
  <DetailPage
132
- title={record?.email ?? strings.adminUsers}
132
+ title={record?.email ?? null}
133
133
  parents={[
134
134
  { ...adminCrumb(strings), to: "/admin" },
135
135
  { label: strings.adminUsers, to: "/admin/users" },