@7365admin1/layer-common 4.97.1-staging.522 → 4.97.1-staging.523

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.
@@ -489,6 +489,101 @@
489
489
  />
490
490
  </template>
491
491
 
492
+ <!-- WHERE THIS PERSON WILL END UP.
493
+ Enrolling is no longer "pick a reader" - they land on every reader
494
+ at the site that serves their account type - so the dialog states
495
+ it rather than asking. The excluded readers are drawn too, with the
496
+ reason: an absent reader reads as a screen that failed to load,
497
+ while "does not serve residents" reads as a setting somebody chose.
498
+ Replaced while a save is running by the per-reader progress below,
499
+ which is the same list with each row's own state. -->
500
+ <template v-if="!selectedUser">
501
+ <div class="field-label">
502
+ {{ readerOutcomes.length ? "Enrolling on" : "Will be enrolled on" }}
503
+ </div>
504
+
505
+ <div v-if="readerOutcomes.length" class="hid-fanout mb-1">
506
+ <div
507
+ v-for="outcome in readerOutcomes"
508
+ :key="outcome.readerId"
509
+ class="hid-fanout__row"
510
+ :class="`hid-fanout__row--${outcome.step}`"
511
+ >
512
+ <v-icon
513
+ :icon="
514
+ outcome.step === 'done'
515
+ ? 'mdi-check-circle-outline'
516
+ : outcome.step === 'failed'
517
+ ? 'mdi-alert-circle-outline'
518
+ : outcome.step === 'working'
519
+ ? 'mdi-progress-upload'
520
+ : 'mdi-clock-outline'
521
+ "
522
+ size="17"
523
+ />
524
+ <div class="hid-fanout__body">
525
+ <strong>{{ outcome.name }}</strong>
526
+ <span v-if="outcome.message">{{ outcome.message }}</span>
527
+ </div>
528
+ <!-- Retry is per reader, because the failure was. Enabled only
529
+ when nothing else is running, so two writes cannot race at
530
+ one device. -->
531
+ <AppButton
532
+ v-if="outcome.step === 'failed'"
533
+ variant="row"
534
+ icon="mdi-refresh"
535
+ :disabled="fanOutRunning"
536
+ @click="retryReader(outcome)"
537
+ />
538
+ </div>
539
+ </div>
540
+
541
+ <div v-else class="hid-fanout mb-1">
542
+ <div
543
+ v-for="target in enrolmentTargets.targets"
544
+ :key="target.readerId"
545
+ class="hid-fanout__row hid-fanout__row--target"
546
+ >
547
+ <v-icon icon="mdi-check" size="17" />
548
+ <div class="hid-fanout__body">
549
+ <strong>{{ target.name }}</strong>
550
+ <span v-if="target.location">{{ target.location }}</span>
551
+ <span v-if="target.warning">{{ target.warning }}</span>
552
+ </div>
553
+ </div>
554
+ <div
555
+ v-for="skipped in enrolmentTargets.excluded"
556
+ :key="skipped.readerId"
557
+ class="hid-fanout__row hid-fanout__row--excluded"
558
+ >
559
+ <v-icon icon="mdi-minus" size="17" />
560
+ <div class="hid-fanout__body">
561
+ <strong>{{ skipped.name }}</strong>
562
+ <span>{{ skipped.reason }}</span>
563
+ </div>
564
+ </div>
565
+ </div>
566
+
567
+ <p v-if="fanOutProgress && fanOutRunning" class="field-hint mb-3">
568
+ {{ fanOutProgress }}
569
+ </p>
570
+ <p
571
+ v-else-if="fanOutResult"
572
+ class="field-hint mb-3"
573
+ :class="{ 'field-hint--error': fanOutResult.tone !== 'success' }"
574
+ >
575
+ {{ fanOutResult.message }}
576
+ </p>
577
+ <p v-else-if="!enrolmentTargets.targets.length" class="field-hint field-hint--error mb-3">
578
+ No reader at this site serves this kind of person yet.
579
+ </p>
580
+ <!-- Each reader numbers its own users, so the ID and registration
581
+ below describe the reader on screen - not the others. -->
582
+ <p v-else-if="enrolmentTargets.targets.length > 1" class="field-hint mb-3">
583
+ Each reader assigns its own ID and registration number.
584
+ </p>
585
+ </template>
586
+
492
587
  <div class="field-label">Name</div>
