@7365admin1/layer-common 4.28.1-staging.358 → 4.28.1-staging.360

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;
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.358",
5
+ "version": "4.28.1-staging.360",
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") {
@@ -42,7 +42,7 @@ import {
42
42
  } from "vuetify-pro-tiptap";
43
43
  import "vuetify-pro-tiptap/style.css";
44
44
 
45
- import { LIGHT_THEME, DARK_THEME } from "../utils/theme";
45
+ import { LIGHT_THEME, DARK_THEME, HERO_LIGHT_THEME, HERO_DARK_THEME } from "../utils/theme";
46
46
  import { MDI_TO_SYMBOL } from "../utils/materialSymbols";
47
47
  import { THEME_COOKIE } from "../composables/useThemePreference";
48
48
  import type { CookieOptions } from "#app";
@@ -175,6 +175,13 @@ export default defineNuxtPlugin((app) => {
175
175
  * theme rather than a blank one.
176
176
  */
177
177
  iservice365: LIGHT_THEME,
178
+ /**
179
+ * The robot fleet's HERO look (owner decision 2026-09-23). Never a
180
+ * default: only `components/Robot/Hero.vue` asks for these, through a
181
+ * `v-theme-provider`, so every other screen keeps the themes above.
182
+ */
183
+ "hero-light": HERO_LIGHT_THEME,
184
+ "hero-dark": HERO_DARK_THEME,
178
185
  },
179
186
  },
180
187
  icons: {
@@ -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
+ }
@@ -210,3 +210,307 @@ export function planSummary(plan: Record<string, any> | null | undefined) {
210
210
  jobs,
211
211
  };
212
212
  }
