@7365admin1/layer-common 4.29.0 → 4.31.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.
@@ -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,139 @@
1
+ import { onBeforeUnmount, ref, watch, type Ref } from "vue";
2
+ import { mergeLiveStates, type TLiveRobotState } from "../utils/robot-display";
3
+
4
+ /**
5
+ * Live robot state for the robots ON SCREEN - one store, one swappable feed.
6
+ *
7
+ * ## The interface a feed implements
8
+ *
9
+ * type TRobotLiveFeed = {
10
+ * // Start delivering states for these robot ids. `push` may be called any
11
+ * // number of times with any subset; each item is a `TLiveRobotState`
12
+ * // (`{ id, ok: false }` = "no answer, show Reconnecting").
13
+ * // `connected(false)` = the feed itself is down ("Connection lost").
14
+ * // Returns a stop function.
15
+ * watch(ids: string[], push: (items) => void, connected: (up: boolean) => void): () => void;
16
+ * };
17
+ *
18
+ * Today's feed is `robotPollingFeed`: `GET /api/robots/network/states?ids=...`
19
+ * every 4 s, paused while the tab is hidden (owner decision 2026-09-23: poll
20
+ * on-screen robots 3-5 s). A site-wide push feed (socket.io room per site - a
21
+ * backend follow-up) only has to implement `watch` the same way; components
22
+ * read `states[id]` / `connected` and never know which feed is behind them.
23
+ */
24
+ export type TRobotLiveFeed = {
25
+ watch(
26
+ ids: string[],
27
+ push: (items: Array<Partial<TLiveRobotState> & { id: string }>) => void,
28
+ connected: (up: boolean) => void,
29
+ ): () => void;
30
+ };
31
+
32
+ /**
33
+ * The polling feed. `fetchStates` returns `{ items }` for up to 50 ids.
34
+ * One request in flight at a time; a failed request marks the feed down (the
35
+ * robots' last states are replaced by "Reconnecting" - never left frozen).
36
+ */
37
+ export function robotPollingFeed(
38
+ fetchStates: (ids: string[]) => Promise<{ items?: Array<Partial<TLiveRobotState> & { id: string }> }>,
39
+ intervalMs = 4000,
40
+ ): TRobotLiveFeed {
41
+ return {
42
+ watch(ids, push, connected) {
43
+ let stopped = false;
44
+ let timer: ReturnType<typeof setTimeout> | undefined;
45
+ const hidden = () => typeof document !== "undefined" && document.visibilityState === "hidden";
46
+
47
+ async function tick() {
48
+ if (stopped) return;
49
+ if (!hidden() && ids.length) {
50
+ try {
51
+ const res = await fetchStates(ids);
52
+ if (stopped) return;
53
+ push(res?.items ?? []);
54
+ connected(true);
55
+ } catch {
56
+ if (stopped) return;
57
+ push(ids.map((id) => ({ id, ok: false })));
58
+ connected(false);
59
+ }
60
+ }
61
+ if (!stopped) timer = setTimeout(tick, intervalMs);
62
+ }
63
+ // Coming back to the tab refreshes at once instead of waiting a tick.
64
+ const onVisible = () => {
65
+ if (hidden() || stopped) return;
66
+ clearTimeout(timer);
67
+ tick();
68
+ };
69
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisible);
70
+ tick();
71
+ return () => {
72
+ stopped = true;
73
+ clearTimeout(timer);
74
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisible);
75
+ };
76
+ },
77
+ };
78
+ }
79
+
80
+ /** The Super Admin network feed: `/api/robots/network/states`. */
81
+ export function networkStatesFeed(intervalMs = 4000): TRobotLiveFeed {
82
+ return robotPollingFeed(
83
+ (ids) =>
84
+ useNuxtApp().$api<{ items: any[] }>("/api/robots/network/states", {
85
+ method: "GET",
86
+ query: { ids: ids.join(",") },
87
+ }),
88
+ intervalMs,
89
+ );
90
+ }
91
+
92
+ /**
93
+ * Any estate screen's feed (Property Management, Hygiene, Security, the
94
+ * console's site drill-down, robot detail): `GET /api/robots/states?ids=...`.
95
+ * The API checks every robot against its own site and narrows by the app's
96
+ * `appSlug`, so a robot this screen may not see simply never arrives.
97
+ */
98
+ export function siteStatesFeed(intervalMs = 4000): TRobotLiveFeed {
99
+ const appSlug = useRuntimeConfig().public?.appSlug as string | undefined;
100
+ return robotPollingFeed(
101
+ (ids) =>
102
+ useNuxtApp().$api<{ items: any[] }>("/api/robots/states", {
103
+ method: "GET",
104
+ query: { ids: ids.join(","), appSlug },
105
+ }),
106
+ intervalMs,
107
+ );
108
+ }
109
+
110
+ /**
111
+ * `states[id]` for every robot in `ids`, kept live by `feed`. Re-watches when
112
+ * the ids change (a new page, a new filter); stops on unmount.
113
+ */
114
+ export default function useRobotLive(ids: Ref<string[]>, feed: TRobotLiveFeed) {
115
+ const states = ref<Record<string, TLiveRobotState>>({});
116
+ const connected = ref(true);
117
+ const lastAt = ref<Date | null>(null);
118
+ let stop: (() => void) | null = null;
119
+
120
+ watch(
121
+ () => ids.value.join(","),
122
+ () => {
123
+ stop?.();
124
+ const list = [...ids.value];
125
+ stop = feed.watch(
126
+ list,
127
+ (items) => {
128
+ states.value = mergeLiveStates(states.value, items);
129
+ lastAt.value = new Date();
130
+ },
131
+ (up) => (connected.value = up),
132
+ );
133
+ },
134
+ { immediate: true },
135
+ );
136
+ onBeforeUnmount(() => stop?.());
137
+
138
+ return { states, connected, lastAt };
139
+ }
@@ -32,6 +32,50 @@ export default function useRobots() {
32
32
  );
