@7365admin1/layer-common 4.28.0 → 4.28.1-staging.356

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 (42) hide show
  1. package/CHANGELOG.md +4 -16
  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/RolePermissionFormCreate.vue +163 -19
  20. package/components/RolePermissionFormPreviewUpdate.vue +230 -19
  21. package/components/RolePermissionMain.vue +19 -0
  22. package/components/VisitorManagement.vue +267 -5
  23. package/composables/useAccessManagement.ts +5 -0
  24. package/composables/useDocument.ts +7 -0
  25. package/composables/useFacility.ts +11 -0
  26. package/composables/useHidAmico.ts +117 -0
  27. package/composables/useHidNavigation.ts +25 -1
  28. package/composables/usePeople.ts +19 -0
  29. package/composables/useSiteCategory.ts +45 -0
  30. package/composables/useSiteEntryPassSettings.ts +26 -0
  31. package/composables/useWebUsb.ts +14 -11
  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/people.d.ts +28 -1
  40. package/utils/hid-permission-assignments.ts +190 -0
  41. package/utils/occupancy-role.ts +109 -0
  42. package/utils/permission-labels.ts +30 -0
@@ -67,8 +67,8 @@
67
67
  <AppField
68
68
  v-model="search"
69
69
  search
70
- placeholder="Search"
71
- @keyup.enter="reloadUsersFromFirstPage"
70
+ placeholder="Search name, UID or registration no."
71
+ @keyup.enter="onSearchSubmit"
72
72
  />
73
73
  <AppSelect
74
74
  v-if="!props.cardManagement"
@@ -96,6 +96,12 @@
96
96
  <span class="app-cell--num">{{ formatHidUid(item.hidUserId) || "N/A" }}</span>
97
97
  </template>
98
98
 
99
+ <!-- The reader allocates this alongside the UID. A row the reader holds
100
+ that we never enrolled has none, so it is not always present. -->
101
+ <template #[`item.registration`]="{ item }">
102
+ <span class="app-cell--num">{{ item.registration || "N/A" }}</span>
103
+ </template>
104
+
99
105
  <!-- The shared chip. `utils/status.ts` now carries Mapped/Unmapped with
100
106
  the same tones this screen's private `getMappingStatusClass` gave
101
107
  them, so the map is one list rather than a fourth private copy. -->
@@ -166,12 +172,12 @@
166
172
  </TableMain>
167
173
 
168
174
  <v-dialog v-model="formDialog" max-width="420" persistent>
169
- <v-card rounded="lg">
170
- <v-card-title class="small-title">
175
+ <v-card class="screen-modal">
176
+ <v-card-title>
171
177
  {{ selectedUser ? "Edit User Information" : "Enroll" }}
172
178
  </v-card-title>
173
179
 
174
- <v-card-text>
180
+ <v-card-text class="screen-modal__body">
175
181
  <div class="photo-wrap">
176
182
  <v-menu>
177
183
  <template #activator="{ props: menuProps }">
@@ -213,6 +219,15 @@
213
219
  />
214
220
  </v-list>
215
221
  </v-menu>
222
+ <!-- Sits under the button because it describes what the button
223
+ is reporting: the reader holds a face, and this is its
224
+ reference. Nothing to show while enrolling - the value does not
225
+ exist until the reader has accepted a photo. -->
226
+ <p v-if="editFacialData" class="photo-facial">
227
+ <span class="photo-facial__label">Facial Data</span>
228
+ <span class="photo-facial__value">{{ editFacialData }}</span>
229
+ </p>
230
+
216
231
  <input
217
232
  ref="photoInput"
218
233
  type="file"
@@ -222,29 +237,96 @@
222
237
  />
223
238
  </div>
224
239
 
225
- <div class="field-label">Name <span>*</span></div>
240
+ <!-- Block / Level / Unit / Resident. Enrolment only.
241
+ Enrollment is resident-only and the resident must already exist
242
+ in iService365 - you pick a person, you do not type one. Name is
243
+ therefore a mirror of that record, never an input, so the reader
244
+ can never end up holding a name the app does not know.
245
+ Every option is derived from the residents themselves, so a
246
+ block, level or unit only appears when somebody lives there.
247
+ The list loads on first touch of Block, not on dialog open.
248
+ Enrolment only, with no exception. Editing does not move
249
+ anybody: the record already carries its block, level and unit,
250
+ `openEdit` loads them into the form and `saveUser` writes them
251
+ back untouched, so the location survives an edit without being
252
+ asked for. A row that never had one keeps not having one; that
253
+ is not a reason to make somebody fill in a location before they
254
+ can change a PIN. -->
255
+ <template v-if="!selectedUser">
256
+ <div class="field-label">Block <span>*</span></div>
257
+ <!-- The listener sits on a wrapper, NOT on AppSelect: AppSelect
258
+ spreads `$attrs` over its v-menu activator AFTER the activator's
259
+ own bindings, so an `@click` here would replace the handler that
260
+ opens the dropdown. `focusin` covers keyboard users, and both
261
+ are idempotent - `ensureOccupancy()` fetches once.
262
+ AppSelect has no `loading` prop either; the placeholder carries
263
+ the loading and empty states instead. -->
264
+ <div @click="onBlockOpened" @focusin="onBlockOpened">
265
+ <AppSelect
266
+ v-model="form.block"
267
+ :items="blockOptions"
268
+ :placeholder="blockPlaceholder"
269
+ klass="mb-3"
270
+ @update:model-value="onBlockChanged"
271
+ />
272
+ </div>
273
+
274
+ <div class="field-label">Level <span>*</span></div>
275
+ <AppSelect
276
+ v-model="form.level"
277
+ :items="levelOptions"
278
+ :disabled="!form.block"
279
+ placeholder="Select level"
280
+ klass="mb-3"
281
+ @update:model-value="onLevelChanged"
282
+ />
283
+
284
+ <div class="field-label">Unit <span>*</span></div>
285
+ <AppSelect
286
+ v-model="form.unit"
287
+ :items="unitOptions"
288
+ :disabled="!form.level"
289
+ placeholder="Select unit"
290
+ klass="mb-3"
291
+ @update:model-value="onUnitChanged"
292
+ />
293
+ </template>
294
+
295
+ <!-- Drawn only where it can offer something: while enrolling, or
296
+ while editing a record whose stored unit gives it a list. A row
297
+ with no unit has no candidates to show, and the dialog is then
298
+ purely the reader's own credentials - photo, PIN, password -
299
+ which is exactly the edit that must not be blocked. -->
300
+ <template v-if="!selectedUser || form.unit">
301
+ <div class="field-label">Resident <span>*</span></div>
302
+ <AppSelect
303
+ v-model="form.subjectId"
304
+ :items="subjectOptions"
305
+ :disabled="!form.unit"
306
+ :placeholder="unitResidentPlaceholder"
307
+ klass="mb-3"
308
+ @update:model-value="onResidentChanged"
309
+ />
310
+ </template>
311
+ <!-- The duplicate check. It is reader-scoped: this resident holding a
312
+ HID user on another gate is normal and says nothing here. -->
313
+ <p v-if="checkingResident" class="field-hint">Checking enrollment...</p>
314
+ <p v-else-if="residentConflict" class="field-hint field-hint--error mb-3">
315
+ {{ residentConflictMessage }}
316
+ </p>
317
+ <p v-else-if="unitResidentNote" class="field-hint mb-3">
318
+ {{ unitResidentNote }}
319
+ </p>
320
+
321
+ <!-- Read-only: it restates the chosen resident, it does not collect
322
+ anything. `selectedUser` is the edit case, where the name is
323
+ whatever the reader already holds. -->
324
+ <div class="field-label">Name</div>
226
325
  <AppField
227
326
  v-model="form.name"
228
327
  aria-label="Name"
229
- placeholder="Enter name"
230
- klass="mb-3"
231
- />
232
-
233
- <div class="field-label">Link To <span>*</span></div>
234
- <AppSelect
235
- v-model="form.subjectCategory"
236
- :items="subjectCategoryOptions"
237
- placeholder="Select person type"
238
- klass="mb-3"
239
- @update:model-value="onSubjectCategoryChanged"
240
- />
241
-
242
- <div class="field-label">Resident / Staff / Provider <span>*</span></div>
243
- <AppSelect
244
- v-model="form.subjectId"
245
- :items="subjectOptions"
246
- :loading="loadingSubjects"
247
- placeholder="Select an existing site record"
328
+ placeholder="Select a resident above"
329
+ readonly
248
330
  klass="mb-3"
