@7365admin1/layer-common 4.22.0 → 4.22.1-staging.352

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 (46) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/components/AccessCardAddForm.vue +5 -4
  3. package/components/AccessCardAssignToUnitForm.vue +3 -2
  4. package/components/AccessCardPreviewDialog.vue +4 -3
  5. package/components/Dialog/UpdateMoreAction.vue +11 -1
  6. package/components/DocumentForm.vue +407 -112
  7. package/components/DocumentManagement.vue +213 -12
  8. package/components/EntryPass/QrTemplatePreview.vue +21 -25
  9. package/components/EntryPassInformation.vue +119 -24
  10. package/components/Facility/BookingSetup.vue +63 -0
  11. package/components/HidAccessLogDashboard.vue +29 -5
  12. package/components/HidAccessPermissions.vue +424 -0
  13. package/components/HidIntercomManagement.vue +148 -14
  14. package/components/HidProfileQrCode.vue +323 -0
  15. package/components/HidReaderManagement.vue +26 -0
  16. package/components/HidReaderUserRoster.vue +32 -2
  17. package/components/HidUserEnrollment.vue +833 -152
  18. package/components/InvitationClientForm.vue +19 -1
  19. package/components/Robot/Fleet.vue +709 -0
  20. package/components/Robot/Form.vue +256 -0
  21. package/components/Robot/Map3D.vue +421 -0
  22. package/components/Robot/Plans.vue +63 -0
  23. package/components/Robot/SpotClean.vue +174 -0
  24. package/components/VisitorManagement.vue +267 -5
  25. package/composables/useAccessManagement.ts +5 -0
  26. package/composables/useDocument.ts +7 -0
  27. package/composables/useFacility.ts +11 -0
  28. package/composables/useHidAmico.ts +117 -0
  29. package/composables/useHidNavigation.ts +25 -1
  30. package/composables/usePeople.ts +19 -0
  31. package/composables/useRobots.ts +236 -0
  32. package/composables/useSiteCategory.ts +45 -0
  33. package/composables/useSiteEntryPassSettings.ts +26 -0
  34. package/composables/useWebUsb.ts +14 -11
  35. package/package.json +2 -2
  36. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  37. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  38. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  39. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  40. package/types/document.d.ts +14 -0
  41. package/types/facility.d.ts +4 -0
  42. package/types/people.d.ts +28 -1
  43. package/utils/building-map.ts +398 -0
  44. package/utils/hid-permission-assignments.ts +190 -0
  45. package/utils/occupancy-role.ts +109 -0
  46. package/utils/robot-display.ts +212 -0
