@7365admin1/layer-common 4.90.2-staging.491 → 4.90.2

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 (77) hide show
  1. package/CHANGELOG.md +10 -4
  2. package/assets/css/primitives.css +0 -57
  3. package/assets/css/screens.css +4 -8
  4. package/components/AccessCardDetailsDialog.vue +6 -59
  5. package/components/AccessCardPreviewDialog.vue +53 -371
  6. package/components/AppSelect.vue +4 -143
  7. package/components/BuildingUnitFormEdit.vue +0 -6
  8. package/components/Dialog/UpdateMoreAction.vue +1 -11
  9. package/components/DocumentForm.vue +112 -407
  10. package/components/DocumentManagement.vue +12 -213
  11. package/components/Facility/BookingSetup.vue +0 -63
  12. package/components/HidAccessLogDashboard.vue +17 -74
  13. package/components/HidIntercomManagement.vue +14 -183
  14. package/components/HidQrCodeConfiguration.vue +195 -17
  15. package/components/HidReaderManagement.vue +0 -398
  16. package/components/HidReaderUserRoster.vue +3 -44
  17. package/components/HidUserEnrollment.vue +292 -2255
  18. package/components/InventoryItemDetail.vue +1 -2
  19. package/components/InventoryLinesDialog.vue +13 -91
  20. package/components/InventoryPhotoInput.vue +6 -44
  21. package/components/InventoryReportsTab.vue +3 -23
  22. package/components/InventoryRequestsTab.vue +4 -27
  23. package/components/InventoryStockTab.vue +0 -3
  24. package/components/InvitationClientForm.vue +1 -19
  25. package/components/InvitationForm.vue +4 -31
  26. package/components/InvitationMain.vue +22 -124
  27. package/components/MemberInformation.vue +4 -4
  28. package/components/PassInformation.vue +2 -2
  29. package/components/SiteSettings.vue +0 -48
  30. package/components/TableMain.vue +7 -22
  31. package/components/VehicleManagement.vue +5 -80
  32. package/components/VisitorForm.vue +19 -65
  33. package/components/VisitorManagement.vue +5 -267
  34. package/composables/useAccessManagement.ts +1 -17
  35. package/composables/useDocument.ts +0 -7
  36. package/composables/useFacility.ts +0 -11
  37. package/composables/useHidAmico.ts +0 -165
  38. package/composables/useHidNavigation.ts +1 -25
  39. package/composables/useInventory.ts +1 -4
  40. package/composables/useMember.ts +0 -12
  41. package/composables/useNFCPatrolReportFilters.ts +3 -21
  42. package/composables/useNFCPatrolRoute.ts +1 -8
  43. package/composables/usePeople.ts +0 -19
  44. package/composables/useServiceProvider.ts +2 -45
  45. package/composables/useSettingsPermission.ts +0 -14
  46. package/composables/useUser.ts +2 -6
  47. package/composables/useVehicle.ts +1 -40
  48. package/composables/useVerification.ts +0 -3
  49. package/middleware/01.auth.ts +7 -3
  50. package/package.json +1 -1
  51. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  52. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  53. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  54. package/types/document.d.ts +0 -14
  55. package/types/facility.d.ts +0 -4
  56. package/types/inventory.d.ts +0 -27
  57. package/types/member.d.ts +0 -4
  58. package/types/people.d.ts +1 -28
  59. package/types/service-provider.d.ts +0 -5
  60. package/types/site.d.ts +1 -7
  61. package/components/BuildingUnitManagement.vue +0 -298
  62. package/components/HidAccessPermissions.vue +0 -424
  63. package/components/HidProfileQrCode.vue +0 -332
  64. package/components/InventoryPoDialog.vue +0 -111
  65. package/components/VehicleQrStickerDialog.vue +0 -249
  66. package/composables/useHidReaderSelection.ts +0 -50
  67. package/composables/useSiteCategory.ts +0 -45
  68. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +0 -23
  69. package/utils/hid-enrolment-subject.ts +0 -344
  70. package/utils/hid-permission-assignments.ts +0 -198
  71. package/utils/hid-reader-selection.ts +0 -52
  72. package/utils/inventory-receiving.ts +0 -90
  73. package/utils/invite-group.ts +0 -61
  74. package/utils/invite-sites.ts +0 -25
  75. package/utils/occupancy-role.ts +0 -109
  76. package/utils/service-type.ts +0 -30
  77. package/utils/vehicle-qr-sticker.ts +0 -184