33
33
  }
34
34
 
35
+ /**
36
+ * One site's robots for the HERO fleet screen: the stored record plus each
37
+ * robot's open fault / OFFLINE record and last-seen, paged. The answer has
38
+ * `pages` and `total` (read them with `listMeta` - never `totalPages`).
39
+ */
40
+ function getSiteFleet(
41
+ organization: string,
42
+ site: string,
43
+ { page = 1, limit = 25, type = "", search = "" }: { page?: number; limit?: number; type?: string; search?: string } = {},
44
+ ) {
45
+ return useNuxtApp().$api<Record<string, any>>(
46
+ `/api/robots/organization/${organization}/site/${site}/fleet`,
47
+ { method: "GET", query: { page, limit, type: type || undefined, search: search || undefined, appSlug } },
48
+ );
49
+ }
50
+
51
+ /** The site's six summary counts (Total · Online · Working · Charging · Faults · Offline). */
52
+ function getSiteSummary(organization: string, site: string, { type = "" }: { type?: string } = {}) {
53
+ return useNuxtApp().$api<Record<string, any>>(
54
+ `/api/robots/organization/${organization}/site/${site}/summary`,
55
+ { method: "GET", query: { type: type || undefined, appSlug } },
56
+ );
57
+ }
58
+
59
+ /** One robot's record for its detail screen: names, serial, open fault. Never a credential. */
60
+ function getRobot(id: string) {
61
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}`, {
62
+ method: "GET",
63
+ query: { appSlug },
64
+ });
65
+ }
66
+
67
+ /**
68
+ * A security robot's patrol routes (ordered, named checkpoints; the one it is
69
+ * heading for) and their schedule. `supported: false` = the brand has no
70
+ * patrol interface - show "Monitoring not available", never an invented route.
71
+ */
72
+ function getPatrolRoutes(id: string) {
73
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}/patrol-routes`, {
74
+ method: "GET",
75
+ query: { appSlug },
76
+ });
77
+ }
78
+
35
79
  /**
36
80
  * Register a robot.
37
81
  *
@@ -212,7 +256,10 @@ export default function useRobots() {
212
256
  | { kind: "return" }
213
257
  | { kind: "full"; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
214
258
  | { kind: "area"; areas: string[]; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
215
- | { kind: "spot"; points: Array<{ x: number; y: number }>; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number },
259
+ | { kind: "spot"; points: Array<{ x: number; y: number }>; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
260
+ | { kind: "pause" | "resume" | "cancel" }
261
+ | { kind: "navigate"; x: number; y: number; theta?: number }
262
+ | { kind: "relocalize"; floorNo: number; x: number; y: number; theta: number },
216
263
  ) {
217
264
  return useNuxtApp().$api<Record<string, any>>(
218
265
  `/api/robots/${id}/command`,
@@ -310,6 +357,10 @@ export default function useRobots() {
310
357
  releaseLiftSession,
311
358
  getRobotLiftSession,
312
359
  getRobots,
360
+ getSiteFleet,
361
+ getSiteSummary,
362
+ getRobot,
363
+ getPatrolRoutes,
313
364
  getRobotBrands,
314
365
  trackRobot,
315
366
  createRobot,
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.29.0",
5
+ "version": "4.31.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.",
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,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
+ }