@@ -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,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"
@@ -0,0 +1,398 @@
1
+ /**
2
+ * Floor plan to 3D layout, in the browser.
3
+ *
4
+ * This is a deliberate copy of the same logic in `@7365admin1/core`, for the
5
+ * same reason `robot-display.ts` is: core is a backend package and a browser
6
+ * cannot import it. The wall extraction has to run where the floor plan image
7
+ * is — the vendor signs its map URLs for about an hour, so the picture is
8
+ * fetched into a canvas at the moment of display and never stored, and the
9
+ * pixels only exist client-side.
10
+ *
11
+ * The two copies must agree, and the agreement is held by the same tests on
12
+ * both sides.
13
+ *
14
+ * ## Why there is no 3D library here
15
+ *
16
+ * The scene is extruded boxes standing on flat floors. A projection and a
17
+ * back-to-front draw order render that correctly in a few hundred lines, and
18
+ * `layer-common` is consumed by eleven web apps — a 3D engine is a large thing
19
+ * to put in all of them for a shape this simple.
20
+ *
21
+ * ponytail: painter's algorithm with a fixed camera. No lighting model, no
22
+ * textures, no orbit. If any of those matter later, swap Three.js in behind
23
+ * `levelSolids` / `projectPoint` — the geometry above them does not change.
24
+ */
25
+
26
+ /** `traffic_editor`'s defaults, matched so our layout and RMF's agree. */
27
+ export const WALL_HEIGHT_M = 2.5;
28
+ export const WALL_THICKNESS_M = 0.1;
29
+ export const DEFAULT_SCALE_M_PER_PX = 0.05;
30
+
31
+ export type TMapVertex = { x: number; y: number; name?: string };
32
+ export type TMapWall = { start: number; end: number; heightM?: number; thicknessM?: number };
33
+
34
+ export type TPlanLevel = {
35
+ name: string;
36
+ elevationM: number;
37
+ scaleMPerPx: number;
38
+ originXM: number;
39
+ originYM: number;
40
+ vertices: TMapVertex[];
41
+ walls: TMapWall[];
42
+ };
43
+
44
+ export type TWallSolid = {
45
+ centre: { x: number; y: number; z: number };
46
+ lengthM: number;
47
+ thicknessM: number;
48
+ heightM: number;
49
+ yaw: number;
50
+ };
51
+
52
+ /* ------------------------------------------------- image to occupancy grid */
53
+
54
+ export type TOccupancyGrid = { data: Uint8Array; width: number; height: number };
55
+
56
+ /**
57
+ * Turn canvas RGBA into one luminance value per pixel.
58
+ *
59
+ * A fully transparent pixel is treated as FREE space, not dark. Map PNGs are
60
+ * commonly transparent outside the surveyed area, and reading alpha 0 as black
61
+ * would wrap the whole plan in a wall.
62
+ */
63
+ export function gridFromImageData(
64
+ rgba: ArrayLike<number>,
65
+ width: number,
66
+ height: number,
67
+ ): TOccupancyGrid {
68
+ const data = new Uint8Array(width * height);
69
+ for (let i = 0, p = 0; p < width * height; i += 4, p++) {
70
+ const alpha = Number(rgba[i + 3]);
71
+ if (alpha === 0) {
72
+ data[p] = 255;
73
+ continue;
74
+ }
75
+ // Rec. 601 luma — close enough for "is this pixel dark", and cheap.
76
+ data[p] =
77
+ (0.299 * Number(rgba[i]) + 0.587 * Number(rgba[i + 1]) + 0.114 * Number(rgba[i + 2])) | 0;
78
+ }
79
+ return { data, width, height };
80
+ }
81
+
82
+ /**
83
+ * Trace walls out of a floor plan, so nobody has to draw them.
84
+ *
85
+ * Horizontal runs first, then vertical runs from what those did not cover, so a
86
+ * long wall is one segment rather than one per pixel. Corners are de-duplicated
87
+ * so the result stays editable afterwards.
88
+ */
89
+ export function wallsFromOccupancyGrid(
90
+ grid: TOccupancyGrid,
91
+ options?: { threshold?: number; minRunPx?: number },
92
+ ): { vertices: TMapVertex[]; walls: TMapWall[] } {
93
+ const threshold = options?.threshold ?? 100;
94
+ const minRun = Math.max(2, options?.minRunPx ?? 6);
95
+ const { data, width, height } = grid;
96
+
97
+ if (!width || !height || !data || data.length < width * height) {
98
+ return { vertices: [], walls: [] };
99
+ }
100
+
101
+ const occupied = (x: number, y: number) => Number(data[y * width + x]) <= threshold;
102
+ const consumed = new Uint8Array(width * height);
103
+ const vertices: TMapVertex[] = [];
104
+ const walls: TMapWall[] = [];
105
+ const index = new Map<string, number>();
106
+
107
+ const vertexAt = (x: number, y: number) => {
108
+ const key = `${x}:${y}`;
109
+ const found = index.get(key);
110
+ if (found !== undefined) return found;
111
+ vertices.push({ x, y });
112
+ index.set(key, vertices.length - 1);
113
+ return vertices.length - 1;
114
+ };
115
+
116
+ for (let y = 0; y < height; y++) {
117
+ let run = 0;
118
+ for (let x = 0; x <= width; x++) {
119
+ if (x < width && occupied(x, y)) {
120
+ run++;
121
+ continue;
122
+ }
123
+ if (run >= minRun) {
124
+ const startX = x - run;
125
+ walls.push({ start: vertexAt(startX, y), end: vertexAt(x - 1, y) });
126
+ for (let i = startX; i < x; i++) consumed[y * width + i] = 1;
127
+ }
128
+ run = 0;
129
+ }
130
+ }
131
+
132
+ for (let x = 0; x < width; x++) {
133
+ let run = 0;
134
+ for (let y = 0; y <= height; y++) {
135
+ if (y < height && occupied(x, y) && !consumed[y * width + x]) {
136
+ run++;
137
+ continue;
138
+ }
139
+ if (run >= minRun) {
140
+ walls.push({ start: vertexAt(x, y - run), end: vertexAt(x, y - 1) });
141
+ }
142
+ run = 0;
143
+ }
144
+ }
145
+
146
+ return { vertices, walls };
147
+ }
148
+
149
+ /* ------------------------------------------------------------- geometry */
150
+
151
+ export function levelScale(level: TPlanLevel): number {
152
+ return level.scaleMPerPx > 0 ? level.scaleMPerPx : DEFAULT_SCALE_M_PER_PX;
153
+ }
154
+
155
+ /**
156
+ * A drawing pixel in site metres.
157
+ *
158
+ * The vertical flip is the occupancy-grid convention: image origin top-left,
159
+ * map origin bottom-left. Without it the building renders mirrored, which reads
160
+ * as "the robot is in the wrong room" rather than as a transform bug.
161
+ */
162
+ export function levelPixelToMetres(
163
+ level: TPlanLevel,
164
+ px: number,
165
+ py: number,
166
+ imageHeightPx: number,
167
+ ): { x: number; y: number } {
168
+ const scale = levelScale(level);
169
+ return {
170
+ x: level.originXM + px * scale,
171
+ y: level.originYM + (imageHeightPx - py) * scale,
172
+ };
173
+ }
174
+
175
+ /** Extrude a level's walls into boxes a renderer can place. */
176
+ export function levelSolids(level: TPlanLevel, imageHeightPx: number): TWallSolid[] {
177
+ const solids: TWallSolid[] = [];
178
+ for (const wall of level.walls ?? []) {
179
+ const a = level.vertices[wall.start];
180
+ const b = level.vertices[wall.end];
181
+ if (!a || !b) continue;
182
+
183
+ const pa = levelPixelToMetres(level, a.x, a.y, imageHeightPx);
184
+ const pb = levelPixelToMetres(level, b.x, b.y, imageHeightPx);
185
+ const lengthM = Math.hypot(pb.x - pa.x, pb.y - pa.y);
186
+ // A zero-length wall renders as a flickering sliver that looks like a
187
+ // graphics fault rather than a map mistake.
188
+ if (lengthM <= 0) continue;
189
+
190
+ const heightM = wall.heightM ?? WALL_HEIGHT_M;
191
+ solids.push({
192
+ centre: {
193
+ x: (pa.x + pb.x) / 2,
194
+ y: (pa.y + pb.y) / 2,
195
+ // Boxes are centred, so a wall standing ON the floor sits at half its
196
+ // own height above the level's elevation.
197
+ z: level.elevationM + heightM / 2,
198
+ },
199
+ lengthM,
200
+ thicknessM: wall.thicknessM ?? WALL_THICKNESS_M,
201
+ heightM,
202
+ yaw: Math.atan2(pb.y - pa.y, pb.x - pa.x),
203
+ });
204
+ }
205
+ return solids;
206
+ }
207
+
208
+ /* ----------------------------------------------------------- projection */
209
+
210
+ export type TView = {
211
+ /** Radians. How far the scene is turned about the vertical axis. */
212
+ rotation: number;
213
+ /** Radians. 0 is a plan view looking straight down; ~0.9 reads as 3D. */
214
+ tilt: number;
215
+ /** Screen pixels per metre. */
216
+ zoom: number;
217
+ /** Where the site origin lands on the canvas. */
218
+ originPx: { x: number; y: number };
219
+ };
220
+
221
+ /**
222
+ * A point in site metres, on the canvas.
223
+ *
224
+ * An axonometric projection: rotate about the vertical axis, then foreshorten
225
+ * the depth axis by the tilt. Parallel, so there is no perspective distortion
226
+ * and a wall is the same size wherever it sits — which is what you want for a
227
+ * floor plan, and is why a full camera is not needed.
228
+ *
229
+ * Screen y grows downward, so height is SUBTRACTED: a taller wall draws further
230
+ * up the canvas.
231
+ */
232
+ export function projectPoint(
233
+ x: number,
234
+ y: number,
235
+ z: number,
236
+ view: TView,
237
+ ): { x: number; y: number } {
238
+ const cos = Math.cos(view.rotation);
239
+ const sin = Math.sin(view.rotation);
240
+
241
+ const rx = x * cos - y * sin;
242
+ const ry = x * sin + y * cos;
243
+
244
+ return {
245
+ x: view.originPx.x + rx * view.zoom,
246
+ y: view.originPx.y + ry * view.zoom * Math.cos(view.tilt) - z * view.zoom * Math.sin(view.tilt),
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Back-to-front order, so nearer walls are drawn over farther ones.
252
+ *
253
+ * Painter's algorithm: with no depth buffer, draw order IS the depth test. Sort
254
+ * by the rotated depth axis, lowest first — get this backwards and the building
255
+ * renders inside out, which looks like a rendering bug and is really a sort.
256
+ */
257
+ export function depthOf(point: { x: number; y: number }, view: TView): number {
258
+ return point.x * Math.sin(view.rotation) + point.y * Math.cos(view.rotation);
259
+ }
260
+
261
+ /** The eight corners of a wall box, in site metres. */
262
+ export function wallCorners(solid: TWallSolid): Array<{ x: number; y: number; z: number }> {
263
+ const hl = solid.lengthM / 2;
264
+ const ht = solid.thicknessM / 2;
265
+ const hh = solid.heightM / 2;
266
+ const cos = Math.cos(solid.yaw);
267
+ const sin = Math.sin(solid.yaw);
268
+
269
+ const corners: Array<{ x: number; y: number; z: number }> = [];
270
+ for (const dz of [-hh, hh]) {
271
+ for (const [dl, dt] of [
272
+ [-hl, -ht],
273
+ [hl, -ht],
274
+ [hl, ht],
275
+ [-hl, ht],
276
+ ] as const) {
277
+ corners.push({
278
+ x: solid.centre.x + dl * cos - dt * sin,
279
+ y: solid.centre.y + dl * sin + dt * cos,
280
+ z: solid.centre.z + dz,
281
+ });
282
+ }
283
+ }
284
+ return corners;
285
+ }
286
+
287
+ /**
288
+ * How big the site is, so a view can be framed without anyone choosing numbers.
289
+ *
290
+ * Returns null for an empty scene rather than a zero-size box: a caller must be
291
+ * able to tell "nothing to show" from "everything is at the origin".
292
+ */
293
+ export function solidsBounds(solids: TWallSolid[]): {
294
+ minX: number; maxX: number; minY: number; maxY: number;
295
+ } | null {
296
+ if (!solids.length) return null;
297
+
298
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
299
+ for (const s of solids) {
300
+ for (const c of wallCorners(s)) {
301
+ if (c.x < minX) minX = c.x;
302
+ if (c.x > maxX) maxX = c.x;
303
+ if (c.y < minY) minY = c.y;
304
+ if (c.y > maxY) maxY = c.y;
305
+ }
306
+ }
307
+ return { minX, maxX, minY, maxY };
308
+ }
309
+
310
+ /**
311
+ * A view that fits the whole site on the canvas.
312
+ *
313
+ * Falls back to a sane zoom for a degenerate scene — a single wall has zero
314
+ * extent on one axis, and dividing by it would give an infinite zoom and a
315
+ * blank canvas.
316
+ */
317
+ export function fitView(
318
+ solids: TWallSolid[],
319
+ canvas: { width: number; height: number },
320
+ options?: { rotation?: number; tilt?: number; paddingPx?: number },
321
+ ): TView {
322
+ const rotation = options?.rotation ?? Math.PI / 5;
323
+ const tilt = options?.tilt ?? 0.95;
324
+ const padding = options?.paddingPx ?? 32;
325
+
326
+ const base: TView = {
327
+ rotation,
328
+ tilt,
329
+ zoom: 20,
330
+ originPx: { x: canvas.width / 2, y: canvas.height / 2 },
331
+ };
332
+
333
+ const bounds = solidsBounds(solids);
334
+ if (!bounds) return base;
335
+
336
+ // Heights count too: a stacked building's top storey must fit on the canvas,
337
+ // not just its footprint. A single level spans 0..wall height as before.
338
+ let minZ = Infinity;
339
+ let maxZ = -Infinity;
340
+ for (const w of solids) {
341
+ minZ = Math.min(minZ, w.centre.z - w.heightM / 2);
342
+ maxZ = Math.max(maxZ, w.centre.z + w.heightM / 2);
343
+ }
344
+ const corners = [
345
+ { x: bounds.minX, y: bounds.minY },
346
+ { x: bounds.maxX, y: bounds.minY },
347
+ { x: bounds.maxX, y: bounds.maxY },
348
+ { x: bounds.minX, y: bounds.maxY },
349
+ ];
350
+ const projected = [0, minZ, maxZ].flatMap((z) =>
351
+ corners.map((p) => projectPoint(p.x, p.y, z, { ...base, zoom: 1, originPx: { x: 0, y: 0 } })),
352
+ );
353
+
354
+ const spanX = Math.max(...projected.map((p) => p.x)) - Math.min(...projected.map((p) => p.x));
355
+ const spanY = Math.max(...projected.map((p) => p.y)) - Math.min(...projected.map((p) => p.y));
356
+
357
+ const usableW = Math.max(1, canvas.width - padding * 2);
358
+ const usableH = Math.max(1, canvas.height - padding * 2);
359
+ const zoom =
360
+ spanX > 0 && spanY > 0
361
+ ? Math.min(usableW / spanX, usableH / spanY)
362
+ : base.zoom;
363
+
364
+ const unit = { ...base, zoom, originPx: { x: 0, y: 0 } };
365
+ const all = [0, minZ, maxZ].flatMap((z) => corners.map((p) => projectPoint(p.x, p.y, z, unit)));
366
+ const centre = {
367
+ x: (Math.min(...all.map((p) => p.x)) + Math.max(...all.map((p) => p.x))) / 2,
368
+ y: (Math.min(...all.map((p) => p.y)) + Math.max(...all.map((p) => p.y))) / 2,
369
+ };
370
+
371
+ return {
372
+ rotation,
373
+ tilt,
374
+ zoom,
375
+ originPx: { x: canvas.width / 2 - centre.x, y: canvas.height / 2 - centre.y },
376
+ };
377
+ }
378
+
379
+ /** Storey height used to stack levels when the plans carry no elevation. */
380
+ export const STOREY_HEIGHT_M = 4;
381
+
382
+ /**
383
+ * Where each floor sits when the building is shown stacked.
384
+ *
385
+ * The robot's maps give a floor NUMBER and nothing about height, so floors are
386
+ * stacked in number order one storey apart. Missing numbers do not leave gaps:
387
+ * a robot mapping floors 1 and 5 shows two levels, not five.
388
+ *
389
+ * ponytail: equal storeys. Real heights need building-map persistence, which
390
+ * is an owner decision still open.
391
+ */
392
+ export function stackedElevations(
393
+ floorNos: number[],
394
+ storeyM = STOREY_HEIGHT_M,
395
+ ): Map<number, number> {
396
+ const ordered = [...new Set(floorNos.filter((n) => Number.isFinite(n)))].sort((a, b) => a - b);
397
+ return new Map(ordered.map((floorNo, i) => [floorNo, i * storeyM]));
398
+ }
@@ -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
+ }