@7365admin1/layer-common 4.187.3 → 4.188.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.188.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 074886e: HID Personal QR (DV-2032): the HID QR Code page shows a code that expires and works once when the site has Personal QR on (countdown, used, expired, hourly limit, preparing and error states, next code made by itself after a scan). Site Settings > HID Reader gets a Personal QR switch with validity minutes (5 to 240) and new codes per person per hour (1 to 20), saved through `metadata.hidPersonalQr`. Sites with it off see the page exactly as before.
8
+
9
+ ### Patch Changes
10
+
11
+ - 7782ca3: IMP-1440: date filters refuse a From later than its To. Visitor Mgmt (every tab, incl. Resident Transactions) shows "The 'To' date must be on or after the 'From' date." under the To date, keeps the rows on screen and skips the fetch and the PDF/CSV reports. New `dateRangeError()` util and an `error` state on `AppDateField` for list pages to do the same.
12
+
3
13
  ## 4.187.3
4
14
 
5
15
  ### Patch Changes
@@ -4090,11 +4100,11 @@ Monthly report: a month that had patrols opens the list of that month's patrol r
4090
4100
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
4091
4101
  own rule from two endpoints the console already calls, unprojected:
4092
4102
 
4093
- GET /api/members/user/:user/app/admin the Seven365 staff membership
4094
- GET /api/roles/id/:role that membership's role document
4103
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
4104
+ GET /api/roles/id/:role that membership's role document
4095
4105
 
4096
- owner = member.type === "admin" && role.type === "admin" && role.default === true
4097
- staff = member.type === "admin" && role.type === "admin"
4106
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
4107
+ staff = member.type === "admin" && role.type === "admin"
4098
4108
 
4099
4109
  `role.default` is the marker because it is the only property of a platform
4100
4110
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -614,6 +614,25 @@ button.app-btn--err {
614
614
  border-color: var(--accent);
615
615
  }
616
616
 
617
+ /* IMP-1440: a field whose value is refused (e.g. a From after its To). Kept
618
+ red while focused too, so the state does not vanish under the cursor. */
619
+ .app-field--error,
620
+ .app-field--error:focus-within {
621
+ border-color: var(--err);
622
+ }
623
+
624
+ .app-field--error .app-field__icon {
625
+ color: var(--err);
626
+ }
627
+
628
+ /* The sentence for a refused field, set beside it in a filter row. */
629
+ .app-field-error {
630
+ color: var(--err);
631
+ font-size: 13px;
632
+ font-weight: 600;
633
+ line-height: 1.4;
634
+ }
635
+
617
636
  .app-field__label {
618
637
  font-size: 13px;
619
638
  font-weight: 600;
@@ -5,9 +5,18 @@
5
5
  ends of a filter row. `<input type="date">` - the browser's own picker, which
6
6
  is the one a phone user already knows and the one that is localised, keyboard
7
7
  accessible and free.
8
+
9
+ `error` (IMP-1440) draws the box in the error colour and marks the input
10
+ invalid. The sentence itself is the caller's to place (a filter row shows it
11
+ beside the dates, `.app-field-error`), so the 40px box never grows a line.
8
12
  -->
9
13
  <template>
10
- <label v-bind="rootAttrs" class="app-field" :class="{ 'app-field--compact': compact }">
14
+ <label
15
+ v-bind="rootAttrs"
16
+ class="app-field"
17
+ :class="{ 'app-field--compact': compact, 'app-field--error': !!error }"
18
+ :title="typeof error === 'string' && error ? error : undefined"
19
+ >
11
20
  <v-icon class="app-field__icon" icon="mdi-calendar-month-outline" size="17" />
12
21
  <span v-if="label" class="app-field__label">{{ label }}</span>
13
22
  <input
@@ -18,6 +27,7 @@
18
27
  :min="min || undefined"
19
28
  :max="max || undefined"
20
29
  :disabled="disabled"
30
+ :aria-invalid="error ? 'true' : undefined"
21
31
  @input="model = ($event.target as HTMLInputElement).value"
22
32
  />
23
33
  </label>
@@ -45,5 +55,7 @@ defineProps({
45
55
  max: { type: String, default: "" },
46
56
  compact: { type: Boolean, default: false },
47
57
  disabled: { type: Boolean, default: false },
58
+ /** true, or the sentence saying what is wrong (also the box's tooltip). */
59
+ error: { type: [Boolean, String], default: false },
48
60
  });
49
61
  </script>
