create-astram-app 0.14.15 → 0.14.16

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-astram-app",
3
- "version": "0.14.15",
3
+ "version": "0.14.16",
4
4
  "license": "MIT",
5
5
  "description": "Scaffolder for a new Astram app — emits a running, framework-enforced NestJS server (deny-by-default, built-in auth/identity to switch on) and, with --with-frontend, a React admin/auth UI, over the immutable @astram/* framework packages.",
6
6
  "type": "module",
@@ -15,7 +15,7 @@
15
15
  "test": "node scripts/run-tests.mjs"
16
16
  },
17
17
  "dependencies": {
18
- "@astram/frontend-core": "^0.17.0",
18
+ "@astram/frontend-core": "^0.18.0",
19
19
  "@astram/sdk": "^0.2.1",
20
20
  "@radix-ui/react-alert-dialog": "^1.1.19",
21
21
  "@radix-ui/react-avatar": "^1.1.10",
@@ -11,7 +11,12 @@
11
11
  * server accepts — one source of truth, no client-side operator table. The server re-validates
12
12
  * (`validateGuidedPolicy`) and enforces the delegated-admin ceiling on save.
13
13
  * ⛔ The target TENANT is never sent — the server authors in the caller's own tenant.
14
- * ⛔ No raw UUID is shown — `policyId` is a delete key only.
14
+ * ⛔ No raw UUID is shown — `policyId` is a delete key only; subject roles render by NAME
15
+ * ("Unknown role" when the name is not known), never by id.
16
+ *
17
+ * "Applies to" (department-scoped policies §5 F): Everyone / Only these roles / Everyone except
18
+ * these roles, picked from the active company's roles (`identity.listCompanyRoles`). The server
19
+ * checks that every role is owned in the caller's reach.
15
20
  */
16
21
  import { useCallback, useEffect, useMemo, useState } from 'react';
17
22
  import { ShieldCheck, Plus, Trash2, Info } from 'lucide-react';
@@ -21,6 +26,7 @@ import AppShell from '@/shell/AppShell';
21
26
  import PageHeader from '@/components/PageHeader';
22
27
  import EntityList from '@/components/EntityList';
23
28
  import ConfirmDialog from '@/components/ConfirmDialog';
29
+ import MultiSelectChecklist from '@/components/MultiSelectChecklist';
24
30
  import { Badge } from '@/components/ui/badge';
25
31
  import { Button } from '@/components/ui/button';
26
32
  import { Input } from '@/components/ui/input';
@@ -32,17 +38,40 @@ import {
32
38
  SelectTrigger,
33
39
  SelectValue,
34
40
  } from '@/components/ui/select';
35
- import { operatorLabel, isNullaryOperator, buildCondition } from './recordPolicyBuilder.js';
41
+ import {
42
+ operatorLabel,
43
+ isNullaryOperator,
44
+ buildCondition,
45
+ isDepartmentOperator,
46
+ offeredOperators,
47
+ buildSubject,
48
+ subjectProblem,
49
+ coversWholeType,
50
+ roleNamesById,
51
+ describeSubject,
52
+ SUBJECT_KINDS,
53
+ SUBJECT_KIND_LABELS,
54
+ DEPARTMENT_OPERATOR_HELP,
55
+ } from './recordPolicyBuilder.js';
36
56
 
37
57
  /** The object types this app lets an admin author policies for. Extend as the app grows. */
38
58
  const AUTHORABLE_TYPES = ['note'];
39
59
 
60
+ /** Role list paging: the server's page cap, and how many pages to read at most. */
61
+ const ROLE_PAGE_LIMIT = 100;
62
+ const ROLE_MAX_PAGES = 10;
63
+
64
+ /** Shown when a saved policy has no conditions and a role subject. */
65
+ const WHOLE_TYPE_TEXT = 'applies to every record of this type';
66
+
40
67
  /** A fresh, empty condition row. */
41
68
  const emptyCondition = () => ({ field: '', operator: '', value: '' });
42
69
 
43
70
  export default function RecordPoliciesPage() {
44
- const { tokens, recordPolicy } = useAuth();
71
+ const { tokens, session, recordPolicy, identity } = useAuth();
45
72
  const token = tokens?.accessToken;
73
+ // Policies are authored in the caller's active company; its roles feed "Applies to".
74
+ const companyUuid = session?.tenantId ?? null;
46
75
 
47
76
  const [typeKey, setTypeKey] = useState(AUTHORABLE_TYPES[0] ?? '');
48
77
  const [schema, setSchema] = useState(null);
@@ -54,8 +83,15 @@ export default function RecordPoliciesPage() {
54
83
  const [action, setAction] = useState('');
55
84
  const [effect, setEffect] = useState('allow');
56
85
  const [conditions, setConditions] = useState([emptyCondition()]);
86
+ const [subjectKind, setSubjectKind] = useState('everyone');
87
+ const [subjectRoleIds, setSubjectRoleIds] = useState([]);
57
88
  const [saving, setSaving] = useState(false);
58
89
 
90
+ // The active company's roles (for the picker and for naming subject roles in the list).
91
+ const [roleRows, setRoleRows] = useState([]);
92
+ const [rolesLoading, setRolesLoading] = useState(true);
93
+ const [rolesError, setRolesError] = useState('');
94
+
59
95
  const [deleteTarget, setDeleteTarget] = useState(null);
60
96
  const [deleteBusy, setDeleteBusy] = useState(false);
61
97
 
@@ -65,6 +101,50 @@ export default function RecordPoliciesPage() {
65
101
  return m;
66
102
  }, [schema]);
67
103
 
104
+ const roleNames = useMemo(() => roleNamesById(roleRows), [roleRows]);
105
+ const roleOptions = useMemo(
106
+ () => [...roleNames].map(([id, name]) => ({ id, name })),
107
+ [roleNames],
108
+ );
109
+
110
+ // The subject kinds this server accepts; an older server without `subjectKinds` ⇒ Everyone only.
111
+ const subjectKinds = useMemo(() => {
112
+ const offered = schema?.subjectKinds;
113
+ return Array.isArray(offered) ? SUBJECT_KINDS.filter((k) => offered.includes(k)) : ['everyone'];
114
+ }, [schema]);
115
+
116
+ useEffect(() => {
117
+ // No active company (should not happen once signed in): the picker shows no roles.
118
+ if (!token || !companyUuid) return undefined;
119
+ let cancelled = false;
120
+ (async () => {
121
+ setRolesLoading(true);
122
+ const rows = [];
123
+ let failure = '';
124
+ for (let page = 1; page <= ROLE_MAX_PAGES; page += 1) {
125
+ const r = await identity.listCompanyRoles(token, companyUuid, {
126
+ page,
127
+ limit: ROLE_PAGE_LIMIT,
128
+ sortBy: 'name',
129
+ sortOrder: 'asc',
130
+ });
131
+ if (cancelled) return;
132
+ if (!r.ok) {
133
+ failure = r.error || 'Could not load roles.';
134
+ break;
135
+ }
136
+ rows.push(...(r.rows ?? []));
137
+ if (rows.length >= (r.total ?? 0) || (r.rows ?? []).length === 0) break;
138
+ }
139
+ setRoleRows(rows);
140
+ setRolesError(failure);
141
+ setRolesLoading(false);
142
+ })();
143
+ return () => {
144
+ cancelled = true;
145
+ };
146
+ }, [identity, token, companyUuid]);
147
+
68
148
  const load = useCallback(async () => {
69
149
  if (!token || !typeKey) return;
70
150
  setLoading(true);
@@ -101,21 +181,48 @@ export default function RecordPoliciesPage() {
101
181
  const removeCondition = (i) =>
102
182
  setConditions((cs) => (cs.length <= 1 ? cs : cs.filter((_, idx) => idx !== i)));
103
183
 
184
+ // Switching the effect drops any operator no longer offered (not_in_my_departments is deny-only).
185
+ const onEffectChange = (next) => {
186
+ setEffect(next);
187
+ setConditions((cs) =>
188
+ cs.map((c) =>
189
+ c.operator && !offeredOperators(fieldsByKey.get(c.field), next).includes(c.operator)
190
+ ? { ...c, operator: '', value: '' }
191
+ : c,
192
+ ),
193
+ );
194
+ };
195
+
196
+ const onSubjectKindChange = (next) => {
197
+ setSubjectKind(next);
198
+ if (next === 'everyone') setSubjectRoleIds([]);
199
+ };
200
+
201
+ // Conditions complete enough to send (field + operator); drives the whole-type notice too.
202
+ const completeConditions = conditions.filter((c) => c.field && c.operator);
203
+
104
204
  const onSave = async () => {
105
205
  if (!action) {
106
206
  toast.error('Pick an action.');
107
207
  return;
108
208
  }
109
- // Build the structured conditions, dropping incomplete rows; a nullary op needs no value.
110
- const built = [];
111
- for (const c of conditions) {
112
- if (!c.field || !c.operator) continue;
113
- const fieldSchema = fieldsByKey.get(c.field);
114
- built.push(buildCondition(c, fieldSchema));
209
+ const subject = buildSubject(subjectKind, subjectRoleIds);
210
+ const problem = subjectProblem(subject);
211
+ if (problem) {
212
+ toast.error(problem);
213
+ return;
115
214
  }
215
+ // Build the structured conditions, dropping incomplete rows; a nullary op needs no value.
216
+ const built = completeConditions.map((c) => buildCondition(c, fieldsByKey.get(c.field)));
116
217
 
117
218
  setSaving(true);
118
- const r = await recordPolicy.author(token, { typeKey, action, effect, conditions: built });
219
+ const r = await recordPolicy.author(token, {
220
+ typeKey,
221
+ action,
222
+ effect,
223
+ conditions: built,
224
+ subject,
225
+ });
119
226
  setSaving(false);
120
227
  if (!r.ok) {
121
228
  toast.error(r.error || 'Could not author the policy.');
@@ -149,7 +256,12 @@ export default function RecordPoliciesPage() {
149
256
  c.value === undefined || isNullaryOperator(c.operator, fieldsByKey.get(c.field));
150
257
  return `${c.field} ${label}${isNullary ? '' : ` ${val}`}`;
151
258
  });
152
- const where = parts.length ? ` where ${parts.join(' AND ')}` : ' (all records)';
259
+ const kind = policy.subject?.kind ?? 'everyone';
260
+ const where = parts.length
261
+ ? ` where ${parts.join(' AND ')}`
262
+ : coversWholeType(0, kind)
263
+ ? ` (${WHOLE_TYPE_TEXT})`
264
+ : ' (all records)';
153
265
  return `${policy.effect} ${policy.action}${where}`;
154
266
  };
155
267
 
@@ -167,6 +279,13 @@ export default function RecordPoliciesPage() {
167
279
  ),
168
280
  },
169
281
  { key: 'action', label: 'Action', render: (row) => row.policy.action },
282
+ {
283
+ key: 'subject',
284
+ label: 'Applies to',
285
+ render: (row) => (
286
+ <span className="text-sm">{describeSubject(row.policy.subject, roleNames)}</span>
287
+ ),
288
+ },
170
289
  {
171
290
  key: 'rule',
172
291
  label: 'Rule',
@@ -224,7 +343,7 @@ export default function RecordPoliciesPage() {
224
343
  <div className="mb-4 flex flex-wrap items-end gap-3">
225
344
  <div className="space-y-1">
226
345
  <Label htmlFor="policy-effect">Effect</Label>
227
- <Select value={effect} onValueChange={setEffect}>
346
+ <Select value={effect} onValueChange={onEffectChange}>
228
347
  <SelectTrigger id="policy-effect" className="w-36">
229
348
  <SelectValue />
230
349
  </SelectTrigger>
@@ -249,15 +368,52 @@ export default function RecordPoliciesPage() {
249
368
  </SelectContent>
250
369
  </Select>
251
370
  </div>
371
+ <div className="space-y-1">
372
+ <Label htmlFor="policy-subject">Applies to</Label>
373
+ <Select
374
+ value={subjectKind}
375
+ onValueChange={onSubjectKindChange}
376
+ disabled={subjectKinds.length <= 1}
377
+ >
378
+ <SelectTrigger id="policy-subject" className="w-60">
379
+ <SelectValue />
380
+ </SelectTrigger>
381
+ <SelectContent>
382
+ {subjectKinds.map((k) => (
383
+ <SelectItem key={k} value={k}>
384
+ {SUBJECT_KIND_LABELS[k]}
385
+ </SelectItem>
386
+ ))}
387
+ </SelectContent>
388
+ </Select>
389
+ </div>
252
390
  </div>
253
391
 
392
+ {subjectKind !== 'everyone' && (
393
+ <div className="mb-4 max-w-md">
394
+ <MultiSelectChecklist
395
+ id="policy-subject-roles"
396
+ label={subjectKind === 'roles' ? 'Only these roles' : 'Except these roles'}
397
+ options={roleOptions}
398
+ value={subjectRoleIds}
399
+ onChange={setSubjectRoleIds}
400
+ loading={rolesLoading && !!companyUuid}
401
+ disabled={saving}
402
+ searchPlaceholder="Search roles…"
403
+ emptyLabel="This company has no roles yet."
404
+ hint="Pick 1 to 16 roles of this company."
405
+ error={rolesError || undefined}
406
+ />
407
+ </div>
408
+ )}
409
+
254
410
  <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
255
411
  Where (all conditions must match)
256
412
  </div>
257
413
  <div className="space-y-2">
258
414
  {conditions.map((c, i) => {
259
415
  const fieldSchema = fieldsByKey.get(c.field);
260
- const validOps = fieldSchema?.validOperators ?? [];
416
+ const validOps = offeredOperators(fieldSchema, effect);
261
417
  const isNullary = isNullaryOperator(c.operator, fieldSchema);
262
418
  const isArray = fieldSchema?.arrayOperators?.includes(c.operator);
263
419
  const isContains = c.operator === 'contains' || c.operator === 'not_contains';
@@ -326,11 +482,25 @@ export default function RecordPoliciesPage() {
326
482
  “contains” is not index-friendly on large tables.
327
483
  </span>
328
484
  )}
485
+
486
+ {isDepartmentOperator(c.operator) && (
487
+ <p className="inline-flex basis-full items-center gap-1 text-xs text-muted-foreground">
488
+ <Info className="size-3.5 shrink-0" aria-hidden="true" />
489
+ {DEPARTMENT_OPERATOR_HELP}
490
+ </p>
491
+ )}
329
492
  </div>
330
493
  );
331
494
  })}
332
495
  </div>
333
496
 
497
+ {coversWholeType(completeConditions.length, subjectKind) && (
498
+ <p className="mt-2 inline-flex items-center gap-1 text-xs text-muted-foreground">
499
+ <Info className="size-3.5 shrink-0" aria-hidden="true" />
500
+ With no conditions, this policy {WHOLE_TYPE_TEXT}.
501
+ </p>
502
+ )}
503
+
334
504
  <div className="mt-3 flex items-center gap-2">
335
505
  <Button type="button" variant="outline" size="sm" onClick={addCondition}>
336
506
  <Plus className="size-4" />
@@ -17,6 +17,8 @@ export const OPERATOR_LABELS = {
17
17
  is_not_null: 'is not empty',
18
18
  is_owner: 'is me',
19
19
  is_not_owner: 'is not me',
20
+ in_my_departments: 'is one of my departments',
21
+ not_in_my_departments: 'is not one of my departments',
20
22
  };
21
23
 
22
24
  /** The label for an operator; falls back to the operator key. */
@@ -24,6 +26,110 @@ export function operatorLabel(op) {
24
26
  return OPERATOR_LABELS[op] ?? op;
25
27
  }
26
28
 
29
+ /** The principal-relative department operators (compare with the viewer's department codes). */
30
+ export const DEPARTMENT_OPERATORS = ['in_my_departments', 'not_in_my_departments'];
31
+
32
+ /** Operators the server accepts only in a deny policy (they would widen an allow). */
33
+ const DENY_ONLY_OPERATORS = ['not_in_my_departments'];
34
+
35
+ /** The help line shown under a department operator. */
36
+ export const DEPARTMENT_OPERATOR_HELP =
37
+ 'Compares with the codes of the departments the viewer is posted to in their active company. ' +
38
+ 'Departments without a code never match.';
39
+
40
+ /** True for `in_my_departments` / `not_in_my_departments`. */
41
+ export function isDepartmentOperator(op) {
42
+ return DEPARTMENT_OPERATORS.includes(op);
43
+ }
44
+
45
+ /**
46
+ * The operators to offer for a field under the chosen effect: the schema's `validOperators`,
47
+ * minus `not_in_my_departments` unless the effect is `deny` (the server refuses it in an allow).
48
+ */
49
+ export function offeredOperators(fieldSchema, effect) {
50
+ const ops = fieldSchema?.validOperators ?? [];
51
+ return effect === 'deny' ? [...ops] : ops.filter((op) => !DENY_ONLY_OPERATORS.includes(op));
52
+ }
53
+
54
+ /** "Applies to" choices, in display order. */
55
+ export const SUBJECT_KINDS = ['everyone', 'roles', 'except_roles'];
56
+
57
+ /** "Applies to" labels. */
58
+ export const SUBJECT_KIND_LABELS = {
59
+ everyone: 'Everyone',
60
+ roles: 'Only these roles',
61
+ except_roles: 'Everyone except these roles',
62
+ };
63
+
64
+ /** The most roles one subject may list (server rule). */
65
+ export const MAX_SUBJECT_ROLES = 16;
66
+
67
+ /** Shown for a subject role id with no known name (never the id itself). */
68
+ export const UNKNOWN_ROLE_LABEL = 'Unknown role';
69
+
70
+ /**
71
+ * The submitted subject: `{ kind: 'everyone' }`, or `{ kind, roleIds }` for `roles` /
72
+ * `except_roles` with the ids trimmed, de-duplicated and empty ones dropped. An unknown kind
73
+ * returns `null` (the page refuses to save; never silently "everyone").
74
+ */
75
+ export function buildSubject(kind, roleIds) {
76
+ if (kind === 'everyone') return { kind: 'everyone' };
77
+ if (kind !== 'roles' && kind !== 'except_roles') return null;
78
+ const ids = [];
79
+ for (const raw of roleIds ?? []) {
80
+ const id = typeof raw === 'string' ? raw.trim() : '';
81
+ if (id && !ids.includes(id)) ids.push(id);
82
+ }
83
+ return { kind, roleIds: ids };
84
+ }
85
+
86
+ /** A reason the subject cannot be saved, or `null` when it can. */
87
+ export function subjectProblem(subject) {
88
+ if (!subject) return 'Pick who the policy applies to.';
89
+ if (subject.kind === 'everyone') return null;
90
+ if (subject.roleIds.length === 0) return 'Pick at least one role.';
91
+ if (subject.roleIds.length > MAX_SUBJECT_ROLES) {
92
+ return `Pick at most ${MAX_SUBJECT_ROLES} roles.`;
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * True when a saved policy covers every record of its type for its subject: no conditions and a
99
+ * subject other than Everyone (the page then says "applies to every record of this type").
100
+ */
101
+ export function coversWholeType(conditionCount, subjectKind) {
102
+ return conditionCount === 0 && subjectKind !== 'everyone';
103
+ }
104
+
105
+ /**
106
+ * Role rows (`{ id, fields: { name } }`, from `listCompanyRoles`) → Map id → name. Rows without an
107
+ * id are dropped; an unnamed role maps to "(unnamed)".
108
+ */
109
+ export function roleNamesById(rows) {
110
+ const names = new Map();
111
+ for (const row of rows ?? []) {
112
+ if (!row || typeof row.id !== 'string' || row.id.length === 0) continue;
113
+ const name = row.fields?.name;
114
+ names.set(row.id, typeof name === 'string' && name.length > 0 ? name : '(unnamed)');
115
+ }
116
+ return names;
117
+ }
118
+
119
+ /**
120
+ * A policy subject in words, by role NAME: "Everyone", "Only: A, B", "Everyone except: A, B".
121
+ * A role id without a known name renders "Unknown role" (never the id). A missing subject reads as
122
+ * Everyone (older servers).
123
+ */
124
+ export function describeSubject(subject, namesById) {
125
+ if (!subject || subject.kind === 'everyone') return SUBJECT_KIND_LABELS.everyone;
126
+ const names = (subject.roleIds ?? []).map((id) => namesById?.get(id) ?? UNKNOWN_ROLE_LABEL);
127
+ const list = names.length > 0 ? names.join(', ') : UNKNOWN_ROLE_LABEL;
128
+ if (subject.kind === 'roles') return `Only: ${list}`;
129
+ if (subject.kind === 'except_roles') return `Everyone except: ${list}`;
130
+ return 'Unknown audience';
131
+ }
132
+
27
133
  /** True when the field's schema lists the operator as taking no value. */
28
134
  export function isNullaryOperator(op, fieldSchema) {
29
135
  return Boolean(fieldSchema?.nullaryOperators?.includes(op));
@@ -6,7 +6,115 @@
6
6
  // node --test src/pages/access/recordPolicyBuilder.test.mjs
7
7
  import { test, describe } from 'node:test';
8
8
  import assert from 'node:assert/strict';
9
- import { operatorLabel, isNullaryOperator, buildCondition } from './recordPolicyBuilder.js';
9
+ import {
10
+ operatorLabel,
11
+ isNullaryOperator,
12
+ buildCondition,
13
+ isDepartmentOperator,
14
+ offeredOperators,
15
+ buildSubject,
16
+ subjectProblem,
17
+ coversWholeType,
18
+ roleNamesById,
19
+ describeSubject,
20
+ SUBJECT_KINDS,
21
+ SUBJECT_KIND_LABELS,
22
+ DEPARTMENT_OPERATOR_HELP,
23
+ } from './recordPolicyBuilder.js';
24
+
25
+ const deptField = {
26
+ key: 'domainCode',
27
+ validOperators: ['eq', 'is_null', 'in_my_departments', 'not_in_my_departments'],
28
+ nullaryOperators: ['is_null', 'in_my_departments', 'not_in_my_departments'],
29
+ arrayOperators: [],
30
+ };
31
+
32
+ describe('department operators (department-scoped policies §5 F)', () => {
33
+ test('labels', () => {
34
+ assert.equal(operatorLabel('in_my_departments'), 'is one of my departments');
35
+ assert.equal(operatorLabel('not_in_my_departments'), 'is not one of my departments');
36
+ });
37
+ test('isDepartmentOperator', () => {
38
+ assert.equal(isDepartmentOperator('in_my_departments'), true);
39
+ assert.equal(isDepartmentOperator('not_in_my_departments'), true);
40
+ assert.equal(isDepartmentOperator('eq'), false);
41
+ });
42
+ test('not_in_my_departments is offered only for a deny policy', () => {
43
+ assert.deepEqual(offeredOperators(deptField, 'allow'), ['eq', 'is_null', 'in_my_departments']);
44
+ assert.deepEqual(offeredOperators(deptField, 'deny'), deptField.validOperators);
45
+ assert.deepEqual(offeredOperators(undefined, 'deny'), []);
46
+ });
47
+ test('a department condition is sent without a value', () => {
48
+ const c = buildCondition(
49
+ { field: 'domainCode', operator: 'not_in_my_departments', value: 'stale' },
50
+ deptField,
51
+ );
52
+ assert.deepEqual(c, { field: 'domainCode', operator: 'not_in_my_departments' });
53
+ });
54
+ test('the help line is the fixed text', () => {
55
+ assert.equal(
56
+ DEPARTMENT_OPERATOR_HELP,
57
+ 'Compares with the codes of the departments the viewer is posted to in their active company. Departments without a code never match.',
58
+ );
59
+ });
60
+ });
61
+
62
+ describe('policy subject ("Applies to")', () => {
63
+ test('labels and order', () => {
64
+ assert.deepEqual(SUBJECT_KINDS, ['everyone', 'roles', 'except_roles']);
65
+ assert.deepEqual(
66
+ SUBJECT_KINDS.map((k) => SUBJECT_KIND_LABELS[k]),
67
+ ['Everyone', 'Only these roles', 'Everyone except these roles'],
68
+ );
69
+ });
70
+ test('buildSubject: everyone ignores role ids', () => {
71
+ assert.deepEqual(buildSubject('everyone', ['r1']), { kind: 'everyone' });
72
+ });
73
+ test('buildSubject: role kinds carry distinct, trimmed, non-empty ids', () => {
74
+ assert.deepEqual(buildSubject('except_roles', ['r1', ' r2 ', 'r1', '', null]), {
75
+ kind: 'except_roles',
76
+ roleIds: ['r1', 'r2'],
77
+ });
78
+ assert.deepEqual(buildSubject('roles', ['r3']), { kind: 'roles', roleIds: ['r3'] });
79
+ });
80
+ test('buildSubject: an unknown kind is null, never everyone', () => {
81
+ assert.equal(buildSubject('role', ['r1']), null);
82
+ assert.equal(buildSubject(undefined, []), null);
83
+ });
84
+ test('subjectProblem', () => {
85
+ assert.equal(subjectProblem({ kind: 'everyone' }), null);
86
+ assert.equal(subjectProblem({ kind: 'roles', roleIds: [] }), 'Pick at least one role.');
87
+ const many = Array.from({ length: 17 }, (_, i) => `r${i}`);
88
+ assert.equal(subjectProblem({ kind: 'roles', roleIds: many }), 'Pick at most 16 roles.');
89
+ assert.equal(subjectProblem({ kind: 'roles', roleIds: many.slice(0, 16) }), null);
90
+ assert.equal(subjectProblem(null), 'Pick who the policy applies to.');
91
+ });
92
+ test('coversWholeType: zero conditions with a role subject', () => {
93
+ assert.equal(coversWholeType(0, 'except_roles'), true);
94
+ assert.equal(coversWholeType(0, 'roles'), true);
95
+ assert.equal(coversWholeType(0, 'everyone'), false);
96
+ assert.equal(coversWholeType(1, 'except_roles'), false);
97
+ });
98
+ test('describeSubject renders role names; an unknown id is "Unknown role", never the id', () => {
99
+ const names = roleNamesById([
100
+ { id: 'r-ceo', fields: { name: 'CEO' } },
101
+ { id: 'r-rev', fields: { name: 'Reviewer' } },
102
+ { id: 'r-x', fields: {} },
103
+ { fields: { name: 'no id' } },
104
+ ]);
105
+ assert.equal(names.get('r-x'), '(unnamed)');
106
+ assert.equal(names.size, 3);
107
+ assert.equal(
108
+ describeSubject({ kind: 'except_roles', roleIds: ['r-ceo', 'r-rev'] }, names),
109
+ 'Everyone except: CEO, Reviewer',
110
+ );
111
+ const only = describeSubject({ kind: 'roles', roleIds: ['r-ceo', 'gone-uuid'] }, names);
112
+ assert.equal(only, 'Only: CEO, Unknown role');
113
+ assert.equal(only.includes('gone-uuid'), false);
114
+ assert.equal(describeSubject({ kind: 'everyone' }, names), 'Everyone');
115
+ assert.equal(describeSubject(undefined, names), 'Everyone');
116
+ });
117
+ });
10
118
 
11
119
  const ownerField = {
12
120
  key: 'created_by',
@@ -8,6 +8,11 @@
8
8
  * write keys (`orgStructure.js`; UX only). "Used by N assignments" disables Delete as a hint; the
9
9
  * server still refuses (409) a delete while any assignment uses the row, and that message is
10
10
  * toasted. Names come from the server; no uuid is ever shown.
11
+ *
12
+ * Departments also carry an optional Code (department-scoped policies SPEC §10): uppercased as
13
+ * typed, checked against `^[A-Z0-9_]{1,32}$` before sending, cleared by emptying the field
14
+ * (`code: null`). Record policies match it; the server's 400/409 message is toasted as is.
15
+ * Branches have no code.
11
16
  */
12
17
  import { useCallback, useEffect, useRef, useState } from 'react';
13
18
  import { MapPin, Network, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';
@@ -25,25 +30,35 @@ import {
25
30
  KINDS,
26
31
  LABELS,
27
32
  canManage,
33
+ codeInput,
28
34
  deleteHint,
35
+ departmentUpdate,
29
36
  displayRows,
30
37
  outcome,
31
38
  usedByLabel,
39
+ validateCode,
32
40
  validateName,
33
41
  } from './orgStructure';
34
42
 
35
- /** The identity-service calls per kind. */
43
+ /**
44
+ * The identity-service calls per kind. `create(identity, token, companyUuid, name, code)` and
45
+ * `rename(identity, token, row, name, code)`; `code` is `null` (no code) and only departments use it.
46
+ */
36
47
  const CALLS = {
37
48
  department: {
38
49
  list: (identity, ...a) => identity.listDepartments(...a),
39
- create: (identity, ...a) => identity.createDepartment(...a),
40
- rename: (identity, ...a) => identity.renameDepartment(...a),
50
+ create: (identity, token, companyUuid, name, code) =>
51
+ code === null
52
+ ? identity.createDepartment(token, companyUuid, name)
53
+ : identity.createDepartment(token, companyUuid, name, code),
54
+ rename: (identity, token, row, name, code) =>
55
+ identity.updateDepartment(token, row.uuid, departmentUpdate(row, name, code)),
41
56
  remove: (identity, ...a) => identity.deleteDepartment(...a),
42
57
  },
43
58
  branch: {
44
59
  list: (identity, ...a) => identity.listBranches(...a),
45
- create: (identity, ...a) => identity.createBranch(...a),
46
- rename: (identity, ...a) => identity.renameBranch(...a),
60
+ create: (identity, token, companyUuid, name) => identity.createBranch(token, companyUuid, name),
61
+ rename: (identity, token, row, name) => identity.renameBranch(token, row.uuid, name),
47
62
  remove: (identity, ...a) => identity.deleteBranch(...a),
48
63
  },
49
64
  };
@@ -51,30 +66,41 @@ const CALLS = {
51
66
  const ICONS = { department: Network, branch: MapPin };
52
67
 
53
68
  /**
54
- * The Add / Rename dialog: one name field, checked with the server's rules before sending.
55
- * Mounted only while open, so each opening starts from the current name (rename) or empty (add).
69
+ * The Add / Rename (Edit, for a department) dialog: a name field, checked with the server's rules
70
+ * before sending, and for a department an optional Code field. Mounted only while open, so each
71
+ * opening starts from the current values (edit) or empty (add).
56
72
  */
57
73
  function NameDialog({ dialog, busy, onSubmit, onCancel }) {
74
+ const withCode = dialog.kind === 'department';
58
75
  const [name, setName] = useState(dialog.row ? dialog.row.label : '');
76
+ const [code, setCode] = useState(dialog.row?.code ?? '');
59
77
  const [error, setError] = useState('');
78
+ const [codeError, setCodeError] = useState('');
60
79
  const fieldId = `org-${dialog.kind}-name`;
80
+ const codeId = `org-${dialog.kind}-code`;
61
81
  const one = LABELS[dialog.kind].one;
62
82
  const submit = () => {
63
83
  const checked = validateName(name);
64
- if (!checked.ok) {
65
- setError(checked.error);
66
- return;
67
- }
68
- setError('');
69
- onSubmit(checked.value);
84
+ const checkedCode = withCode ? validateCode(code) : { ok: true, value: null };
85
+ setError(checked.ok ? '' : checked.error);
86
+ setCodeError(checkedCode.ok ? '' : checkedCode.error);
87
+ if (!checked.ok || !checkedCode.ok) return;
88
+ onSubmit(checked.value, checkedCode.value);
70
89
  };
90
+ const editVerb = withCode ? 'Edit' : 'Rename';
71
91
 
72
92
  return (
73
93
  <ConfirmDialog
74
94
  open
75
- title={dialog.row ? `Rename “${dialog.row.label}”` : `Add a ${one}`}
76
- message={dialog.row ? `Enter the new name for this ${one}.` : `Name the new ${one}.`}
77
- confirmLabel={dialog.row ? 'Rename' : 'Add'}
95
+ title={dialog.row ? `${editVerb} “${dialog.row.label}”` : `Add a ${one}`}
96
+ message={
97
+ dialog.row
98
+ ? withCode
99
+ ? `Change the name or code of this ${one}.`
100
+ : `Enter the new name for this ${one}.`
101
+ : `Name the new ${one}.`
102
+ }
103
+ confirmLabel={dialog.row ? (withCode ? 'Save' : 'Rename') : 'Add'}
78
104
  busy={busy}
79
105
  onConfirm={submit}
80
106
  onCancel={onCancel}
@@ -98,6 +124,32 @@ function NameDialog({ dialog, busy, onSubmit, onCancel }) {
98
124
  </p>
99
125
  )}
100
126
  </div>
127
+ {withCode && (
128
+ <div className="mt-3 space-y-1.5">
129
+ <Label htmlFor={codeId} variant="field">
130
+ Code (optional)
131
+ </Label>
132
+ <Input
133
+ id={codeId}
134
+ value={code}
135
+ onChange={(e) => setCode(codeInput(e.target.value))}
136
+ maxLength={64}
137
+ autoCapitalize="characters"
138
+ spellCheck={false}
139
+ aria-invalid={!!codeError}
140
+ aria-describedby={codeError ? `${codeId}-error` : `${codeId}-hint`}
141
+ />
142
+ {codeError ? (
143
+ <p id={`${codeId}-error`} className="text-xs text-destructive">
144
+ {codeError}
145
+ </p>
146
+ ) : (
147
+ <p id={`${codeId}-hint`} className="text-xs text-muted-foreground">
148
+ Up to 32 of A–Z, 0–9 or _. Record policies match this code. Leave empty for none.
149
+ </p>
150
+ )}
151
+ </div>
152
+ )}
101
153
  </ConfirmDialog>
102
154
  );
103
155
  }
@@ -135,14 +187,15 @@ function OrgUnitList({ kind, companyUuid, perms, token, identity }) {
135
187
  load();
136
188
  }, [load]);
137
189
 
138
- const onSubmitName = async (name) => {
190
+ const onSubmitName = async (name, code) => {
139
191
  if (!dialog) return;
140
192
  setDialogBusy(true);
141
193
  const r = dialog.row
142
- ? await CALLS[kind].rename(identity, token, dialog.row.uuid, name)
143
- : await CALLS[kind].create(identity, token, companyUuid, name);
194
+ ? await CALLS[kind].rename(identity, token, dialog.row, name, code)
195
+ : await CALLS[kind].create(identity, token, companyUuid, name, code);
144
196
  setDialogBusy(false);
145
- const o = outcome(r, kind, dialog.row ? 'rename' : 'create');
197
+ const editAction = kind === 'department' ? 'update' : 'rename';
198
+ const o = outcome(r, kind, dialog.row ? editAction : 'create');
146
199
  if (o.kind === 'error') {
147
200
  toast.error(o.text);
148
201
  return;
@@ -168,8 +221,19 @@ function OrgUnitList({ kind, companyUuid, perms, token, identity }) {
168
221
 
169
222
  const columns = [
170
223
  { key: 'name', label: 'Name', render: (row) => row.fields.name },
224
+ ...(kind === 'department'
225
+ ? [
226
+ {
227
+ key: 'code',
228
+ label: 'Code',
229
+ render: (row) =>
230
+ row.unit.code ? <span className="font-mono text-sm">{row.unit.code}</span> : '—',
231
+ },
232
+ ]
233
+ : []),
171
234
  { key: 'usedBy', label: 'Used by', render: (row) => usedByLabel(row.unit) || '—' },
172
235
  ];
236
+ const editLabel = kind === 'department' ? 'Edit' : 'Rename';
173
237
  if (perms.rename || perms.remove) {
174
238
  columns.push({
175
239
  key: 'actions',
@@ -184,10 +248,10 @@ function OrgUnitList({ kind, companyUuid, perms, token, identity }) {
184
248
  variant="ghost"
185
249
  size="sm"
186
250
  onClick={() => setDialog({ kind, row: row.unit })}
187
- aria-label={`Rename ${row.unit.label}`}
251
+ aria-label={`${editLabel} ${row.unit.label}`}
188
252
  >
189
253
  <Pencil className="size-4" />
190
- Rename
254
+ {editLabel}
191
255
  </Button>
192
256
  )}
193
257
  {perms.remove && (
@@ -76,6 +76,48 @@ export function validateName(name) {
76
76
  return { ok: true, value };
77
77
  }
78
78
 
79
+ /**
80
+ * A department code (department-scoped policies SPEC §10): 1–32 of A–Z, 0–9 or _, after a trim.
81
+ * Record policies match it byte for byte; a department without a code never matches. Branches have
82
+ * no code.
83
+ */
84
+ export const DEPARTMENT_CODE_PATTERN = /^[A-Z0-9_]{1,32}$/;
85
+
86
+ /** The fixed message for a code that does not match (the server sends the same text). */
87
+ export const DEPARTMENT_CODE_ERROR = 'Department code must be 1–32 characters A–Z, 0–9 or _.';
88
+
89
+ /** The code input as the user types: uppercased (validation happens on submit). */
90
+ export function codeInput(raw) {
91
+ return String(raw ?? '').toUpperCase();
92
+ }
93
+
94
+ /**
95
+ * Check a typed department code before sending. Blank (after a trim) ⇒ no code (`value: null`);
96
+ * otherwise it must match {@link DEPARTMENT_CODE_PATTERN}. The server re-validates and decides
97
+ * uniqueness (409).
98
+ * @param {unknown} raw
99
+ * @returns {{ ok: true, value: string | null } | { ok: false, error: string }}
100
+ */
101
+ export function validateCode(raw) {
102
+ const value = String(raw ?? '').trim();
103
+ if (value.length === 0) return { ok: true, value: null };
104
+ if (!DEPARTMENT_CODE_PATTERN.test(value)) return { ok: false, error: DEPARTMENT_CODE_ERROR };
105
+ return { ok: true, value };
106
+ }
107
+
108
+ /**
109
+ * The `updateDepartment` body for an edit: always the name (as Rename sends today), plus `code`
110
+ * only when it changed; `code: null` clears an existing code.
111
+ * @param {{ code?: string | null } | null | undefined} row the department as listed
112
+ * @param {string} name the validated name
113
+ * @param {string | null} code the validated code (`null` = none)
114
+ * @returns {{ name: string, code?: string | null }}
115
+ */
116
+ export function departmentUpdate(row, name, code) {
117
+ const current = typeof row?.code === 'string' && row.code.length > 0 ? row.code : null;
118
+ return current === code ? { name } : { name, code };
119
+ }
120
+
79
121
  /**
80
122
  * Whether Delete is offered for a row. `usedBy` > 0 ⇒ disabled with the reason; `usedBy` absent
81
123
  * (the caller cannot read assignments) ⇒ enabled. Advisory only: `usedBy` counts the assignments
@@ -102,8 +144,9 @@ export function usedByLabel(row) {
102
144
 
103
145
  /**
104
146
  * Rows sorted by name for display, labels only (an unnamed row shows "(unnamed)", never its id).
105
- * @param {Array<{ uuid?: string, name?: string, usedBy?: number }> | null | undefined} rows
106
- * @returns {Array<{ uuid: string, label: string, usedBy?: number }>}
147
+ * A department's `code` is kept when it has one.
148
+ * @param {Array<{ uuid?: string, name?: string, usedBy?: number, code?: string | null }> | null | undefined} rows
149
+ * @returns {Array<{ uuid: string, label: string, usedBy?: number, code?: string }>}
107
150
  */
108
151
  export function displayRows(rows) {
109
152
  return (rows || [])
@@ -112,19 +155,21 @@ export function displayRows(rows) {
112
155
  uuid: r.uuid,
113
156
  label: typeof r.name === 'string' && r.name.length > 0 ? r.name : '(unnamed)',
114
157
  ...(typeof r.usedBy === 'number' ? { usedBy: r.usedBy } : {}),
158
+ ...(typeof r.code === 'string' && r.code.length > 0 ? { code: r.code } : {}),
115
159
  }))
116
160
  .sort((a, b) => a.label.localeCompare(b.label));
117
161
  }
118
162
 
119
- const DONE = { create: 'added', rename: 'renamed', delete: 'deleted' };
120
- const VERB = { create: 'add', rename: 'rename', delete: 'delete' };
163
+ const DONE = { create: 'added', rename: 'renamed', update: 'updated', delete: 'deleted' };
164
+ const VERB = { create: 'add', rename: 'rename', update: 'update', delete: 'delete' };
121
165
 
122
166
  /**
123
- * The toast for a create / rename / delete result: success text, or the server's message on a
124
- * refusal (duplicate name, still in use, out of reach), else a fixed fallback.
167
+ * The toast for a create / rename / update / delete result: success text, or the server's message
168
+ * on a refusal (duplicate name or code, bad code, still in use, out of reach), else a fixed
169
+ * fallback.
125
170
  * @param {{ ok: boolean, error?: string } | null | undefined} result
126
171
  * @param {'department' | 'branch'} kind
127
- * @param {'create' | 'rename' | 'delete'} action
172
+ * @param {'create' | 'rename' | 'update' | 'delete'} action
128
173
  * @returns {{ kind: 'success' | 'error', text: string }}
129
174
  */
130
175
  export function outcome(result, kind, action) {
@@ -15,8 +15,77 @@ import {
15
15
  outcome,
16
16
  usedByLabel,
17
17
  validateName,
18
+ DEPARTMENT_CODE_ERROR,
19
+ codeInput,
20
+ validateCode,
21
+ departmentUpdate,
18
22
  } from './orgStructure.js';
19
23
 
24
+ describe('department code (department-scoped policies §10)', () => {
25
+ test('the error text is fixed', () => {
26
+ assert.equal(DEPARTMENT_CODE_ERROR, 'Department code must be 1–32 characters A–Z, 0–9 or _.');
27
+ });
28
+ test('typing uppercases', () => {
29
+ assert.equal(codeInput('qa_1'), 'QA_1');
30
+ assert.equal(codeInput(undefined), '');
31
+ });
32
+ test('valid codes pass after a trim', () => {
33
+ assert.deepEqual(validateCode('QA'), { ok: true, value: 'QA' });
34
+ assert.deepEqual(validateCode(' SHEQ_2 '), { ok: true, value: 'SHEQ_2' });
35
+ assert.deepEqual(validateCode('A'.repeat(32)), { ok: true, value: 'A'.repeat(32) });
36
+ });
37
+ test('blank means no code', () => {
38
+ assert.deepEqual(validateCode(''), { ok: true, value: null });
39
+ assert.deepEqual(validateCode(' '), { ok: true, value: null });
40
+ assert.deepEqual(validateCode(null), { ok: true, value: null });
41
+ });
42
+ test('bad codes are refused with the fixed message', () => {
43
+ for (const bad of ['qa', 'Q A', 'QA-1', 'A'.repeat(33), 'É', 'QA.']) {
44
+ assert.deepEqual(validateCode(bad), { ok: false, error: DEPARTMENT_CODE_ERROR }, bad);
45
+ }
46
+ });
47
+ test('departmentUpdate sends code only when it changed; clearing sends null', () => {
48
+ assert.deepEqual(departmentUpdate({ code: 'QA' }, 'Quality', 'QA'), { name: 'Quality' });
49
+ assert.deepEqual(departmentUpdate({ code: 'QA' }, 'Quality', null), {
50
+ name: 'Quality',
51
+ code: null,
52
+ });
53
+ assert.deepEqual(departmentUpdate({}, 'Quality', 'QA'), { name: 'Quality', code: 'QA' });
54
+ assert.deepEqual(departmentUpdate({}, 'Quality', null), { name: 'Quality' });
55
+ assert.deepEqual(departmentUpdate({ code: 'QA' }, 'Quality', 'QA2'), {
56
+ name: 'Quality',
57
+ code: 'QA2',
58
+ });
59
+ });
60
+ test('displayRows keeps a department code; none ⇒ no key', () => {
61
+ assert.deepEqual(
62
+ displayRows([
63
+ { uuid: 'd-1', name: 'Quality Assurance', code: 'QA' },
64
+ { uuid: 'd-2', name: 'Facilities', code: null },
65
+ ]),
66
+ [
67
+ { uuid: 'd-2', label: 'Facilities' },
68
+ { uuid: 'd-1', label: 'Quality Assurance', code: 'QA' },
69
+ ],
70
+ );
71
+ });
72
+ test('update outcome text; a 409 keeps the server message', () => {
73
+ assert.deepEqual(outcome({ ok: true }, 'department', 'update'), {
74
+ kind: 'success',
75
+ text: 'Department updated',
76
+ });
77
+ const message = 'Another department of this company already uses this code.';
78
+ assert.deepEqual(outcome({ ok: false, error: message }, 'department', 'update'), {
79
+ kind: 'error',
80
+ text: message,
81
+ });
82
+ assert.deepEqual(outcome({ ok: false }, 'department', 'update'), {
83
+ kind: 'error',
84
+ text: 'Could not update the department.',
85
+ });
86
+ });
87
+ });
88
+
20
89
  describe('permission keys', () => {
21
90
  test('department and branch keys match the server routes', () => {
22
91
  assert.deepEqual(KINDS, ['department', 'branch']);
@@ -24,13 +24,13 @@
24
24
  "postinstall": "node scripts/sync-astram-guide.mjs"
25
25
  },
26
26
  "dependencies": {
27
- "@astram/core": "1.20.0",
28
- "@astram/engine": "0.22.0",
29
- "@astram/guard": "0.36.0",
27
+ "@astram/core": "1.21.0",
28
+ "@astram/engine": "0.22.1",
29
+ "@astram/guard": "0.37.0",
30
30
  "@astram/guide": "^0.2.8",
31
- "@astram/identity": "0.34.2",
32
- "@astram/messaging": "0.1.27",
33
- "@astram/migrate": "0.7.10",
31
+ "@astram/identity": "0.35.0",
32
+ "@astram/messaging": "0.1.28",
33
+ "@astram/migrate": "0.7.11",
34
34
  "@astram/sdk": "^0.2.0",
35
35
  "@nestjs/common": "^11.2.7",
36
36
  "@nestjs/core": "^11.2.7",