@7365admin1/layer-common 4.15.3-staging.328 → 4.15.3-staging.329

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.
@@ -0,0 +1,424 @@
1
+ <template>
2
+ <v-dialog v-model="open" max-width="760" scrollable>
3
+ <v-card class="hid-access-permissions">
4
+ <v-card-title class="hid-access-permissions__title">
5
+ <div>
6
+ <div class="text-h6">Access Permissions</div>
7
+ <div class="text-caption text-medium-emphasis">{{ readerLabel }}</div>
8
+ </div>
9
+ </v-card-title>
10
+
11
+ <v-divider />
12
+
13
+ <!-- The one precondition the server enforces before it will talk about
14
+ permissions at all. Saying it here beats letting the first request
15
+ fail with the same sentence in a snackbar. -->
16
+ <v-alert
17
+ v-if="!readerLocation"
18
+ type="warning"
19
+ variant="tonal"
20
+ density="compact"
21
+ class="ma-4"
22
+ >
23
+ Set a location on this HID Face Reader before managing permissions.
24
+ </v-alert>
25
+
26
+ <template v-else>
27
+ <div class="hid-access-permissions__intro">
28
+ <p class="text-body-2 text-medium-emphasis mb-0">
29
+ Residents enrolled on this reader. Enrolling already grants access — switch
30
+ somebody off to close the door to them without removing their face, card
31
+ or PIN.
32
+ </p>
33
+ </div>
34
+
35
+ <v-card-text class="hid-access-permissions__body">
36
+ <TableMain
37
+ :headers="headers"
38
+ :items="rows"
39
+ :loading="loading"
40
+ :items-per-page="-1"
41
+ :page="page"
42
+ :pages="pages"
43
+ :page-range="pageRange"
44
+ item-value="rowKey"
45
+ @refresh="loadEnrolled"
46
+ @update:page="goToPage"
47
+ >
48
+ <template #extension>
49
+ <div class="app-filter-row">
50
+ <AppField
51
+ v-model="search"
52
+ search
53
+ placeholder="Search name, unit or registration"
54
+ @keyup.enter="searchFromFirstPage"
55
+ />
56
+ </div>
57
+ </template>
58
+
59
+ <template #[`item.name`]="{ item }">
60
+ <div class="hid-access-permissions__person">
61
+ <div>{{ item.name || "—" }}</div>
62
+ <div class="text-caption text-medium-emphasis">{{ item.subtitle || "—" }}</div>
63
+ </div>
64
+ </template>
65
+
66
+ <template #[`item.selected`]="{ item }">
67
+ <div v-if="!item.assignable" class="hid-access-permissions__toggle">
68
+ <span class="text-caption text-medium-emphasis">{{ item.reason }}</span>
69
+ </div>
70
+ <div v-else class="hid-access-permissions__toggle">
71
+ <v-switch
72
+ :model-value="item.selected"
73
+ :disabled="saving"
74
+ color="primary"
75
+ density="compact"
76
+ hide-details
77
+ :aria-label="`Door access for ${item.name}`"
78
+ @update:model-value="(value) => toggle(item, value === true)"
79
+ />
80
+ <span
81
+ class="text-caption"
82
+ :class="item.selected ? 'text-success' : 'text-medium-emphasis'"
83
+ >
84
+ {{ item.selected ? "Has access" : "No access" }}
85
+ </span>
86
+ </div>
87
+ </template>
88
+ </TableMain>
89
+ </v-card-text>
90
+ </template>
91
+
92
+ <v-divider />
93
+
94
+ <v-card-actions class="hid-access-permissions__actions">
95
+ <span v-if="readerLocation" class="text-caption text-medium-emphasis">
96
+ {{ assignedTotal }} with access on this reader
97
+ </span>
98
+ <v-spacer />
99
+ <AppButton variant="ghost" :disabled="saving" @click="open = false">Cancel</AppButton>
100
+ <AppButton
101
+ icon="mdi-content-save-outline"
102
+ :loading="saving"
103
+ :disabled="!readerLocation || !dirty || saving"
104
+ @click="save"
105
+ >
106
+ Save Permissions
107
+ </AppButton>
108
+ </v-card-actions>
109
+ </v-card>
110
+
111
+ <v-snackbar v-model="snackbar.show" :color="snackbar.color" timeout="3500">
112
+ {{ snackbar.message }}
113
+ </v-snackbar>
114
+ </v-dialog>
115
+ </template>
116
+
117
+ <script setup lang="ts">
118
+ import {
119
+ applySelection,
120
+ hasChanges,
121
+ readCandidatePage,
122
+ seedAssignments,
123
+ setAssignment,
124
+ toAssignmentPayload,
125
+ type HidAssignmentState,
126
+ } from "../utils/hid-permission-assignments";
127
+
128
+ /**
129
+ * WHO MAY PASS THIS READER — a review and revoke screen, not a picker.
130
+ *
131
+ * Enrolling somebody now grants them access: `createIdentity` writes the
132
+ * assignment, and the reconcile puts them in the reader's group in the same
133
+ * pass. A property manager therefore has ONE thing to do, and this screen
134
+ * exists for the other direction — taking access away again.
135
+ *
136
+ * So it lists the people ENROLLED on this reader rather than everybody at the
137
+ * site. Switching somebody off removes their assignment, and the reconcile then
138
+ * deletes their `user_groups` row; their identity, face, card and PIN are left
139
+ * alone, so they stay recognisable at the door and are simply refused.
140
+ *
141
+ * The editing model lives in `utils/hid-permission-assignments.ts`, because the
142
+ * save is whole-reader while the list is one page at a time — and getting that
143
+ * wrong silently revokes everybody who is not on screen. See the tests there.
144
+ */
145
+ const props = defineProps<{
146
+ modelValue: boolean;
147
+ site: string;
148
+ org: string;
149
+ reader: Record<string, unknown> | null;
150
+ }>();
151
+
152
+ const emit = defineEmits<{
153
+ (event: "update:modelValue", value: boolean): void;
154
+ (event: "saved"): void;
155
+ }>();
156
+
157
+ const { getSitePermissions, getIdentities, updateSitePermissions } = useHidAmico();
158
+
159
+ /* Name over unit in one cell rather than a "Unit" column — see `subtitleOf`. */
160
+ const headers = [
161
+ { title: "Resident", value: "name", sortable: false },
162
+ { title: "Door access", value: "selected", sortable: false, width: 190 },
163
+ ];
164
+
165
+ const search = ref("");
166
+ const page = ref(1);
167
+ const pages = ref(1);
168
+ const pageRange = ref("");
169
+ const loading = ref(false);
170
+ const saving = ref(false);
171
+ const enrolled = ref<THidPermissionCandidate[]>([]);
172
+ const snackbar = reactive({ show: false, color: "success", message: "" });
173
+
174
+ /** What the server holds, and the working copy. The pair drives `dirty`. */
175
+ const savedState = ref<HidAssignmentState>(new Map());
176
+ const draft = ref<HidAssignmentState>(new Map());
177
+
178
+ const open = computed({
179
+ get: () => props.modelValue,
180
+ set: (value: boolean) => emit("update:modelValue", value),
181
+ });
182
+
183
+ const readerId = computed(() => String(props.reader?._id ?? ""));
184
+ const readerLocation = computed(() => String(props.reader?.location ?? "").trim());
185
+ const readerLabel = computed(() => {
186
+ const name = String(props.reader?.name ?? "").trim() || "HID Face Reader";
187
+ return readerLocation.value ? `${name} · ${readerLocation.value}` : name;
188
+ });
189
+
190
+ const assignedTotal = computed(() => draft.value.size);
191
+ const dirty = computed(() => hasChanges(savedState.value, draft.value));
192
+ /* The draft is the truth once the dialog is open, so `selected` is recomputed
193
+ on every render rather than trusted from the row. */
194
+ const rows = computed(() => applySelection(enrolled.value, draft.value));
195
+
196
+ watch(
197
+ () => [props.modelValue, readerId.value] as const,
198
+ ([isOpen]) => {
199
+ if (!isOpen || !readerId.value) return;
200
+ search.value = "";
201
+ page.value = 1;
202
+ void loadAll();
203
+ },
204
+ { immediate: true },
205
+ );
206
+
207
+ async function loadAll() {
208
+ if (!readerLocation.value) return;
209
+ await loadAssignments();
210
+ await loadEnrolled();
211
+ }
212
+
213
+ /**
214
+ * `getSitePermissions` returns the reader's assignments across ALL categories.
215
+ * That is what makes a whole-reader payload possible from a paged view, so it
216
+ * is loaded once per opening rather than once per page.
217
+ */
218
+ async function loadAssignments() {
219
+ try {
220
+ const response = await getSitePermissions(props.site, props.org, readerId.value);
221
+ const assignments = response?.data?.assignments ?? [];
222
+ savedState.value = seedAssignments(assignments);
223
+ draft.value = seedAssignments(assignments);
224
+ } catch (error) {
225
+ showToast(getErrorMessage(error, "Unable to load this reader's permissions."), "error");
226
+ }
227
+ }
228
+
229
+ function toRecord(value: unknown): Record<string, unknown> {
230
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
231
+ }
232
+
233
+ /**
234
+ * The subject an identity names, in the order `createIdentity` validates them.
235
+ *
236
+ * A visitor returns null and is left out of the list: visitor access comes from
237
+ * `user_access_rules`, not from a group, so there is nothing here to switch
238
+ * off. An identity linked to nobody — a device user the reader holds that was
239
+ * never tied to a person — is dropped for the same reason.
240
+ */
241
+ function subjectOf(identity: Record<string, unknown>) {
242
+ if (identity.person) {
243
+ return { subjectId: String(identity.person), category: "resident" as const };
244
+ }
245
+ if (identity.member) {
246
+ return { subjectId: String(identity.member), category: "property_management" as const };
247
+ }
248
+ if (identity.serviceProvider) {
249
+ return { subjectId: String(identity.serviceProvider), category: "service_provider" as const };
250
+ }
251
+ return null;
252
+ }
253
+
254
+ /**
255
+ * Why a row cannot be switched, in words the reader of the screen can act on.
256
+ *
257
+ * The row is still DRAWN. Dropping one silently is what made the pager say
258
+ * "1-9 of 9" over seven rows: the count comes from the server and the rows came
259
+ * from a filtered list, so people vanished with nothing to say they had.
260
+ *
261
+ * What lands here is a resident identity holding only an account link - no
262
+ * person, member or service-provider record - which leaves no subject to
263
+ * assign. Visitors never reach it: they are excluded by the query above,
264
+ * because their access comes from `user_access_rules` rather than a group and
265
+ * there would be nothing here to switch.
266
+ */
267
+ function unassignableReason() {
268
+ return "Not linked to a person";
269
+ }
270
+
271
+ /**
272
+ * The unit, when the enrolment captured one.
273
+ *
274
+ * `unitLabel` and NOT `block`/`level`/`unit`: those three hold ObjectIds, and
275
+ * the enrolment form resolves them through the occupancy tree before storing
276
+ * the readable label beside them. `buildUnitLabel` carries the warning this
277
+ * ignored once already — joining the raw values stamps
278
+ * "665f.../665f.../665f..." into the column.
279
+ *
280
+ * Falls back to the registration number, which is what the rows created by an
281
+ * assignment rather than an enrolment carry instead of a unit.
282
+ */
283
+ function subtitleOf(identity: Record<string, unknown>) {
284
+ const metadata = toRecord(identity.metadata);
285
+ return String(metadata.unitLabel ?? "").trim()
286
+ || String(identity.registration ?? "").trim();
287
+ }
288
+
289
+ async function loadEnrolled() {
290
+ if (!readerId.value || !readerLocation.value) return;
291
+ loading.value = true;
292
+ try {
293
+ const response = await getIdentities(readerId.value, {
294
+ page: page.value,
295
+ limit: 10,
296
+ search: search.value.trim(),
297
+ // Residents only, and filtered by the SERVER rather than here. The pager's
298
+ // count comes back from the same query, so narrowing the list on this side
299
+ // would print a total that never matched the rows under it.
300
+ type: "resident",
301
+ });
302
+ const result = readCandidatePage(response);
303
+ /*
304
+ * EVERY row the server returned, including the ones this screen cannot act
305
+ * on. A visitor's access comes from `user_access_rules` rather than a group,
306
+ * and an identity linked to nobody has no subject to assign - but both are
307
+ * still enrolled on this reader, and the count in the pager counts them. They
308
+ * are drawn with the switch disabled and a reason, instead of disappearing.
309
+ */
310
+ enrolled.value = result.items.map((row) => {
311
+ const identity = toRecord(row);
312
+ const subject = subjectOf(identity);
313
+ const metadata = toRecord(identity.metadata);
314
+ return {
315
+ subjectId: subject?.subjectId ?? "",
316
+ category: subject?.category ?? "resident",
317
+ // The row's own key. `subjectId` is empty for the rows below, and two
318
+ // empty keys would collapse into one row in the table.
319
+ rowKey: String(identity._id ?? identity.hidUserId ?? Math.random()),
320
+ assignable: Boolean(subject),
321
+ reason: subject ? "" : unassignableReason(),
322
+ name: String(metadata.name ?? "").trim()
323
+ || String(identity.registration ?? "").trim()
324
+ || "—",
325
+ subtitle: subtitleOf(identity),
326
+ intercom: false,
327
+ selected: false,
328
+ } as THidPermissionCandidate;
329
+ });
330
+ // `pages` only. The page number stays whatever the pager set — this
331
+ // endpoint's `paginate` never echoes it back, so reading one here pinned
332
+ // the screen to page one on every fetch.
333
+ pages.value = result.pages;
334
+ pageRange.value = result.pageRange;
335
+ } catch (error) {
336
+ enrolled.value = [];
337
+ pages.value = 1;
338
+ pageRange.value = "";
339
+ showToast(getErrorMessage(error, "Unable to load the people enrolled on this reader."), "error");
340
+ } finally {
341
+ loading.value = false;
342
+ }
343
+ }
344
+
345
+ function goToPage(value: number) {
346
+ page.value = Number(value) || 1;
347
+ void loadEnrolled();
348
+ }
349
+
350
+ function searchFromFirstPage() {
351
+ page.value = 1;
352
+ void loadEnrolled();
353
+ }
354
+
355
+ function toggle(item: THidPermissionCandidate, selected: boolean) {
356
+ if (!String(item.subjectId ?? "")) return;
357
+ draft.value = setAssignment(
358
+ draft.value,
359
+ savedState.value,
360
+ String(item.subjectId ?? ""),
361
+ item.category,
362
+ selected,
363
+ );
364
+ }
365
+
366
+ async function save() {
367
+ if (!dirty.value || saving.value) return;
368
+ saving.value = true;
369
+ try {
370
+ await updateSitePermissions(
371
+ props.site,
372
+ props.org,
373
+ readerId.value,
374
+ toAssignmentPayload(draft.value),
375
+ );
376
+ // The server reconciles the device inside this call: anybody switched off
377
+ // loses their `user_groups` row before it returns, so a success here means
378
+ // the door has already been updated.
379
+ savedState.value = new Map(draft.value);
380
+ showToast("HID permissions updated.");
381
+ emit("saved");
382
+ open.value = false;
383
+ } catch (error) {
384
+ showToast(getErrorMessage(error, "Unable to update HID permissions."), "error");
385
+ } finally {
386
+ saving.value = false;
387
+ }
388
+ }
389
+
390
+ function showToast(message: string, color = "success") {
391
+ snackbar.message = message;
392
+ snackbar.color = color;
393
+ snackbar.show = true;
394
+ }
395
+
396
+ function getErrorMessage(error: unknown, fallback: string) {
397
+ const record = toRecord(error);
398
+ const data = toRecord(record.data);
399
+ return String(data.message ?? "") || String(record.message ?? "") || fallback;
400
+ }
401
+ </script>
402
+
403
+ <style scoped lang="scss">
404
+ .hid-access-permissions {
405
+ &__title { padding-block: 16px; }
406
+
407
+ &__intro { padding: 12px 16px 0; }
408
+
409
+ &__body {
410
+ padding-top: 8px;
411
+ min-height: 320px;
412
+ }
413
+
414
+ &__actions { padding: 12px 16px; }
415
+
416
+ &__person > div:first-child { font-weight: 500; }
417
+
418
+ &__toggle {
419
+ display: flex;
420
+ align-items: center;
421
+ gap: 8px;
422
+ }
423
+ }
424
+ </style>
@@ -87,6 +87,7 @@
87
87
 
