@7365admin1/layer-common 4.21.3 → 4.21.4-staging.339

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 (38) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/components/AnprCameraBadge.vue +142 -0
  3. package/components/DocumentForm.vue +407 -112
  4. package/components/DocumentManagement.vue +213 -12
  5. package/components/EntryPass/QrTemplatePreview.vue +21 -25
  6. package/components/EntryPassInformation.vue +119 -24
  7. package/components/Facility/BookingSetup.vue +63 -0
  8. package/components/HidAccessLogDashboard.vue +29 -5
  9. package/components/HidAccessPermissions.vue +424 -0
  10. package/components/HidIntercomManagement.vue +48 -1
  11. package/components/HidProfileQrCode.vue +323 -0
  12. package/components/HidReaderManagement.vue +26 -0
  13. package/components/HidReaderUserRoster.vue +32 -2
  14. package/components/HidUserEnrollment.vue +833 -152
  15. package/components/InvitationClientForm.vue +19 -1
  16. package/components/PlateNumberDisplay.vue +91 -1
  17. package/components/VehicleForm.vue +246 -2
  18. package/components/VehicleManagement.vue +302 -51
  19. package/components/VisitorManagement.vue +357 -5
  20. package/composables/useAccessManagement.ts +5 -0
  21. package/composables/useDocument.ts +7 -0
  22. package/composables/useFacility.ts +11 -0
  23. package/composables/useHidAmico.ts +97 -0
  24. package/composables/useHidNavigation.ts +25 -1
  25. package/composables/usePeople.ts +19 -0
  26. package/composables/useVehicle.ts +83 -1
  27. package/composables/useWebUsb.ts +14 -11
  28. package/package.json +1 -1
  29. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  30. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  31. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  32. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  33. package/types/document.d.ts +14 -0
  34. package/types/facility.d.ts +4 -0
  35. package/types/people.d.ts +5 -2
  36. package/types/vehicle.d.ts +57 -2
  37. package/utils/hid-permission-assignments.ts +190 -0
  38. package/utils/vehicle-actions.ts +45 -17
@@ -115,6 +115,24 @@ export default function () {
115
115
  });
116
116
  }
117
117
 
118
+ /**
119
+ * The blocks, levels and units at a site that actually have an occupant.
120
+ * The other half of the unit picker: this narrows the cascade, then
121
+ * `getPeopleByUnit` answers "which person in this unit?".
122
+ */
123
+ async function getOccupiedStructure(
124
+ site: string,
125
+ { type = "", status = "active", block = "", level = "" } = {}
126
+ ) {
127
+ return await useNuxtApp().$api<Record<string, any>>(
128
+ `/api/people/site/${site}/occupied-structure`,
129
+ {
130
+ method: "GET",
131
+ query: { type, status, block, level },
132
+ }
133
+ );
134
+ }
135
+
118
136
  async function getPeopleByUnit(
119
137
  _id: string,
120
138
  { status = "active", type = "" } = {}
@@ -148,6 +166,7 @@ export default function () {
148
166
  findPersonByPlateNumberMultipleResult,
149
167
  findPersonByContact,
150
168
  getPeopleByUnit,
169
+ getOccupiedStructure,
151
170
  searchCompanyList,
152
171
  findUsersByPlateNumber,
153
172
  reviewResidentPerson,
@@ -7,10 +7,14 @@ export default function useVehicle() {
7
7
  type = "",
8
8
  category = "",
9
9
  site = "",
10
+ status = "",
11
+ view = "",
10
12
  } = {}) {
13
+ // `view` is the screen's tab: residents, season-passes or block-listed.
14
+ // Every status comes back unless `status` narrows it.
11
15
  return await useNuxtApp().$api<Record<string, any>>("/api/vehicles", {
12
16
  method: "GET",
13
- query: { search, page, limit, order, type, category, site },
17
+ query: { search, page, limit, order, type, category, site, status, view },
14
18
  });
15
19
  }
16
20
 
@@ -121,6 +125,68 @@ export default function useVehicle() {
121
125
  );
122
126
  }
123
127
 