@@ -0,0 +1,249 @@
1
+ <!--
2
+ PERSONAL QR, Site Settings > HID Reader (DV-2032).
3
+
4
+ One switch, `site.metadata.hidPersonalQr` { enabled, validityMinutes,
5
+ maxPerHour }, saved alone through `useSiteFeatureSettings` like every other
6
+ per-site switch. Core validates it (`hid-personal-qr.util.ts`: 5 to 240
7
+ minutes, 1 to 20 codes per hour) and the fields here refuse the same values
8
+ before a request is sent. Off, or never saved, is today's fixed QR code.
9
+
10
+ Mounted after `HidQrCodeConfiguration` in the panel `SiteSettings.vue` draws
11
+ only for `hid-mgmt:manage-hid-settings`; the server still checks the write.
12
+ Same type scale as the other two HID panels: a 13px/700 label over a
13
+ 12px/600 muted line, the shared `.app-switch` toggle and `AppField` boxes.
14
+ -->
15
+ <template>
16
+ <section class="hid-personal-qr" data-test="hid-personal-qr-settings">
17
+ <div class="section-label">Personal QR</div>
18
+
19
+ <div class="hid-personal-qr__row">
20
+ <div class="hid-personal-qr__copy">
21
+ <div class="section-label">Use Personal QR</div>
22
+ <p class="section-description">
23
+ Residents, staff and service providers get a QR code that expires and works once. Visitors keep their
24
+ visitor passes.
25
+ </p>
26
+ </div>
27
+ <v-switch
28
+ v-model="enabled"
29
+ class="app-switch"
30
+ hide-details
31
+ aria-label="Use Personal QR"
32
+ data-test="hid-personal-qr-switch"
33
+ @update:model-value="savedNote = false"
34
+ />
35
+ </div>
36
+
37
+ <div v-if="enabled" class="hid-personal-qr__fields">
38
+ <div class="hid-personal-qr__field">
39
+ <AppField
40
+ v-model="validityInput"
41
+ label="Valid for"
42
+ type="number"
43
+ min="5"
44
+ max="240"
45
+ step="5"
46
+ inputmode="numeric"
47
+ data-test="hid-personal-qr-validity"
48
+ @update:model-value="savedNote = false"
49
+ >
50
+ <template #trailing><span class="hid-personal-qr__unit">minutes</span></template>
51
+ </AppField>
52
+ <p class="section-description" :class="{ 'hid-personal-qr__bad': validityError }">
53
+ {{ validityError || "From 5 to 240 minutes. Each code also works only once." }}
54
+ </p>
55
+ </div>
56
+ <div class="hid-personal-qr__field">
57
+ <AppField
58
+ v-model="maxInput"
59
+ label="New codes per person per hour"
60
+ type="number"
61
+ min="1"
62
+ max="20"
63
+ step="1"
64
+ inputmode="numeric"
65
+ data-test="hid-personal-qr-max"
66
+ @update:model-value="savedNote = false"
67
+ >
68
+ <template #trailing><span class="hid-personal-qr__unit">codes</span></template>
69
+ </AppField>
70
+ <p class="section-description" :class="{ 'hid-personal-qr__bad': maxError }">
71
+ {{ maxError || "Stops people making codes to hand out. From 1 to 20." }}
72
+ </p>
73
+ </div>
74
+ </div>
75
+
76
+ <v-alert v-else type="info" variant="tonal" density="compact" class="mt-3">
77
+ While Personal QR is off, people keep their current QR code, which does not expire.
78
+ </v-alert>
79
+
80
+ <v-alert type="warning" variant="tonal" density="compact" class="mt-3">
81
+ Turning this on does not remove the QR codes people already have. Old codes are removed from the readers in a
82
+ separate step, after people have updated their app.
83
+ </v-alert>
84
+
85
+ <div class="hid-personal-qr__save">
86
+ <span v-if="savedNote" class="hid-personal-qr__saved" role="status">Saved</span>
87
+ <AppButton
88
+ :disabled="!loaded || saving || !valid"
89
+ data-test="hid-personal-qr-save"
90
+ @click="save"
91
+ >
92
+ Save
93
+ </AppButton>
94
+ </div>
95
+
96
+ <Snackbar v-model="toast.show" :text="toast.message" :color="toast.color" />
97
+ </section>
98
+ </template>
99
+
100
+ <script setup lang="ts">
101
+ import useSiteFeatureSettings from "../composables/useSiteFeatureSettings";
102
+ import {
103
+ PERSONAL_QR_MAX_PER_HOUR,
104
+ PERSONAL_QR_VALIDITY_MINUTES,
105
+ personalQrNumberError,
106
+ readPersonalQrSettings,
107
+ } from "../utils/hid-personal-qr";
108
+
109
+ const props = defineProps({
110
+ siteId: { type: String, required: true },
111
+ /** `site.metadata.hidPersonalQr` as read; null for a site that never saved it. */
112
+ saved: { type: Object as PropType<Record<string, unknown> | null>, default: null },
113
+ /** The site has been read; Save stays off until then. */
114
+ loaded: { type: Boolean, default: false },
115
+ });
116
+ const emit = defineEmits(["saved"]);
117
+
118
+ const enabled = ref(false);
119
+ const validityInput = ref(String(PERSONAL_QR_VALIDITY_MINUTES.default));
120
+ const maxInput = ref(String(PERSONAL_QR_MAX_PER_HOUR.default));
121
+ const savedNote = ref(false);
122
+
123
+ watch(
124
+ () => props.saved,
125
+ (value) => {
126
+ const settings = readPersonalQrSettings(value);
127
+ enabled.value = settings.enabled;
128
+ validityInput.value = String(settings.validityMinutes);
129
+ maxInput.value = String(settings.maxPerHour);
130
+ },
131
+ { immediate: true },
132
+ );
133
+
134
+ const validityError = computed(() => personalQrNumberError(validityInput.value, PERSONAL_QR_VALIDITY_MINUTES, "minutes"));
135
+ const maxError = computed(() => personalQrNumberError(maxInput.value, PERSONAL_QR_MAX_PER_HOUR, "codes"));
136
+ /* The fields are hidden while off, so only an ON save is held back by them. */
137
+ const valid = computed(() => !enabled.value || (!validityError.value && !maxError.value));
138
+
139
+ /**
140
+ * The value core stores. Off still carries numbers (the schema wants them in
141
+ * range): what was typed when it is valid, otherwise what was saved before.
142
+ */
143
+ function payload() {
144
+ const before = readPersonalQrSettings(props.saved);
145
+ return {
146
+ enabled: enabled.value,
147
+ validityMinutes: validityError.value ? before.validityMinutes : Number(validityInput.value),
148
+ maxPerHour: maxError.value ? before.maxPerHour : Number(maxInput.value),
149
+ };
150
+ }
151
+
152
+ const { saveSiteFeature } = useSiteFeatureSettings();
153
+ const saving = ref(false);
154
+ const toast = reactive({ show: false, message: "", color: "" });
155
+
156
+ async function save() {
157
+ if (!props.loaded || !valid.value) return;
158
+ saving.value = true;
159
+ savedNote.value = false;
160
+ try {
161
+ await saveSiteFeature(props.siteId, "hidPersonalQr", payload());
162
+ savedNote.value = true;
163
+ emit("saved");
164
+ } catch (e: any) {
165
+ Object.assign(toast, { show: true, message: e?.data?.message || "Could not save.", color: "error" });
166
+ } finally {
167
+ saving.value = false;
168
+ }
169
+ }
170
+ </script>
171
+
172
+ <style scoped>
173
+ .hid-personal-qr {
174
+ padding: 8px 0 4px;
175
+ }
176
+
177
+ .section-label {
178
+ margin: 0 0 6px;
179
+ color: var(--text);
180
+ font-family: var(--font-sans);
181
+ font-size: 13px;
182
+ font-weight: 700;
183
+ }
184
+
185
+ .section-description {
186
+ margin: 0;
187
+ color: var(--muted);
188
+ font-family: var(--font-sans);
189
+ font-size: 12px;
190
+ font-weight: 600;
191
+ line-height: 1.5;
192
+ }
193
+
194
+ .hid-personal-qr__row {
195
+ display: flex;
196
+ align-items: center;
197
+ justify-content: space-between;
198
+ gap: 24px;
199
+ padding: 10px 0 6px;
200
+ }
201
+
202
+ .hid-personal-qr__copy {
203
+ min-width: 0;
204
+ }
205
+
206
+ .hid-personal-qr__fields {
207
+ display: grid;
208
+ grid-template-columns: repeat(2, minmax(180px, 280px));
209
+ gap: 18px;
210
+ padding: 8px 0 4px;
211
+ }
212
+
213
+ .hid-personal-qr__field {
214
+ display: grid;
215
+ gap: 6px;
216
+ min-width: 0;
217
+ }
218
+
219
+ .hid-personal-qr__unit {
220
+ padding-right: 10px;
221
+ color: var(--muted);
222
+ font-size: 12.5px;
223
+ font-weight: 600;
224
+ }
225
+
226
+ .hid-personal-qr__bad {
227
+ color: var(--err);
228
+ }
229
+
230
+ .hid-personal-qr__save {
231
+ display: flex;
232
+ align-items: center;
233
+ justify-content: flex-end;
234
+ gap: 12px;
235
+ margin-top: 16px;
236
+ }
237
+
238
+ .hid-personal-qr__saved {
239
+ color: var(--ok);
240
+ font-size: 13px;
241
+ font-weight: 700;
242
+ }
243
+
244
+ @media (max-width: 600px) {
245
+ .hid-personal-qr__fields {
246
+ grid-template-columns: 1fr;
247
+ }
248
+ }
249
+ </style>
@@ -11,6 +11,12 @@
11
11
  can press Generate admit themselves. So the screen reports what the permissions
