@7365admin1/layer-common 4.73.0 → 4.73.1-staging.452

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 (45) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/assets/css/primitives.css +43 -0
  3. package/components/AccessCardPreviewDialog.vue +286 -50
  4. package/components/AppSelect.vue +77 -3
  5. package/components/BuildingUnitFormEdit.vue +6 -0
  6. package/components/BuildingUnitManagement.vue +298 -0
  7. package/components/Dialog/UpdateMoreAction.vue +11 -1
  8. package/components/DocumentForm.vue +407 -112
  9. package/components/DocumentManagement.vue +213 -12
  10. package/components/Facility/BookingSetup.vue +63 -0
  11. package/components/HidAccessLogDashboard.vue +74 -17
  12. package/components/HidAccessPermissions.vue +424 -0
  13. package/components/HidIntercomManagement.vue +183 -14
  14. package/components/HidProfileQrCode.vue +332 -0
  15. package/components/HidQrCodeConfiguration.vue +17 -195
  16. package/components/HidReaderManagement.vue +398 -0
  17. package/components/HidReaderUserRoster.vue +44 -3
  18. package/components/HidUserEnrollment.vue +845 -155
  19. package/components/InvitationClientForm.vue +19 -1
  20. package/components/VisitorForm.vue +12 -0
  21. package/components/VisitorManagement.vue +267 -5
  22. package/composables/useDocument.ts +7 -0
  23. package/composables/useFacility.ts +11 -0
  24. package/composables/useHidAmico.ts +165 -0
  25. package/composables/useHidNavigation.ts +25 -1
  26. package/composables/useHidReaderSelection.ts +50 -0
  27. package/composables/useMember.ts +12 -0
  28. package/composables/usePeople.ts +19 -0
  29. package/composables/useSecurityPermission.ts +20 -0
  30. package/composables/useServiceProvider.ts +33 -2
  31. package/composables/useSiteCategory.ts +45 -0
  32. package/package.json +1 -1
  33. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  34. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  35. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  36. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  37. package/types/document.d.ts +14 -0
  38. package/types/facility.d.ts +4 -0
  39. package/types/member.d.ts +4 -0
  40. package/types/people.d.ts +28 -1
  41. package/types/service-provider.d.ts +5 -0
  42. package/utils/hid-permission-assignments.ts +190 -0
  43. package/utils/hid-reader-selection.ts +52 -0
  44. package/utils/occupancy-role.ts +109 -0
  45. package/utils/service-type.ts +30 -0