493
588
  <AppField
494
589
  v-model="form.name"
@@ -994,8 +1089,15 @@ import {
994
1089
  type HidEnrolmentSubject,
995
1090
  } from "../utils/hid-enrolment-subject";
996
1091
  /* Mirrors core's audience rules — core is what enforces them; this only decides
997
- which types are worth offering. */
998
- import { availableEnrolmentSubjects } from "../utils/hid-reader-audiences";
1092
+ what is worth offering and where an enrolment lands. */
1093
+ import {
1094
+ availableEnrolmentSubjects,
1095
+ fanOutProgressText,
1096
+ fanOutSummary,
1097
+ partitionEnrolmentTargets,
1098
+ type THidReaderOutcome,
1099
+ type THidReaderStep,
1100
+ } from "../utils/hid-reader-audiences";
999
1101
  /* The SAME filter the Members > Service Providers screen applies, not a second
1000
1102
  copy of the rule: a picker that disagrees with the screen the operator was
1001
1103
  just looking at is a picker they cannot trust. Core applies it to the Excel
@@ -1054,6 +1156,7 @@ const {
1054
1156
  createIdentity,
1055
1157
  updateIdentity,
1056
1158
  deleteIdentity,
1159
+ pushStoredFace,
1057
1160
  getSitePermissions,
1058
1161
  updateSitePermissions,
1059
1162
  } = useHidAmico();
@@ -1401,6 +1504,50 @@ const enrolmentSubjects = computed(() => availableEnrolmentSubjects(
1401
1504
  ));
1402
1505
  const subjectCategoryOptions = computed(() => enrolmentSubjects.value.options);
1403
1506
 
1507
+ /* ── WHICH READERS THIS ENROLMENT LANDS ON ─────────────────────────────────
1508
+ *
1509
+ * Enrolling is no longer "pick a reader". A person belongs on every reader at
1510
+ * the site that serves their account type, so the dialog states where they will
1511
+ * end up and why anything is left out, rather than asking.
1512
+ *
1513
+ * The excluded list is drawn too. An absent reader with no reason reads as a
1514
+ * screen that failed to load; a reader with "does not serve residents" beside it
1515
+ * reads as a setting somebody chose.
1516
+ */
1517
+ const enrolmentTargets = computed(() => partitionEnrolmentTargets(
1518
+ readers.value as Array<Record<string, unknown>>,
1519
+ permissionCategoryOf(form.subjectCategory),
1520
+ ));
1521
+
1522
+ /**
1523
+ * How each reader is getting on, in the order they are being written.
1524
+ *
1525
+ * Held for the whole save so the list can be read after it finishes: a reader
1526
+ * that failed keeps its row and its Retry, and the person stays enrolled on the
1527
+ * ones that worked. Cleared when the dialog opens, never when a save ends.
1528
+ */
1529
+ const readerOutcomes = ref<THidReaderOutcome[]>([]);
1530
+ const fanOutRunning = ref(false);
1531
+ const fanOutProgress = computed(() => fanOutProgressText(readerOutcomes.value));
1532
+ const fanOutResult = computed(() =>
1533
+ readerOutcomes.value.length && !fanOutRunning.value
1534
+ ? fanOutSummary(readerOutcomes.value)
1535
+ : null
1536
+ );
1537
+ const failedReaders = computed(() =>
1538
+ readerOutcomes.value.filter((outcome) => outcome.step === "failed")
1539
+ );
1540
+
1541
+ function setReaderStep(
1542
+ readerId: string,
1543
+ step: THidReaderStep,
1544
+ extra: { message?: string; retryable?: boolean } = {},
1545
+ ) {
1546
+ readerOutcomes.value = readerOutcomes.value.map((outcome) => (
1547
+ outcome.readerId === readerId ? { ...outcome, step, ...extra } : outcome
1548
+ ));
1549
+ }
1550
+
1404
1551
  /* Why a type is missing, and - when none is left - why there is nothing to pick.
1405
1552
  An absent option with no explanation reads as a broken screen. */