@@ -1,50 +0,0 @@
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
- }
@@ -1,45 +0,0 @@
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
- }
@@ -1,23 +0,0 @@
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>
@@ -1,344 +0,0 @@
1
- /**
2
- * WHO A HID ENROLMENT IS FOR — the pure decisions behind the subject picker.
3
- *
4
- * `HidUserEnrollment.vue` can enrol a resident or a staff member. The write path
5
- * always carried both (`subjectLink` maps them onto `person` or `member`); what
6
- * was missing was a way to choose. These are the parts of that choice worth
7
- * testing on their own, kept here because a `.vue` component has no test harness
8
- * in this repo.
9
- */
10
-
11
- /**
12
- * What the ENROLLING dropdown offers. Three of these four are the server's own
13
- * permission categories; `service_provider_staff` is this screen's own value
14
- * and deliberately not one of them - see `subjectLinkOf`.
15
- */
16
- export type HidEnrolmentSubject =
17
- | "resident"
18
- | "property_management"
19
- | "service_provider_staff";
20
-
21
- /**
22
- * The dropdown's options, in the order they are drawn.
23
- *
24
- * `title`/`value` because `AppSelect` takes that shape.
25
- */
26
- export const HID_ENROLMENT_SUBJECTS: ReadonlyArray<{
27
- title: string;
28
- value: HidEnrolmentSubject;
29
- }> = [
30
- { title: "Resident", value: "resident" },
31
- { title: "Member", value: "property_management" },
32
- { title: "Service provider", value: "service_provider_staff" },
33
- ];
34
-
35
- /**
36
- * What an EDIT calls the subject it is already attached to.
37
- *
38
- * Wider than the dropdown on purpose. An identity's category cannot change after
39
- * it is created, so an edit states it rather than offering it — and the records
40
- * in the wild include `service_provider`, which the dropdown does not offer yet
41
- * but `openEdit` does resolve. Falling back to the first option would label a
42
- * contractor "Resident", which is worse than saying nothing useful.
43
- */
44
- export function subjectCategoryLabel(category: unknown): string {
45
- const labels: Record<string, string> = {
46
- resident: "Resident",
47
- property_management: "Member",
48
- // The dropdown's own value: ONE PERSON from a provider company.
49
- service_provider_staff: "Service provider",
50
- // The server's category, which names a COMPANY. Records in the wild carry
51
- // it, and an edit must not call such a row a resident.
52
- service_provider: "Service provider",
53
- visitor: "Visitor",
54
- };
55
- return labels[String(category ?? "")] ?? "Unknown";
56
- }
57
-
58
- /**
59
- * One page of `GET /api/members`, read defensively.
60
- *
61
- * `paginate` puts `{ items, pages }` at the root, but `items` sits under `data`
62
- * on some of this product's endpoints, so both are read — the same allowance
63
- * `readCandidatePage` makes. A response that carries neither is an empty page
64
- * rather than a thrown error: an empty staff picker with a placeholder beats a
65
- * broken dialog.
66
- */
67
- export function readMemberPage(response: unknown): {
68
- items: Record<string, unknown>[];
69
- pages: number;
70
- total: number;
71
- } {
72
- const source = (response && typeof response === "object" ? response : {}) as Record<string, unknown>;
73
- const nested = (source.data && typeof source.data === "object" ? source.data : {}) as Record<string, unknown>;
74
- const raw = Array.isArray(source.items)
75
- ? source.items
76
- : Array.isArray(nested.items)
77
- ? nested.items
78
- : [];
79
- const pages = Number(source.pages ?? nested.pages ?? 1);
80
- const items = raw.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === "object");
81
- /*
82
- * `total` drives "showing 10 of 23" and the Load more button. It falls back to
83
- * the page's own length, not to zero, so a response without it simply reads as
84
- * "this is everything" — a missing count must never make the button offer a
85
- * page that is not there.
86
- */
87
- const total = Number(source.total ?? nested.total ?? items.length);
88
- return {
89
- items,
90
- pages: Number.isFinite(pages) && pages > 0 ? Math.floor(pages) : 1,
91
- total: Number.isFinite(total) && total >= 0 ? Math.floor(total) : items.length,
92
- };
93
- }
94
-
95
- /**
96
- * Can this member actually be enrolled?
97
- *
98
- * Reader access is bound by USER id — `resolvePermissionUserBindings` in
99
- * `iservice365-core` drops every subject without one — so a member with no app
100
- * account cannot be given access and is not a candidate. The id arrives as a
101
- * string from JSON but may be an object if a caller passes a raw document, so
102
- * both are read rather than trusting the shape.
103
- */
104
- export function memberHasAccount(row: Record<string, unknown> | null | undefined): boolean {
105
- const user = row?.user;
106
- if (!user) return false;
107
- if (typeof user === "object") {
108
- const id = (user as { _id?: unknown; toString?: () => string })._id ?? user;
109
- return Boolean(String(id ?? "").trim());
110
- }
111
- return Boolean(String(user).trim());
112
- }
113
-
114
- /**
115
- * How a member reads in the picker: their name, and their role beneath it.
116
- *
117
- * THE ACCOUNT'S NAME FIRST, then the membership's. The two diverge — a
118
- * membership is created with whatever name was typed at invite time, and the
119
- * person may have set their own on the account since — and the account name is
120
- * the one they are known by. `userName` comes from the members endpoint's own
121
- * lookup into `users`; a member with no account has none, but such a row is not
122
- * a candidate anyway (`memberHasAccount`).
123
- *
124
- * Every step falls back, because a row with no name at all still has to be
125
- * selectable rather than blank, or it cannot be told apart from the next one.
126
- */
127
- export function memberCandidateOf(row: Record<string, unknown>): {
128
- subjectId: string;
129
- name: string;
130
- subtitle: string;
131
- } {
132
- const text = (value: unknown) => String(value ?? "").trim();
133
- return {
134
- subjectId: text(row._id),
135
- name: text(row.userName) || text(row.name) || text(row.email) || "Member",
136
- subtitle: text(row.roleName) || text(row.email) || "",
137
- };
138
- }
139
-
140
- /**
141
- * Why somebody the operator can see elsewhere is not in this list.
142
- *
143
- * Left unexplained, an absence reads as a broken screen — the same reason the
144
- * resident cascade carries `unitResidentNote`. Returns "" when there is nothing
145
- * to say, so the caller can render it unconditionally.
146
- */
147
- export function hiddenSubjectNote(count: number, noun: "resident" | "member"): string {
148
- if (!Number.isFinite(count) || count <= 0) return "";
149
- const whole = Math.floor(count);
150
- const subject = whole === 1 ? `1 ${noun}` : `${whole} ${noun}s`;
151
- const verb = whole === 1 ? "is" : "are";
152
- const holder = whole === 1 ? "that person has" : "they have";
153
- return `${subject} at this site ${verb} not listed:`
154
- + ` HID enrollment needs an app account, and ${holder} none yet.`;
155
- }
156
-
157
- /* ── THE LINK THAT REACHES THE DEVICE ──────────────────────────────────── */
158
-
159
- /**
160
- * WHICH SUBJECT FIELD AN ENROLMENT WRITES, and what the identity is called.
161
- *
162
- * This is the one decision in the dialog that changes who a door lets in, so it
163
- * lives here with tests rather than inline in the template's script.
164
- *
165
- * `service_provider_staff` links through `member`, NOT `serviceProvider`, and
166
- * that is the whole design:
167
- *
168
- * - `serviceProvider` names a `site.service-providers` row, which is a COMPANY.
169
- * `resolvePermissionUserBindings` expands one into every active member of
170
- * that organisation with NO site filter, so granting it puts a 200-person
171
- * firm on a door that eight of them attend.
172
- * - A provider employee's membership lives in `members` with `siteId` set to
173
- * this site - `members` carries a unique index on `{org, siteId, user, type}`,
174
- * so it cannot exist there without one. That makes the person site-scoped by
175
- * construction, which is the whole point.
176
- *
177
- * The identity `type` is `"contractor"` rather than `"staff"`, and it is load
178
- * bearing on the server as well as here: core's `permissionSubjectOfIdentity`
179
- * reads it to tell a contractor's `member` link from a property-management one,
180
- * and files the grant under `service_provider_member` or `property_management`
181
- * accordingly. It is also what the Access Permissions tabs filter on.
182
- *
183
- * An earlier version filed provider staff under `property_management`, since that
184
- * category's subject list already accepts these rows. It worked for access and
185
- * failed for identity: `permissionIdentityType` derives the identity's type from
186
- * the category, so every contractor came back as `staff` - and because the
187
- * reconcile rewrites the identity it finds, the `"contractor"` written here was
188
- * overwritten seconds later.
189
- *
190
- * An empty `subjectId` returns `{}` ON PURPOSE. Sending `person: ""` is not
191
- * "leave this alone", it is "clear it": the server reads an empty string as the
192
- * link being removed and then refuses the write for having no subject at all.
193
- */
194
- export function subjectLinkOf(
195
- category: unknown,
196
- subjectId: unknown,
197
- ): {
198
- person?: string;
199
- member?: string;
200
- serviceProvider?: string;
201
- type?: "resident" | "staff" | "contractor";
202
- } {
203
- const id = String(subjectId ?? "").trim();
204
- if (!id) return {};
205
- const of = (
206
- field: "person" | "member" | "serviceProvider",
207
- type: "resident" | "staff" | "contractor",
208
- ) => ({
209
- person: field === "person" ? id : "",
210
- member: field === "member" ? id : "",
211
- serviceProvider: field === "serviceProvider" ? id : "",
212
- type,
213
- });
214
- switch (String(category ?? "")) {
215
- case "resident":
216
- return of("person", "resident");
217
- case "service_provider_staff":
218
- return of("member", "contractor");
219
- case "service_provider":
220
- return of("serviceProvider", "contractor");
221
- default:
222
- return of("member", "staff");
223
- }
224
- }
225
-
226
- /**
227
- * Which PERMISSION CATEGORY an enrolment's access grant is stored under.
228
- *
229
- * Mirrors `permissionSubjectOfIdentity` in core, which reads the stored links
230
- * rather than this dropdown: a `member` link resolves to `property_management`
231
- * whatever the identity's `type` says. Provider staff therefore share the staff
232
- * category, which is correct - they are validated against the same subject list
233
- * - and the identity `type` is what tells them apart on screen.
234
- */
235
- export function permissionCategoryOf(category: unknown): string {
236
- const value = String(category ?? "");
237
- if (value === "resident") return "resident";
238
- if (value === "service_provider") return "service_provider";
239
- if (value === "service_provider_staff") return "service_provider_member";
240
- return "property_management";
241
- }
242
-
243
- /* ── PROVIDER STAFF AS PICKER ROWS ─────────────────────────────────────── */
244
-
245
- /**
246
- * Can this provider employee be enrolled?
247
- *
248
- * Two conditions, and both have to be checked here rather than trusted from the
249
- * list. An app account, because reader access is bound by user id
250
- * (`memberHasAccount`). And an ACTIVE membership: `getProviderMembersBySite`
251
- * returns everyone who is not deleted, so a suspended person is in the list the
252
- * Members screen draws - marked, deliberately, so the property manager can see
253
- * them. Offering a suspended person a door is a different matter.
254
- */
255
- export function providerCanEnrol(
256
- row: Record<string, unknown> | null | undefined,
257
- ): boolean {
258
- if (!memberHasAccount(row)) return false;
259
- return String(row?.status ?? "").trim() === "active";
260
- }
261
-
262
- /**
263
- * How a provider employee reads in the picker: their name, their company and
264
- * the service beneath it.
265
- *
266
- * The company comes FIRST in the subtitle. Two contractors with the same first
267
- * name are common, and which firm somebody belongs to is what the property
268
- * manager actually recognises them by - the service type alone ("Security")
269
- * describes half the list.
270
- */
271
- export function providerCandidateOf(row: Record<string, unknown>): {
272
- subjectId: string;
273
- name: string;
274
- subtitle: string;
275
- } {
276
- const text = (value: unknown) => String(value ?? "").trim();
277
- const parts = [text(row.company), text(row.typeLabel)].filter(Boolean);
278
- return {
279
- subjectId: text(row._id),
280
- name: text(row.name) || text(row.email) || "Service provider",
281
- subtitle: parts.join(" · ") || text(row.role) || text(row.email) || "",
282
- };
283
- }
284
-
285
- /**
286
- * Does this list tell us who has an app account?
287
- *
288
- * `GET /api/service-providers/site-members` only began returning `user` in core
289
- * 3.130; before that the service layer dropped it even though the repository
290
- * projected it. Frontend and backend deploy separately, so this screen can run
291
- * against either. Asked of the ROWS rather than of a version number: the key is
292
- * present on every row or on none.
293
- *
294
- * It matters because the answer flips a filter from "cannot be bound to a door"
295
- * to "unknown", and a screen that silently reports NOBODY can be enrolled is
296
- * worse than one that offers somebody the server then refuses by name.
297
- */
298
- export function providerAccountsKnown(
299
- rows: ReadonlyArray<Record<string, unknown>>,
300
- ): boolean {
301
- return rows.some((row) => Boolean(row) && typeof row === "object" && "user" in row);
302
- }
303
-
304
- /**
305
- * Who may be offered a door, from whatever the endpoint returned.
306
- *
307
- * With accounts known, both conditions apply (`providerCanEnrol`). Without them,
308
- * active membership is all that can be checked here — the server still refuses
309
- * anyone it cannot bind, with a message naming them, which is a better failure
310
- * than an empty picker.
311
- */
312
- export function providerEnrollableRows<T extends Record<string, unknown>>(
313
- rows: ReadonlyArray<T>,
314
- ): T[] {
315
- const known = providerAccountsKnown(rows);
316
- return rows.filter((row) =>
317
- known ? providerCanEnrol(row) : String(row?.status ?? "").trim() === "active",
318
- );
319
- }
320
-
321
- /* ── THE SERVICE FILTER'S "ALL" ────────────────────────────────────────── */
322
-
323
- /**
324
- * WHY "ALL SERVICES" CANNOT BE THE EMPTY STRING HERE.
325
- *
326
- * `filterProviderMembers` reads an empty `type` as "do not filter", and the
327
- * Members screen's own filter uses `value: ""` for All services - but that screen
328
- * draws a Vuetify `v-select`, which renders an empty value perfectly well.
329
- *
330
- * `AppSelect` does not. Its `hasSingleValue` is false for `""`, so the field
331
- * falls back to the placeholder, draws in the placeholder's grey, and the option
332
- * is never marked as the chosen one in the menu. The filter worked; it just
333
- * looked like nothing was selected and like only the real services existed.
334
- *
335
- * So the option carries a real value here and is translated on the way to the
336
- * filter. Changing `AppSelect` instead would touch every one of its callers.
337
- */
338
- export const HID_ALL_SERVICES = "all";
339
-
340
- /** The `type` to filter by: "" for All services, the service code otherwise. */
341
- export function serviceFilterOf(selected: unknown): string {
342
- const value = String(selected ?? "").trim();
343
- return value === HID_ALL_SERVICES ? "" : value;
344
- }
@@ -1,198 +0,0 @@
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
- /**
31
- * The real categories. `intercom` is a candidate FILTER, never a category.
32
- *
33
- * Mirrors `HID_PERMISSION_CATEGORIES` in core, and has to: `seedAssignments`
34
- * DROPS a row whose category is not in this list, so a category missing here
35
- * silently loses that grant from the edit state - and the save that follows,
36
- * being a whole-reader replace, would revoke it.
37
- */
38
- export const HID_PERMISSION_CATEGORIES: THidPermissionCategory[] = [
39
- "resident",
40
- "property_management",
41
- "service_provider",
42
- "service_provider_member",
43
- ];
44
-
45
- export type HidAssignmentState = Map<string, { category: THidPermissionCategory; intercom: boolean }>;
46
-
47
- /** Body row for `updateSitePermissions` — exactly the keys Joi allows. */
48
- export type HidAssignmentPayload = {
49
- subjectId: string;
50
- category: THidPermissionCategory;
51
- intercom: boolean;
52
- };
53
-
54
- function isRealCategory(value: unknown): value is THidPermissionCategory {
55
- return HID_PERMISSION_CATEGORIES.includes(value as THidPermissionCategory);
56
- }
57
-
58
- /**
59
- * The reader's CURRENT assignments, as the edit state.
60
- *
61
- * Seeded from `getSitePermissions`, which returns every category at once —
62
- * that is what makes a whole-reader payload possible from a one-category view.
63
- * Rows with an unrecognised category are dropped rather than carried: sending
64
- * one back fails the enum check and takes the entire save with it.
65
- */
66
- export function seedAssignments(
67
- assignments: readonly THidPermissionAssignment[] | undefined | null,
68
- ): HidAssignmentState {
69
- const state: HidAssignmentState = new Map();
70
- if (!Array.isArray(assignments)) return state;
71
- for (const assignment of assignments) {
72
- const subjectId = String(assignment?.subjectId ?? "");
73
- if (!subjectId || !isRealCategory(assignment?.category)) continue;
74
- state.set(subjectId, {
75
- category: assignment.category,
76
- intercom: assignment.intercom === true,
77
- });
78
- }
79
- return state;
80
- }
81
-
82
- /**
83
- * Add or remove one person.
84
- *
85
- * `saved` is the state the dialog opened with, and it is consulted for one
86
- * reason: the `intercom` flag. Nothing here edits that flag, but
87
- * `userHasSiteIntercomPermission` reads it off these same rows, so it must
88
- * survive a round trip through the checkbox.
89
- *
90
- * - **Untick then save** drops it, which is right — an unassigned person
91
- * holding a dangling intercom right would keep answering the door panel
92
- * after losing the door.
93
- * - **Untick then re-tick, without saving** must restore it. Removing from the
94
- * draft forgets the flag, so re-adding recovers it from `saved`; otherwise a
95
- * misclick corrected a second later would silently revoke intercom on the
96
- * next save, with nothing on screen to show it had happened.
97
- */
98
- export function setAssignment(
99
- state: HidAssignmentState,
100
- saved: HidAssignmentState,
101
- subjectId: string,
102
- category: THidPermissionCategory,
103
- selected: boolean,
104
- ): HidAssignmentState {
105
- const next: HidAssignmentState = new Map(state);
106
- const id = String(subjectId ?? "");
107
- if (!id || !isRealCategory(category)) return next;
108
- if (!selected) {
109
- next.delete(id);
110
- return next;
111
- }
112
- const intercom = next.get(id)?.intercom ?? saved.get(id)?.intercom ?? false;
113
- next.set(id, { category, intercom: intercom === true });
114
- return next;
115
- }
116
-
117
- /** The whole reader's assignments, narrowed to the three keys the API accepts. */
118
- export function toAssignmentPayload(state: HidAssignmentState): HidAssignmentPayload[] {
119
- return [...state.entries()].map(([subjectId, value]) => ({
120
- subjectId,
121
- category: value.category,
122
- intercom: value.intercom === true,
123
- }));
124
- }
125
-
126
- /**
127
- * The server sends `selected` with each candidate, describing what is SAVED.
128
- * Once the dialog is open the local edit state is the truth, so the flag is
129
- * recomputed rather than trusted — otherwise paging or searching would redraw
130
- * a row with the saved value and quietly discard an unsaved tick.
131
- */
132
- export function applySelection(
133
- candidates: readonly THidPermissionCandidate[] | undefined | null,
134
- state: HidAssignmentState,
135
- ): THidPermissionCandidate[] {
136
- if (!Array.isArray(candidates)) return [];
137
- return candidates.map((candidate) => ({
138
- ...candidate,
139
- selected: state.has(String(candidate?.subjectId ?? "")),
140
- }));
141
- }
142
-
143
- /** Per-category totals for the dialog header, counted over the whole reader. */
144
- export function countByCategory(state: HidAssignmentState): Record<THidPermissionCategory, number> {
145
- const counts = { resident: 0, property_management: 0, service_provider: 0 } as Record<
146
- THidPermissionCategory,
147
- number
148
- >;
149
- for (const value of state.values()) counts[value.category] += 1;
150
- return counts;
151
- }
152
-
153
- /** Has anything changed since the dialog opened? Drives the Save button. */
154
- export function hasChanges(saved: HidAssignmentState, draft: HidAssignmentState): boolean {
155
- if (saved.size !== draft.size) return true;
156
- for (const [subjectId, value] of draft) {
157
- const before = saved.get(subjectId);
158
- if (!before) return true;
159
- if (before.category !== value.category) return true;
160
- if (before.intercom !== value.intercom) return true;
161
- }
162
- return false;
163
- }
164
-
165
- /**
166
- * What a listing response tells us: the rows, and how many pages exist.
167
- *
168
- * It deliberately does NOT return the current page, and the caller must keep
169
- * owning that. `paginate` in `@7365admin1/node-server-utils` returns only
170
- * `{ items, pages, pageRange }` — it never echoes the page it was asked for. A
171
- * caller that read one back therefore got a default on every fetch and pinned
172
- * itself to page one, so the pager moved and the rows never did.
173
- *
174
- * `items` sits at the root on some of these endpoints and under `data` on
175
- * others, so both are read.
176
- */
177
- export function readCandidatePage(response: unknown): {
178
- items: THidPermissionCandidate[];
179
- pages: number;
180
- pageRange: string;
181
- } {
182
- const source = (response && typeof response === "object" ? response : {}) as Record<string, unknown>;
183
- const nested = (source.data && typeof source.data === "object" ? source.data : {}) as Record<string, unknown>;
184
- const items = Array.isArray(source.items)
185
- ? source.items
186
- : Array.isArray(nested.items)
187
- ? nested.items
188
- : [];
189
- const pages = Number(source.pages ?? nested.pages ?? 1);
190
- // `paginate` builds this ("1-10 of 37") and the table renders it verbatim.
191
- // Without it the pager draws its placeholder, "-- - -- of --".
192
- const pageRange = String(source.pageRange ?? nested.pageRange ?? "");
193
- return {
194
- items: items as THidPermissionCandidate[],
195
- pages: Number.isFinite(pages) && pages > 0 ? pages : 1,
196
- pageRange,
197
- };
198
- }