249
331
  />
250
332
 
@@ -256,11 +338,11 @@
256
338
  v-model="form.registration"
257
339
  aria-label="Registration No."
258
340
  placeholder="Enter registration no."
259
- :readonly="!selectedUser"
341
+ readonly
260
342
  klass="mb-3"
261
343
  />
262
344
 
263
- <div class="field-label">Access PIN (optional)</div>
345
+ <div class="field-label">PIN (optional)</div>
264
346
  <!--
265
347
  The handoff draws no password field anywhere (the sign-in screens
266
348
  are the owner's own), so the reveal toggle is this product's, not
@@ -270,8 +352,8 @@
270
352
  -->
271
353
  <AppField
272
354
  v-model="form.accessPin"
273
- aria-label="Access PIN"
274
- placeholder="Enter numeric access PIN"
355
+ aria-label="PIN"
356
+ placeholder="Enter pin"
275
357
  inputmode="numeric"
276
358
  autocomplete="new-password"
277
359
  :type="showPin ? 'text' : 'password'"
@@ -280,7 +362,7 @@
280
362
  <button
281
363
  type="button"
282
364
  class="app-field__trailing"
283
- :aria-label="showPin ? 'Hide access PIN' : 'Show access PIN'"
365
+ :aria-label="showPin ? 'Hide PIN' : 'Show PIN'"
284
366
  @click="showPin = !showPin"
285
367
  >
286
368
  <v-icon :icon="showPin ? 'mdi-eye-off' : 'mdi-eye'" size="18" />
@@ -295,28 +377,62 @@
295
377
  <v-checkbox
296
378
  v-if="selectedUser && pinEnrolled"
297
379
  v-model="removePinRequested"
298
- label="Remove current access PIN"
380
+ label="Remove current PIN"
381
+ density="compact"
382
+ hide-details
383
+ />
384
+
385
+ <!-- Password: the reader stores only a hash plus its salt, so there
386
+ is nothing to read back and the field is always empty on open.
387
+ Same reveal toggle as the PIN above. -->
388
+ <div class="field-label mt-3">Password (optional)</div>
389
+ <AppField
390
+ v-model="form.password"
391
+ aria-label="Password"
392
+ :placeholder="selectedUser && passwordSet ? 'Enter a new password' : 'Enter password'"
393
+ autocomplete="new-password"
394
+ :type="showPassword ? 'text' : 'password'"
395
+ >
396
+ <template #trailing>
397
+ <button
398
+ type="button"
399
+ class="app-field__trailing"
400
+ :aria-label="showPassword ? 'Hide password' : 'Show password'"
401
+ @click="showPassword = !showPassword"
402
+ >
403
+ <v-icon :icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'" size="18" />
404
+ </button>
405
+ </template>
406
+ </AppField>
407
+ <p class="field-hint">
408
+ {{ selectedUser && passwordSet ? "A password is set. Leave blank to keep it." : "Used with the user ID on the reader keypad." }}
409
+ </p>
410
+ <v-checkbox
411
+ v-if="selectedUser && passwordSet"
412
+ v-model="removePasswordRequested"
413
+ label="Remove current password"
299
414
  density="compact"
300
415
  hide-details
301
416
  />
302
417
  </v-card-text>
303
418
 
304
- <!-- The split footer bar, as panel 2 keeps it: `v-btn` because it needs
305
- `:loading` and a full-bleed shape the handoff does not draw. Only
306
- the colours change - they were fixed hexes on both themes. -->
307
- <v-card-actions class="pa-0">
419
+ <!-- The shared modal footer: `screen-btn-ghost` + `screen-btn-primary`
420
+ on `v-btn`, the same pair every other module's dialog uses
421
+ (`assets/css/screens.css`). `v-btn` stays because the submit needs
422
+ `:loading`, which `AppButton` does not carry. -->
423
+ <v-card-actions class="screen-modal__footer">
308
424
  <v-btn
309
- class="text-none action-cancel"
425
+ class="text-none screen-btn-ghost"
310
426
  variant="flat"
311
- height="44"
312
427
  @click="formDialog = false"
313
- >Cancel</v-btn
314
428
  >
429
+ Cancel
430
+ </v-btn>
315
431
  <v-btn
316
- class="text-none action-submit"
432
+ class="text-none screen-btn-primary"
317
433
  variant="flat"
318
- height="44"
319
434
  :loading="saving"
435
+ :disabled="Boolean(residentConflict) || checkingResident"
320
436
  @click="saveUser"
321
437
  >
322
438
  Save
@@ -328,9 +444,9 @@
328
444
  <HidCameraCaptureDialog v-model="cameraDialog" @capture="onCameraCapture" />
329
445
 
330
446
  <v-dialog v-model="viewDialog" max-width="430">
331
- <v-card rounded="lg">
332
- <v-card-title class="small-title">User Information</v-card-title>
333
- <v-card-text>
447
+ <v-card class="screen-modal">
448
+ <v-card-title>User Information</v-card-title>
449
+ <v-card-text class="screen-modal__body">
334
450
  <div class="detail-grid">
335
451
  <span>Name</span><strong>{{ getName(selectedUser) }}</strong>
336
452
  <span>User ID</span
@@ -347,21 +463,22 @@
347
463
  ><strong>{{
348
464
  selectedUser ? getMappingStatus(selectedUser) : "N/A"
349
465
  }}</strong>
350
- <span>Access PIN</span
466
+ <span>PIN</span
351
467
  ><strong>{{ selectedUser?.metadata?.pinEnrolled ? "Configured" : "N/A" }}</strong>
468
+ <span>Password</span
469
+ ><strong>{{ selectedUser?.metadata?.passwordSet ? "Configured" : "N/A" }}</strong>
352
470
  </div>
353
471
  </v-card-text>
354
- <v-card-actions>
355
- <v-spacer />
472
+ <v-card-actions class="screen-modal__footer">
356
473
  <AppButton variant="ghost" @click="viewDialog = false">Close</AppButton>
357
474
  </v-card-actions>
358
475
  </v-card>
359
476
  </v-dialog>
360
477
 
361
478
  <v-dialog v-model="cardDialog" max-width="560" persistent>
362
- <v-card rounded="lg">
363
- <v-card-title class="small-title">Physical HID Cards</v-card-title>
364
- <v-card-text>
479
+ <v-card class="screen-modal">
480
+ <v-card-title>Physical HID Cards</v-card-title>
481
+ <v-card-text class="screen-modal__body">
365
482
  <p class="hid-card-user">
366
483
  {{ getName(cardUser) }}
367
484
  <span>{{ cardUser ? formatHidUid(cardUser.hidUserId) : "" }}</span>
@@ -452,6 +569,11 @@
452
569
  Present the physical card to the selected Amico reader. The request will time out after 30 seconds.
453
570
  </v-alert>
454
571
 
572
+ <!-- Reading the card at the reader is the primary way in: it is the
573
+ only one that does not require knowing the facility code and card
574
+ number up front, which are printed on nothing the operator holds.
575
+ Assigning by hand stays for the cards whose values are already
576
+ known. -->
455
577
  <div class="hid-card-actions mt-4">
456
578
  <AppButton
457
579
  variant="secondary"
@@ -470,14 +592,16 @@
470
592
  <AppButton
471
593
  v-if="enrollingCard"
472
594
  variant="ghost"
595
+ :disabled="cancellingCard"
473
596
  @click="cancelPhysicalCardEnrollment"
474
597
  >
475
- Cancel Reading
598
+ {{ cancellingCard ? "Cancelling…" : "Cancel Reading" }}
476
599
  </AppButton>
477
600
  </div>
478
601
  </v-card-text>
479
- <v-card-actions>
480
- <v-spacer />
602
+ <v-card-actions class="screen-modal__footer">
603
+ <!-- Closing mid-read would leave the reader listening with nothing
604
+ to receive the card it reads. -->
481
605
  <AppButton variant="ghost" :disabled="enrollingCard" @click="cardDialog = false">
482
606
  Close
483
607
  </AppButton>
@@ -486,31 +610,31 @@
486
610
  </v-dialog>
487
611
 
488
612
  <v-dialog v-model="deleteDialog" max-width="360" persistent>
489
- <v-card rounded="lg">
490
- <v-card-title class="small-title">Delete</v-card-title>
491
- <v-card-text class="text-body-2">
613
+ <v-card class="screen-modal">
614
+ <v-card-title>Delete</v-card-title>
615
+ <v-card-text class="screen-modal__body text-body-2">
492
616
  Are you sure you want to permanently delete this HID user?
493
617
  <div class="text-caption text-medium-emphasis mt-2">
494
618
  This action will remove the user from the HID reader and mark the
495
619
  identity as deleted.
496
620
  </div>
497
621
  </v-card-text>
498
- <v-card-actions class="pa-0">
622
+ <v-card-actions class="screen-modal__footer">
499
623
  <v-btn
500
- class="text-none action-cancel"
624
+ class="text-none screen-btn-ghost"
501
625
  variant="flat"
502
- height="44"
503
626
  @click="deleteDialog = false"
504
- >Cancel</v-btn
505
627
  >
628
+ Cancel
629
+ </v-btn>
506
630
  <v-btn
507
- class="text-none action-submit"
631
+ class="text-none screen-btn-primary"
508
632
  variant="flat"
509
- height="44"
510
633
  :loading="deleting"
511
634
  @click="deleteUser"
512
- >Delete</v-btn
513
635
  >
636
+ Delete
637
+ </v-btn>
514
638
  </v-card-actions>
515
639
  </v-card>
516
640
  </v-dialog>
@@ -527,6 +651,13 @@ const props = defineProps({
527
651
  type: String,
528
652
  required: true,
529
653
  },
654
+ // Which organisation the access this enrolment grants belongs to. Saving now
655
+ // assigns the person to the reader, and the assignment is stored per
656
+ // organisation - see `schemaCreateHidAmicoIdentity`.
657
+ org: {
658
+ type: String,
659
+ default: "",
660
+ },
530
661
  cardManagement: {
531
662
  type: Boolean,
532
663
  default: false,
@@ -547,11 +678,13 @@ const {
547
678
  getUserPinStatus,
548
679
  setUserPin,
549
680
  deleteUserPin,
681
+ getUserPasswordStatus,
682
+ setUserPassword,
683
+ deleteUserPassword,
550
684
  runObjectOperation,
551
685
  createIdentity,
552
686
  updateIdentity,
553
687
  deleteIdentity,
554
- getPermissionCandidates,
555
688
  } = useHidAmico();
556
689
 
557
690
  type HidMetadata = Record<string, unknown> & {
@@ -566,6 +699,7 @@ type HidMetadata = Record<string, unknown> & {
566
699
  lastAccessAt?: string;
567
700
  facialScores?: Record<string, unknown>;
568
701
  pinEnrolled?: boolean;
702
+ passwordSet?: boolean;
569
703
  hidPhysicalCards?: HidCard[];
570
704
  };
571
705
 
@@ -639,7 +773,14 @@ const physicalCardErrorsByUserId = ref<Record<string, string>>({});
639
773
  const loadingCards = ref(false);
640
774
  const savingCard = ref(false);
641
775
  const enrollingCard = ref(false);
776
+ /*
777
+ * Cancelling makes the in-flight enrol REJECT, and that rejection is expected
778
+ * rather than a failure. Without this flag the cancel raises an error toast on
779
+ * top of the one confirming it, which reads as the cancel having gone wrong.
780
+ */
642
781
  const cardEnrollmentCancelled = ref(false);
782
+ /** The cancel's own round trip to the reader — a second or two, not the enrol's. */
783
+ const cancellingCard = ref(false);
643
784
  const deletingCardId = ref("");
644
785
  const showPin = ref(false);
645
786
  const pinEnrolled = ref(false);
@@ -661,13 +802,61 @@ function hasFacialEnrollment(user?: HidUser | null) {
661
802
  user?.metadata?.imageTimestamp
662
803
  );
663
804
  }
805
+
806
+ /**
807
+ * The reader's own reference for the enrolled face, shown while editing.
808
+ *
809
+ * We hold neither the image nor the biometric template - the reader does - so
810
+ * this value is the only handle on the enrollment there is. `getFacialData` is
811
+ * the roster's Facial Data column, reused here so the dialog and the table
812
+ * cannot disagree; it answers "N/A" when there is nothing, which is the case
813
+ * this must not draw a row for.
814
+ */
815
+ const editFacialData = computed(() => {
816
+ if (!selectedUser.value) return "";
817
+ const value = String(getFacialData(selectedUser.value) ?? "").trim();
818
+ return value && value !== "N/A" ? value : "";
819
+ });
664
820
  const removePinRequested = ref(false);
821
+ const passwordSet = ref(false);
822
+ const showPassword = ref(false);
823
+ const removePasswordRequested = ref(false);
665
824
  const snackbar = reactive({
666
825
  show: false,
667
826
  color: "success",
668
827
  message: "",
669
828
  });
670
829
 
830
+ type OccupiedUnit = { _id: string; name: string; people: number };
831
+ type OccupiedLevel = { _id: string; name: string; units?: OccupiedUnit[] };
832
+ type OccupiedBlock = {
833
+ _id: string;
834
+ name: string;
835
+ block: number | null;
836
+ levels?: OccupiedLevel[];
837
+ };
838
+ type UnitPerson = {
839
+ _id: string;
840
+ name?: string;
841
+ unitName?: string;
842
+ /**
843
+ * The resident's app account, and the reason this field is read here.
844
+ *
845
+ * A HID identity is refused unless its subject is a valid permission subject
846
+ * at the site, and for a resident that means a `site.people` row WITH a
847
+ * linked user - `assertPermissionSubject` in `iservice365-core` filters on
848
+ * exactly this field. The permission model has no way to represent anyone
849
+ * else: `resolvePermissionUserBindings` binds reader access by user id and
850
+ * drops every row without one, so a resident enrolled without an account
851
+ * would end up on the reader holding no access rules at all.
852
+ *
853
+ * The picker this replaced was fed by that same server-side function, so it
854
+ * could never offer an unenrollable resident. The unit cascade asks People
855
+ * Management instead, which has no such filter - hence this one.
856
+ */
857
+ user?: string | null;
858
+ };
859
+
671
860
  const form = reactive({
672
861
  reader: "",
673
862
  block: "",
@@ -678,6 +867,7 @@ const form = reactive({
678
867
  registration: "",
679
868
  isAdministrator: false,
680
869
  accessPin: "",
870
+ password: "",
681
871
  photoPreview: "",
682
872
  subjectCategory: "resident" as THidPermissionCategory,
683
873
  subjectId: "",
@@ -685,18 +875,131 @@ const form = reactive({
685
875
 
686
876
  const route = useRoute();
687
877
  const orgId = computed(() => String(route.params.org || ""));
688
- const permissionCandidates = ref<THidPermissionCandidate[]>([]);
689
- const loadingSubjects = ref(false);
690
- const subjectCategoryOptions = [
691
- { title: "Resident", value: "resident" },
692
- { title: "Property management", value: "property_management" },
693
- { title: "Service provider", value: "service_provider" },
694
- ];
695
- const subjectOptions = computed(() => permissionCandidates.value.map((candidate) => ({
696
- title: candidate.subtitle ? `${candidate.name} · ${candidate.subtitle}` : candidate.name,
697
- value: candidate.subjectId,
878
+
879
+ // The cascade runs on People Management's own endpoints, the same pair the
880
+ // resident forms use:
881
+ // GET /api/people/site/:site/occupied-structure - blocks/levels/units that
882
+ // actually have an occupant, so the picker cannot offer an empty unit
883
+ // GET /api/people/unit/:unit - who is in the chosen one
884
+ // Both are fetched on FIRST USE, never when the dialog opens.
885
+ const { getOccupiedStructure, getPeopleByUnit } = usePeople();
886
+
887
+ // `resident,tenant` matches the occupancy endpoint's own default, so the units
888
+ // it offers and the people this returns are the same set. Asking the two
889
+ // halves different questions is how a unit ends up offered but empty.
890
+ const OCCUPANT_TYPES = "resident,tenant";
891
+
892
+ const occupiedBlocks = ref<OccupiedBlock[]>([]);
893
+ const occupancyLoaded = ref(false);
894
+ const loadingOccupancy = ref(false);
895
+ const unitPeople = ref<UnitPerson[]>([]);
896
+ const loadingUnitPeople = ref(false);
897
+
898
+ // "Is this resident already enrolled on THIS reader?" - the reader keeps its own
899
+ // user table, so the same person at a different gate is normal and does not
900
+ // count. Held here rather than derived, because it is the answer to a request.
901
+ //
902
+ // The server refuses the duplicate as well (`createIdentity` in
903
+ // `iservice365-core`), but by the time it answers, `saveUser` has already
904
+ // created a user on the physical device and has to roll it back. Asking here
905
+ // keeps that off the reader entirely.
906
+ const residentConflict = ref<HidUser | null>(null);
907
+ const checkingResident = ref(false);
908
+
909
+ // One spelling of a block, used by the picker and by the label stamped onto the
910
+ // record. Two copies of this expression is how the dropdown and the Unit column
911
+ // drift apart.
912
+ function formatBlockTitle(block?: OccupiedBlock | null) {
913
+ if (!block) return "";
914
+ return block.name
915
+ ? `Block ${block.block} (${block.name})`
916
+ : `Block ${block.block ?? ""}`.trim();
917
+ }
918
+
919
+ const blockOptions = computed(() => occupiedBlocks.value.map((block) => ({
920
+ title: formatBlockTitle(block),
921
+ value: String(block._id ?? ""),
922
+ })));
923
+
924
+ const levelOptions = computed(() => {
925
+ const block = occupiedBlocks.value.find((item) => String(item._id ?? "") === form.block);
926
+ return (block?.levels ?? []).map((level) => ({
927
+ title: String(level.name ?? ""),
928
+ value: String(level._id ?? ""),
929
+ }));
930
+ });
931
+
932
+ const unitOptions = computed(() => {
933
+ const block = occupiedBlocks.value.find((item) => String(item._id ?? "") === form.block);
934
+ const level = (block?.levels ?? []).find((item) => String(item._id ?? "") === form.level);
935
+ return (level?.units ?? []).map((unit) => ({
936
+ title: String(unit.name ?? ""),
937
+ value: String(unit._id ?? ""),
938
+ }));
939
+ });
940
+
941
+ // Only the residents the server will actually accept - see `UnitPerson.user`.
942
+ // Offering the rest produced "The linked HID identity subject is not active at
943
+ // this site." at the very end of enrollment, after a user had already been
944
+ // written to the reader.
945
+ const enrollableUnitPeople = computed(() =>
946
+ unitPeople.value.filter((person) => Boolean(person.user)),
947
+ );
948
+
949
+ const unenrollableUnitPeopleCount = computed(
950
+ () => unitPeople.value.length - enrollableUnitPeople.value.length,
951
+ );
952
+
953
+ // `_id` here is `site.people._id`, which is exactly the `person` that
954
+ // `createIdentity` maps a HID user to.
955
+ const subjectOptions = computed(() => enrollableUnitPeople.value.map((person) => ({
956
+ title: String(person.name ?? "Resident"),
957
+ value: String(person._id ?? ""),
698
958
  })));
699
959
 
960
+ // Says why somebody the operator can see in People Management is missing here.
961
+ // Without it the unit just looks empty and the screen looks broken.
962
+ const unitResidentNote = computed(() => {
963
+ if (!form.unit || loadingUnitPeople.value || !unenrollableUnitPeopleCount.value) return "";
964
+ const count = unenrollableUnitPeopleCount.value;
965
+ const subject = count === 1 ? "1 resident" : `${count} residents`;
966
+ const verb = count === 1 ? "is" : "are";
967
+ return `${subject} in this unit ${verb} not listed: HID enrollment needs a resident app account, and ${count === 1 ? "that person has" : "they have"} none yet.`;
968
+ });
969
+
970
+ const blockPlaceholder = computed(() => {
971
+ if (loadingOccupancy.value) return "Loading...";
972
+ if (occupancyLoaded.value && !blockOptions.value.length) {
973
+ return "No occupied units at this site";
974
+ }
975
+ return "Select block";
976
+ });
977
+
978
+ const unitResidentPlaceholder = computed(() => {
979
+ if (!form.unit) return "Select a unit first";
980
+ if (loadingUnitPeople.value) return "Loading residents...";
981
+ if (enrollableUnitPeople.value.length) return "Select a resident";
982
+ // The two empty cases are different problems with different fixes, so they
983
+ // do not share a sentence: nobody lives here, versus nobody here can be
984
+ // enrolled yet. `unitResidentNote` carries the detail for the second.
985
+ return unitPeople.value.length
986
+ ? "No resident here can be enrolled yet"
987
+ : "No residents in this unit";
988
+ });
989
+
990
+ // Names the HID user that is in the way, so the operator can go and edit it
991
+ // rather than being told only that something is wrong.
992
+ const residentConflictMessage = computed(() => {
993
+ const conflict = residentConflict.value;
994
+ if (!conflict) return "";
995
+ const label = [getName(conflict), formatHidUid(conflict.hidUserId)]
996
+ .filter(Boolean)
997
+ .join(" · ");
998
+ return label
999
+ ? `Already enrolled on this reader as ${label}. Edit that HID user instead of enrolling again.`
1000
+ : "Already enrolled on this reader. Edit that HID user instead of enrolling again.";
1001
+ });
1002
+
700
1003
  const cardForm = reactive({
701
1004
  cardType: "pacs" as "pacs" | "csn",
702
1005
  facilityCode: "",
@@ -738,6 +1041,8 @@ const userHeaders = [
738
1041
  { title: "Name", value: "name", sortable: false },
739
1042
  { title: "Facial Data", value: "facialData", sortable: false },
740
1043
  { title: "UID", value: "hidUserId", sortable: false },
1044
+ // Reads in the same order the dialog asks for them: UID then registration.
1045
+ { title: "Registration No.", value: "registration", sortable: false },
741
1046
  { title: "Status", value: "status", sortable: false },
742
1047
  { title: "", value: "action-table", sortable: false },
743
1048
  ];
@@ -767,6 +1072,32 @@ function reloadUsersFromFirstPage() {
767
1072
  loadUsers();
768
1073
  }
769
1074
 
1075
+ /**
1076
+ * Typing is the search.
1077
+ *
1078
+ * The field used to reload on `@keyup.enter` and on nothing else, so a screen
1079
+ * that looks like every other search box did nothing at all unless you guessed
1080
+ * that Enter was required - no request left the browser.
1081
+ *
1082
+ * Debounced, because each reload is a login/load/logout round trip to a reader
1083
+ * over a VPN, not a database query. Enter still works and skips the wait.
1084
+ */
1085
+ const SEARCH_DEBOUNCE_MS = 400;
1086
+ let searchDebounce: ReturnType<typeof setTimeout> | undefined;
1087
+
1088
+ function onSearchInput() {
1089
+ clearTimeout(searchDebounce);
1090
+ searchDebounce = setTimeout(reloadUsersFromFirstPage, SEARCH_DEBOUNCE_MS);
1091
+ }
1092
+
1093
+ function onSearchSubmit() {
1094
+ clearTimeout(searchDebounce);
1095
+ reloadUsersFromFirstPage();
1096
+ }
1097
+
1098
+ watch(search, onSearchInput);
1099
+ onBeforeUnmount(() => clearTimeout(searchDebounce));
1100
+
770
1101
  const readerOptions = computed(() =>
771
1102
  readers.value.map((reader) => ({
772
1103
  title: `${reader.name || reader.deviceId || reader._id} — ${reader.portalName || "Portal not configured"}`,
@@ -810,6 +1141,16 @@ async function loadReaders() {
810
1141
  }
811
1142
  }
812
1143
 
1144
+ /**
1145
+ * Discards a load whose answer arrives after a newer one started.
1146
+ *
1147
+ * Each reload is a slow round trip to a reader over a VPN, and typing now fires
1148
+ * them, so "abc" can have three in flight at once. Without this the reply to
1149
+ * "a" can land last and repopulate the table with the wrong rows. Same monotonic
1150
+ * counter `HidAccessLogDashboard` uses.
1151
+ */
1152
+ const loadUsersSequence = ref(0);
1153
+
813
1154
  async function loadUsers() {
814
1155
  if (!selectedReaderId.value) {
815
1156
  users.value = [];
@@ -819,18 +1160,54 @@ async function loadUsers() {
819
1160
  return;
820
1161
  }
821
1162
 
1163
+ const sequence = loadUsersSequence.value + 1;
1164
+ loadUsersSequence.value = sequence;
822
1165
  loading.value = true;
823
1166
  try {
824
- const response = await getReaderUsers(selectedReaderId.value, {
825
- page: page.value,
826
- limit: limit.value,
827
- search: search.value.trim(),
828
- status: status.value.toLowerCase() as "mapped" | "unmapped" | "",
829
- });
1167
+ // `userType: "user"` is REQUIRED here, not a nicety. The reader keeps
1168
+ // visitors in the same `users` table, marked `user_type_id = 1`, and the
1169
+ // API's default is `all`. Visitor rows are written by our own visitor-QR
1170
+ // issuance and are never removed - revoke only pushes `end_time` into the
1171
+ // past - so without this filter the enrollment roster counts every visitor
1172
+ // pass ever issued and drifts further from the reader's own Users screen
1173
+ // with each one. This screen enrolls and edits real people; visitors are
1174
+ // owned by the visitor module.
1175
+ let clientFiltersVisitors = false;
1176
+ let response: unknown;
1177
+ try {
1178
+ response = await getReaderUsers(selectedReaderId.value, {
1179
+ page: page.value,
1180
+ limit: limit.value,
1181
+ search: search.value.trim(),
1182
+ status: status.value.toLowerCase() as "mapped" | "unmapped" | "",
1183
+ userType: "user",
1184
+ });
1185
+ } catch (error: unknown) {
1186
+ if (!isUnsupportedUserTypeFilter(error)) throw error;
1187
+
1188
+ // A deployed API can lag behind this shared layer. Keep the roster
1189
+ // correct on one that has not added `userType` yet, the same way
1190
+ // HidReaderUserRoster does, rather than failing the whole screen.
1191
+ clientFiltersVisitors = true;
1192
+ response = await getReaderUsers(selectedReaderId.value, {
1193
+ page: 1,
1194
+ limit: 100,
1195
+ search: search.value.trim(),
1196
+ status: status.value.toLowerCase() as "mapped" | "unmapped" | "",
1197
+ });
1198
+ }
830
1199
  const responseRecord = toRecord(response);
831
1200
  const responseData = toRecord(responseRecord.data);
832
1201
  const responseItems = responseRecord.items ?? responseData.items ?? [];
833
- const pageItems = (Array.isArray(responseItems) ? responseItems : []).map(toHidUser);
1202
+ const allItems = (Array.isArray(responseItems) ? responseItems : []).map(toHidUser);
1203
+ const matchingItems = clientFiltersVisitors
1204
+ ? allItems.filter((user) => !isVisitorUser(user))
1205
+ : allItems;
1206
+ const pageStart = (page.value - 1) * limit.value;
1207
+ const pageItems = clientFiltersVisitors
1208
+ ? matchingItems.slice(pageStart, pageStart + limit.value)
1209
+ : matchingItems;
1210
+ if (sequence !== loadUsersSequence.value) return;
834
1211
  administratorUserIds.value = new Set(
835
1212
  pageItems
836
1213
  .filter((user) => user.isAdministrator === true)
@@ -838,13 +1215,22 @@ async function loadUsers() {
838
1215
  .filter((userId: number | undefined): userId is number => Boolean(userId)),
839
1216
  );
840
1217
  users.value = pageItems;
841
- total.value = Number(responseRecord.total ?? responseData.total ?? users.value.length);
842
- pages.value = Number(responseRecord.pages ?? responseData.pages ?? 1);
843
- serverPageRange.value = String(responseRecord.pageRange ?? responseData.pageRange ?? "");
1218
+ total.value = clientFiltersVisitors
1219
+ ? matchingItems.length
1220
+ : Number(responseRecord.total ?? responseData.total ?? users.value.length);
1221
+ pages.value = clientFiltersVisitors
1222
+ ? Math.max(1, Math.ceil(total.value / limit.value))
1223
+ : Number(responseRecord.pages ?? responseData.pages ?? 1);
1224
+ // The server's `pageRange` counts the unfiltered page, so it cannot be
1225
+ // trusted once this screen has done the filtering itself.
1226
+ serverPageRange.value = clientFiltersVisitors
1227
+ ? ""
1228
+ : String(responseRecord.pageRange ?? responseData.pageRange ?? "");
844
1229
  if (props.cardManagement) {
845
1230
  await loadVisibleUserCards(users.value);
846
1231
  }
847
1232
  } catch (error) {
1233
+ if (sequence !== loadUsersSequence.value) return;
848
1234
  console.error("Unable to load HID reader users:", error);
849
1235
  showToast("Unable to load HID users from reader.", "error");
850
1236
  users.value = [];
@@ -855,7 +1241,9 @@ async function loadUsers() {
855
1241
  pages.value = 1;
856
1242
  serverPageRange.value = "";
857
1243
  } finally {
858
- loading.value = false;
1244
+ // Only the newest load owns the spinner; an older one finishing must not
1245
+ // clear it while that newer one is still running.
1246
+ if (sequence === loadUsersSequence.value) loading.value = false;
859
1247
  }
860
1248
  }
861
1249
 
@@ -870,6 +1258,10 @@ function resetForm() {
870
1258
  form.registration = "";
871
1259
  form.isAdministrator = false;
872
1260
  form.accessPin = "";
1261
+ form.password = "";
1262
+ passwordSet.value = false;
1263
+ showPassword.value = false;
1264
+ removePasswordRequested.value = false;
873
1265
  pinEnrolled.value = false;
874
1266
  showPin.value = false;
875
1267
  removePinRequested.value = false;
@@ -879,32 +1271,165 @@ function resetForm() {
879
1271
  facialEnrolled.value = false;
880
1272
  form.subjectCategory = "resident";
881
1273
  form.subjectId = "";
1274
+ residentConflict.value = null;
1275
+ checkingResident.value = false;
882
1276
  }
883
1277
 
884
- async function loadSubjectCandidates() {
885
- const readerId = form.reader || selectedReaderId.value;
886
- if (!readerId || !orgId.value) {
887
- permissionCandidates.value = [];
888
- return;
1278
+
1279
+ /** Surface what the API actually said - a bare "unable to load" hides the
1280
+ * difference between a permission refusal, a bad id and a server fault. */
1281
+ function apiReason(error: unknown) {
1282
+ const record = toRecord(error);
1283
+ const data = toRecord(record.data);
1284
+ return toText(data.message) || toText(record.message) || toText(record.statusMessage);
1285
+ }
1286
+
1287
+ // Called when the Block select is first touched, not when the dialog opens.
1288
+ async function ensureOccupancy() {
1289
+ if (!props.site || occupancyLoaded.value || loadingOccupancy.value) return;
1290
+ loadingOccupancy.value = true;
1291
+ try {
1292
+ const response = toRecord(await getOccupiedStructure(props.site, {
1293
+ type: OCCUPANT_TYPES,
1294
+ status: "active",
1295
+ }));
1296
+ const data = toRecord(response.data);
1297
+ const blocks = response.blocks ?? data.blocks ?? [];
1298
+ occupiedBlocks.value = (Array.isArray(blocks) ? blocks : []) as OccupiedBlock[];
1299
+ occupancyLoaded.value = true;
1300
+ } catch (error: unknown) {
1301
+ console.error("Unable to load occupied units:", error);
1302
+ occupiedBlocks.value = [];
1303
+ const reason = apiReason(error);
1304
+ showToast(
1305
+ reason ? `Unable to load units: ${reason}` : "Unable to load units for this site.",
1306
+ "error",
1307
+ );
1308
+ } finally {
1309
+ loadingOccupancy.value = false;
889
1310
  }
890
- loadingSubjects.value = true;
1311
+ }
1312
+
1313
+ async function loadUnitPeople() {
1314
+ unitPeople.value = [];
1315
+ if (!form.unit) return;
1316
+ loadingUnitPeople.value = true;
891
1317
  try {
892
- const response = await getPermissionCandidates(props.site, {
893
- orgId: orgId.value,
894
- readerId,
895
- category: form.subjectCategory,
896
- page: 1,
897
- limit: 500,
1318
+ const response = await getPeopleByUnit(form.unit, {
1319
+ status: "active",
1320
+ type: OCCUPANT_TYPES,
898
1321
  });
899
- permissionCandidates.value = response.items ?? response.data?.items ?? [];
1322
+ const record = toRecord(response);
1323
+ const rows = Array.isArray(response)
1324
+ ? response
1325
+ : record.data ?? record.items ?? [];
1326
+ unitPeople.value = (Array.isArray(rows) ? rows : []) as UnitPerson[];
1327
+ } catch (error: unknown) {
1328
+ console.error("Unable to load residents for the unit:", error);
1329
+ const reason = apiReason(error);
1330
+ showToast(
1331
+ reason ? `Unable to load residents: ${reason}` : "Unable to load residents for this unit.",
1332
+ "error",
1333
+ );
900
1334
  } finally {
901
- loadingSubjects.value = false;
1335
+ loadingUnitPeople.value = false;
902
1336
  }
903
1337
  }
904
1338
 
905
- async function onSubjectCategoryChanged() {
1339
+ function onBlockChanged() {
1340
+ form.level = "";
1341
+ form.unit = "";
1342
+ unitPeople.value = [];
1343
+ clearResidentSelection();
1344
+ }
1345
+
1346
+ // Wrapper `@click`/`@focusin` on the Block select: load once, on first touch.
1347
+ async function onBlockOpened() {
1348
+ await ensureOccupancy();
1349
+ }
1350
+
1351
+ function onLevelChanged() {
1352
+ form.unit = "";
1353
+ unitPeople.value = [];
1354
+ clearResidentSelection();
1355
+ }
1356
+
1357
+ async function onUnitChanged() {
1358
+ clearResidentSelection();
1359
+ await loadUnitPeople();
1360
+ }
1361
+
1362
+ function clearResidentSelection() {
906
1363
  form.subjectId = "";
907
- await loadSubjectCandidates();
1364
+ residentConflict.value = null;
1365
+ // Name only ever mirrors a chosen resident, so it clears with the choice.
1366
+ if (!selectedUser.value) form.name = "";
1367
+ }
1368
+
1369
+ // The auto-fill the whole cascade exists for.
1370
+ async function onResidentChanged() {
1371
+ const person = unitPeople.value.find(
1372
+ (item) => String(item._id) === String(form.subjectId),
1373
+ );
1374
+ form.name = String(person?.name ?? "");
1375
+ await checkResidentEnrollment();
1376
+ }
1377
+
1378
+ /**
1379
+ * The HID user this resident already holds on the selected reader, or null.
1380
+ *
1381
+ * `subject`, not `person`. The same resident is stored under different ids
1382
+ * depending on which screen wrote the row - the permissions screen keys on
1383
+ * their user account, this screen on the record the picker offered - so a
1384
+ * filter on one field alone reports "not enrolled" for somebody who plainly is.
1385
+ * `subject` follows the record to its account and matches every link field,
1386
+ * which is exactly what the server does before it accepts an enrollment.
1387
+ *
1388
+ * Reader-scoped by the endpoint itself.
1389
+ */
1390
+ async function findResidentIdentity(readerId: string, personId: string) {
1391
+ const response = await getIdentities(readerId, {
1392
+ page: 1,
1393
+ // A resident should hold at most one, but ask for a few: on the edit screen
1394
+ // the first row back can be the very identity being edited, and skipping it
1395
+ // must not hide a real second one behind it.
1396
+ limit: 10,
1397
+ subject: personId,
1398
+ });
1399
+ const responseRecord = toRecord(response);
1400
+ const responseData = toRecord(responseRecord.data);
1401
+ const responseItems =
1402
+ responseRecord.items ?? responseData.items ?? responseData.identities ?? [];
1403
+ const identities = (Array.isArray(responseItems) ? responseItems : []).map(toHidUser);
1404
+ const editingId = String(selectedUser.value?._id ?? "");
1405
+
1406
+ return (
1407
+ identities.find((identity) => !editingId || String(identity._id ?? "") !== editingId) ?? null
1408
+ );
1409
+ }
1410
+
1411
+ /**
1412
+ * Sets `residentConflict` for the currently selected resident.
1413
+ *
1414
+ * Fails OPEN: if the lookup itself errors the operator is not blocked, because
1415
+ * the server refuses the duplicate anyway. This is a courtesy check that keeps
1416
+ * a doomed enrollment off the physical reader, not the guard itself.
1417
+ */
1418
+ async function checkResidentEnrollment() {
1419
+ residentConflict.value = null;
1420
+ const readerId = selectedReaderId.value || form.reader || readers.value[0]?._id;
1421
+ if (!readerId || !form.subjectId || form.subjectCategory !== "resident") return null;
1422
+
1423
+ checkingResident.value = true;
1424
+ try {
1425
+ residentConflict.value = await findResidentIdentity(readerId, form.subjectId);
1426
+ return residentConflict.value;
1427
+ } catch (error: unknown) {
1428
+ console.error("Unable to check whether this resident is already enrolled:", error);
1429
+ return null;
1430
+ } finally {
1431
+ checkingResident.value = false;
1432
+ }
908
1433
  }
909
1434
 
910
1435
  async function openEnroll() {
@@ -916,7 +1441,6 @@ async function openEnroll() {
916
1441
  ]);
917
1442
  form.hidUserId = hidUserId;
918
1443
  form.registration = registration;
919
- await loadSubjectCandidates();
920
1444
  formDialog.value = true;
921
1445
  }
922
1446
 
@@ -931,6 +1455,10 @@ async function openEdit(user: HidUser) {
931
1455
  form.registration = user.registration ?? "";
932
1456
  form.isAdministrator = hasAdministratorRule(user);
933
1457
  form.accessPin = "";
1458
+ form.password = "";
1459
+ showPassword.value = false;
1460
+ removePasswordRequested.value = false;
1461
+ passwordSet.value = Boolean(user.metadata?.passwordSet);
934
1462
  pinEnrolled.value = Boolean(user.metadata?.pinEnrolled);
935
1463
  removePinRequested.value = false;
936
1464
  form.photoPreview = "";
@@ -941,17 +1469,31 @@ async function openEdit(user: HidUser) {
941
1469
  ? "service_provider"
942
1470
  : "property_management";
943
1471
  form.subjectId = String(user.person || user.member || user.serviceProvider || "");
944
- await loadSubjectCandidates();
1472
+ // The resident this user already holds is not a conflict with itself. A real
1473
+ // one only appears if the operator reassigns the row to somebody else.
1474
+ residentConflict.value = null;
1475
+ // The location is not drawn when editing, but it is still carried: these
1476
+ // three form fields are what `saveUser` writes back and what `buildUnitLabel`
1477
+ // resolves into the Unit column, so a save must not blank them.
1478
+ //
1479
+ // `ensureOccupancy` is what lets `buildUnitLabel` turn them back into names.
1480
+ // The unit's residents are loaded too, because the Resident select IS drawn
1481
+ // here and its options come from that list - without it the select shows the
1482
+ // stored id instead of a name.
1483
+ await ensureOccupancy();
1484
+ if (form.unit) await loadUnitPeople();
945
1485
  selectedPhotoFile.value = null;
946
1486
  removePhotoRequested.value = false;
947
1487
  formDialog.value = true;
948
1488
 
949
1489
  try {
950
- const status = await getUserPinStatus(
951
- form.reader,
952
- toHidNumericId(user.hidUserId),
953
- );
954
- pinEnrolled.value = Boolean(status?.data?.pinEnrolled);
1490
+ const hidUserId = toHidNumericId(user.hidUserId);
1491
+ const [pinStatus, passwordStatus] = await Promise.all([
1492
+ getUserPinStatus(form.reader, hidUserId),
1493
+ getUserPasswordStatus(form.reader, hidUserId),
1494
+ ]);
1495
+ pinEnrolled.value = Boolean(pinStatus?.data?.pinEnrolled);
1496
+ passwordSet.value = Boolean(passwordStatus?.data?.passwordSet);
955
1497
  } catch {
956
1498
  // Preserve the last known status if the reader is temporarily offline.
957
1499
  }
@@ -1030,12 +1572,28 @@ function onPhotoChange(event: Event) {
1030
1572
  async function saveUser() {
1031
1573
  const readerId =
1032
1574
  selectedReaderId.value || form.reader || readers.value[0]?._id;
1033
- if (!readerId || !form.name || !form.hidUserId || !form.registration || !form.subjectId) {
1034
- showToast("Please complete the required HID user fields.", "error");
1575
+ // A resident is required to ENROL, because an identity has to be linked to
1576
+ // somebody. It is not required to edit: the reader holds users we never
1577
+ // enrolled, and changing a photo, a PIN or a password on one of those is a
1578
+ // reader-side operation that has nothing to say about who they are. Demanding
1579
+ // a resident there refuses a save for a field the dialog does not even draw.
1580
+ const missing = !readerId
1581
+ ? "a reader"
1582
+ : !selectedUser.value && !form.subjectId
1583
+ ? "a resident"
1584
+ : !form.name
1585
+ ? "a name"
1586
+ : !form.hidUserId
1587
+ ? "an ID"
1588
+ : !form.registration
1589
+ ? "a registration number"
1590
+ : "";
1591
+ if (missing) {
1592
+ showToast(`This HID user needs ${missing} before it can be saved.`, "error");
1035
1593
  return;
1036
1594
  }
1037
1595
  if (form.accessPin && !/^\d{1,32}$/.test(form.accessPin)) {
1038
- showToast("Access PIN must contain numbers only.", "error");
1596
+ showToast("PIN must contain numbers only.", "error");
1039
1597
  return;
1040
1598
  }
1041
1599
  if (selectedPhotoFile.value && (!selectedReader.value?.portalId || !selectedReader.value?.portalName)) {
@@ -1043,6 +1601,16 @@ async function saveUser() {
1043
1601
  return;
1044
1602
  }
1045
1603
 
1604
+ // Re-asked here, not trusted from the select: the dialog can sit open while
1605
+ // somebody else enrolls the same resident, and the reader is only ever
1606
+ // written to below this line. A duplicate caught here costs one request; the
1607
+ // same duplicate caught by the server costs a created HID user and a rollback.
1608
+ const alreadyEnrolled = await checkResidentEnrollment();
1609
+ if (alreadyEnrolled) {
1610
+ showToast(residentConflictMessage.value, "error");
1611
+ return;
1612
+ }
1613
+
1046
1614
  saving.value = true;
1047
1615
  let newlyCreatedHidUserId: number | undefined;
1048
1616
  try {
@@ -1056,22 +1624,33 @@ async function saveUser() {
1056
1624
  return;
1057
1625
  }
1058
1626
 
1627
+ // The link is sent only when the form actually holds one. Sending
1628
+ // `person: ""` is not "leave it alone", it is "clear it": the server reads
1629
+ // an empty string as a link being removed and then refuses the write for
1630
+ // having no subject at all. Omitting the keys is what makes it keep the
1631
+ // subject the record already has.
1632
+ const subjectLink = form.subjectId
1633
+ ? {
1634
+ person: form.subjectCategory === "resident" ? form.subjectId : "",
1635
+ member: form.subjectCategory === "property_management" ? form.subjectId : "",
1636
+ serviceProvider: form.subjectCategory === "service_provider" ? form.subjectId : "",
1637
+ type: (form.subjectCategory === "resident"
1638
+ ? "resident"
1639
+ : form.subjectCategory === "service_provider"
1640
+ ? "contractor"
1641
+ : "staff") as
1642
+ | "resident"
1643
+ | "staff"
1644
+ | "contractor"
1645
+ | "visitor"
1646
+ | "unknown",
1647
+ }
1648
+ : {};
1649
+
1059
1650
  const payload = {
1060
1651
  hidUserId: String(hidUser.id),
1061
1652
  registration: form.registration,
1062
- person: form.subjectCategory === "resident" ? form.subjectId : "",
1063
- member: form.subjectCategory === "property_management" ? form.subjectId : "",
1064
- serviceProvider: form.subjectCategory === "service_provider" ? form.subjectId : "",
1065
- type: (form.subjectCategory === "resident"
1066
- ? "resident"
1067
- : form.subjectCategory === "service_provider"
1068
- ? "contractor"
1069
- : "staff") as
1070
- | "resident"
1071
- | "staff"
1072
- | "contractor"
1073
- | "visitor"
1074
- | "unknown",
1653
+ ...subjectLink,
1075
1654
  status: "active" as const,
1076
1655
  metadata: {
1077
1656
  name: form.name,
@@ -1088,6 +1667,7 @@ async function saveUser() {
1088
1667
  imageTimestamp: selectedUser.value?.metadata?.imageTimestamp || "",
1089
1668
  facialScores: selectedUser.value?.metadata?.facialScores || {},
1090
1669
  pinEnrolled: pinEnrolled.value,
1670
+ passwordSet: passwordSet.value,
1091
1671
  hidPhysicalCards: selectedUser.value?.metadata?.hidPhysicalCards || [],
1092
1672
  },
1093
1673
  };
@@ -1097,17 +1677,22 @@ async function saveUser() {
1097
1677
  const facialResult = await syncFacialImage(readerId, hidUser.id);
1098
1678
  applyFacialResult(payload.metadata, facialResult);
1099
1679
  payload.metadata.pinEnrolled = await syncAccessPin(readerId, hidUser.id);
1680
+ payload.metadata.passwordSet = await syncPassword(readerId, hidUser.id);
1100
1681
  if (selectedUser.value._id) {
1101
1682
  await updateIdentity(selectedUser.value._id, payload);
1102
- } else {
1683
+ } else if (form.subjectId) {
1103
1684
  await saveIdentityOnReader(readerId, payload);
1104
1685
  }
1686
+ // else: a user the reader holds and we have never linked. The photo, PIN
1687
+ // and password above are already on the device; creating an identity for
1688
+ // it would need a subject we deliberately no longer ask for here.
1105
1689
  } else {
1106
1690
  const created = await createHidUserOnReader(readerId, hidUser);
1107
1691
  if (created) newlyCreatedHidUserId = hidUser.id;
1108
1692
  const facialResult = await syncFacialImage(readerId, hidUser.id);
1109
1693
  applyFacialResult(payload.metadata, facialResult);
1110
1694
  payload.metadata.pinEnrolled = await syncAccessPin(readerId, hidUser.id);
1695
+ payload.metadata.passwordSet = await syncPassword(readerId, hidUser.id);
1111
1696
  await saveIdentityOnReader(readerId, payload);
1112
1697
  selectedReaderId.value = readerId;
1113
1698
  }
@@ -1143,6 +1728,25 @@ async function saveUser() {
1143
1728
  }
1144
1729
  }
1145
1730
 
1731
+ async function syncPassword(readerId: string, hidUserId: number) {
1732
+ // Mirrors syncAccessPin. Removal wins over a typed value, and a blank field
1733
+ // means "leave whatever is on the reader alone" - the hash cannot be read
1734
+ // back, so blank can never mean "clear it".
1735
+ if (removePasswordRequested.value) {
1736
+ await deleteUserPassword(readerId, hidUserId);
1737
+ passwordSet.value = false;
1738
+ form.password = "";
1739
+ return false;
1740
+ }
1741
+ if (form.password) {
1742
+ await setUserPassword(readerId, hidUserId, form.password);
1743
+ form.password = "";
1744
+ passwordSet.value = true;
1745
+ return true;
1746
+ }
1747
+ return passwordSet.value;
1748
+ }
1749
+
1146
1750
  async function syncAccessPin(readerId: string, hidUserId: number) {
1147
1751
  if (removePinRequested.value) {
1148
1752
  await deleteUserPin(readerId, hidUserId);
@@ -1253,7 +1857,7 @@ async function saveIdentityOnReader(
1253
1857
  }
1254
1858
 
1255
1859
  try {
1256
- await createIdentity(readerId, { ...payload, site: props.site });
1860
+ await createIdentity(readerId, { ...payload, site: props.site, ...(props.org ? { orgId: props.org } : {}) });
1257
1861
  } catch (error: unknown) {
1258
1862
  const message = getHidErrorMessage(error);
1259
1863
  if (!message.toLowerCase().includes("already exists")) throw error;
@@ -1447,6 +2051,21 @@ function toHidUserObject(identity: Pick<HidUser, "hidUserId" | "name" | "registr
1447
2051
  };
1448
2052
  }
1449
2053
 
2054
+ function isVisitorUser(user: HidUser) {
2055
+ // The reader marks visitors with `user_type_id = 1`; a real user leaves the
2056
+ // field null. `metadata.hidUserTypeId` is what our API forwards it as.
2057
+ return Number(user.metadata?.hidUserTypeId ?? user.user_type_id) === 1;
2058
+ }
2059
+
2060
+ function isUnsupportedUserTypeFilter(error: unknown) {
2061
+ const record = toRecord(error);
2062
+ const data = toRecord(record.data);
2063
+ const message = toText(data.message) || toText(record.message);
2064
+ const normalized = message.toLowerCase();
2065
+ return normalized.includes("usertype")
2066
+ && (normalized.includes("not allowed") || normalized.includes("unknown"));
2067
+ }
2068
+
1450
2069
  function toHidNumericId(value: unknown) {
1451
2070
  const raw = String(value ?? "").trim();
1452
2071
  if (!raw) return undefined;
@@ -1585,6 +2204,14 @@ async function assignPhysicalCard() {
1585
2204
  }
1586
2205
  }
1587
2206
 
2207
+ /**
2208
+ * Read a physical card by presenting it to the reader.
2209
+ *
2210
+ * The way most cards get assigned, because it is the only one that does not
2211
+ * require knowing the facility code and card number in advance - neither is
2212
+ * printed on the card, and an operator holding a blank fob has no way to look
2213
+ * them up. The reader listens for 30 seconds and reports what it read.
2214
+ */
1588
2215
  async function enrollPhysicalCard() {
1589
2216
  const { readerId, hidUserId } = getCardReaderAndUser();
1590
2217
  if (!readerId || !hidUserId) return;
@@ -1597,6 +2224,8 @@ async function enrollPhysicalCard() {
1597
2224
  await loadUsers();
1598
2225
  showToast("Physical HID card read and enrolled on the reader.");
1599
2226
  } catch (error: unknown) {
2227
+ // Cancelling rejects the request above. That is the operator getting what
2228
+ // they asked for, so it must not also be reported as a failure.
1600
2229
  if (!cardEnrollmentCancelled.value) {
1601
2230
  showToast(getHidErrorMessage(error), "error");
1602
2231
  }
@@ -1605,15 +2234,49 @@ async function enrollPhysicalCard() {
1605
2234
  }
1606
2235
  }
1607
2236
 
2237
+ /**
2238
+ * Stop the reader listening.
2239
+ *
2240
+ * Told to the DEVICE, not just the screen: abandoning the request on this side
2241
+ * would leave the reader waiting out its 30 seconds and enrolling whatever card
2242
+ * was presented in the meantime.
2243
+ */
2244
+ /**
2245
+ * Stop the reader listening, and hand the dialog straight back.
2246
+ *
2247
+ * Told to the DEVICE, not just the screen: abandoning the request on this side
2248
+ * would leave the reader waiting out its remaining seconds and enrolling
2249
+ * whatever card was presented in the meantime.
2250
+ *
2251
+ * The part worth understanding is what the ENROL request does next. The server
2252
+ * cannot tell a cancelled read from a failed one - the reader simply reports no
2253
+ * card - so the enrol that is still in flight ends as a 400, seconds after the
2254
+ * cancel. Waiting for it was the bug: Cancel appeared to do nothing until that
2255
+ * rejection finally arrived.
2256
+ *
2257
+ * So the dialog is released as soon as the DEVICE confirms it has stopped, and
2258
+ * the doomed enrol is left to land on its own. `cardEnrollmentCancelled` is set
2259
+ * before anything is awaited, which is what keeps its 400 silent.
2260
+ */
1608
2261
  async function cancelPhysicalCardEnrollment() {
1609
2262
  const { readerId } = getCardReaderAndUser();
1610
2263
  if (!readerId) return;
2264
+ // Set first, awaited second: the enrol can reject at any point from here.
1611
2265
  cardEnrollmentCancelled.value = true;
2266
+ cancellingCard.value = true;
1612
2267
  try {
1613
2268
  await cancelUserCardEnrollment(readerId);
2269
+ // Only now, because the enrollment lock is released by the call above.
2270
+ // Re-enabling Read at Reader any earlier invites a second attempt that
2271
+ // the reader refuses with "already running".
2272
+ enrollingCard.value = false;
1614
2273
  showToast("Physical HID card reading cancelled.");
1615
2274
  } catch (error: unknown) {
2275
+ // The cancel itself failing is real and worth saying: the reader may still
2276
+ // be listening, so the dialog stays in its reading state.
1616
2277
  showToast(getHidErrorMessage(error), "error");
2278
+ } finally {
2279
+ cancellingCard.value = false;
1617
2280
  }
1618
2281
  }
1619
2282
 
@@ -1649,8 +2312,21 @@ function getPhysicalCardSubtitle(card: HidCard) {
1649
2312
  }
1650
2313
 
1651
2314
  function buildUnitLabel() {
1652
- const parts = [form.block, form.level, form.unit].filter(Boolean);
1653
- return parts.length ? `BLK ${parts.join("/")}` : "";
2315
+ // `form.block/level/unit` hold ObjectIds, so the label has to resolve them
2316
+ // back to names through the occupancy tree. Joining the raw values would
2317
+ // stamp "665f.../665f.../665f..." onto the record and into the Unit column.
2318
+ const block = occupiedBlocks.value.find((item) => String(item._id ?? "") === form.block);
2319
+ const level = (block?.levels ?? []).find((item) => String(item._id ?? "") === form.level);
2320
+ const unit = (level?.units ?? []).find((item) => String(item._id ?? "") === form.unit);
2321
+ const parts = [
2322
+ formatBlockTitle(block),
2323
+ String(level?.name ?? ""),
2324
+ String(unit?.name ?? ""),
2325
+ ].filter(Boolean);
2326
+ // Editing a record enrolled before the cascade existed: keep its stored
2327
+ // label rather than blanking it.
2328
+ if (!parts.length) return String(selectedUser.value?.metadata?.unitLabel ?? "");
2329
+ return parts.join(" / ");
1654
2330
  }
1655
2331
 
1656
2332
  function getName(user?: HidUser | null) {
@@ -1937,12 +2613,6 @@ function toHidCard(value: unknown): HidCard {
1937
2613
  max-width: 320px;
1938
2614
  }
1939
2615
 
1940
- .small-title {
1941
- font-size: 14px;
1942
- font-weight: 700;
1943
- color: var(--text);
1944
- }
1945
-
1946
2616
  /* Was `#4f5a66` / `#e53935` - the same two greys on both themes. */
1947
2617
  .field-label {
1948
2618
  color: var(--text2);
@@ -1964,12 +2634,42 @@ function toHidCard(value: unknown): HidCard {
1964
2634
  line-height: 1.45;
1965
2635
  }
1966
2636
 
2637
+ /* Same line, saying the field is refused rather than explained. `--err` is the
2638
+ token the required-field asterisk already uses. */
2639
+ .field-hint--error {
2640
+ color: var(--err);
2641
+ }
2642
+
1967
2643
  .photo-wrap {
1968
2644
  display: grid;
1969
2645
  place-items: center;
1970
2646
  margin-bottom: 14px;
1971
2647
  }
1972
2648
 
2649
+ .photo-facial {
2650
+ margin: 10px 0 0;
2651
+ text-align: center;
2652
+ }
2653
+
2654
+ /* The same small muted word `.field-label` uses, so the caption reads as a
2655
+ field label rather than as a second heading. */
2656
+ .photo-facial__label {
2657
+ display: block;
2658
+ color: var(--muted);
2659
+ font-size: 12px;
2660
+ font-weight: 600;
2661
+ }
2662
+
2663
+ .photo-facial__value {
2664
+ display: block;
2665
+ margin-top: 2px;
2666
+ font-size: 13.5px;
2667
+ font-weight: 500;
2668
+ /* The reader's reference is a long unbroken number; let it wrap rather than
2669
+ widen the dialog. */
2670
+ word-break: break-all;
2671
+ }
2672
+
1973
2673
  .photo-button {
1974
2674
  width: 120px;
1975
2675
  height: 120px;
@@ -2143,25 +2843,6 @@ function toHidCard(value: unknown): HidCard {
2143
2843
  color: var(--muted);
2144
2844
  }
2145
2845
 
2146
- /* The split footer bar. The handoff does not draw one, so the SHAPE is the
2147
- screen's own; only the colours change - `#062d42` was a fixed navy that sat
2148
- on the dark card unchanged. Same treatment as panel 2. */
2149
- .action-cancel,
2150
- .action-submit {
2151
- flex: 1;
2152
- border-radius: 0;
2153
- }
2154
-
2155
- .action-cancel {
2156
- background: var(--card);
2157
- color: var(--text2);
2158
- }
2159
-
2160
- .action-submit {
2161
- background: var(--accent-strong);
2162
- color: var(--on-accent-strong);
2163
- }
2164
-
2165
2846
  @media (max-width: 960px) {
2166
2847
  .hid-user-filters :deep(.app-field),
2167
2848
  .hid-user-filters :deep(.app-select) {