88
88
  <v-list density="compact" min-width="180">
89
89
  <v-list-item title="View" @click="openView(item)" />
90
+ <v-list-item title="Access Permissions" @click="openPermissions(item)" />
90
91
  <v-list-item title="Sync HID Reader" @click="openSyncConfirm(item)" />
91
92
  <v-list-item title="Test Connection" @click="openTestConfirm(item)" />
92
93
  <v-list-item title="Edit" @click="openEdit(item)" />
@@ -241,6 +242,18 @@
241
242
  </v-card-actions>
242
243
  </v-card>
243
244
  </v-dialog>
245
+
246
+ <!-- Who may actually pass this reader. Enrolment makes a person
247
+ RECOGNISABLE; this is what puts them in the group the access rule is
248
+ attached to, and without it a recognised person is refused at the
249
+ door. Reloads the list on save so the reader's own counts stay true. -->
250
+ <HidAccessPermissions
251
+ v-model="permissionsDialog"
252
+ :site="props.site"
253
+ :org="props.org"
254
+ :reader="selectedReader"
255
+ @saved="loadReaders"
256
+ />
244
257
  </section>
245
258
  </template>
246
259
 
@@ -322,6 +335,13 @@ const props = defineProps({
322
335
  type: String,
323
336
  required: true,
324
337
  },
338
+ // The permission endpoints are org-scoped (`assertOrganizationSiteAccess`),
339
+ // and this component previously had no reason to know the org. Passed from
340
+ // the page, as `HidQrCodeConfiguration` already does.
341
+ org: {
342
+ type: String,
343
+ required: true,
344
+ },
325
345
  });