@@ -0,0 +1,50 @@
1
+ import {
2
+ EMPTY_HID_READER_CHOICE,
3
+ resolveHidReaderId,
4
+ type HidReaderChoice,
5
+ } from "../utils/hid-reader-selection";
6
+
7
+ /**
8
+ * ONE HID READER CHOICE, SHARED BY EVERY HID SCREEN.
9
+ *
10
+ * Declared at MODULE scope on purpose. Each screen held its own `ref("")`, and
11
+ * because the HID screens are separate pages the ref was rebuilt on every
12
+ * navigation — HID Reader Users, HID Cards, Access Logs and HID QR Code each
13
+ * reset to the first reader no matter what had just been picked next door.
14
+ *
15
+ * A module-scoped ref is enough because moving between those pages is a ROUTE
16
+ * change, not a page load: the menu's items carry a `route` and
17
+ * `NavigationItem.vue` renders them through `:to`, so vue-router handles them
18
+ * and this module is never re-evaluated.
19
+ *
20
+ * Deliberately NOT persisted. `localStorage` would carry the choice through a
21
+ * hard refresh as well, which is a real but much smaller benefit than the
22
+ * navigation case, and it is worth adding only once somebody has felt the
23
+ * absence. See `utils/hid-reader-selection.ts` for the staleness rule that
24
+ * would have to hold either way.
25
+ *
26
+ * Intercom keeps its own reader and is not wired to this. Its question is which
27
+ * panel you are calling, not which door you are administering, and joining them
28
+ * would mean switching reader on Access Logs changed who you would dial.
29
+ */
30
+ const choice = ref<HidReaderChoice>({ ...EMPTY_HID_READER_CHOICE });
31
+
32
+ export default function useHidReaderSelection() {
33
+ /** Remember a choice. The site travels with it; an id alone means nothing. */
34
+ function selectHidReader(siteId: string, readerId: string) {
35
+ choice.value = { siteId: String(siteId ?? ""), readerId: String(readerId ?? "") };
36
+ }
37
+
38
+ /**
39
+ * The reader this screen should show, given the readers it just loaded.
40
+ *
41
+ * Call it after the reader list arrives, and write the answer back with
42
+ * `selectHidReader` so the screens agree on what "current" means even when
43
+ * one of them had to fall back to the first reader.
44
+ */
45
+ function resolveForSite(siteId: string, readers: readonly { _id?: unknown }[]) {
46
+ return resolveHidReaderId(siteId, readers, choice.value);
47
+ }
48
+
49
+ return { choice, selectHidReader, resolveForSite };
50
+ }
@@ -70,6 +70,8 @@ export default function useMember() {
70
70
  status = "active",
71
71
  siteId = "",
72
72
  roleState = "",
73
+ /** A building unit id, or "none": members on no unit yet. */
74
+ unit = "",
73
75
  } = {}) {
74
76
  const query: Record<string, any> = { page, limit, type, status };
75
77
 
@@ -79,6 +81,7 @@ export default function useMember() {
79
81
  if (user) query.user = user;
80
82
  if (org) query.org = org;
81
83
  if (siteId) query.siteId = siteId;
84
+ if (unit) query.unit = unit;
82
85
  return useNuxtApp().$api<Record<string, any>>("/api/members", {
83
86
  method: "GET",
84
87
  query,
@@ -154,6 +157,14 @@ export default function useMember() {
154
157
  });
155
158
  }
156
159
 
160
+ /** Attach a member to a building unit, or detach them (`unit` ""). */
161
+ function updateMemberUnit(id: string, unit: string) {
162
+ return useNuxtApp().$api<Record<string, any>>("/api/members/unit", {
163
+ method: "PUT",
164
+ body: { id, unit },
165
+ });
166
+ }
167
+
157
168
  function getByUserTypeOrg(user: string, type: string, org: string) {
158
169
  return useNuxtApp().$api<TMember>(
159
170
  `/api/members/user/${user}/app/${type}/org`,
@@ -197,6 +208,7 @@ export default function useMember() {
197
208
  return {
198
209
  getSiteAccess,
199
210
  saveSiteAccess,
211
+ updateMemberUnit,
200
212
  members,
201
213
  member,
202
214
  page,
@@ -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,
@@ -714,6 +714,21 @@ export default function useSecurityPermission() {
714
714
  description:
715
715
  "Allows the user to start NFC patrolling on a specific route.",
716
716
  },
717
+ // Copied from Property. The security web app's NFC Patrol > Routes page
718
+ // gates Add, Edit and Delete on these, and API-core's `nfcPatrol` gate
719
+ // asks for the same strings on route create and update.
720
+ "add-nfc-patrol": {
721
+ check: true,
722
+ description: "Allows the user to add routes.",
723
+ },
724
+ "update-nfc-patrol": {
725
+ check: true,
726
+ description: "Allows the user to edit routes.",
727
+ },
728
+ "delete-nfc-patrol": {
729
+ check: true,
730
+ description: "Allows the user to delete routes.",
731
+ },
717
732
  },
718
733
  // NEW. Seeing the CCTV wall, as distinct from setting cameras up
719
734
  // (`site-settings:manage-cctv-camera`).
@@ -743,6 +758,11 @@ export default function useSecurityPermission() {
743
758
  siteSettingsPermissions["manage-resident-visitors"],
744
759
  "manage-work-order-settings":
745
760
  siteSettingsPermissions["manage-work-order-settings"],
761
+ // The security web app's Site Settings shows the NFC Management and NFC
762
+ // Patrol Settings panels on these, as Property's does.
763
+ "manage-nfc-management": siteSettingsPermissions["manage-nfc-management"],
764
+ "manage-nfc-patrol-settings":
765
+ siteSettingsPermissions["manage-nfc-patrol-settings"],
746
766
  "manage-red-dot-settings": {
747
767
  check: true,
748
768
  description:
@@ -15,6 +15,9 @@ export type TSiteProviderMember = {
15
15
  lastLoginAt?: string | null;
16
16
  /** a subcontractor: the provider that brought its company onto the site */
17
17
  invitedVia?: string;
18
+ /** The building unit this person is attached to (a unit's Management tab). */
19
+ unit?: string | null;
20
+ unitName?: string;
18
21
  };
19
22
 
20
23
  export type TSiteProviderCompany = {
@@ -90,6 +93,8 @@ export default function useServiceProvider() {
90
93
  status = "",
91
94
  /** "engagements": also providers engaged through an accepted invitation. */
92
95
  include = "",
96
+ /** A building unit id, or "none": providers on no unit yet. */
97
+ unit = "",
93
98
  } = {}) {
94
99
  return useNuxtApp().$api<Record<string, any>>("/api/service-providers", {
95
100
  method: "GET",
@@ -102,6 +107,7 @@ export default function useServiceProvider() {
102
107
  siteId,
103
108
  ...(status ? { status } : {}),
104
109
  ...(include ? { include } : {}),
110
+ ...(unit ? { unit } : {}),
105
111
  },
106
112
  });
107
113
  }
@@ -269,6 +275,17 @@ export default function useServiceProvider() {
269
275
  );
270
276
  }
271
277
 
278
+ /** Attach a provider to a building unit, or detach it (`unit` ""). */
279
+ async function updateUnit(id: string, unit: string) {
280
+ return useNuxtApp().$api<Record<string, any>>(
281
+ `/api/service-providers/${id}/unit`,
282
+ {
283
+ method: "PATCH",
284
+ body: { unit },
285
+ }
286
+ );
287
+ }
288
+
272
289
  async function getByEmail({
273
290
  email = "",
274
291
  orgId = "",
@@ -293,17 +310,29 @@ export default function useServiceProvider() {
293
310
  * Members > Service Providers: the provider people with access to this
294
311
  * site, and one entry per provider company with its head count. The
295
312
  * site's own organisation only - the server refuses anyone else.
313
+ * `unit`: a building unit id, or "none" (people on no unit yet).
296
314
  */
297
- function getSiteMembers(siteId: string): Promise<{
315
+ function getSiteMembers(siteId: string, unit = ""): Promise<{
298
316
  items: TSiteProviderMember[];
299
317
  companies: TSiteProviderCompany[];
300
318
  }> {
301
319
  return useNuxtApp().$api("/api/service-providers/site-members", {
302
320
  method: "GET",
303
- query: { siteId },
321
+ query: { siteId, ...(unit ? { unit } : {}) },
304
322
  });
305
323
  }
306
324
 
325
+ /** Attach one of those people to a building unit, or detach them (`unit` ""). */
326
+ function updateSiteMemberUnit(id: string, unit: string) {
327
+ return useNuxtApp().$api<Record<string, any>>(
328
+ `/api/service-providers/site-members/${id}/unit`,
329
+ {
330
+ method: "PATCH",
331
+ body: { unit },
332
+ }
333
+ );
334
+ }
335
+
307
336
  /** The same list as an Excel file, under the same filters. */
308
337
  function exportSiteMembers(
309
338
  siteId: string,
@@ -320,6 +349,7 @@ export default function useServiceProvider() {
320
349
 
321
350
  return {
322
351
  getSiteMembers,
352
+ updateSiteMemberUnit,
323
353
  exportSiteMembers,
324
354
  serviceProviders,
325
355
  serviceProvider,
@@ -338,6 +368,7 @@ export default function useServiceProvider() {
338
368
  add,
339
369
  addViaInvite,
340
370
  updateStatus,
371
+ updateUnit,
341
372
  getByEmail,
342
373
  };
343
374
  }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * THE CATEGORY OF THE SITE THE USER IS CURRENTLY IN.
3
+ *
4
+ * One shared answer, published once by the application's layout from the site
5
+ * it already loaded for the switcher, and read by anything that has to behave
6
+ * differently on a commercial or industrial site - the business Add Tenant
7
+ * form, the tenant list. Publishing it rather than re-fetching it per
8
+ * component means no two screens can disagree about which site this is.
9
+ *
10
+ * READ FROM THE CUSTOMER-SITE RECORD, NOT THE SITE RECORD. Both carry a
11
+ * `category` and `customer-site.service` keeps them equal (it writes the site
12
+ * on create and on update), but `siteSchema` DEFAULTS the site's own copy to
13
+ * `commercial` - so a site created without an explicit category reads back as
14
+ * commercial there even when it is a residential estate. The customer-site
15
+ * copy has no default: it is either the category somebody chose or nothing.
16
+ *
17
+ * An empty category means "not published yet" or "never set", and every
18
+ * caller must behave as it did before this existed - never assume commercial
19
+ * from silence.
20
+ */
21
+ const BUSINESS_SITE_CATEGORIES: string[] = ["commercial", "industrial"];
22
+
23
+ export default function useSiteCategory() {
24
+ const siteCategory = useState<string>("current-site-category", () => "");
25
+
26
+ function setSiteCategory(value?: string | null) {
27
+ siteCategory.value = typeof value === "string" ? value : "";
28
+ }
29
+
30
+ /**
31
+ * The categories whose units are LET TO A BUSINESS rather than lived in.
32
+ *
33
+ * These are the sites where a unit has an owner, an occupier and often a
34
+ * person in charge who is neither, so they are the sites that ask for a
35
+ * tenant's standing and print it back (see `OCCUPANCY_ROLE_OPTIONS`).
36
+ *
37
+ * The category never changes what the APPLICATION is called: the rail says
38
+ * Property Management on every site it serves.
39
+ */
40
+ const isBusinessSite = computed(() =>
41
+ BUSINESS_SITE_CATEGORIES.includes(siteCategory.value),
42
+ );
43
+
44
+ return { siteCategory, isBusinessSite, setSiteCategory };
45
+ }
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.73.0",
5
+ "version": "4.73.1-staging.452",
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/member.d.ts CHANGED
@@ -10,6 +10,10 @@ declare type TMember = {
10
10
  customerOrgId?: string;
11
11
  customerSiteId?: string;
12
12
  status?: string;
13
+ email?: string;
14
+ /** The building unit this member manages (a unit's Management tab). */
15
+ unit?: string | null;
16
+ unitName?: string;
13
17
  createdAt?: string;
14
18
  updatedAt?: string;
15
19
  deletedAt?: string;
package/types/people.d.ts CHANGED
@@ -22,11 +22,38 @@ declare type TPeople = {
22
22
  email?: string;
23
23
  files?: { name: string, id: string }[];
24
24
  isOwner?: boolean;
25
+ /**
26
+ * Owner / occupant / person-in-charge, as the BUSINESS people form asks it.
27
+ * Absent on everyone else - `isOwner` is still the flag that decides unit
28
+ * ownership, and the server derives it from this when it is sent. See
29
+ * `OccupancyRoles` in core's `person.model.ts`.
30
+ */
31
+ occupancyRole?: TOccupancyRole;
32
+ // Link to this person's `users` row. Empty for the person types that carry
33
+ // no login, and empty for a resident whose account was never written.
34
+ user?: string;
35
+ };
36
+
37
+ declare type TOccupancyRole = "owner" | "occupant" | "person-in-charge";
38
+
39
+ /** One standing and everything the product says about it. See `utils/occupancy-role.ts`. */
40
+ declare type TOccupancyRoleOption = {
41
+ value: TOccupancyRole;
42
+ /** The label a stored role is printed with. */
43
+ title: string;
44
+ /** The row menu's wording. */
45
+ action: string;
46
+ /** The confirmation's heading and its sentence. */
47
+ prompt: string;
48
+ description: string;
25
49
  };
26
50
 
27
51
  declare type TPlateNumber = { plateNumber: string, recNo?: string, _id?: string, status: TVehicleStatus, type: TVehicleType, anprCameras?: TVehicleAnprCamera[] };
28
52
 
29
53
 
30
- declare type TPeoplePayload = Pick<TGuest, "name" | "block" | "level" | "unit" | "unitName" | "contact" | "plateNumber" | "nric" | "contact" | "remarks" | "org" | "site" | "start" | "end" | "type" | "isOwner"> & { status?: string }
54
+ // `""` is the FORM's "nothing picked yet" - it is stripped from the payload
55
+ // before it is sent, because absence is what the server reads as "never
56
+ // asked". See `PeopleFormMgmt.vue`.
57
+ 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; occupancyRole?: TOccupancyRole | "" }
31
58
 
32
59
  declare type TPeopleType = "guest" | "resident" | "tenant"
@@ -7,6 +7,11 @@ declare type TServiceProvider = {
7
7
  serviceProviderOrgId: string;
8
8
  type: string;
9
9
  nature: string;
10
+ status?: string;
11
+ email?: string;
12
+ /** The building unit this provider serves (a unit's Management tab). */
13
+ unit?: string | null;
14
+ unitName?: string;
10
15
  };
11
16
 
12
17
  declare type TServiceProviderName = {
@@ -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
+ }