213
+
214
+ /* ==========================================================================
215
+ * HERO robot fleet - the rules behind the shared components in
216
+ * `components/Robot/`. Every decision a HERO component makes is one of these
217
+ * functions; the components only call them and draw the answer.
218
+ *
219
+ * Colours are named as HERO theme colours (`utils/theme.ts`), never hexes.
220
+ * ======================================================================== */
221
+
222
+ export type TRobotType = "cleaning" | "security";
223
+
224
+ /** A HERO theme colour a status or state is drawn in. `ink` = text as a fill. */
225
+ export type THeroTone = "success" | "warning" | "info" | "error" | "ink" | "accent";
226
+
227
+ export type THeroStatus = {
228
+ label: string;
229
+ tone: THeroTone;
230
+ /** The chip's dot blinks while the robot is doing something. */
231
+ blink: boolean;
232
+ };
233
+
234
+ /** Modes during which the robot is moving or changing state on its own. */
235
+ const BLINKING: ReadonlySet<string> = new Set(["WORKING", "IN_TRANSIT", "CHARGING_CYCLE", "MANUAL"]);
236
+
237
+ /**
238
+ * The status chip: the exact label, its tone and whether its dot blinks.
239
+ *
240
+ * Built on `robotDisplay` so the words can never drift from the existing
241
+ * screens. One HERO rule on top: a SECURITY robot that is working is
242
+ * "Patrolling", not "Cleaning". The tone is `robotDisplay`'s colour with the
243
+ * handoff's one substitution - its "primary" (Cleaning/Patrolling) is ink.
244
+ */
245
+ export function robotStatus(mode: unknown, type?: unknown): THeroStatus {
246
+ const d = robotDisplay(mode);
247
+ return {
248
+ label: mode === "WORKING" && type === "security" ? "Patrolling" : d.label,
249
+ tone: d.color === "primary" ? "ink" : (d.color as THeroTone),
250
+ blink: typeof mode === "string" && BLINKING.has(mode),
251
+ };
252
+ }
253
+
254
+ /**
255
+ * The battery reading, or null - and null means RENDER NOTHING.
256
+ *
257
+ * A brand that cannot measure its battery must not show "0%", which reads as
258
+ * flat. Only a finite number counts; it is clamped to 0-100 and rounded.
259
+ * Fill: >=45 success, 20-44 warning, <20 accent.
260
+ */
261
+ export function batteryReading(value: unknown): { pct: number; tone: THeroTone; text: string } | null {
262
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
263
+ const pct = Math.round(Math.min(Math.max(value, 0), 100));
264
+ const tone: THeroTone = pct >= 45 ? "success" : pct >= 20 ? "warning" : "accent";
265
+ return { pct, tone, text: `${pct}%` };
266
+ }
267
+
268
+ /**
269
+ * Every command the platform can send, and the brand capability it needs - a
270
+ * copy of core's `COMMAND_NEEDS` (`robot-adapter.util.ts`). The capability
271
+ * badge is measured against THIS list: it is about what a robot will DO when
272
+ * told, never about what it reports.
273
+ */
274
+ const COMMAND_NEEDS: Readonly<Record<string, string>> = {
275
+ full: "startProcess",
276
+ area: "startProcess",
277
+ spot: "spotClean",
278
+ return: "sendToDock",
279
+ pause: "pauseProcess",
280
+ resume: "pauseProcess",
281
+ cancel: "pauseProcess",
282
+ navigate: "navigateToPoint",
283
+ relocalize: "relocalize",
284
+ };
285
+
286
+ /** Telemetry a brand may declare - reporting only, never a command. */
287
+ const TELEMETRY = ["readLocation", "battery", "floorReporting", "pathAndEta", "processCompletion"];
288
+
289
+ export type TCapabilityLevel = "Full control" | "Basic control" | "Read-only" | "No interface";
290
+
291
+ /**
292
+ * The capability badge (owner rule, 2026-09-23): COMMAND level, never telemetry.
293
+ *
294
+ * - Full control: accepts every command (Demo);
295
+ * - Basic control: accepts some commands but not all (Ounitech: clean all / area, dock);
296
+ * - Read-only: reports telemetry but accepts no command;
297
+ * - No interface: no connection at all - nothing declared (the security robot today).
298
+ *
299
+ * Derived from the brand's declared capabilities (`/robots/:id/state` or
300
+ * `/robots/brands`), NOT core's Open-RMF `robotTier`, which weighs telemetry.
301
+ * Missing / unknown capabilities claim the least.
302
+ */
303
+ export function capabilityLabel(capabilities: Record<string, unknown> | null | undefined): TCapabilityLevel {
304
+ const caps = capabilities && typeof capabilities === "object" ? capabilities : {};
305
+ const kinds = Object.keys(COMMAND_NEEDS);
306
+ const accepted = kinds.filter((k) => caps[COMMAND_NEEDS[k]!] === true).length;
307
+ if (accepted === kinds.length) return "Full control";
308
+ if (accepted > 0) return "Basic control";
309
+ return TELEMETRY.some((t) => caps[t] === true) ? "Read-only" : "No interface";
310
+ }
311
+
312
+ /** The badge: Full control is outlined accent; the rest neutral; No interface struck through. */
313
+ export function capabilityBadge(capabilities: Record<string, unknown> | null | undefined): {
314
+ label: TCapabilityLevel;
315
+ variant: "outline" | "neutral" | "struck";
316
+ } {
317
+ const label = capabilityLabel(capabilities);
318
+ const variant = label === "Full control" ? "outline" : label === "No interface" ? "struck" : "neutral";
319
+ return { label, variant };
320
+ }
321
+
322
+ /** The facts a brand may or may not report, in the order the "Not reported" line lists them. */
323
+ const REPORTED_FACTS: ReadonlyArray<{ fact: "battery" | "floor" | "position"; needs: string }> = [
324
+ { fact: "battery", needs: "battery" },
325
+ { fact: "floor", needs: "floorReporting" },
326
+ { fact: "position", needs: "readLocation" },
327
+ ];
328
+
329
+ /** Which facts this brand reports - a fact cell it cannot fill says "Not reported". */
330
+ export function reportedFacts(capabilities: Record<string, unknown> | null | undefined) {
331
+ const caps = capabilities ?? {};
332
+ return Object.fromEntries(REPORTED_FACTS.map((f) => [f.fact, caps[f.needs] === true])) as Record<
333
+ "battery" | "floor" | "position",
334
+ boolean
335
+ >;
336
+ }
337
+
338
+ /**
339
+ * "Not reported by Ounitech: battery, floor" - shown on robot detail so a
340
+ * missing fact reads as the brand's limit, not a fault. The brand's trailing
341
+ * model list ("Ounitech (Q3-G / Q3-W)") is dropped. Null when nothing is missing.
342
+ */
343
+ export function notReportedLine(brand: unknown, capabilities: Record<string, unknown> | null | undefined): string | null {
344
+ const facts = reportedFacts(capabilities);
345
+ const missing = REPORTED_FACTS.filter((f) => !facts[f.fact]).map((f) => f.fact);
346
+ if (!missing.length) return null;
347
+ const name = (typeof brand === "string" ? brand : "").replace(/\s*\([^)]*\)\s*$/, "").trim() || "this brand";
348
+ return `Not reported by ${name}: ${missing.join(", ")}`;
349
+ }
350
+
351
+ export type TRobotCommandKind =
352
+ | "full"
353
+ | "area"
354
+ | "return"
355
+ | "pause"
356
+ | "resume"
357
+ | "cancel"
358
+ | "navigate"
359
+ | "relocalize";
360
+
361
+ /**
362
+ * The command bar's buttons, in bar order; each needs `COMMAND_NEEDS[kind]`.
363
+ * `spot` is not here: spot clean is the plan's own control (`SpotClean.vue`).
364
+ */
365
+ const COMMANDS: ReadonlyArray<{ kind: TRobotCommandKind; label: string }> = [
366
+ { kind: "full", label: "Clean all" },
367
+ { kind: "area", label: "Clean area" },
368
+ { kind: "return", label: "Return to dock" },
369
+ { kind: "pause", label: "Pause" },
370
+ { kind: "resume", label: "Resume" },
371
+ { kind: "cancel", label: "Cancel" },
372
+ { kind: "navigate", label: "Go to point" },
373
+ { kind: "relocalize", label: "Set position" },
374
+ ];
375
+
376
+ export type TRobotCommand = { kind: TRobotCommandKind; label: string; primary: boolean };
377
+
378
+ /**
379
+ * The command bar's buttons - HIDDEN, never greyed, when any rule says no.
380
+ *
381
+ * - brand: only commands its declared capabilities support;
382
+ * - role: only a Manager (`canCommand`, i.e. the app's command permission);
383
+ * - online: only a robot confirmed online (`online === true`);
384
+ * - context: Pause only while working, Resume only while paused;
385
+ * - type: a security robot has no cleaning jobs, so no Clean all / Clean area.
386
+ *
387
+ * Returns [] whenever the bar should not render at all.
388
+ */
389
+ export function visibleCommands(input: {
390
+ capabilities?: Record<string, unknown> | null;
391
+ canCommand?: unknown;
392
+ online?: unknown;
393
+ mode?: unknown;
394
+ type?: unknown;
395
+ } | null | undefined): TRobotCommand[] {
396
+ if (!input || input.canCommand !== true || input.online !== true) return [];
397
+ const caps = input.capabilities ?? {};
398
+ return COMMANDS.filter((c) => {
399
+ if (caps[COMMAND_NEEDS[c.kind]!] !== true) return false;
400
+ if (c.kind === "pause" && input.mode !== "WORKING") return false;
401
+ if (c.kind === "resume" && input.mode !== "PAUSED") return false;
402
+ if ((c.kind === "full" || c.kind === "area") && input.type === "security") return false;
403
+ return true;
404
+ }).map((c) => ({ kind: c.kind, label: c.label, primary: c.kind === "full" }));
405
+ }
406
+
407
+ /**
408
+ * One key per fault OCCURRENCE, so an alert fires once per occurrence.
409
+ *
410
+ * The same code clearing and coming back later is a new occurrence (a new
411
+ * `since`), so it alerts again; the same fault seen on every poll is not.
412
+ * With no `since`, the message stands in. No fault -> null (nothing to alert).
413
+ */
414
+ export function faultKey(
415
+ robotId: unknown,
416
+ fault: { code?: unknown; message?: unknown; since?: unknown } | null | undefined,
417
+ ): string | null {
418
+ if (!fault || (robotId !== 0 && !robotId)) return null;
419
+ const code = typeof fault.code === "string" ? fault.code.trim() : "";
420
+ const message = typeof fault.message === "string" ? fault.message.trim() : "";
421
+ if (!code && !message) return null;
422
+ const since = fault.since instanceof Date ? fault.since.toISOString() : fault.since;
423
+ const when = typeof since === "string" || typeof since === "number" ? String(since) : message;
424
+ return `${robotId}|${code}|${when}`;
425
+ }
426
+
427
+ /** True the first time a fault occurrence is seen; records it in `seen`. */
428
+ export function shouldNotifyFault(key: string | null, seen: Set<string>): boolean {
429
+ if (!key || seen.has(key)) return false;
430
+ seen.add(key);
431
+ return true;
432
+ }
433
+
434
+ /**
435
+ * The table footer. `page` is 1-based (Vuetify's); out-of-range pages clamp.
436
+ * "Showing 1–10 of 60 robots"; nothing to show reads "No robots".
437
+ */
438
+ export function pageRange(page: unknown, perPage: unknown, total: unknown, noun = "robots") {
439
+ const size = typeof perPage === "number" && perPage > 0 ? Math.floor(perPage) : 10;
440
+ const count = typeof total === "number" && total > 0 ? Math.floor(total) : 0;
441
+ const pages = Math.max(1, Math.ceil(count / size));
442
+ const asked = typeof page === "number" && page >= 1 ? Math.floor(page) : 1;
443
+ const p = Math.min(asked, pages);
444
+ const from = count ? (p - 1) * size + 1 : 0;
445
+ const to = Math.min(p * size, count);
446
+ return {
447
+ page: p,
448
+ pages,
449
+ from,
450
+ to,
451
+ total: count,
452
+ hasPrev: p > 1,
453
+ hasNext: p < pages,
454
+ text: count ? `Showing ${from}–${to} of ${count} ${noun}` : `No ${noun}`,
455
+ };
456
+ }
457
+
458
+ /** How many of a summary cell's tick segments are filled: value/total of 20. */
459
+ export function summaryTicks(value: unknown, total: unknown, segments = 20): number {
460
+ const v = typeof value === "number" && value > 0 ? value : 0;
461
+ const t = typeof total === "number" && total > 0 ? total : 0;
462
+ if (!t) return 0;
463
+ return Math.round(Math.min(1, v / t) * segments);
464
+ }
465
+
466
+ /** Faults and Offline turn accent (and blink) when there are any; all else is ink. */
467
+ export function summaryAlert(kind: unknown, value: unknown): boolean {
468
+ return (kind === "faults" || kind === "offline") && typeof value === "number" && value > 0;
469
+ }
470
+
471
+ /**
472
+ * The count-up: `target` after `elapsed` of `duration` ms, ease-out cubic.
473
+ * Whole numbers only - a robot count is never 12.4.
474
+ */
475
+ export function countUpValue(target: number, elapsed: number, duration = 900): number {
476
+ if (!(duration > 0) || elapsed >= duration) return target;
477
+ const t = Math.max(0, elapsed) / duration;
478
+ return Math.round(target * (1 - Math.pow(1 - t, 3)));
479
+ }
480
+
481
+ export type TLiftState = "requested" | "riding" | "released" | "timed out";
482
+
483
+ /**
484
+ * A lift-queue row's chip tone and its bottom progress stripe:
485
+ * riding = fast moving stripe, requested = slow, timed out = solid accent,
486
+ * released = none.
487
+ */
488
+ export function liftState(state: unknown): { label: string; tone: THeroTone; stripe: "fast" | "slow" | "solid" | "none" } {
489
+ switch (state) {
490
+ case "requested": return { label: "requested", tone: "info", stripe: "slow" };
491
+ case "riding": return { label: "riding", tone: "ink", stripe: "fast" };
492
+ case "released": return { label: "released", tone: "success", stripe: "none" };
493
+ case "timed out": return { label: "timed out", tone: "error", stripe: "solid" };
494
+ default: return { label: "unknown", tone: "error", stripe: "none" };
495
+ }
496
+ }
497
+
498
+ /** The map editor's tools, in toolbar order. */
499
+ export const MAP_TOOLS = [
500
+ { id: "wall", label: "Wall" },
501
+ { id: "zone", label: "Zone" },
502
+ { id: "door", label: "Door" },
503
+ { id: "lift", label: "Lift shaft" },
504
+ { id: "move", label: "Move" },
505
+ { id: "delete", label: "Delete" },
506
+ ] as const;
507
+
508
+ /** A write-only credential's placeholder: once saved it is acknowledged, never shown. */
509
+ export function credentialPlaceholder(saved: unknown): string {
510
+ return saved === true ? "Saved · hidden. Enter to replace" : "Paste from the brand portal";
511
+ }
512
+
513
+ /** The HERO theme for the app's current light/dark setting. */
514
+ export function heroThemeName(appThemeIsDark: unknown): "hero-dark" | "hero-light" {
515
+ return appThemeIsDark === true ? "hero-dark" : "hero-light";
516
+ }