12
12
  screen says (`assigned`) and warns when a code would be refused at the door,
13
13
  rather than handing out something that silently fails.
14
+
15
+ PERSONAL QR (DV-2032). When the site turns Personal QR on, the response
16
+ carries a `personalQr` block and the code lasts a set time and works once.
17
+ The page then shows a countdown, watches for the code being used at the door
18
+ and gets the next one by itself (`utils/hid-personal-qr.ts` decides when).
19
+ Without the block every line of the original page below is unchanged.
14
20
  -->
15
21
  <template>
16
22
  <div class="hid-profile-qr">
@@ -66,6 +72,128 @@
66
72
  screen.
67
73
  </v-alert>
68
74
 
75
+ <!-- Personal QR: timed, one time codes. Only when the site has it on. -->
76
+ <template v-if="personalOn">
77
+ <div v-if="pqPhase === 'preparing'" class="hid-pqr__empty" role="status">
78
+ <v-progress-circular indeterminate size="28" width="3" color="primary" />
79
+ <strong>Preparing your Personal QR…</strong>
80
+ <span>This takes a few seconds.</span>
81
+ </div>
82
+
83
+ <template v-else-if="pqPhase === 'error'">
84
+ <v-alert type="error" variant="tonal" density="compact" class="mb-4">
85
+ Unable to prepare your Personal QR. Check your connection and try again.
86
+ </v-alert>
87
+ <div class="hid-pqr__empty">No code right now</div>
88
+ <div class="hid-profile-qr__actions">
89
+ <AppButton @click="refreshAndOpen">Try again</AppButton>
90
+ </div>
91
+ </template>
92
+
93
+ <template v-else-if="activeView">
94
+ <div class="hid-profile-qr__code">
95
+ <img v-if="qrImage" :src="qrImage" alt="Your HID QR code" width="220" height="220" />
96
+ <div class="hid-pqr__pills">
97
+ <span class="hid-pqr__pill hid-pqr__pill--time">
98
+ <svg class="hid-pqr__ring" viewBox="0 0 22 22" aria-hidden="true">
99
+ <circle cx="11" cy="11" r="9" class="hid-pqr__ring-track" />
100
+ <circle
101
+ cx="11"
102
+ cy="11"
103
+ r="9"
104
+ class="hid-pqr__ring-fill"
105
+ :stroke-dasharray="RING_LENGTH"
106
+ :stroke-dashoffset="ringOffset"
107
+ transform="rotate(-90 11 11)"
108
+ />
109
+ </svg>
110
+ Valid for {{ formatCountdown(activeView.secondsLeft) }}
111
+ </span>
112
+ <span class="hid-pqr__pill">Works once</span>
113
+ </div>
114
+ <p class="hid-profile-qr__issued">
115
+ Made {{ formatPersonalQrTime(profile?.issuedAt) }} · Expires
116
+ {{ formatPersonalQrTime(activeView.expiresAt) }}
117
+ </p>
118
+ </div>
119
+ <p class="field-hint">
120
+ Show it at the door. After it is used, a new code appears here.
121
+ </p>
122
+ <div class="hid-profile-qr__actions">
123
+ <AppButton
124
+ variant="ghost"
125
+ :disabled="!profile?.qrEnabled"
126
+ @click="issue(true)"
127
+ >
128
+ Get a new code
129
+ </AppButton>
130
+ </div>
131
+ </template>
132
+
133
+ <template v-else-if="pqView?.kind === 'used'">
134
+ <v-alert type="success" variant="tonal" density="compact" class="mb-4">
135
+ Used at the door at {{ formatPersonalQrTime(pqView.usedAt) || "just now" }}.
136
+ Getting your next code…
137
+ </v-alert>
138
+ <div class="hid-profile-qr__code">
139
+ <div class="hid-pqr__dim">
140
+ <img v-if="qrImage" :src="qrImage" alt="" width="220" height="220" />
141
+ <div class="hid-pqr__over">
142
+ <v-progress-circular indeterminate size="20" width="2" color="primary" />
143
+ Getting your next code…
144
+ </div>
145
+ </div>
146
+ <div class="hid-pqr__pills">
147
+ <span class="hid-pqr__pill hid-pqr__pill--ok">Used</span>
148
+ </div>
149
+ </div>
150
+ </template>
151
+
152
+ <template v-else-if="pqView?.kind === 'expired'">
153
+ <div class="hid-profile-qr__code">
154
+ <div class="hid-pqr__dim">
155
+ <img v-if="qrImage" :src="qrImage" alt="" width="220" height="220" />
156
+ <div class="hid-pqr__over">
157
+ <span>This code expired at {{ formatPersonalQrTime(pqView.expiresAt) }}.</span>
158
+ <span>It no longer opens the door.</span>
159
+ </div>
160
+ </div>
161
+ <div class="hid-pqr__pills">
162
+ <span class="hid-pqr__pill">Expired</span>
163
+ </div>
164
+ </div>
165
+ <div class="hid-profile-qr__actions">
166
+ <AppButton :disabled="!profile?.qrEnabled" @click="issue(false)">
167
+ Get a new code
168
+ </AppButton>
169
+ </div>
170
+ </template>
171
+
172
+ <template v-else-if="pqView?.kind === 'limit'">
173
+ <v-alert type="warning" variant="tonal" density="compact" class="mb-4">
174
+ You have made {{ pq?.maxPerHour }} codes in the last hour. You can get a new
175
+ one at {{ formatPersonalQrTime(pqView.nextIssueAt) }}. Your face and card
176
+ still open the door.
177
+ </v-alert>
178
+ <div class="hid-pqr__empty">No code right now</div>
179
+ <div class="hid-profile-qr__actions">
180
+ <AppButton variant="ghost" disabled>
181
+ Get a new code at {{ formatPersonalQrTime(pqView.nextIssueAt) }}
182
+ </AppButton>
183
+ </div>
184
+ </template>
185
+
186
+ <template v-else>
187
+ <div class="hid-pqr__empty">No code right now</div>
188
+ <div class="hid-profile-qr__actions">
189
+ <AppButton :disabled="!profile?.qrEnabled" @click="issue(false)">
190
+ Get a new code
191
+ </AppButton>
192
+ </div>
193
+ </template>
194
+ </template>
195
+
196
+ <template v-else>
69
197
  <div v-if="qrImage" class="hid-profile-qr__code">
