@7365admin1/layer-common 4.28.1-staging.357 → 4.28.1-staging.359

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.
@@ -376,6 +376,7 @@ const visitorRecords = ref<Record<string, HidAccessRecord>>({});
376
376
  const logs = ref<HidAccessRecord[]>([]);
377
377
  const liveAccessLogs = ref<HidAccessRecord[]>([]);
378
378
  const administratorUserIds = ref<Set<number>>(new Set());
379
+ const { selectHidReader, resolveForSite } = useHidReaderSelection();
379
380
  const selectedReaderId = ref("");
380
381
  const activeTab = ref<AccessTab>("all");
381
382
  const search = ref("");
@@ -592,9 +593,11 @@ async function loadReaders() {
592
593
  if (!props.site) return;
593
594
  const response = await getReaders({ site: props.site, page: 1, limit: 100 });
594
595
  readers.value = response?.items ?? response?.data?.items ?? response?.data?.readers ?? [];
595
- if (!selectedReaderId.value && readers.value.length) {
596
- selectedReaderId.value = readers.value[0]._id;
597
- }
596
+ /* Shared with every other HID screen — see `useHidReaderSelection`. The
597
+ resolver refuses a remembered reader that is not this site's, so a site
598
+ switch or a deleted reader falls back to the first rather than querying
599
+ an id the site does not own. */
600
+ selectedReaderId.value = resolveForSite(props.site, readers.value);
598
601
  }
599
602
 