128
+ /**
129
+ * Block: status "blocked", category "Block Listed", and the plate goes on
130
+ * every ANPR camera's blocklist (and off its allowed list).
131
+ */
132
+ async function blockVehicle({ site, id }: { site: string; id: string }) {
133
+ return await useNuxtApp().$api<Record<string, any>>(
134
+ `/api/vehicles/blocklist/id/${id}`,
135
+ {
136
+ method: "PUT",
137
+ body: { site },
138
+ }
139
+ );
140
+ }
141
+
142
+ /**
143
+ * Unblock: status "unblocked", category stays "Block Listed", and the plate
144
+ * comes off every camera's blocklist. It is NOT whitelisted again.
145
+ */
146
+ async function unblockVehicle({ site, id }: { site: string; id: string }) {
147
+ return await useNuxtApp().$api<Record<string, any>>(
148
+ `/api/vehicles/blocklist-delete/id/${id}`,
149
+ {
150
+ method: "PUT",
151
+ body: { site },
152
+ }
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Which of these plates the site already holds - one per plate, whatever its
158
+ * status - with the tab (`view`) and status of each.
159
+ */
160
+ async function checkExistingPlates({ site, plateNumbers }: { site: string; plateNumbers: string[] }) {
161
+ return await useNuxtApp().$api<{
162
+ items: Array<{
163
+ _id: string;
164
+ plateNumber: string;
165
+ input: string;
166
+ status: TVehicleStatus;
167
+ type: TVehicleType;
168
+ category: string;
169
+ seasonPassType: string;
170
+ name: string;
171
+ view: "residents" | "season-passes" | "block-listed";
172
+ }>;
173
+ }>("/api/vehicles/existing-plates", {
174
+ method: "POST",
175
+ body: { site, plateNumbers },
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Save the add form's details on an existing vehicle and move it to that
181
+ * form's tab: Residents, Season Passes or Block Listed.
182
+ */
183
+ async function moveVehicle(id: string, payload: Partial<TVehiclePayload>) {
184
+ return await useNuxtApp().$api<{ message: string }>(`/api/vehicles/move/id/${id}`, {
185
+ method: "PUT",
186
+ body: payload,
187
+ });
188
+ }
189
+
124
190
  async function getVehicleByNRIC(search: string) {
125
191
  return await useNuxtApp().$api<Record<string, any>>(
126
192
  `/api/vehicles/nric`,
@@ -146,6 +212,18 @@ export default function useVehicle() {
146
212
  label = "Active"
147
213
  color = "green"
148
214
  break;
215
+ case 'temporary':
216
+ label = "Temporary"
217
+ color = "teal"
218
+ break;
219
+ case 'blocked':
220
+ label = "Blocked"
221
+ color = "red"
222
+ break;
223
+ case 'unblocked':
224
+ label = "Unblocked"
225
+ color = "blue-grey"
226
+ break;
149
227
  case 'rejected':
150
228
  label = "Rejected"
151
229
  color = "red"
@@ -189,6 +267,10 @@ function getSpecificVehicleById(id: string){
189
267
  getVehicleByNRIC,
190
268
  formatVehicleStatus,
191
269
  approveVehicle,
270
+ blockVehicle,
271
+ unblockVehicle,
272
+ checkExistingPlates,
273
+ moveVehicle,
192
274
  searchMultipleVehiclesByUnitId,
193
275
  getSpecificVehicleById
194
276
  };
@@ -345,16 +345,19 @@ export default function useWebUsb() {
345
345
  70,
346
346
  );
347
347
 
348
- const qrSmall = 140;
349
- const qrCenter = 250;
350
- const margin = 20;
351
- const qrCanvas = await QRCode.toCanvas(qrUrlImage, { width: qrCenter });
348
+ // The pass used to print five copies of the same QR - four 140px ones at
349
+ // the corners around a 250px centre - so a strip could be cut apart. It now
350
+ // prints a single large QR filling that same band (y 90 to 440, above the
351
+ // company name at y 470), which scans far more reliably on a thermal print.
352
+ // Generated at the size it is drawn at: the old corner copies were
353
+ // downscaled from the 250px canvas, which softened their modules.
354
+ const qrSize = 350;
355
+ const qrCanvas = await QRCode.toCanvas(qrUrlImage, {
356
+ width: qrSize,
357
+ margin: 1,
358
+ });
352
359
 
353
- ctx.drawImage(qrCanvas, margin, 90, qrSmall, qrSmall);
354
- ctx.drawImage(qrCanvas, canvas.width - qrSmall - margin, 90, qrSmall, qrSmall);
355
- ctx.drawImage(qrCanvas, (canvas.width - qrCenter) / 2, 110, qrCenter, qrCenter);
356
- ctx.drawImage(qrCanvas, margin, 300, qrSmall, qrSmall);
357
- ctx.drawImage(qrCanvas, canvas.width - qrSmall - margin, 300, qrSmall, qrSmall);
360
+ ctx.drawImage(qrCanvas, (canvas.width - qrSize) / 2, 90, qrSize, qrSize);
358
361
 
359
362
  ctx.font = "25px Arial";
360
363
  ctx.fillText(companyName || "", canvas.width / 2, 470);
@@ -401,8 +404,8 @@ export default function useWebUsb() {
401
404
  /**
402
405
  * The self-service onboarding QR: one large QR code, a "SCAN QR CODE"-style
403
406
  * subtext, and a dark site-name banner along the bottom - a single-purpose
404
- * gate sign, not the multi-copy visitor-pass receipt `createReceiptLayout`
405
- * produces (that one prints several QRs to be cut apart and handed out).
407
+ * gate sign, not the visitor-pass receipt `createReceiptLayout` produces
408
+ * (that one pairs its QR with company, date, access and instruction lines).
406
409
  */
407
410
  async function createOnboardingQrLayout(
408
411
  qrUrlImage: string,
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.21.3",
5
+ "version": "4.21.4-staging.339",
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>
@@ -0,0 +1,23 @@
1
+ <template>
2
+ <v-container fluid>
3
+ <HidEnabledGate
4
+ :site="siteId"
5
+ :org="orgId"
6
+ message="Enable HID as a service for this site before generating a QR code."
7
+ >
8
+ <HidProfileQrCode :site="siteId" />
9
+ </HidEnabledGate>
10
+ </v-container>
11
+ </template>
12
+
13
+ <script setup lang="ts">
14
+ definePageMeta({
15
+ layout: "default",
16
+ middleware: ["01-auth", "02-org"],
17
+ memberOnly: true,
18
+ });
19
+
20
+ const route = useRoute();
21
+ const siteId = computed(() => String(route.params.site ?? ""));
22
+ const orgId = computed(() => String(route.params.org ?? ""));
23
+ </script>
@@ -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>
@@ -3,4 +3,18 @@ declare type TDocument = {
3
3
  name: string;
4
4
  attachment: string;
5
5
  type: string;
6
+ /**
7
+ * Set at upload or renewal, absent when the document never expires.
8
+ *
9
+ * An ISO instant on the way out of the API and a `YYYY-MM-DD` string on the
10
+ * way back in, which is what `InputDatePicker` binds to - hence the loose
11
+ * type rather than `string`.
12
+ */
13
+ expiryDate?: string | Date | null;
14
+ remarks?: string;
15
+ size?: number;
16
+ parentId?: string | null;
17
+ createdAt?: string | Date;
18
+ updatedAt?: string | Date;
19
+ status?: string;
6
20
  };
@@ -73,6 +73,10 @@ declare type TFacility = {
73
73
  hourInterval?: number;
74
74
  isBookingFeeEnabled: boolean;
75
75
  isGuestEnabled: boolean;
76
+ /** Residents may complete this facility's checklist themselves. */
77
+ isResidentChecklistEnabled?: boolean;
78
+ /** Security may complete it. Mutually exclusive with the above. */
79
+ isSecurityChecklistEnabled?: boolean;
76
80
  bookingAmount: number | null;
77
81
  peakBookingFeeAmount?: number | null;
78
82
  bookingFeeGuestAmount?: number | null;
package/types/people.d.ts CHANGED
@@ -22,11 +22,14 @@ declare type TPeople = {
22
22
  email?: string;
23
23
  files?: { name: string, id: string }[];
24
24
  isOwner?: boolean;
25
+ // Link to this person's `users` row. Empty for the person types that carry
26
+ // no login, and empty for a resident whose account was never written.
27
+ user?: string;
25
28
  };
26
29
 
27
- declare type TPlateNumber = { plateNumber: string, recNo: string, _id?: string, status: "active" | "deleted" | "pending", type: TVehicleType };
30
+ declare type TPlateNumber = { plateNumber: string, recNo?: string, _id?: string, status: TVehicleStatus, type: TVehicleType, anprCameras?: TVehicleAnprCamera[] };
28
31
 
29
32
 
30
- declare type TPeoplePayload = Pick<TGuest, "name" | "block" | "level" | "unit" | "unitName" | "contact" | "plateNumber" | "nric" | "contact" | "remarks" | "org" | "site" | "start" | "end" | "type" | "isOwner"> & { status?: string }
33
+ declare type TPeoplePayload = Pick<TGuest, "name" | "block" | "level" | "unit" | "unitName" | "contact" | "plateNumber" | "nric" | "contact" | "remarks" | "org" | "site" | "start" | "end" | "type" | "isOwner"> & { status?: string; user?: string }
31
34
 
32
35
  declare type TPeopleType = "guest" | "resident" | "tenant"
@@ -2,7 +2,20 @@ declare type TVehicle = {
2
2
  plateNumber: string;
3
3
  plates?: TPlateNumber[]; // For display purposes, the API will return an array of plate numbers if there are multiple associated with the same vehicle record
4
4
  type: TVehicleType;
5
- category: "resident" | "visitor";
5
+ /**
6
+ * resident (whitelist), season_pass (season pass), visitor / contractor
7
+ * (added as Block Listed). A blocked vehicle keeps its category.
8
+ * "Block Listed" is on older records only.
9
+ */
10
+ category:
11
+ | "resident"
12
+ | "season_pass"
13
+ | "visitor"
14
+ | "contractor"
15
+ | "delivery"
16
+ | "pick-up"
17
+ | "drop-off"
18
+ | "Block Listed";
6
19
  direction: "entry" | "exit" | "both" | "none";
7
20
  name: string;
8
21
  phoneNumber?: string;
@@ -24,13 +37,55 @@ declare type TVehicle = {
24
37
  site?: string;
25
38
  org?: string;
26
39
  _id?: string;
40
+ /** No longer written: every camera keeps its own recNo, so the plate is the id. */
27
41
  recNo?: string;
28
42
  status?: TVehicleStatus;
43
+ /** The last 20 changes, oldest first. */
44
+ history?: TVehicleHistoryEntry[];
45
+ anprCameras?: TVehicleAnprCamera[];
29
46
  peopleId?: string; // For linking to a people record, if applicable
30
47
  };
31
48
 
32
49
  declare type TVehicleType = "whitelist" | "blocklist";
33
- declare type TVehicleStatus = "active" | 'inactive' | "pending" | "deleted" | "rejected" ;
50
+ /**
51
+ * active - whitelisted, on the cameras' allowed list
52
+ * temporary - a season pass: whitelisted until its end date (the camera
53
+ * stops opening for it by itself once that date passes)
54
+ * blocked - on every camera's blocklist, category "Block Listed"
55
+ * unblocked - taken off every blocklist, and on no allowed list
56
+ * pending - waiting for approval, not on any camera
57
+ * deleted - soft-deleted, not on any camera
58
+ * inactive / rejected - older records
59
+ */
60
+ declare type TVehicleStatus =
61
+ | "active"
62
+ | "temporary"
63
+ | "blocked"
64
+ | "unblocked"
65
+ | "pending"
66
+ | "deleted"
67
+ | "inactive"
68
+ | "rejected";
69
+
70
+ /** An ANPR camera a plate is on, as the vehicle's last camera change recorded it. */
71
+ declare type TVehicleAnprCamera = {
72
+ /** The camera's URL - its unique id. */
73
+ host: string;
74
+ camera: string;
75
+ name: string;
76
+ /** entry, both, residents, visitors, exit */
77
+ direction: string;
78
+ list: "allowed" | "blocked";
79
+ };
80
+
81
+ declare type TVehicleHistoryEntry = {
82
+ action: string;
83
+ updatedBy: string | null;
84
+ /** Resolved by the server from `updatedBy`, for display. */
85
+ updatedByName?: string;
86
+ updatedAt: string;
87
+ fields: string[];
88
+ };
34
89
 
35
90
  declare type TVehiclePayload = Pick<
36
91
  TVehicle,
@@ -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
+ }