1406
1553
  const subjectCategoryNote = computed(() => {
@@ -2624,6 +2771,7 @@ async function openEnroll() {
2624
2771
  // onto Member with an empty list. Loaded after the dialog is up, not before:
2625
2772
  // the request must not delay it, and the picker carries its own loading
2626
2773
  // placeholder. Fresh each opening, because staff change between them.
2774
+ readerOutcomes.value = [];
2627
2775
  resetMemberCandidates();
2628
2776
  resetProviderCandidates();
2629
2777
  if (isMemberSubject.value) await loadMemberCandidates();
@@ -2819,7 +2967,6 @@ async function saveUser() {
2819
2967
  }
2820
2968
 
2821
2969
  saving.value = true;
2822
- let newlyCreatedHidUserId: number | undefined;
2823
2970
  try {
2824
2971
  const hidUser = toHidUserObject({
2825
2972
  hidUserId: form.hidUserId,
@@ -2878,47 +3025,225 @@ async function saveUser() {
2878
3025
  // and password above are already on the device; creating an identity for
2879
3026
  // it would need a subject we deliberately no longer ask for here.
2880
3027
  } else {
2881
- const created = await createHidUserOnReader(readerId, hidUser);
2882
- if (created) newlyCreatedHidUserId = hidUser.id;
2883
- const facialResult = await syncFacialImage(readerId, hidUser.id);
2884
- applyFacialResult(payload.metadata, facialResult);
2885
- payload.metadata.pinEnrolled = await syncAccessPin(readerId, hidUser.id);
2886
- payload.metadata.passwordSet = await syncPassword(readerId, hidUser.id);
2887
- await saveIdentityOnReader(readerId, payload);
2888
- selectedReaderId.value = readerId;
3028
+ /*
3029
+ * EVERY READER THAT SERVES THIS PERSON, one at a time.
3030
+ *
3031
+ * Sequential rather than parallel on purpose: each reader is an embedded
3032
+ * server, several of them are reached over the same VPN, and the operator
3033
+ * is watching a list that only means anything if the rows settle in order.
3034
+ * It is also what keeps a failure attributable to one reader.
3035
+ *
3036
+ * The loop does not stop at the first failure. A reader being asleep is the
3037
+ * ordinary case, and abandoning the rest would deny somebody three doors
3038
+ * because of a fourth.
3039
+ */
3040
+ const targets = enrolmentTargets.value.targets;
3041
+ if (!targets.length) {
3042
+ showToast(
3043
+ "No reader at this site serves this kind of person. Switch an account type"
3044
+ + " on for a reader before enrolling anybody.",
3045
+ "error",
3046
+ );
3047
+ return;
3048
+ }
3049
+
3050
+ readerOutcomes.value = targets.map((target) => ({
3051
+ readerId: target.readerId,
3052
+ name: target.name,
3053
+ step: "waiting" as const,
3054
+ }));
3055
+ fanOutRunning.value = true;
3056
+ for (const target of targets) {
3057
+ setReaderStep(target.readerId, "working");
3058
+ try {
3059
+ await enrolOnReader(target.readerId);
3060
+ setReaderStep(target.readerId, "done");
3061
+ } catch (error: unknown) {
3062
+ setReaderStep(target.readerId, "failed", {
3063
+ message: getHidErrorMessage(error),
3064
+ // Retry needs no photo in hand once one is on file - that is what
3065
+ // the stored image bought. Without it, a retry can only work while
3066
+ // the capture is still in this dialog.
3067
+ retryable: true,
3068
+ });
3069
+ console.error(`Unable to enroll on reader ${target.readerId}:`, error);
3070
+ }
3071
+ }
3072
+ fanOutRunning.value = false;
3073
+
3074
+ const summary = fanOutSummary(readerOutcomes.value);
3075
+ await loadUsers();
3076
+ /*
3077
+ * THE DIALOG STAYS OPEN WHEN ANYTHING FAILED, because the Retry lives in
3078
+ * it. Closing would leave the operator with a toast naming readers they
3079
+ * can no longer act on.
3080
+ */
3081
+ if (summary.tone === "success") formDialog.value = false;
3082
+ showToast(
3083
+ summary.message,
3084
+ summary.tone === "success" ? "success" : "error",
3085
+ );
3086
+ return;
2889
3087
  }
2890
3088
 
2891
3089
  formDialog.value = false;
2892
3090
  await loadUsers();
2893
- showToast(
2894
- selectedUser.value?._id
2895
- ? "HID user updated on reader."
2896
- : "HID user enrolled on reader."
2897
- );
3091
+ showToast("HID user updated on reader.");
3092
+ } catch (error: unknown) {
3093
+ // No rollback here any more: `enrolOnReader` undoes ITS OWN reader, which is
3094
+ // the only place a HID user is created. A second copy of that logic here
3095
+ // could only ever fire for a reader this function no longer touches.
3096
+ console.error("Unable to save HID user:", error);
3097
+ showToast(getHidErrorMessage(error), "error");
3098
+ } finally {
3099
+ saving.value = false;
3100
+ fanOutRunning.value = false;
3101
+ // Discard the captured image on every path. On a part-way failure this is what stops
3102
+ // the photo lingering in the open form after a retry or a cancel.
3103
+ form.photoPreview = "";
3104
+ selectedPhotoFile.value = null;
3105
+ removePhotoRequested.value = false;
3106
+ }
3107
+ }
3108
+
3109
+ /**
3110
+ * ENROL THIS PERSON ON ONE READER.
3111
+ *
3112
+ * Lifted out of `saveUser` so the fan-out loop and the per-reader Retry run the
3113
+ * SAME sequence. Two paths that each "enrol on a reader" would drift, and the
3114
+ * one that drifts is the retry - the path nobody exercises until something has
3115
+ * already gone wrong.
3116
+ *
3117
+ * Every reader allocates its own UID and registration number, from the device
3118
+ * that will hold them. Reading one reader's numbering and writing it to another
3119
+ * is how two people end up sharing a UID.
3120
+ *
3121
+ * Rolls back ITS OWN reader only. A reader that failed should not undo the three
3122
+ * that worked - the person genuinely has access on those, and the whole point of
3123
+ * a per-reader result is that a partial enrolment is a real, recoverable state.
3124
+ */
3125
+ async function enrolOnReader(readerId: string) {
3126
+ const uid = await getNextUid(readerId);
3127
+ const registration = await getNextRegistration(readerId);
3128
+ const hidUser = toHidUserObject({
3129
+ hidUserId: uid,
3130
+ name: form.name,
3131
+ registration,
3132
+ });
3133
+ if (!hidUser.id) {
3134
+ throw new Error("This reader did not return a usable HID user ID.");
3135
+ }
3136
+
3137
+ let created = false;
3138
+ try {
3139
+ created = Boolean(await createHidUserOnReader(readerId, hidUser));
3140
+ const payload = {
3141
+ hidUserId: String(hidUser.id),
3142
+ registration,
3143
+ ...subjectLinkOf(form.subjectCategory, form.subjectId),
3144
+ status: "active" as const,
3145
+ metadata: {
3146
+ name: form.name,
3147
+ block: form.block,
3148
+ level: form.level,
3149
+ unit: form.unit,
3150
+ unitLabel: buildUnitLabel(),
3151
+ facialEnrolled: false,
3152
+ facialEnrolledAt: "",
3153
+ facialData: "",
3154
+ imageTimestamp: "",
3155
+ facialScores: {},
3156
+ pinEnrolled: false,
3157
+ passwordSet: false,
3158
+ hidPhysicalCards: [],
3159
+ },
3160
+ };
3161
+ applyFacialResult(payload.metadata, await syncFacialImage(readerId, hidUser.id));
3162
+ payload.metadata.pinEnrolled = await syncAccessPin(readerId, hidUser.id);
3163
+ payload.metadata.passwordSet = await syncPassword(readerId, hidUser.id);
3164
+ await saveIdentityOnReader(readerId, payload);
2898
3165
  } catch (error: unknown) {
2899
- if (newlyCreatedHidUserId) {
3166
+ if (created) {
2900
3167
  try {
2901
3168
  await runObjectOperation(readerId, {
2902
3169
  operation: "destroy",
2903
3170
  object: "users",
2904
- where: { users: { id: newlyCreatedHidUserId } },
3171
+ where: { users: { id: hidUser.id } },
2905
3172
  });
2906
3173
  } catch (rollbackError) {
2907
3174
  console.error(
2908
- "Unable to roll back the partially enrolled HID user:",
2909
- rollbackError
3175
+ `Unable to roll back the partially enrolled HID user on reader ${readerId}:`,
3176
+ rollbackError,
2910
3177
  );
2911
3178
  }
2912
3179
  }
2913
- console.error("Unable to save HID user:", error);
3180
+ throw error;
3181
+ }
3182
+ }
3183
+
3184
+ /**
3185
+ * TRY ONE READER AGAIN.
3186
+ *
3187
+ * Runs the same `enrolOnReader` the fan-out ran, so the retry cannot drift from
3188
+ * the thing it is retrying - and the drift would be invisible until somebody
3189
+ * needed it.
3190
+ *
3191
+ * When the capture is no longer in the dialog - reopened, or a photo discarded
3192
+ * after the first attempt - the face comes from the copy on file instead, which
3193
+ * is the whole reason the image is stored. Without that, retrying a reader that
3194
+ * was asleep meant bringing the person back.
3195
+ */
3196
+ /**
3197
+ * This person's iService account id, read off a reader that already has them.
3198
+ *
3199
+ * The form holds a SUBJECT - a resident record, a membership - and the account
3200
+ * behind it is resolved server-side, so the only way to learn it on this side is
3201
+ * to read back an identity that has been written. Returns "" when no reader has
3202
+ * one yet, which is also the case where there is no stored photo to push.
3203
+ */
3204
+ async function enrolledAccountId() {
3205
+ const done = readerOutcomes.value.find((outcome) => outcome.step === "done");
3206
+ if (!done || !form.subjectId) return "";
3207
+ try {
3208
+ const identity = await findResidentIdentity(done.readerId, form.subjectId);
3209
+ return String(identity?.user ?? "");
3210
+ } catch (error: unknown) {
3211
+ console.error("Unable to resolve the account behind this enrolment:", error);
3212
+ return "";
3213
+ }
3214
+ }
3215
+
3216
+ async function retryReader(outcome: THidReaderOutcome) {
3217
+ if (fanOutRunning.value) return;
3218
+ fanOutRunning.value = true;
3219
+ setReaderStep(outcome.readerId, "working", { message: "" });
3220
+ try {
3221
+ await enrolOnReader(outcome.readerId);
3222
+ /*
3223
+ * NO PHOTO IN HAND, so use the one on file.
3224
+ *
3225
+ * `enrolOnReader` sends the capture when the dialog still holds it. Reopened
3226
+ * after a failure, it does not - and that is exactly when the stored image
3227
+ * earns its keep. The account id is read off a reader that already worked,
3228
+ * because it is the server that resolves a subject to an account and the
3229
+ * form only ever knew the subject.
3230
+ */
3231
+ if (!selectedPhotoFile.value) {
3232
+ const accountId = await enrolledAccountId();
3233
+ if (accountId) await pushStoredFace(outcome.readerId, accountId);
3234
+ }
3235
+ setReaderStep(outcome.readerId, "done", { message: "" });
3236
+ await loadUsers();
3237
+ showToast(`Enrolled on ${outcome.name}.`);
3238
+ } catch (error: unknown) {
3239
+ setReaderStep(outcome.readerId, "failed", {
3240
+ message: getHidErrorMessage(error),
3241
+ retryable: true,
3242
+ });
3243
+ console.error(`Retry failed on reader ${outcome.readerId}:`, error);
2914
3244
  showToast(getHidErrorMessage(error), "error");
2915
3245
  } finally {
2916
- saving.value = false;
2917
- // Discard the captured image on every path. On a part-way failure this is what stops
2918
- // the photo lingering in the open form after a retry or a cancel.
2919
- form.photoPreview = "";
2920
- selectedPhotoFile.value = null;
2921
- removePhotoRequested.value = false;
3246
+ fanOutRunning.value = false;
2922
3247
  }
2923
3248
  }
2924
3249
 
@@ -3642,9 +3967,16 @@ function getFacialData(user: HidUser) {
3642
3967
  );
3643
3968
  }
3644
3969
 
3645
- async function getNextUid() {
3646
- const readerIds = await getExistingHidReaderIds();
3647
- const maxNumber = users.value.reduce((max, user) => {
3970
+ async function getNextUid(readerId: string) {
3971
+ const readerIds = await getExistingHidReaderIds(readerId);
3972
+ /*
3973
+ * `users.value` is the ROSTER ON SCREEN, which belongs to the selected reader.
3974
+ * It is still consulted for the one reader the operator is looking at - it
3975
+ * catches a number the device has but has not reported - and it is simply a
3976
+ * second opinion for the others, never the only one: `readerIds` above comes
3977
+ * from the reader being allocated for.
3978
+ */
3979
+ const maxNumber = (readerId === selectedReaderId.value ? users.value : []).reduce((max, user) => {
3648
3980
  const match = String(user.hidUserId ?? "").match(/^UID(\d+)$/i);
3649
3981
  return Math.max(
3650
3982
  max,
@@ -3677,17 +4009,26 @@ async function getNextRegistration() {
3677
4009
  return String(maxRegistration + 1).padStart(width, "0");
3678
4010
  }
3679
4011
 
3680
- async function getExistingHidReaderIds() {
3681
- const users = await getExistingHidReaderUsers(["id"]);
4012
+ async function getExistingHidReaderIds(readerId: string) {
4013
+ const users = await getExistingHidReaderUsers(readerId, ["id"]);
3682
4014
  return users
3683
4015
  .map((user) => toHidNumericId(user.hidUserId) || 0)
3684
4016
  .filter((value) => Number.isInteger(value) && value > 0);
3685
4017
  }
3686
4018
 
3687
- async function getExistingHidReaderUsers(fields?: string[]) {
3688
- if (!selectedReaderId.value) return [];
4019
+ /**
4020
+ * A reader's own `users` rows.
4021
+ *
4022
+ * `readerId` is a parameter rather than the screen's selection, because every
4023
+ * reader numbers its own users: enrolling one person across three readers means
4024
+ * three different UIDs and three different registration numbers, each allocated
4025
+ * from the device that will hold it. Reading one reader's numbering and writing
4026
+ * it to another is how two people end up sharing a UID.
4027
+ */
4028
+ async function getExistingHidReaderUsers(readerId: string, fields?: string[]) {
4029
+ if (!readerId) return [];
3689
4030
  try {
3690
- const response = await runObjectOperation(selectedReaderId.value, {
4031
+ const response = await runObjectOperation(readerId, {
3691
4032
  operation: "load",
3692
4033
  object: "users",
3693
4034
  ...(fields ? { fields } : {}),
@@ -3963,6 +4304,56 @@ watch(selectedReaderId, (value) => {
3963
4304
  /* The bulk button and the sentence that says what it does. Stacked rather than
3964
4305
  side by side: the sentence is the part that stops somebody expecting this to
3965
4306
  enrol faces, so it must not be squeezed into a margin at narrow widths. */
4307
+ /* The reader list, and the same list as a progress strip once a save starts.
4308
+ Rows rather than chips: each one carries a reason or a failure, and those are
4309
+ sentences. */
4310
+ .hid-fanout {
4311
+ display: flex;
4312
+ flex-direction: column;
4313
+ gap: 4px;
4314
+ }
4315
+
4316
+ .hid-fanout__row {
4317
+ display: flex;
4318
+ align-items: flex-start;
4319
+ gap: 8px;
4320
+ padding: 6px 8px;
4321
+ border-radius: 6px;
4322
+ background: var(--surface2, rgba(127, 127, 127, 0.06));
4323
+ }
4324
+
4325
+ .hid-fanout__body {
4326
+ display: flex;
4327
+ flex-direction: column;
4328
+ min-width: 0;
4329
+ }
4330
+
4331
+ .hid-fanout__body strong {
4332
+ font-size: 13px;
4333
+ font-weight: 700;
4334
+ }
4335
+
4336
+ /* Reasons and failures wrap rather than clip: a truncated explanation is worse
4337
+ than none, because it reads as a bug rather than as a setting. */
4338
+ .hid-fanout__body span {
4339
+ color: var(--muted);
4340
+ font-size: 12px;
4341
+ line-height: 1.4;
4342
+ white-space: normal;
4343
+ }
4344
+
4345
+ .hid-fanout__row--excluded {
4346
+ opacity: 0.72;
4347
+ }
4348
+
4349
+ .hid-fanout__row--failed {
4350
+ color: var(--err);
4351
+ }
4352
+
4353
+ .hid-fanout__row--done {
4354
+ color: var(--ok, var(--accent-text));
4355
+ }
4356
+
3966
4357
  .hid-bulk-cta {
3967
4358
  display: flex;
3968
4359
  flex-direction: column;
@@ -398,6 +398,25 @@ export default function useHidAmico() {
398
398
  }
399
399
 
400
400
 
401
+ /**
402
+ * Put a person's STORED enrolment photo on a reader.
403
+ *
404
+ * No body: the image is the one already on file from when they were first
405
+ * captured. This is what makes a reader that was offline during an enrolment
406
+ * retryable WITHOUT the person coming back - a face template lives on one
407
+ * device and cannot be copied, so the alternative is a fresh capture at every
408
+ * reader.
409
+ *
410
+ * Keyed by the iService account, not a HID user id: the caller does not know
411
+ * which number the person carries on which reader, and the server looks it up.
412
+ */
413
+ function pushStoredFace(readerId: string, userId: string) {
414
+ return useNuxtApp().$api<{ data: HidFacialEnrollmentResult; message?: string }>(
415
+ `${basePath}/readers/${readerId}/accounts/${userId}/stored-face`,
416
+ { method: "POST" },
417
+ );
418
+ }
419
+
401
420
  function setUserImage(
402
421
  readerId: string,
403
422
  hidUserId: string | number,
@@ -681,6 +700,7 @@ export default function useHidAmico() {
681
700
  reconcileReaderIdentificationMethods,
682
701
  getLogs,
683
702
  setUserImage,
703
+ pushStoredFace,
684
704
  deleteUserImage,
685
705
  getUserCards,
686
706
  assignUserCard,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.97.1-staging.522",
5
+ "version": "4.97.1-staging.523",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -273,3 +273,166 @@ export function audiencesLeftWithNoReader(
273
273
  })
274
274
  .map((field) => ({ audience: field.value, label: field.label }));
275
275
  }
276
+
277
+ /* ── WHICH READERS AN ENROLMENT LANDS ON ───────────────────────────────── */
278
+
279
+ /**
280
+ * One reader's standing as a target for enrolling a person of some category.
281
+ *
282
+ * `reason` is what to tell the operator about a reader left out; `warning` what
283
+ * to tell them about one included that may not answer. Sentences, not codes —
284
+ * the only consumer is a list somebody reads before pressing Save.
285
+ */
286
+ export type THidEnrolmentTarget = {
287
+ readerId: string;
288
+ name: string;
289
+ location: string;
290
+ included: boolean;
291
+ reason?: string;
292
+ warning?: string;
293
+ };
294
+
295
+ /**
296
+ * SPLIT A SITE'S READERS INTO THE ONES THIS PERSON BELONGS ON AND THE REST.
297
+ *
298
+ * Mirrors `partitionEnrolmentTargets` in core, which is the authority — core
299
+ * refuses a grant on a reader that does not serve the category, so this only
300
+ * decides what to draw. The copy exists because layer-common cannot import it.
301
+ *
302
+ * Three conditions, checked in the order that produces the most useful sentence
303
+ * rather than the order they are stored in. A reader that is switched off should
304
+ * say so; telling the operator it "does not serve residents" would be true of
305
+ * nothing and send them to the audience switches instead of the enable switch.
306
+ *
307
+ * AN OFFLINE READER IS STILL A TARGET. `offline` means we have not heard from
308
+ * it, not that it is unconfigured: the access grant is a database write that
309
+ * succeeds and the device write is retried. Excluding it would quietly deny
310
+ * somebody a door because a reader was asleep.
311
+ */
312
+ export function partitionEnrolmentTargets(
313
+ readers: ReadonlyArray<Record<string, unknown> | null | undefined>,
314
+ category: unknown,
315
+ ): { targets: THidEnrolmentTarget[]; excluded: THidEnrolmentTarget[] } {
316
+ const targets: THidEnrolmentTarget[] = [];
317
+ const excluded: THidEnrolmentTarget[] = [];
318
+
319
+ for (const reader of readers) {
320
+ if (!reader) continue;
321
+ const readerId = String(reader._id ?? "").trim();
322
+ if (!readerId) continue;
323
+ const base = {
324
+ readerId,
325
+ name: String(reader.name ?? "").trim() || "HID Reader",
326
+ location: String(reader.location ?? "").trim(),
327
+ };
328
+
329
+ const status = String(reader.status ?? "");
330
+ if (reader.enabled === false || status === "inactive" || status === "deleted") {
331
+ excluded.push({ ...base, included: false, reason: "This reader is switched off." });
332
+ continue;
333
+ }
334
+ if (!reader.portalId || !String(reader.portalName ?? "").trim()) {
335
+ excluded.push({
336
+ ...base,
337
+ included: false,
338
+ reason: "No access portal is selected on this reader.",
339
+ });
340
+ continue;
341
+ }
342
+ const audience = audienceOfCategory(category);
343
+ if (!audience) {
344
+ excluded.push({
345
+ ...base,
346
+ included: false,
347
+ reason: "This kind of person cannot be granted a reader.",
348
+ });
349
+ continue;
350
+ }
351
+ if (!readerServesAudience(reader, audience)) {
352
+ excluded.push({
353
+ ...base,
354
+ included: false,
355
+ reason: `This reader does not serve ${audienceLabel(audience)}.`,
356
+ });
357
+ continue;
358
+ }
359
+
360
+ targets.push({
361
+ ...base,
362
+ included: true,
363
+ ...(status === "offline"
364
+ ? { warning: "Not heard from recently. Access is granted now and the reader updated when it answers." }
365
+ : {}),
366
+ });
367
+ }
368
+
369
+ return { targets, excluded };
370
+ }
371
+
372
+ /** What each account type is called in a sentence about a door. */
373
+ export function audienceLabel(audience: unknown): string {
374
+ const labels: Record<string, string> = {
375
+ resident: "residents",
376
+ residentVisitor: "resident visitors",
377
+ member: "members",
378
+ serviceProvider: "service providers",
379
+ };
380
+ return labels[String(audience ?? "")] ?? "that kind of person";
381
+ }
382
+
383
+ /* ── HOW A FAN-OUT WENT ────────────────────────────────────────────────── */
384
+
385
+ export type THidReaderStep = "waiting" | "working" | "done" | "failed";
386
+
387
+ export type THidReaderOutcome = {
388
+ readerId: string;
389
+ name: string;
390
+ step: THidReaderStep;
391
+ /** What failed, in words the operator can act on. */
392
+ message?: string;
393
+ /** Whether a stored face is available, so Retry can be offered without the person. */
394
+ retryable?: boolean;
395
+ };
396
+
397
+ /** "2 of 4 readers" — what the progress line says while a save is running. */
398
+ export function fanOutProgressText(outcomes: ReadonlyArray<THidReaderOutcome>): string {
399
+ const total = outcomes.length;
400
+ if (!total) return "";
401
+ const settled = outcomes.filter((o) => o.step === "done" || o.step === "failed").length;
402
+ return `${settled} of ${total} ${total === 1 ? "reader" : "readers"}`;
403
+ }
404
+
405
+ /**
406
+ * What to say once a fan-out has finished.
407
+ *
408
+ * A PARTIAL RESULT IS NOT A FAILURE, and must not read as one: the person has
409
+ * access on the readers that worked, and the rest can be retried without them
410
+ * being present. Saying "enrolment failed" would send the operator to re-do work
411
+ * that is already done.
412
+ */
413
+ export function fanOutSummary(outcomes: ReadonlyArray<THidReaderOutcome>): {
414
+ tone: "success" | "partial" | "error";
415
+ message: string;
416
+ } {
417
+ const total = outcomes.length;
418
+ const done = outcomes.filter((o) => o.step === "done").length;
419
+ const failed = outcomes.filter((o) => o.step === "failed").length;
420
+
421
+ if (!total) return { tone: "error", message: "No reader at this site serves this person." };
422
+ if (!failed) {
423
+ return {
424
+ tone: "success",
425
+ message: `Enrolled on ${done} ${done === 1 ? "reader" : "readers"}.`,
426
+ };
427
+ }
428
+ if (!done) {
429
+ return {
430
+ tone: "error",
431
+ message: `Could not enroll on any of the ${total} ${total === 1 ? "reader" : "readers"}. Nothing was changed on them.`,
432
+ };
433
+ }
434
+ return {
435
+ tone: "partial",
436
+ message: `Enrolled on ${done} of ${total} readers. ${failed} can be retried — the person does not need to be present.`,
437
+ };
438
+ }