70
198
  <img :src="qrImage" alt="Your HID QR code" width="220" height="220" />
71
199
  <p class="hid-profile-qr__issued">
@@ -105,6 +233,7 @@
105
233
  Regenerating replaces the previous code. The old one stops working
106
234
  immediately.
107
235
  </p>
236
+ </template>
108
237
  </template>
109
238
  </v-card-text>
110
239
  </v-card>
@@ -118,6 +247,14 @@
118
247
  <script setup lang="ts">
119
248
  import QRCode from "qrcode";
120
249
  import type { HidProfileQr } from "../composables/useHidAmico";
250
+ import {
251
+ PERSONAL_QR_POLL_MS,
252
+ formatCountdown,
253
+ formatPersonalQrTime,
254
+ personalQrView,
255
+ shouldAutoIssue,
256
+ toPersonalQr,
257
+ } from "../utils/hid-personal-qr";
121
258
 
122
259
  const props = defineProps<{ site: string }>();
123
260
 
@@ -217,18 +354,24 @@ async function loadReaders() {
217
354
 
218
355
  async function loadProfile() {
219
356
  if (!selectedReaderId.value) return;
357
+ /* A reader switch starts Personal QR from nothing: no old code, no pending
358
+ "next code" request for the reader just left. */
359
+ clearTimeout(usedTimer);
360
+ if (personalOn.value) qrImage.value = "";
361
+ pqPhase.value = "ready";
220
362
  loading.value = true;
221
363
  try {
222
364
  const response = await getProfileQr(selectedReaderId.value);
223
- profile.value = response?.data ?? null;
224
- await renderQr(profile.value?.qrValue || "");
365
+ await applyProfile(response?.data ?? null);
225
366
  } catch (error: unknown) {
226
367
  profile.value = null;
227
368
  qrImage.value = "";
228
- showToast(errorMessage(error), "error");
369
+ if (personalOn.value) pqPhase.value = "error";
370
+ else showToast(errorMessage(error), "error");
229
371
  } finally {
230
372
  loading.value = false;
231
373
  }
374
+ await openPersonal();
232
375
  }
233
376
 
234
377
  async function generate() {
@@ -262,9 +405,192 @@ async function remove() {
262
405
  }
263
406
  }
264
407
 
408
+ /* ── PERSONAL QR ──────────────────────────────────────────────────────────
409
+ Everything below only acts while the site has Personal QR on. With it off,
410
+ `personalOn` stays false, no timer starts and the page is the one above. */
411
+
412
+ /** The site's setting, as the last good response said. Per site, so it survives a reader switch. */
413
+ const personalOn = ref(false);
414
+ /** "preparing" while a new code is being written to the reader. */
415
+ const pqPhase = ref<"ready" | "preparing" | "error">("ready");
416
+ /** The browser clock the countdown runs on, ticked every second while a code is active. */
417
+ const now = ref(Date.now());
418
+ const pageVisible = ref(true);
419
+ /** The reader a GET or POST is running for: never two at once for one reader. */
420
+ let busyFor = "";
421
+ let tickTimer: ReturnType<typeof setInterval> | undefined;
422
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
423
+ let usedTimer: ReturnType<typeof setTimeout> | undefined;
424
+ let limitTimer: ReturnType<typeof setTimeout> | undefined;
425
+
426
+ const pq = computed(() => toPersonalQr(profile.value?.personalQr));
427
+ const pqView = computed(() => (pq.value ? personalQrView(pq.value, new Date(now.value)) : null));
428
+ const activeView = computed(() => (pqView.value?.kind === "active" ? pqView.value : null));
429
+
430
+ const RING_LENGTH = 2 * Math.PI * 9;
431
+ const ringOffset = computed(() => {
432
+ const view = activeView.value;
433
+ if (!view || view.totalSeconds <= 0) return RING_LENGTH;
434
+ const left = Math.min(1, Math.max(0, view.secondsLeft / view.totalSeconds));
435
+ return RING_LENGTH * (1 - left);
436
+ });
437
+
438
+ /**
439
+ * Takes a profile response. Off: exactly what the page always did. On: the
440
+ * image is redrawn only when a value comes back, which is only for an active
441
+ * code, so a used or expired code stays on screen dimmed under its notice.
442
+ */
443
+ async function applyProfile(data: HidProfileQr | null) {
444
+ profile.value = data;
445
+ personalOn.value = Boolean(toPersonalQr(data?.personalQr));
446
+ now.value = Date.now();
447
+ if (!personalOn.value) {
448
+ await renderQr(profile.value?.qrValue || "");
449
+ return;
450
+ }
451
+ if (data?.qrValue) await renderQr(data.qrValue);
452
+ }
453
+
454
+ /** On opening the page (or the reader, or the tab coming back): a missing, used or expired code is replaced. */
455
+ async function openPersonal() {
456
+ const current = pq.value;
457
+ if (!current || pqPhase.value !== "ready" || !profile.value?.qrEnabled) return;
458
+ if (shouldAutoIssue(current, new Date(), "open")) await issue(false);
459
+ }
460
+
461
+ /**
462
+ * POST for a code. `renew` forces a new one (the "Get a new code" button on a
463
+ * working code). On a refusal the GET says whether it was the hourly limit,
464
+ * which the page shows as such; anything else is the error state.
465
+ */
466
+ async function issue(renew: boolean) {
467
+ const readerId = selectedReaderId.value;
468
+ if (!readerId || busyFor === readerId) return;
469
+ busyFor = readerId;
470
+ clearTimeout(usedTimer);
471
+ pqPhase.value = "preparing";
472
+ try {
473
+ const response = await issueProfileQr(readerId, renew ? { renew: true } : {});
474
+ if (readerId !== selectedReaderId.value) return;
475
+ await applyProfile(response?.data ?? null);
476
+ pqPhase.value = "ready";
477
+ } catch {
478
+ if (readerId !== selectedReaderId.value) return;
479
+ try {
480
+ const response = await getProfileQr(readerId);
481
+ if (readerId !== selectedReaderId.value) return;
482
+ await applyProfile(response?.data ?? null);
483
+ pqPhase.value = pqView.value?.kind === "limit" ? "ready" : "error";
484
+ } catch {
485
+ pqPhase.value = "error";
486
+ }
487
+ } finally {
488
+ if (busyFor === readerId) busyFor = "";
489
+ }
490
+ }
491
+
492
+ /** "Try again", the limit time passing and the tab coming back: GET, then the open rule. */
493
+ async function refreshAndOpen() {
494
+ const readerId = selectedReaderId.value;
495
+ if (!readerId || busyFor === readerId) return;
496
+ busyFor = readerId;
497
+ let fresh = false;
498
+ try {
499
+ const response = await getProfileQr(readerId);
500
+ if (readerId !== selectedReaderId.value) return;
501
+ await applyProfile(response?.data ?? null);
502
+ pqPhase.value = "ready";
503
+ fresh = true;
504
+ } catch {
505
+ if (readerId === selectedReaderId.value && personalOn.value) pqPhase.value = "error";
506
+ } finally {
507
+ if (busyFor === readerId) busyFor = "";
508
+ }
509
+ if (fresh) await openPersonal();
510
+ }
511
+
512
+ /** While a code is active: has it been used at the door? */
513
+ async function poll() {
514
+ const readerId = selectedReaderId.value;
515
+ if (!readerId || busyFor === readerId) return;
516
+ busyFor = readerId;
517
+ try {
518
+ const response = await getProfileQr(readerId);
519
+ if (readerId !== selectedReaderId.value || pqPhase.value !== "ready") return;
520
+ await applyProfile(response?.data ?? null);
521
+ } catch {
522
+ // A missed poll is retried on the next one; the code on screen is still valid.
523
+ return;
524
+ } finally {
525
+ if (busyFor === readerId) busyFor = "";
526
+ }
527
+ const current = pq.value;
528
+ if (current && shouldAutoIssue(current, new Date(), "watch")) {
529
+ clearTimeout(usedTimer);
530
+ usedTimer = setTimeout(() => issue(false), 1500);
531
+ }
532
+ }
533
+
534
+ /* The countdown ticks only while a code is active. */
535
+ watch(
536
+ () => activeView.value !== null,
537
+ (active) => {
538
+ clearInterval(tickTimer);
539
+ tickTimer = active ? setInterval(() => { now.value = Date.now(); }, 1000) : undefined;
540
+ },
541
+ );
542
+
543
+ /* Polling: only an active code, only while the tab is in view, never during a load or a new code. */
544
+ const pollWanted = computed(() =>
545
+ personalOn.value
546
+ && pqPhase.value === "ready"
547
+ && !loading.value
548
+ && pageVisible.value
549
+ && activeView.value !== null,
550
+ );
551
+ watch(pollWanted, (wanted) => {
552
+ clearInterval(pollTimer);
553
+ pollTimer = wanted ? setInterval(poll, PERSONAL_QR_POLL_MS) : undefined;
554
+ });
555
+
556
+ /* The hourly limit: one timer for when a new code is allowed again. */
557
+ watch(
558
+ () => (pqView.value?.kind === "limit" ? pqView.value.nextIssueAt : null),
559
+ (nextIssueAt) => {
560
+ clearTimeout(limitTimer);
561
+ if (!nextIssueAt) return;
562
+ const wait = Math.max(0, new Date(nextIssueAt).getTime() - Date.now()) + 500;
563
+ limitTimer = setTimeout(() => {
564
+ now.value = Date.now();
565
+ refreshAndOpen();
566
+ }, wait);
567
+ },
568
+ );
569
+
570
+ function onVisibilityChange() {
571
+ pageVisible.value = document.visibilityState === "visible";
572
+ if (pageVisible.value && personalOn.value && !loading.value && pqPhase.value !== "preparing") {
573
+ refreshAndOpen();
574
+ }
575
+ }
576
+
577
+ onMounted(() => {
578
+ pageVisible.value = document.visibilityState === "visible";
579
+ document.addEventListener("visibilitychange", onVisibilityChange);
580
+ });
581
+
582
+ onBeforeUnmount(() => {
583
+ document.removeEventListener("visibilitychange", onVisibilityChange);
584
+ clearInterval(tickTimer);
585
+ clearInterval(pollTimer);
586
+ clearTimeout(usedTimer);
587
+ clearTimeout(limitTimer);
588
+ });
589
+
265
590
  watch(
266
591
  () => props.site,
267
592
  async () => {
593
+ personalOn.value = false;
268
594
  await loadReaders();
269
595
  await loadProfile();
270
596
  },
@@ -333,4 +659,98 @@ watch(selectedReaderId, (value) => {
333
659
  gap: 8px;
334
660
  flex-wrap: wrap;
335
661
  }
662
+
663
+ /* Personal QR. Tokens only, so both themes follow. */
664
+ .hid-pqr__empty {
665
+ display: grid;
666
+ justify-items: center;
667
+ gap: 6px;
668
+ padding: 28px 0 22px;
669
+ color: var(--muted);
670
+ font-size: 13.5px;
671
+ text-align: center;
672
+ }
673
+
674
+ .hid-pqr__empty strong {
675
+ color: var(--text);
676
+ font-weight: 600;
677
+ }
678
+
679
+ .hid-pqr__pills {
680
+ display: flex;
681
+ justify-content: center;
682
+ gap: 8px;
683
+ flex-wrap: wrap;
684
+ margin-top: 10px;
685
+ }
686
+
687
+ .hid-pqr__pill {
688
+ display: inline-flex;
689
+ align-items: center;
690
+ gap: 6px;
691
+ padding: 4px 10px;
692
+ border-radius: var(--r-pill);
693
+ background: var(--hover);
694
+ color: var(--text2);
695
+ font-size: 12px;
696
+ font-weight: 700;
697
+ font-variant-numeric: tabular-nums;
698
+ }
699
+
700
+ .hid-pqr__pill--time {
701
+ background: var(--accent-soft);
702
+ color: var(--accent-text);
703
+ }
704
+
705
+ .hid-pqr__pill--ok {
706
+ background: var(--ok-bg);
707
+ color: var(--ok);
708
+ }
709
+
710
+ .hid-pqr__ring {
711
+ width: 14px;
712
+ height: 14px;
713
+ }
714
+
715
+ .hid-pqr__ring-track,
716
+ .hid-pqr__ring-fill {
717
+ fill: none;
718
+ stroke-width: 3;
719
+ }
720
+
721
+ .hid-pqr__ring-track {
722
+ stroke: var(--border);
723
+ }
724
+
725
+ .hid-pqr__ring-fill {
726
+ stroke: var(--accent);
727
+ stroke-linecap: round;
728
+ }
729
+
730
+ .hid-pqr__dim {
731
+ position: relative;
732
+ display: grid;
733
+ place-items: center;
734
+ min-width: 220px;
735
+ min-height: 220px;
736
+ }
737
+
738
+ .hid-pqr__dim img {
739
+ opacity: 0.18;
740
+ }
741
+
742
+ .hid-pqr__over {
743
+ position: absolute;
744
+ inset: 0;
745
+ display: flex;
746
+ flex-direction: column;
747
+ align-items: center;
748
+ justify-content: center;
749
+ gap: 6px;
750
+ padding: 16px;
751
+ color: var(--text);
752
+ font-size: 13.5px;
753
+ font-weight: 600;
754
+ text-align: center;
755
+ }
336
756
  </style>
@@ -186,7 +186,7 @@
186
186
  </v-expansion-panel-text>
187
187
  </v-expansion-panel>
188
188
 
189
- <!-- HID on or off for the site and the HID QR configuration:
189
+ <!-- HID on or off for the site, the HID QR configuration and Personal QR:
190
190
  `hid-mgmt:manage-hid-settings` (`useHidAccessPermission`). -->
191
191
  <v-expansion-panel v-if="canManageHidSettings">
192
192
  <v-expansion-panel-title>
@@ -202,6 +202,9 @@
202
202
  />
203
203
  <v-divider class="my-4" />
204
204
  <HidQrCodeConfiguration :site="siteId" :org="orgId" />
205
+ <v-divider class="my-4" />
206
+ <HidPersonalQrSettings :site-id="siteId" :saved="(siteData as any)?.metadata?.hidPersonalQr"
207
+ :loaded="!!siteData" @saved="refreshSiteData" />
205
208
  </v-expansion-panel-text>
206
209
  </v-expansion-panel>
207
210
 
@@ -123,16 +123,22 @@
123
123
  <span class="text-caption">Not Checked Out</span>
124
124
  </template>
125
125
  </v-checkbox>
126
+ <!-- IMP-1440: a From after its To is not sent - both boxes turn
127
+ red, the To box says why, and the list keeps its rows. -->
126
128
  <InputDatePicker
127
129
  v-model="dateFrom"
128
130
  density="compact"
129
131
  hide-details
132
+ aria-label="Date from"
133
+ :error="!!dateRangeProblem"
130
134
  :max="todayOnly ? sgToday : undefined"
131
135
  />
132
136
  <InputDatePicker
133
137
  v-model="dateTo"
134
138
  density="compact"
135
- hide-details
139
+ hide-details="auto"
140
+ aria-label="Date to"
141
+ :error-messages="dateRangeProblem ? [dateRangeProblem] : []"
136
142
  :max="todayOnly ? sgToday : undefined"
137
143
  />
138
144
  <!-- iSecure: every tab but Unregistered; the Guests tab offers
@@ -1890,6 +1896,7 @@ import { barrierCameraOf, barrierMessage, barrierOf, VISITOR_ACTION_SUCCESS } fr
1890
1896
  import useVisitorCameraChoices from "../composables/useVisitorCameraChoices";
1891
1897
  import { VISITOR_CAMERA_LABEL } from "../utils/visitor-camera";
1892
1898
  import { notAfterToday, sgDateOf, type VisitorDateDefault } from "../utils/visitor-date-default";
1899
+ import { dateRangeError } from "../utils/date-range";
1893
1900
  import usePassKey from "../composables/usePassKey";
1894
1901
  import {
1895
1902
  VISITOR_SEARCH_DEBOUNCE_MS,
@@ -2299,6 +2306,8 @@ const defaultDateFrom = () =>
2299
2306
 
2300
2307
  const dateTo = ref(defaultDateTo());
2301
2308
  const dateFrom = ref(defaultDateFrom());
2309
+ /** IMP-1440: "" while the range can be fetched, else the sentence shown under To. */
2310
+ const dateRangeProblem = computed(() => dateRangeError(dateFrom.value, dateTo.value));
2302
2311
 
2303
2312
  function sgDayStart(day: string) {
2304
2313
  return day ? new Date(`${day}T00:00:00+08:00`).toISOString() : undefined;
@@ -3090,6 +3099,9 @@ const {
3090
3099
  } = await useLazyAsyncData(
3091
3100
  "get-all-visitors",
3092
3101
  async () => {
3102
+ // IMP-1440: a From after its To is not applied. `null` leaves the rows on
3103
+ // screen as they are (the watcher below only takes a real answer).
3104
+ if (dateRangeProblem.value) return null;
3093
3105
  const params: any = {
3094
3106
  page: page.value,
3095
3107
  site: siteId,
@@ -4097,6 +4109,7 @@ function buildReportParams(): any {
4097
4109
  }
4098
4110
 
4099
4111
  async function handleDownloadPDFReport() {
4112
+ if (dateRangeProblem.value) return showMessage(dateRangeProblem.value, "error");
4100
4113
  try {
4101
4114
  showMessage("Generating PDF report...", "info");
4102
4115
 
@@ -4126,6 +4139,7 @@ async function handleDownloadPDFReport() {
4126
4139
  }
4127
4140
 
4128
4141
  async function handleDownloadCSVReport() {
4142
+ if (dateRangeProblem.value) return showMessage(dateRangeProblem.value, "error");
4129
4143
  try {
4130
4144
  showMessage("Generating CSV report...", "info");
4131
4145
 
@@ -42,6 +42,12 @@ export type HidProfileQr = {
42
42
  issuedAt: string;
43
43
  /** null when the permission lookup itself failed, so "unknown" stays distinct from "no". */
44
44
  assigned: boolean | null;
45
+ /**
46
+ * Present only when the site turned Personal QR on (DV-2031): timed, one time
47
+ * codes. Read it through `toPersonalQr` (`utils/hid-personal-qr.ts`); absent
48
+ * means today's fixed code.
49
+ */
50
+ personalQr?: unknown;
45
51
  };
46
52
 
47
53
  type HidIdentityPayload = {
@@ -236,10 +242,14 @@ export default function useHidAmico() {
236
242
  );
237
243
  }
238
244
 
239
- function issueProfileQr(readerId: string) {
245
+ /**
246
+ * With no options, returns the current code (or makes one), as before.
247
+ * `{ renew: true }` forces a new Personal QR; it counts toward the hourly limit.
248
+ */
249
+ function issueProfileQr(readerId: string, options: { renew?: boolean } = {}) {
240
250
  return useNuxtApp().$api<{ data: HidProfileQr }>(
241
251
  `${basePath}/readers/${readerId}/profile-qr`,
242
- { method: "POST" },
252
+ options.renew ? { method: "POST", body: { renew: true } } : { method: "POST" },
243
253
  );
244
254
  }
245
255
 
@@ -19,6 +19,8 @@ export const SITE_FEATURE_KEYS = [
19
19
  "robotSharedSpace",
20
20
  "manpower",
21
21
  "cctvEngine",
22
+ // HID Personal QR (DV-2031/2032): timed, one time codes. Absent or off = today's fixed code.
23
+ "hidPersonalQr",
22
24
  ] as const;
23
25
 
24
26
  export type TSiteFeatureKey = (typeof SITE_FEATURE_KEYS)[number];
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.187.3",
5
+ "version": "4.188.0",
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.",
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A list's From / To date filter (IMP-1440).
3
+ *
4
+ * A From later than its To used to be sent as it was: the server found nothing
5
+ * between them and the list just went empty, with no word why. Every list that
6
+ * filters by a day range asks this first and, when it answers, shows the
7
+ * sentence and keeps the rows it already has instead of fetching.
8
+ */
9
+
10
+ export const DATE_RANGE_ERROR = "The 'To' date must be on or after the 'From' date.";
11
+
12
+ const pad2 = (value: number) => String(value).padStart(2, "0");
13
+
14
+ /**
15
+ * The calendar day a filter value names, "YYYY-MM-DD", or "" when it names none.
16
+ * A "YYYY-MM-DD…" string is read as written (no time zone shift); a Date is read
17
+ * as the day it is on this device, as the date pickers show it.
18
+ */
19
+ export function rangeDay(value: unknown): string {
20
+ if (!value) return "";
21
+ if (typeof value === "string") {
22
+ const match = /^(\d{4}-\d{2}-\d{2})/.exec(value.trim());
23
+ if (match) return match[1];
24
+ }
25
+ const date = value instanceof Date ? value : new Date(value as string | number);
26
+ if (isNaN(date.getTime())) return "";
27
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
28
+ }
29
+
30
+ /**
31
+ * The plain-words problem with a From / To pair, or "" when the list may be
32
+ * fetched. The same day at both ends is a valid one-day range; a missing end is
33
+ * left to the caller's own default.
34
+ */
35
+ export function dateRangeError(from: unknown, to: unknown): string {
36
+ const start = rangeDay(from);
37
+ const end = rangeDay(to);
38
+ if (!start || !end) return "";
39
+ return start > end ? DATE_RANGE_ERROR : "";
40
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * PERSONAL QR (DV-2031 core, DV-2032 screens): a member's own HID code when
3
+ * the site has turned it on. Each code lasts a set time (default one hour) and
4
+ * works once; the reader enforces both. Pure, so `node --test` can load it.
5
+ *
6
+ * The server adds `personalQr` to the profile QR response only for a site with
7
+ * the setting on. Without it the HID QR Code page is exactly what it was
8
+ * before. Ported from the resident app's helper so every app behaves the same.
9
+ */
10
+
11
+ export type PersonalQrState = "none" | "active" | "used" | "expired";
12
+
13
+ export type PersonalQr = {
14
+ state: PersonalQrState;
15
+ expiresAt: string | null;
16
+ usedAt: string | null;
17
+ validityMinutes: number;
18
+ maxPerHour: number;
19
+ /** Set only while the hourly limit refuses a new code. */
20
+ nextIssueAt: string | null;
21
+ /** Whether the current code was written with door access at this reader. */
22
+ access: boolean | null;
23
+ };
24
+
25
+ export type PersonalQrView =
26
+ | { kind: "active"; secondsLeft: number; totalSeconds: number; expiresAt: string }
27
+ | { kind: "used"; usedAt: string | null }
28
+ | { kind: "expired"; expiresAt: string | null }
29
+ | { kind: "limit"; nextIssueAt: string }
30
+ | { kind: "none" };
31
+
32
+ /** How often the open page asks whether the code has been used at the door. */
33
+ export const PERSONAL_QR_POLL_MS = 5000;
34
+
35
+ /** The bounds core validates on `site.metadata.hidPersonalQr` (`hid-personal-qr.util.ts`). */
36
+ export const PERSONAL_QR_VALIDITY_MINUTES = Object.freeze({ min: 5, max: 240, default: 60 });
37
+ export const PERSONAL_QR_MAX_PER_HOUR = Object.freeze({ min: 1, max: 20, default: 5 });
38
+
39
+ type Bounds = { min: number; max: number; default: number };
40
+
41
+ const STATES: readonly PersonalQrState[] = ["none", "active", "used", "expired"];
42
+
43
+ const asRecord = (value: unknown): Record<string, unknown> => (
44
+ typeof value === "object" && value !== null && !Array.isArray(value)
45
+ ? value as Record<string, unknown>
46
+ : {}
47
+ );
48
+
49
+ const isoOrNull = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null);
50
+
51
+ const positiveInteger = (value: unknown, fallback: number) => {
52
+ const parsed = typeof value === "number" ? value : Number.NaN;
53
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
54
+ };
55
+
56
+ const time = (value: string | null) => {
57
+ if (!value) return null;
58
+ const parsed = new Date(value).getTime();
59
+ return Number.isFinite(parsed) ? parsed : null;
60
+ };
61
+
62
+ /** Null when the block is absent or not switched on: today's fixed code. */
63
+ export function toPersonalQr(value: unknown): PersonalQr | null {
64
+ const row = asRecord(value);
65
+ if (row.enabled !== true) return null;
66
+ const state = STATES.includes(row.state as PersonalQrState) ? row.state as PersonalQrState : "none";
67
+ return {
68
+ state,
69
+ expiresAt: isoOrNull(row.expiresAt),
70
+ usedAt: isoOrNull(row.usedAt),
71
+ validityMinutes: positiveInteger(row.validityMinutes, PERSONAL_QR_VALIDITY_MINUTES.default),
72
+ maxPerHour: positiveInteger(row.maxPerHour, PERSONAL_QR_MAX_PER_HOUR.default),
73
+ nextIssueAt: isoOrNull(row.nextIssueAt),
74
+ access: typeof row.access === "boolean" ? row.access : null,
75
+ };
76
+ }
77
+
78
+ function limitedUntil(pq: PersonalQr, now: Date) {
79
+ const next = time(pq.nextIssueAt);
80
+ return next !== null && next > now.getTime() ? pq.nextIssueAt : null;
81
+ }
82
+
83
+ /**
84
+ * What the page draws. An "active" code is checked against the browser clock
85
+ * too, so a code whose time ran out while the page was open greys out at once
86
+ * rather than at the next poll. A code with no readable expiry is never drawn
87
+ * as working. Order: working code, then the hourly limit, then used, expired
88
+ * or none.
89
+ */
90
+ export function personalQrView(pq: PersonalQr, now: Date): PersonalQrView {
91
+ if (pq.state === "active") {
92
+ const expires = time(pq.expiresAt);
93
+ if (expires !== null && expires > now.getTime()) {
94
+ return {
95
+ kind: "active",
96
+ secondsLeft: Math.ceil((expires - now.getTime()) / 1000),
97
+ totalSeconds: pq.validityMinutes * 60,
98
+ expiresAt: pq.expiresAt as string,
99
+ };
100
+ }
101
+ }
102
+ const limit = limitedUntil(pq, now);
103
+ if (limit) return { kind: "limit", nextIssueAt: limit };
104
+ if (pq.state === "used") return { kind: "used", usedAt: pq.usedAt };
105
+ if (pq.state === "active" || pq.state === "expired") return { kind: "expired", expiresAt: pq.expiresAt };
106
+ return { kind: "none" };
107
+ }
108
+
109
+ /**
110
+ * Whether to ask for a new code without a click.
111
+ * * "open": the page was just opened or came back into view: anything but a
112
+ * working code is replaced.
113
+ * * "watch": the page stayed open: only a code just used at the door is
114
+ * replaced. An expired one waits for a click, so leaving the page open does
115
+ * not use up the hourly limit.
116
+ * Never while the hourly limit refuses.
117
+ */
118
+ export function shouldAutoIssue(pq: PersonalQr, now: Date, trigger: "open" | "watch"): boolean {
119
+ const view = personalQrView(pq, now);
120
+ if (trigger === "watch") return view.kind === "used";
121
+ return view.kind === "none" || view.kind === "used" || view.kind === "expired";
122
+ }
123
+
124
+ const pad = (value: number) => String(value).padStart(2, "0");
125
+
126
+ /** `55:32`; from one hour `1:00:00`. Never negative. */
127
+ export function formatCountdown(seconds: number): string {
128
+ const total = Number.isFinite(seconds) ? Math.max(0, Math.round(seconds)) : 0;
129
+ const hours = Math.floor(total / 3600);
130
+ const minutes = Math.floor((total % 3600) / 60);
131
+ const rest = total % 60;
132
+ return hours > 0 ? `${hours}:${pad(minutes)}:${pad(rest)}` : `${pad(minutes)}:${pad(rest)}`;
133
+ }
134
+
135
+ /** `9:14 AM` in the browser's own time zone, the same clock shape as `formatLastActive`. Empty for a missing or bad value. */
136
+ export function formatPersonalQrTime(value: string | null | undefined): string {
137
+ if (!value) return "";
138
+ const date = new Date(value);
139
+ if (Number.isNaN(date.getTime())) return "";
140
+ return date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true });
141
+ }
142
+
143
+ /* ── Site Settings: `site.metadata.hidPersonalQr` ──────────────────────── */
144
+
145
+ export type PersonalQrSettings = { enabled: boolean; validityMinutes: number; maxPerHour: number };
146
+
147
+ function boundedInteger(value: unknown, bounds: Bounds) {
148
+ if (value === null || value === undefined || value === "") return bounds.default;
149
+ const parsed = Number(value);
150
+ if (!Number.isFinite(parsed)) return bounds.default;
151
+ return Math.min(bounds.max, Math.max(bounds.min, Math.floor(parsed)));
152
+ }
153
+
154
+ /**
155
+ * The saved switch, as core reads it (`resolvePersonalQrSettings`): off unless
156
+ * `enabled` is literally true, numbers defaulted and clamped.
157
+ */
158
+ export function readPersonalQrSettings(saved: unknown): PersonalQrSettings {
159
+ const row = asRecord(saved);
160
+ return {
161
+ enabled: row.enabled === true,
162
+ validityMinutes: boundedInteger(row.validityMinutes, PERSONAL_QR_VALIDITY_MINUTES),
163
+ maxPerHour: boundedInteger(row.maxPerHour, PERSONAL_QR_MAX_PER_HOUR),
164
+ };
165
+ }
166
+
167
+ /** Empty when the typed value is a whole number in range (what core accepts), otherwise the message to show. */
168
+ export function personalQrNumberError(input: string | number, bounds: Bounds, unit: string): string {
169
+ const text = String(input ?? "").trim();
170
+ const value = /^\d+$/.test(text) ? Number(text) : Number.NaN;
171
+ return Number.isInteger(value) && value >= bounds.min && value <= bounds.max
172
+ ? ""
173
+ : `Enter a number from ${bounds.min} to ${bounds.max} ${unit}.`;
174
+ }