326
346
 
327
347
  const {
@@ -347,6 +367,7 @@ const viewDialog = ref(false);
347
367
  const confirmDialog = ref(false);
348
368
  const resultDialog = ref(false);
349
369
  const selectedReader = ref<HidRecord | null>(null);
370
+ const permissionsDialog = ref(false);
350
371
  const pendingAction = ref<"test" | "sync" | "delete" | null>(null);
351
372
  const actionStage = ref<"confirm" | "review" | "loading">("confirm");
352
373
  const resultSuccess = ref(true);
@@ -484,6 +505,11 @@ function openView(reader: HidRecord) {
484
505
  viewDialog.value = true;
485
506
  }
486
507
 
508
+ function openPermissions(reader: HidRecord) {
509
+ selectedReader.value = reader;
510
+ permissionsDialog.value = true;
511
+ }
512
+
487
513
  function openTestConfirm(reader?: HidRecord | null) {
488
514
  if (reader) selectedReader.value = reader;
489
515
  pendingAction.value = "test";
@@ -623,6 +623,13 @@ const props = defineProps({
623
623
  type: String,
624
624
  required: true,
625
625
  },
626
+ // Which organisation the access this enrolment grants belongs to. Saving now
627
+ // assigns the person to the reader, and the assignment is stored per
628
+ // organisation - see `schemaCreateHidAmicoIdentity`.
629
+ org: {
630
+ type: String,
631
+ default: "",
632
+ },
626
633
  cardManagement: {
627
634
  type: Boolean,
628
635
  default: false,
@@ -1811,7 +1818,7 @@ async function saveIdentityOnReader(
1811
1818
  }
1812
1819
 
1813
1820
  try {
1814
- await createIdentity(readerId, { ...payload, site: props.site });
1821
+ await createIdentity(readerId, { ...payload, site: props.site, ...(props.org ? { orgId: props.org } : {}) });
1815
1822
  } catch (error: unknown) {
1816
1823
  const message = getHidErrorMessage(error);
1817
1824
  if (!message.toLowerCase().includes("already exists")) throw error;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.15.3-staging.328",
5
+ "version": "4.15.3-staging.329",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing HID users."
7
7
  >
8
- <HidUserEnrollment :site="siteId" />
8
+ <HidUserEnrollment :site="siteId" :org="orgId" />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing physical HID cards."
7
7
  >
8
- <HidUserEnrollment :site="siteId" card-management />
8
+ <HidUserEnrollment :site="siteId" :org="orgId" card-management />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing HID readers."
7
7
  >
8
- <HidReaderManagement :site="siteId" />
8
+ <HidReaderManagement :site="siteId" :org="orgId" />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -0,0 +1,190 @@
1
+ /**
2
+ * WHO IS ASSIGNED TO A HID READER — the editing model behind the permissions
3
+ * dialog.
4
+ *
5
+ * This is the step that actually grants access. Enrolling a person gives the
6
+ * reader a face, a card or a PIN it can RECOGNISE; it puts nobody in the group
7
+ * the access rule is attached to, so a recognised person is still refused at
8
+ * the door (access log event 6). `PUT /sites/:siteId/permissions` is the only
9
+ * call in the system that writes that group membership.
10
+ *
11
+ * Two contracts make this file necessary rather than inlining the logic in the
12
+ * component:
13
+ *
14
+ * 1. **The PUT REPLACES the whole assignment set for the reader.** The server
15
+ * keeps other readers' rows and overwrites this reader's with exactly what
16
+ * is sent. The candidate list, however, is fetched ONE CATEGORY AT A TIME.
17
+ * Saving from the tab in front of you while sending only that tab's people
18
+ * would silently revoke every resident if you were looking at the service
19
+ * providers tab. So the edit state is held for the whole reader and the
20
+ * payload is always built from all of it.
21
+ *
22
+ * 2. **The body schema accepts three keys and nothing else.**
23
+ * `hidPermissionAssignmentSchema` is `{ subjectId, category, intercom }`,
24
+ * and Joi rejects unknown keys rather than stripping them. The candidate
25
+ * rows carry `name`, `subtitle`, `location` and friends for display, so the
26
+ * payload has to be narrowed deliberately — passing a candidate straight
27
+ * through is a 400.
28
+ */
29
+
30
+ /** The three real categories. `intercom` is a candidate FILTER, never a category. */
31
+ export const HID_PERMISSION_CATEGORIES: THidPermissionCategory[] = [
32
+ "resident",
33
+ "property_management",
34
+ "service_provider",
35
+ ];
36
+
37
+ export type HidAssignmentState = Map<string, { category: THidPermissionCategory; intercom: boolean }>;
38
+
39
+ /** Body row for `updateSitePermissions` — exactly the keys Joi allows. */
40
+ export type HidAssignmentPayload = {
41
+ subjectId: string;
42
+ category: THidPermissionCategory;
43
+ intercom: boolean;
44
+ };
45
+
46
+ function isRealCategory(value: unknown): value is THidPermissionCategory {
47
+ return HID_PERMISSION_CATEGORIES.includes(value as THidPermissionCategory);
48
+ }
49
+
50
+ /**
51
+ * The reader's CURRENT assignments, as the edit state.
52
+ *
53
+ * Seeded from `getSitePermissions`, which returns every category at once —
54
+ * that is what makes a whole-reader payload possible from a one-category view.
55
+ * Rows with an unrecognised category are dropped rather than carried: sending
56
+ * one back fails the enum check and takes the entire save with it.
57
+ */
58
+ export function seedAssignments(
59
+ assignments: readonly THidPermissionAssignment[] | undefined | null,
60
+ ): HidAssignmentState {
61
+ const state: HidAssignmentState = new Map();
62
+ if (!Array.isArray(assignments)) return state;
63
+ for (const assignment of assignments) {
64
+ const subjectId = String(assignment?.subjectId ?? "");
65
+ if (!subjectId || !isRealCategory(assignment?.category)) continue;
66
+ state.set(subjectId, {
67
+ category: assignment.category,
68
+ intercom: assignment.intercom === true,
69
+ });
70
+ }
71
+ return state;
72
+ }
73
+
74
+ /**
75
+ * Add or remove one person.
76
+ *
77
+ * `saved` is the state the dialog opened with, and it is consulted for one
78
+ * reason: the `intercom` flag. Nothing here edits that flag, but
79
+ * `userHasSiteIntercomPermission` reads it off these same rows, so it must
80
+ * survive a round trip through the checkbox.
81
+ *
82
+ * - **Untick then save** drops it, which is right — an unassigned person
83
+ * holding a dangling intercom right would keep answering the door panel
84
+ * after losing the door.
85
+ * - **Untick then re-tick, without saving** must restore it. Removing from the
86
+ * draft forgets the flag, so re-adding recovers it from `saved`; otherwise a
87
+ * misclick corrected a second later would silently revoke intercom on the
88
+ * next save, with nothing on screen to show it had happened.
89
+ */
90
+ export function setAssignment(
91
+ state: HidAssignmentState,
92
+ saved: HidAssignmentState,
93
+ subjectId: string,
94
+ category: THidPermissionCategory,
95
+ selected: boolean,
96
+ ): HidAssignmentState {
97
+ const next: HidAssignmentState = new Map(state);
98
+ const id = String(subjectId ?? "");
99
+ if (!id || !isRealCategory(category)) return next;
100
+ if (!selected) {
101
+ next.delete(id);
102
+ return next;
103
+ }
104
+ const intercom = next.get(id)?.intercom ?? saved.get(id)?.intercom ?? false;
105
+ next.set(id, { category, intercom: intercom === true });
106
+ return next;
107
+ }
108
+
109
+ /** The whole reader's assignments, narrowed to the three keys the API accepts. */
110
+ export function toAssignmentPayload(state: HidAssignmentState): HidAssignmentPayload[] {
111
+ return [...state.entries()].map(([subjectId, value]) => ({
112
+ subjectId,
113
+ category: value.category,
114
+ intercom: value.intercom === true,
115
+ }));
116
+ }
117
+
118
+ /**
119
+ * The server sends `selected` with each candidate, describing what is SAVED.
120
+ * Once the dialog is open the local edit state is the truth, so the flag is
121
+ * recomputed rather than trusted — otherwise paging or searching would redraw
122
+ * a row with the saved value and quietly discard an unsaved tick.
123
+ */
124
+ export function applySelection(
125
+ candidates: readonly THidPermissionCandidate[] | undefined | null,
126
+ state: HidAssignmentState,
127
+ ): THidPermissionCandidate[] {
128
+ if (!Array.isArray(candidates)) return [];
129
+ return candidates.map((candidate) => ({
130
+ ...candidate,
131
+ selected: state.has(String(candidate?.subjectId ?? "")),
132
+ }));
133
+ }
134
+
135
+ /** Per-category totals for the dialog header, counted over the whole reader. */
136
+ export function countByCategory(state: HidAssignmentState): Record<THidPermissionCategory, number> {
137
+ const counts = { resident: 0, property_management: 0, service_provider: 0 } as Record<
138
+ THidPermissionCategory,
139
+ number
140
+ >;
141
+ for (const value of state.values()) counts[value.category] += 1;
142
+ return counts;
143
+ }
144
+
145
+ /** Has anything changed since the dialog opened? Drives the Save button. */
146
+ export function hasChanges(saved: HidAssignmentState, draft: HidAssignmentState): boolean {
147
+ if (saved.size !== draft.size) return true;
148
+ for (const [subjectId, value] of draft) {
149
+ const before = saved.get(subjectId);
150
+ if (!before) return true;
151
+ if (before.category !== value.category) return true;
152
+ if (before.intercom !== value.intercom) return true;
153
+ }
154
+ return false;
155
+ }
156
+
157
+ /**
158
+ * What a listing response tells us: the rows, and how many pages exist.
159
+ *
160
+ * It deliberately does NOT return the current page, and the caller must keep
161
+ * owning that. `paginate` in `@7365admin1/node-server-utils` returns only
162
+ * `{ items, pages, pageRange }` — it never echoes the page it was asked for. A
163
+ * caller that read one back therefore got a default on every fetch and pinned
164
+ * itself to page one, so the pager moved and the rows never did.
165
+ *
166
+ * `items` sits at the root on some of these endpoints and under `data` on
167
+ * others, so both are read.
168
+ */
169
+ export function readCandidatePage(response: unknown): {
170
+ items: THidPermissionCandidate[];
171
+ pages: number;
172
+ pageRange: string;
173
+ } {
174
+ const source = (response && typeof response === "object" ? response : {}) as Record<string, unknown>;
175
+ const nested = (source.data && typeof source.data === "object" ? source.data : {}) as Record<string, unknown>;
176
+ const items = Array.isArray(source.items)
177
+ ? source.items
178
+ : Array.isArray(nested.items)
179
+ ? nested.items
180
+ : [];
181
+ const pages = Number(source.pages ?? nested.pages ?? 1);
182
+ // `paginate` builds this ("1-10 of 37") and the table renders it verbatim.
183
+ // Without it the pager draws its placeholder, "-- - -- of --".
184
+ const pageRange = String(source.pageRange ?? nested.pageRange ?? "");
185
+ return {
186
+ items: items as THidPermissionCandidate[],
187
+ pages: Number.isFinite(pages) && pages > 0 ? pages : 1,
188
+ pageRange,
189
+ };
190
+ }