600
603
  async function loadDashboard() {
@@ -1572,6 +1575,12 @@ function escapeHtml(value: unknown) {
1572
1575
  .replace(/"/g, "&quot;")
1573
1576
  .replace(/'/g, "&#039;");
1574
1577
  }
1578
+
1579
+ /* Publish every change, including the seed above: a screen that had to fall
1580
+ back to the first reader should leave the others agreeing with it. */
1581
+ watch(selectedReaderId, (value) => {
1582
+ if (value) selectHidReader(props.site, value);
1583
+ });
1575
1584
  </script>
1576
1585
 
1577
1586
  <style scoped>
@@ -126,6 +126,7 @@ const { getReaders, getProfileQr, issueProfileQr, deleteProfileQr } = useHidAmic
126
126
  type HidReaderOption = { _id: string; name?: string; portalName?: string };
127
127
 
128
128
  const readers = ref<HidReaderOption[]>([]);
129
+ const { selectHidReader, resolveForSite } = useHidReaderSelection();
129
130
  const selectedReaderId = ref("");
130
131
  const profile = ref<HidProfileQr | null>(null);
131
132
  const qrImage = ref("");
@@ -203,9 +204,11 @@ async function loadReaders() {
203
204
  const data = toRecord(response.data);
204
205
  const items = response.items ?? data.items ?? data.readers ?? [];
205
206
  readers.value = (Array.isArray(items) ? items : []).filter((reader) => reader?._id);
206
- if (!selectedReaderId.value && readers.value.length) {
207
- selectedReaderId.value = String(readers.value[0]._id);
208
- }
207
+ /* Shared with every other HID screen — see `useHidReaderSelection`. The
208
+ resolver refuses a remembered reader that is not this site's, so a site
209
+ switch or a deleted reader falls back to the first rather than querying
210
+ an id the site does not own. */
211
+ selectedReaderId.value = resolveForSite(props.site, readers.value);
209
212
  }
210
213
 
211
214
  async function loadProfile() {
@@ -263,6 +266,12 @@ watch(
263
266
  },
264
267
  { immediate: true },
265
268
  );
269
+
270
+ /* Publish every change, including the seed above: a screen that had to fall
271
+ back to the first reader should leave the others agreeing with it. */
272
+ watch(selectedReaderId, (value) => {
273
+ if (value) selectHidReader(props.site, value);
274
+ });
266
275
  </script>
267
276
 
268
277
  <style scoped>
@@ -208,6 +208,7 @@ const {
208
208
  } = useHidAmico();
209
209
  const readers = ref<HidReader[]>([]);
210
210
  const users = ref<HidReaderUser[]>([]);
211
+ const { selectHidReader, resolveForSite } = useHidReaderSelection();
211
212
  const selectedReaderId = ref("");
212
213
  const search = ref("");
213
214
  const userType = ref<"all" | "user" | "visitor">("all");
@@ -270,7 +271,11 @@ async function loadReaders() {
270
271
  readers.value = (Array.isArray(items) ? items : [])
271
272
  .map(toReader)
272
273
  .filter((reader): reader is HidReader => reader !== null);
273
- if (!selectedReaderId.value && readers.value.length) selectedReaderId.value = readers.value[0]._id;
274
+ /* Shared with every other HID screen — see `useHidReaderSelection`. The
275
+ resolver refuses a remembered reader that is not this site's, so a site
276
+ switch or a deleted reader falls back to the first rather than querying
277
+ an id the site does not own. */
278
+ selectedReaderId.value = resolveForSite(props.site, readers.value);
274
279
  } catch (error: unknown) {
275
280
  readers.value = [];
276
281
  showToast(getErrorMessage(error), "error");
@@ -541,6 +546,12 @@ function toNumber(value: unknown, fallback: number) {
541
546
  const number = Number(value);
542
547
  return Number.isFinite(number) ? number : fallback;
543
548
  }
549
+
550
+ /* Publish every change, including the seed above: a screen that had to fall
551
+ back to the first reader should leave the others agreeing with it. */
552
+ watch(selectedReaderId, (value) => {
553
+ if (value) selectHidReader(props.site, value);
554
+ });
544
555
  </script>
545
556
 
546
557
  <style scoped>
@@ -750,6 +750,7 @@ type HidIdentityPayload = Record<string, unknown> & {
750
750
  const readers = ref<HidReader[]>([]);
751
751
  const users = ref<HidUser[]>([]);
752
752
  const administratorUserIds = ref<Set<number>>(new Set());
753
+ const { selectHidReader, resolveForSite } = useHidReaderSelection();
753
754
  const selectedReaderId = ref("");
754
755
  const search = ref("");
755
756
  const status = ref("");
@@ -1136,9 +1137,11 @@ async function loadReaders() {
1136
1137
  readers.value = (Array.isArray(items) ? items : [])
1137
1138
  .map(toHidReader)
1138
1139
  .filter((reader): reader is HidReader => reader !== null);
1139
- if (!selectedReaderId.value && readers.value.length) {
1140
- selectedReaderId.value = readers.value[0]._id;
1141
- }
1140
+ /* Shared with every other HID screen — see `useHidReaderSelection`. The
1141
+ resolver refuses a remembered reader that is not this site's, so a site
1142
+ switch or a deleted reader falls back to the first rather than querying
1143
+ an id the site does not own. */
1144
+ selectedReaderId.value = resolveForSite(props.site, readers.value);
1142
1145
  }
1143
1146
 
1144
1147
  /**
@@ -2577,6 +2580,12 @@ function toHidCard(value: unknown): HidCard {
2577
2580
  source: card.source === "reader" || card.source === "manual" || card.source === "device" ? card.source : undefined,
2578
2581
  };
2579
2582
  }
2583
+
2584
+ /* Publish every change, including the seed above: a screen that had to fall
2585
+ back to the first reader should leave the others agreeing with it. */
2586
+ watch(selectedReaderId, (value) => {
2587
+ if (value) selectHidReader(props.site, value);
2588
+ });
2580
2589
  </script>
2581
2590
 
2582
2591
  <style scoped>
@@ -89,11 +89,29 @@
89
89
  have already ticked is still selected and will still be saved.
90
90
  </div>
91
91
 
92
+ <!--
93
+ Matched, but every match is switched off and off is hidden. A
94
+ blank panel would read as the search having failed, which is a
95
+ different thing with a different remedy.
96
+ -->
97
+ <div
98
+ v-else-if="!hasShownModules"
99
+ class="pa-6 text-center text-body-2 text-medium-emphasis"
100
+ >
101
+ Nothing is switched on yet. Show the switched-off modules to
102
+ start granting.
103
+ </div>
104
+
92
105
  <template
93
106
  v-for="(actions, resourceKey, resourceIndex) in visiblePermissions"
94
107
  :key="resourceKey"
95
108
  >
96
- <v-divider v-if="resourceIndex > 0" />
109
+ <v-divider
110
+ v-if="
111
+ isModuleShown(String(resourceKey)) &&
112
+ String(resourceKey) !== firstShownResource
113
+ "
114
+ />
97
115
 
98
116
  <!--
99
117
  Category row. The whole row is the accordion header: one
@@ -102,6 +120,7 @@
102
120
  granting a module is never confused with looking at it.
103
121
  -->
104
122
  <v-list-item
123
+ v-if="isModuleShown(String(resourceKey))"
105
124
  density="compact"
106
125
  :ripple="false"
107
126
  :class="[
@@ -203,6 +222,19 @@
203
222
  </div>
204
223
 
205
224
  <div class="role-create__footer">
225
+ <AppButton
226
+ v-if="disabledModuleCount > 0 || !showDisabledModules"
227
+ variant="ghost"
228
+ class="role-create__footer-left"
229
+ @click="showDisabledModules = !showDisabledModules"
230
+ >
231
+ {{
232
+ showDisabledModules
233
+ ? "Hide switched-off modules"
234
+ : `Show ${disabledModuleCount} switched-off`
235
+ }}
236
+ </AppButton>
237
+
206
238
  <AppButton variant="ghost" @click="cancel">{{ props.cancelText }}</AppButton>
207
239
  <AppButton :disabled="!validForm || disable" @click="submit">Submit</AppButton>
208
240
  </div>
@@ -468,6 +500,7 @@ function cancel() {
468
500
  name.value = "";
469
501
  permState.value = { selected: [], enabled: [] };
470
502
  expandedResource.value = null;
503
+ showDisabledModules.value = true;
471
504
  // A query left behind would greet the next person with a filtered list and
472
505
  // no obvious reason for it.
473
506
  moduleSearch.value = "";
@@ -525,6 +558,46 @@ const visiblePermissions = computed(() => {
525
558
  return matches;
526
559
  });
527
560
 
561
+ /*
562
+ * HIDING THE MODULES THIS ROLE DOES NOT TOUCH -- the same button the update
563
+ * dialog carries.
564
+ *
565
+ * DEFAULTS THE OTHER WAY HERE, and deliberately. A role being CREATED has
566
+ * nothing switched on, so hiding the switched-off modules would open this
567
+ * dialog on an empty list and put a click between the user and the only thing
568
+ * they came to do. Reading an existing role is the opposite case: the four
569
+ * granted modules are the point and the other 27 are noise.
570
+ *
571
+ * PURELY WHAT IS DRAWN. `visiblePermissions` -- not this -- is what Select All
572
+ * and `isAllSelected` act on, so hiding a row never changes what a click grants
573
+ * and never changes what is saved.
574
+ */
575
+ const showDisabledModules = ref(true);
576
+
577
+ function isModuleShown(resource: string) {
578
+ return showDisabledModules.value || isCategoryEnabled(resource);
579
+ }
580
+
581
+ /** The modules actually drawn, in order -- so the divider knows which is first. */
582
+ const shownResources = computed(() =>
583
+ Object.keys(visiblePermissions.value).filter((resource) =>
584
+ isModuleShown(resource)
585
+ )
586
+ );
587
+
588
+ const firstShownResource = computed(() => shownResources.value[0] ?? "");
589
+
590
+ const hasShownModules = computed(() => shownResources.value.length > 0);
591
+
592
+ const disabledModuleCount = computed(
593
+ () =>
594
+ Object.keys(visiblePermissions.value).filter(
595
+ (resource) => !isCategoryEnabled(resource)
596
+ ).length
597
+ );
598
+
599
+
600
+
528
601
  const hasVisiblePermissions = computed(
529
602
  () => Object.keys(visiblePermissions.value).length > 0
530
603
  );
@@ -627,6 +700,10 @@ const isAllSelected = computed(() => {
627
700
  /* The design's dialog footer. Deliberately not the shared
628
701
  `.screen-modal__footer` - that class is on the batch-D branch (#1150), not
629
702
  on this base, and a second copy in `screens.css` would collide with it. */
703
+ .role-create__footer-left {
704
+ margin-right: auto;
705
+ }
706
+
630
707
  .role-create__footer {
631
708
  display: flex;
632
709
  justify-content: flex-end;
@@ -53,11 +53,29 @@
53
53
  role already holds is untouched and will still be saved.
54
54
  </div>
55
55
 
56
+ <!--
57
+ Matched, but every match is switched off and off is hidden. A
58
+ blank panel here would read as the search having failed, which
59
+ is a different thing and has a different remedy.
60
+ -->
61
+ <div
62
+ v-else-if="!hasShownModules"
63
+ class="pa-6 text-center text-body-2 text-medium-emphasis"
64
+ >
65
+ This role grants nothing here yet. Show the switched-off modules
66
+ to grant one.
67
+ </div>
68
+
56
69
  <template
57
70
  v-for="(actions, resourceKey, resourceIndex) in visiblePermissions"
58
71
  :key="resourceKey"
59
72
  >
60
- <v-divider v-if="resourceIndex > 0" />
73
+ <v-divider
74
+ v-if="
75
+ isModuleShown(String(resourceKey)) &&
76
+ String(resourceKey) !== firstShownResource
77
+ "
78
+ />
61
79
  <!--
62
80
  The whole row is the accordion header: one module is open at
63
81
  a time, so clicking this one closes whichever was open. The
@@ -66,6 +84,7 @@
66
84
  mode works the same way, without the switch being live.
67
85
  -->
68
86
  <v-list-item
87
+ v-if="isModuleShown(String(resourceKey))"
69
88
  density="compact"
70
89
  :ripple="false"
71
90
  :class="[
@@ -207,6 +226,19 @@
207
226
  </div>
208
227
 
209
228
  <div class="role-perm__footer">
229
+ <AppButton
230
+ v-if="disabledModuleCount > 0 || showDisabledModules"
231
+ variant="ghost"
232
+ class="role-perm__footer-left"
233
+ @click="showDisabledModules = !showDisabledModules"
234
+ >
235
+ {{
236
+ showDisabledModules
237
+ ? "Hide switched-off modules"
238
+ : `Show ${disabledModuleCount} switched-off`
239
+ }}
240
+ </AppButton>
241
+
210
242
  <AppButton v-if="!edit" variant="ghost" @click="emit('cancel')">Close</AppButton>
211
243
  <AppButton v-else variant="ghost" @click="cancelEdit()">Cancel</AppButton>
212
244
 
@@ -480,6 +512,43 @@ const sortedNotOffered = computed(() =>
480
512
  sortResourcesByLabel(props.notOfferedPermissions as Record<string, any>)
481
513
  );
482
514
 
515
+ /*
516
+ * HIDING THE MODULES THIS ROLE DOES NOT TOUCH.
517
+ *
518
+ * 31 modules, four of them granted: the 27 greyed rows were the bulk of the
519
+ * scroll and none of them said anything. Off is hidden by default and the
520
+ * footer button brings them back.
521
+ *
522
+ * PURELY WHAT IS DRAWN. `visiblePermissions` -- not this -- is what Select All
523
+ * and `isAllSelected` act on, so hiding a row never changes what a click grants
524
+ * and never changes what is saved.
525
+ */
526
+ const showDisabledModules = ref(false);
527
+
528
+ function isModuleShown(resource: string) {
529
+ return showDisabledModules.value || isCategoryEnabled(resource);
530
+ }
531
+
532
+ /** The modules actually drawn, in order -- so the divider knows which is first. */
533
+ const shownResources = computed(() =>
534
+ Object.keys(visiblePermissions.value).filter((resource) =>
535
+ isModuleShown(resource)
536
+ )
537
+ );
538
+
539
+ const firstShownResource = computed(() => shownResources.value[0] ?? "");
540
+
541
+ const hasShownModules = computed(() => shownResources.value.length > 0);
542
+
543
+ const disabledModuleCount = computed(
544
+ () =>
545
+ Object.keys(visiblePermissions.value).filter(
546
+ (resource) => !isCategoryEnabled(resource)
547
+ ).length
548
+ );
549
+
550
+
551
+
483
552
  const hasNotOffered = computed(
484
553
  () => Object.keys(props.notOfferedPermissions || {}).length > 0
485
554
  );
@@ -488,7 +557,13 @@ const hasVisiblePermissions = computed(
488
557
  () => Object.keys(visiblePermissions.value).length > 0
489
558
  );
490
559
 
491
- /** The `resource:action` keys currently on screen. */
560
+ /**
561
+ * The `resource:action` keys the search matched -- NOT the subset currently
562
+ * drawn. Hiding the switched-off modules is a view convenience; Select All
563
+ * still means every module the query matched, or the whole catalogue with no
564
+ * query. Tying it to the drawn subset would make Select All a no-op exactly
565
+ * when it is most useful.
566
+ */
492
567
  const visibleKeys = computed(() =>
493
568
  Object.entries(visiblePermissions.value).flatMap(([resource, actions]) =>
494
569
  Object.keys((actions as Record<string, unknown>) || {}).map(
@@ -564,6 +639,8 @@ function cancelEdit() {
564
639
  function resetExpansion() {
565
640
  expandedResources.value = [];
566
641
  expandedResource.value = null;
642
+ // Back to the quiet default: the next role is read before it is edited.
643
+ showDisabledModules.value = false;
567
644
  }
568
645
 
569
646
  // Reopening the dialog on another role must not inherit the last one's open
@@ -691,6 +768,10 @@ async function submit() {
691
768
  /* The design's dialog footer. Deliberately not the shared
692
769
  `.screen-modal__footer` - that class is on the batch-D branch (#1150), not
693
770
  on this base, and a second copy in `screens.css` would collide with it. */
771
+ .role-perm__footer-left {
772
+ margin-right: auto;
773
+ }
774
+
694
775
  .role-perm__footer {
695
776
  display: flex;
696
777
  justify-content: flex-end;
@@ -153,7 +153,11 @@
153
153
  the colour word keeps the width and lets the edge fall back to
154
154
  `--v-border-color`, which is the design's `--border` in each theme. -->
155
155
  <v-card flat outlined class="pa-2" border="sm" :loading="loadingPlateNumberDetails">
156
- <v-data-table :items="selectedVehicleObject[key]" :headers="plateHeadersView" hide-default-footer>
156
+ <!-- `hide-default-footer` alone kept Vuetify's default page size of
157
+ 10 with no pager, so a resident with 54 plates showed only the
158
+ first 10 here while the row menu listed all 54. Show every plate. -->
159
+ <v-data-table :items="selectedVehicleObject[key]" :headers="plateHeadersView"
160
+ :items-per-page="-1" hide-default-footer>
157
161
  <!-- A season pass's dates, large enough to read at a
158
162
  glance: green while valid, red once expired. -->
159
163
  <template #item.passDates="{ item: pass }">
@@ -292,13 +296,34 @@
292
296
  {{ value ? formatDate(value) : "" }}
293
297
  </template>
294
298
  <template #item.action="{ value }">
295
- {{ historyActionLabel(value) }}
299
+ <span class="history-action" :class="`history-action--${value}`">
300
+ {{ historyActionLabel(value) }}
301
+ </span>
296
302
  </template>
297
303
  <template #item.updatedByName="{ item: entry }">
298
304
  {{ entry.updatedByName || (entry.updatedBy ? "Unknown user" : "System") }}
299
305
  </template>
300
- <template #item.fields="{ value }">
301
- {{ formatHistoryFields(value) }}
306
+ <!-- "Status: from Blocked to Unblocked", one change per line, only
307
+ the values bold. Created lists what it was saved with. Entries
308
+ written before values were kept list the field names only. -->
309
+ <template #item.fields="{ item: entry }">
310
+ <div v-if="visibleChanges(entry).length" class="history-changes">
311
+ <div v-for="change in visibleChanges(entry)" :key="change.field">
312
+ <span class="history-label">{{ formatCamelCaseToWords(change.field) }}:</span>
313
+ <template v-if="entry.action === 'created'">
314
+ <span class="history-value">{{ formatHistoryValue(change, "to") }}</span>
315
+ </template>
316
+ <template v-else>
317
+ <span class="history-word">from</span>
318
+ <span class="history-value history-value--from">{{ formatHistoryValue(change, "from") }}</span>
319
+ <span class="history-word">to</span>
320
+ <span class="history-value">{{ formatHistoryValue(change, "to") }}</span>
321
+ </template>
322
+ </div>
323
+ </div>
324
+ <span v-else class="history-legacy">
325
+ {{ formatHistoryFields(entry.fields) }}<template v-if="entry.fields?.length"> (values not recorded)</template>
326
+ </span>
302
327
  </template>
303
328
  </v-data-table>
304
329
  </v-card-text>
@@ -322,6 +347,7 @@ import {
322
347
  // `error.message` put ofetch's own developer string in the delete dialog:
323
348
  // `[PUT] "/api/vehicles/6a9691f25648d7633171c9e3": 502`.
324
349
  import { errorConverter } from '../utils/data';
350
+ import { isPermissionRefusalError } from '../utils/permission-refusal';
325
351
 
326
352
 
327
353
 
@@ -400,7 +426,7 @@ const historyHeaders = [
400
426
  { title: "Date", value: "updatedAt" },
401
427
  { title: "Updated By", value: "updatedByName" },
402
428
  { title: "Action", value: "action" },
403
- { title: "Fields Updated", value: "fields", sortable: false },
429
+ { title: "Changes", value: "fields", sortable: false, minWidth: "280px" },
404
430
  ]
405
431
 
406
432
  /**
@@ -705,6 +731,8 @@ const HISTORY_ACTIONS: Record<string, string> = {
705
731
  blocked: "Blocked",
706
732
  unblocked: "Unblocked",
707
733
  deleted: "Deleted",
734
+ moved: "Moved",
735
+ synced: "Synced",
708
736
  };
709
737
 
710
738
  function historyActionLabel(action: string) {
@@ -712,9 +740,42 @@ function historyActionLabel(action: string) {
712
740
  return HISTORY_ACTIONS[action] ?? action.charAt(0).toUpperCase() + action.slice(1);
713
741
  }
714
742
 
743
+ const HISTORY_DATE_FIELDS = new Set(["start", "end", "deletedAt", "expiredAt"]);
744
+
745
+ /** Bookkeeping fields the reader has no use for - not shown in History. */
746
+ const HISTORY_HIDDEN_FIELDS = new Set(["blockedFrom", "deletedAt", "recNo", "anprCameras"]);
747
+
748
+ function visibleChanges(entry: TVehicleHistoryEntry) {
749
+ return (entry.changes ?? []).filter((change) => !HISTORY_HIDDEN_FIELDS.has(change.field));
750
+ }
751
+
752
+ /** One side of a change, read the way the rest of the screen reads it. */
753
+ function formatHistoryValue(change: TVehicleFieldChange, side: "from" | "to") {
754
+ const value = change[side];
755
+ const name = side === "from" ? change.fromName : change.toName;
756
+ if (value === null || value === undefined || value === "") return "-";
757
+ switch (change.field) {
758
+ case "block":
759
+ case "level":
760
+ case "unit":
761
+ return name || "(removed)";
762
+ case "status":
763
+ return formatVehicleStatus(String(value) as TVehicleStatus).label || String(value);
764
+ case "category":
765
+ case "type":
766
+ return formatValues(change.field, value);
767
+ case "seasonPassType":
768
+ case "blockedFrom":
769
+ return formatCamelCaseToWords(String(value));
770
+ }
771
+ if (HISTORY_DATE_FIELDS.has(change.field)) return formatDate(String(value));
772
+ return String(value);
773
+ }
774
+
715
775
  function formatHistoryFields(fields: string[] | undefined) {
716
- if (!Array.isArray(fields) || !fields.length) return "-";
717
- return fields.map((f) => formatCamelCaseToWords(f)).join(", ");
776
+ const shown = (fields ?? []).filter((f) => !HISTORY_HIDDEN_FIELDS.has(f));
777
+ if (!shown.length) return "-";
778
+ return shown.map((f) => formatCamelCaseToWords(f)).join(", ");
718
779
  }
719
780
 
720
781
  /** Fetches the plate's own record: the list does not carry `history`. */
@@ -743,11 +804,31 @@ async function openHistory(item: TPlateNumber) {
743
804
  * the host app's `useLocalPermission()`.
744
805
  */
745
806
  const vehiclePermissions = computed(() => ({
746
- canUpdateVehicle: props.canUpdateVehicle,
747
- canDeleteVehicle: props.canDeleteVehicle,
748
- canApproveVehicle: props.canApproveVehicle,
807
+ canUpdateVehicle: props.canUpdateVehicle && !revoked.update,
808
+ canDeleteVehicle: props.canDeleteVehicle && !revoked.delete,
809
+ canApproveVehicle: props.canApproveVehicle && !revoked.approve,
749
810
  }));
750
811
 
812
+ /**
813
+ * Rights the SERVER has just refused, hidden at once.
814
+ *
815
+ * The role on screen was read at page load; if an administrator has since
816
+ * unticked a right, the server refuses the action. `plugins/API.ts` re-reads
817
+ * the role in the background so the props catch up, but that is a round trip
818
+ * (and skipped inside its cool-down), so the refused item is taken off the
819
+ * menus here immediately. Whenever the host sends a fresh answer for that gate
820
+ * the local override is dropped and the host's answer stands again - so a
821
+ * right given back is not kept hidden.
822
+ */
823
+ const revoked = reactive({ update: false, delete: false, approve: false });
824
+ watch(() => props.canUpdateVehicle, () => { revoked.update = false; });
825
+ watch(() => props.canDeleteVehicle, () => { revoked.delete = false; });
826
+ watch(() => props.canApproveVehicle, () => { revoked.approve = false; });
827
+
828
+ function revokeOnRefusal(error: unknown, right: keyof typeof revoked) {
829
+ if (isPermissionRefusalError(error)) revoked[right] = true;
830
+ }
831
+
751
832
  /**
752
833
  * One entry point for every menu item, in both menus, so a new action can only
753
834
  * be added in one place and cannot be forgotten in the other.
@@ -853,6 +934,8 @@ async function submitDelete() {
853
934
  // raising the snackbar - and `error.response._data` throws on a network
854
935
  // error - so a refused delete showed the operator nothing at all.
855
936
  deleteError.value = errorConverter(error);
937
+ // Refused for want of the right: take Delete off both menus now.
938
+ revokeOnRefusal(error, "delete");
856
939
  // The dialog stays open and the row stays in the table - nothing is removed
857
940
  // optimistically, so what is on screen still matches the database.
858
941
  } finally {
@@ -904,6 +987,7 @@ async function submitBlock() {
904
987
  await getVehiclesRefresh();
905
988
  } catch (error: any) {
906
989
  actionError.value = errorConverter(error);
990
+ revokeOnRefusal(error, "update");
907
991
  } finally {
908
992
  blockingVehicle.value = false;
909
993
  }
@@ -926,6 +1010,7 @@ async function submitUnblock() {
926
1010
  await getVehiclesRefresh();
927
1011
  } catch (error: any) {
928
1012
  actionError.value = errorConverter(error);
1013
+ revokeOnRefusal(error, "update");
929
1014
  } finally {
930
1015
  unblockingVehicle.value = false;
931
1016
  }
@@ -951,6 +1036,7 @@ async function submitApprove() {
951
1036
  await getVehiclesRefresh();
952
1037
  } catch (error: any) {
953
1038
  actionError.value = errorConverter(error);
1039
+ revokeOnRefusal(error, "approve");
954
1040
  } finally {
955
1041
  approvingVehicle.value = false;
956
1042
  }
@@ -972,6 +1058,60 @@ watch(activeTab, () => {
972
1058
  </script>
973
1059
 
974
1060
  <style scoped>
1061
+ .history-changes {
1062
+ display: flex;
1063
+ flex-direction: column;
1064
+ gap: 4px;
1065
+ padding: 6px 0;
1066
+ line-height: 1.5;
1067
+ white-space: normal;
1068
+ }
1069
+ .history-label {
1070
+ opacity: 0.65;
1071
+ margin-right: 4px;
1072
+ }
1073
+ .history-word {
1074
+ font-weight: 400;
1075
+ opacity: 0.55;
1076
+ margin: 0 4px;
1077
+ }
1078
+ .history-value {
1079
+ font-weight: 700;
1080
+ }
1081
+ .history-value--from {
1082
+ opacity: 0.75;
1083
+ }
1084
+ .history-legacy {
1085
+ font-style: italic;
1086
+ opacity: 0.6;
1087
+ }
1088
+ /* Action badges, as in the approved sample. Tinted from the theme's own
1089
+ colours so they read in light and dark. */
1090
+ .history-action {
1091
+ display: inline-block;
1092
+ font-size: 12px;
1093
+ font-weight: 600;
1094
+ padding: 2px 10px;
1095
+ border-radius: 12px;
1096
+ white-space: nowrap;
1097
+ background: rgba(var(--v-theme-on-surface), 0.08);
1098
+ }
1099
+ .history-action--created,
1100
+ .history-action--approved,
1101
+ .history-action--restored {
1102
+ background: rgba(var(--v-theme-success), 0.15);
1103
+ color: rgb(var(--v-theme-success));
1104
+ }
1105
+ .history-action--blocked,
1106
+ .history-action--deleted {
1107
+ background: rgba(var(--v-theme-error), 0.15);
1108
+ color: rgb(var(--v-theme-error));
1109
+ }
1110
+ .history-action--moved,
1111
+ .history-action--updated {
1112
+ background: rgba(var(--v-theme-primary), 0.15);
1113
+ color: rgb(var(--v-theme-primary));
1114
+ }
975
1115
  .plate-remarks {
976
1116
  display: inline-block;
977
1117
  max-width: 220px;
@@ -0,0 +1,50 @@
1
+ import {
2
+ EMPTY_HID_READER_CHOICE,
3
+ resolveHidReaderId,
4
+ type HidReaderChoice,
5
+ } from "../utils/hid-reader-selection";
6
+
7
+ /**
8
+ * ONE HID READER CHOICE, SHARED BY EVERY HID SCREEN.
9
+ *
10
+ * Declared at MODULE scope on purpose. Each screen held its own `ref("")`, and
11
+ * because the HID screens are separate pages the ref was rebuilt on every
12
+ * navigation — HID Reader Users, HID Cards, Access Logs and HID QR Code each
13
+ * reset to the first reader no matter what had just been picked next door.
14
+ *
15
+ * A module-scoped ref is enough because moving between those pages is a ROUTE
16
+ * change, not a page load: the menu's items carry a `route` and
17
+ * `NavigationItem.vue` renders them through `:to`, so vue-router handles them
18
+ * and this module is never re-evaluated.
19
+ *
20
+ * Deliberately NOT persisted. `localStorage` would carry the choice through a
21
+ * hard refresh as well, which is a real but much smaller benefit than the
22
+ * navigation case, and it is worth adding only once somebody has felt the
23
+ * absence. See `utils/hid-reader-selection.ts` for the staleness rule that
24
+ * would have to hold either way.
25
+ *
26
+ * Intercom keeps its own reader and is not wired to this. Its question is which
27
+ * panel you are calling, not which door you are administering, and joining them
28
+ * would mean switching reader on Access Logs changed who you would dial.
29
+ */
30
+ const choice = ref<HidReaderChoice>({ ...EMPTY_HID_READER_CHOICE });
31
+
32
+ export default function useHidReaderSelection() {
33
+ /** Remember a choice. The site travels with it; an id alone means nothing. */
34
+ function selectHidReader(siteId: string, readerId: string) {
35
+ choice.value = { siteId: String(siteId ?? ""), readerId: String(readerId ?? "") };
36
+ }
37
+
38
+ /**
39
+ * The reader this screen should show, given the readers it just loaded.
40
+ *
41
+ * Call it after the reader list arrives, and write the answer back with
42
+ * `selectHidReader` so the screens agree on what "current" means even when
43
+ * one of them had to fall back to the first reader.
44
+ */
45
+ function resolveForSite(siteId: string, readers: readonly { _id?: unknown }[]) {
46
+ return resolveHidReaderId(siteId, readers, choice.value);
47
+ }
48
+
49
+ return { choice, selectHidReader, resolveForSite };
50
+ }
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.28.1-staging.357",
5
+ "version": "4.28.1-staging.359",
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.",
package/plugins/API.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { isPermissionRefusal } from "../utils/permission-refusal";
2
+
1
3
  export default defineNuxtPlugin((nuxtApp) => {
2
4
  const { cookieConfig } = useRuntimeConfig().public;
3
5
 
@@ -14,9 +16,12 @@ export default defineNuxtPlugin((nuxtApp) => {
14
16
  // read it. Re-read it in the background (plugins/secure-member.client.ts)
15
17
  // so the screen stops offering what the server refuses. The request itself
16
18
  // still fails as before; nothing here retries it.
19
+ //
20
+ // Both refusal shapes count: API-core's 403 + PERMISSION_DENIED and core's
21
+ // 401 + "You do not have permission ..." (vehicle writes and every other
22
+ // `requireSiteReach` gate). See utils/permission-refusal.ts.
17
23
  onResponseError({ response }) {
18
- if (response?.status !== 403) return;
19
- if ((response as any)?._data?.code !== "PERMISSION_DENIED") return;
24
+ if (!isPermissionRefusal(response?.status, (response as any)?._data)) return;
20
25
  if (!import.meta.client) return;
21
26
  const refresh = (nuxtApp as any).$refreshAppRole;
22
27
  if (typeof refresh === "function") {
@@ -85,6 +85,17 @@ declare type TVehicleHistoryEntry = {
85
85
  updatedByName?: string;
86
86
  updatedAt: string;
87
87
  fields: string[];
88
+ /** What each field changed from and to. Absent on older entries. */
89
+ changes?: TVehicleFieldChange[];
90
+ };
91
+
92
+ declare type TVehicleFieldChange = {
93
+ field: string;
94
+ from: string | number | boolean | null;
95
+ to: string | number | boolean | null;
96
+ /** Block / level / unit: the name the server resolved for the id. */
97
+ fromName?: string;
98
+ toName?: string;
88
99
  };
89
100
 
90
101
  declare type TVehiclePayload = Pick<
@@ -0,0 +1,52 @@
1
+ /**
2
+ * WHICH HID READER THE OPERATOR IS WORKING ON — the one rule behind it.
3
+ *
4
+ * Every HID screen used to hold its own `ref("")` and default it to
5
+ * `readers[0]`, so picking HID 2 on HID Reader Users and clicking through to
6
+ * HID Cards put you back on HID 1. They are separate PAGES, so the component
7
+ * unmounted and the ref was rebuilt from scratch every time — there was no way
8
+ * to make a choice stick. "I am working on HID 2" is a mode, not a per-screen
9
+ * preference.
10
+ *
11
+ * Navigation between those pages is a route change rather than a page load
12
+ * (`NavigationItem.vue` renders the menu's `route` through `:to`), so the
13
+ * module-scoped ref in `useHidReaderSelection` survives it. This file holds the
14
+ * part worth testing: deciding whether a remembered choice may still be used.
15
+ */
16
+
17
+ export type HidReaderChoice = { siteId: string; readerId: string };
18
+
19
+ /** Anything with an id — the four screens all carry a different reader shape. */
20
+ type ReaderLike = { _id?: unknown };
21
+
22
+ export const EMPTY_HID_READER_CHOICE: HidReaderChoice = { siteId: "", readerId: "" };
23
+
24
+ /**
25
+ * The reader a screen should show, given what this site actually has.
26
+ *
27
+ * A remembered id is honoured ONLY when it belongs to this site and is still in
28
+ * the list. That single condition covers every way it goes stale:
29
+ *
30
+ * - the operator switched site, so the id belongs to a site they have left
31
+ * - the reader was deleted or deactivated since they chose it
32
+ * - nothing has been chosen yet
33
+ *
34
+ * In all three the first reader is returned instead. The alternative — using
35
+ * the id anyway — sends requests for a reader the site does not own, which come
36
+ * back empty and read on screen as a reader with no users, no cards and no
37
+ * logs, rather than as the mistake it is.
38
+ */
39
+ export function resolveHidReaderId(
40
+ siteId: string,
41
+ readers: readonly ReaderLike[] | null | undefined,
42
+ choice: HidReaderChoice = EMPTY_HID_READER_CHOICE,
43
+ ): string {
44
+ const ids = (Array.isArray(readers) ? readers : [])
45
+ .map((reader) => String(reader?._id ?? ""))
46
+ .filter(Boolean);
47
+
48
+ if (choice.siteId === String(siteId ?? "") && ids.includes(choice.readerId)) {
49
+ return choice.readerId;
50
+ }
51
+ return ids[0] ?? "";
52
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * "The server refused this because the role no longer holds the right."
3
+ *
4
+ * The role is read on page load, so an administrator who unticks a right
5
+ * afterwards leaves the screen offering an action the server now refuses.
6
+ * `plugins/API.ts` re-reads the role on that refusal so the screen catches up,
7
+ * and a screen can hide the refused action at once instead of waiting for it.
8
+ *
9
+ * Two shapes are live, and both have to count:
10
+ *
11
+ * - API-core's gates answer 403 with `code: "PERMISSION_DENIED"`.
12
+ * - core's per-site gates (`requireSiteReach` -> `authorizeSite`, e.g. every
13
+ * vehicle write) throw `UnauthorizedError`, so they answer **401** with only
14
+ * `{ status: "error", message: "You do not have permission to ..." }`.
15
+ * Checking for 403 + code alone is why a refused vehicle delete left the
16
+ * Delete item on screen.
17
+ *
18
+ * A plain 401 ("Not authorized.", an expired session) is NOT a permission
19
+ * change and never matches: only the "You do not have permission" sentence
20
+ * every one of those gates writes does.
21
+ */
22
+ export const PERMISSION_DENIED_CODE = "PERMISSION_DENIED";
23
+
24
+ const PERMISSION_SENTENCE = /^you do not have permission\b/i;
25
+
26
+ export function isPermissionRefusal(status: unknown, body: unknown): boolean {
27
+ if (status !== 401 && status !== 403) return false;
28
+ const data = (body ?? {}) as Record<string, unknown>;
29
+ if (status === 403 && data.code === PERMISSION_DENIED_CODE) return true;
30
+ const message = typeof data.message === "string" ? data.message.trim() : "";
31
+ return PERMISSION_SENTENCE.test(message);
32
+ }
33
+
34
+ /** The same question asked of a thrown `$fetch` error. */
35
+ export function isPermissionRefusalError(error: any): boolean {
36
+ const status =
37
+ error?.response?.status ?? error?.statusCode ?? error?.status ?? null;
38
+ const body = error?.response?._data ?? error?.data ?? null;
39
+ return isPermissionRefusal(status, body);
40
+ }