@7365admin1/layer-common 4.29.0 → 4.30.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,13 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.30.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e460aca: Robots: shared pieces for the HERO network view - Needs attention, Clients drill-down, Faults & alerts table, fault bell, live indicator, a feed-agnostic live-state store (`useRobotLive` with a 4 s polling feed, paused while the tab is hidden, swappable for a push feed), summary cells that show "—" for unmeasured values, and display helpers (split lines, since/ago text, Reconnecting instead of stale facts). Not used by any app until the org network page adopts them.
8
+
9
+ A robot with no interface now shows an UNKNOWN status chip (error tone); "No interface" appears only on the capability badge.
10
+
3
11
  ## 4.29.0
4
12
 
5
13
  ### Minor Changes
@@ -1355,11 +1363,11 @@
1355
1363
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
1356
1364
  own rule from two endpoints the console already calls, unprojected:
1357
1365
 
1358
- GET /api/members/user/:user/app/admin the Seven365 staff membership
1359
- GET /api/roles/id/:role that membership's role document
1366
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
1367
+ GET /api/roles/id/:role that membership's role document
1360
1368
 
1361
- owner = member.type === "admin" && role.type === "admin" && role.default === true
1362
- staff = member.type === "admin" && role.type === "admin"
1369
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
1370
+ staff = member.type === "admin" && role.type === "admin"
1363
1371
 
1364
1372
  `role.default` is the marker because it is the only property of a platform
1365
1373
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -428,6 +428,154 @@
428
428
  }
429
429
  .hero-toast__square { width: 8px; height: 8px; flex: none; background: var(--hero-accent); }
430
430
 
431
+ /* ------------------------------------------- network view (phase b) */
432
+
433
+ /* A whole robot page inside an app layout's padded container. */
434
+ .hero-page {
435
+ display: flex;
436
+ flex-direction: column;
437
+ gap: 20px;
438
+ margin: -24px;
439
+ padding: 20px 24px 40px;
440
+ min-height: calc(100vh - 64px);
441
+ }
442
+
443
+ /* Page head: kicker + H2 left, actions right. */
444
+ .hero-head { display: flex; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
445
+ .hero-head__spacer { flex: 1; }
446
+ .hero-head__actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
447
+
448
+ /* Header strip above the page: sub-views, live indicator, bell. */
449
+ .hero-bar {
450
+ position: relative;
451
+ display: flex;
452
+ align-items: center;
453
+ gap: 12px;
454
+ flex-wrap: wrap;
455
+ padding-bottom: 10px;
456
+ border-bottom: 2px solid var(--hero-divider);
457
+ /* the sweep travels past the right edge; clip it there, keep it on the rule */
458
+ overflow-x: clip;
459
+ overflow-y: visible;
460
+ }
461
+ .hero-bar__sweep {
462
+ position: absolute;
463
+ bottom: -2px;
464
+ height: 2px;
465
+ width: 20%;
466
+ background: linear-gradient(90deg, transparent, var(--hero-accent), transparent);
467
+ animation: heroSweep 5s linear infinite;
468
+ pointer-events: none;
469
+ }
470
+ .hero-bar__sweep--off { display: none; }
471
+ .hero-nav { display: flex; gap: 0; }
472
+ .hero-nav__item {
473
+ font: inherit;
474
+ font-size: 13px;
475
+ color: var(--hero-text);
476
+ background: transparent;
477
+ border: 0;
478
+ border-bottom: 3px solid transparent;
479
+ padding: 6px 14px;
480
+ cursor: pointer;
481
+ }
482
+ .hero-nav__item[aria-current="page"] { border-bottom-color: var(--hero-accent); font-weight: 700; background: var(--hero-surface); }
483
+ .hero-nav__item:hover { background: color-mix(in srgb, var(--hero-text) 5%, transparent); }
484
+
485
+ .hero-live { display: flex; align-items: center; gap: 8px; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
486
+ .hero-live__dot { width: 8px; height: 8px; display: inline-block; background: var(--hero-accent); animation: heroPulse 2s ease-out infinite; }
487
+ .hero-live__dot--off { background: var(--hero-neutral-300); animation: none; }
488
+
489
+ .hero-bell.v-btn { gap: 8px; padding: 5px 10px; min-height: 0; height: auto; }
490
+ .hero-bell.v-btn .v-btn__content { gap: 8px; }
491
+ .hero-bell--on.v-btn { color: var(--hero-accent); border-color: var(--hero-accent); }
492
+
493
+ /* Two columns that stack below ~900px: main + aside. */
494
+ .hero-split { display: flex; flex-wrap: wrap; gap: 24px; align-items: flex-start; }
495
+ .hero-split__main { display: flex; flex-direction: column; gap: 12px; min-width: 0; flex: 999 1 560px; }
496
+ .hero-split__aside { display: flex; flex-direction: column; gap: 20px; min-width: 0; flex: 1 1 300px; }
497
+
498
+ /* Filters row: native controls, the handoff's look. */
499
+ .hero-filters { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
500
+ .hero-filters .hero-input { width: auto; min-height: 32px; padding: 4px 8px; font-size: 13px; }
501
+ .hero-filters .hero-input--search { width: 220px; }
502
+ /* Vuetify's reset strips the native arrow; draw one in the text colour. */
503
+ .hero-filters select.hero-input {
504
+ appearance: none;
505
+ padding-right: 26px;
506
+ background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
507
+ background-position: calc(100% - 13px) 50%, calc(100% - 9px) 50%;
508
+ background-size: 4px 4px;
509
+ background-repeat: no-repeat;
510
+ cursor: pointer;
511
+ }
512
+ .hero-filters select.hero-input:disabled { opacity: 0.5; cursor: not-allowed; }
513
+ .hero-filters__spacer { flex: 1; }
514
+ .hero-filters__label { font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; opacity: 0.6; }
515
+ .hero-check { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; cursor: pointer; white-space: nowrap; }
516
+ .hero-check input { width: 14px; height: 14px; margin: 0; accent-color: var(--hero-accent); cursor: pointer; }
517
+
518
+ /* Asides: Needs attention, Clients drill down. */
519
+ .hero-aside__head {
520
+ display: flex;
521
+ align-items: baseline;
522
+ gap: 8px;
523
+ border-top: 2px solid var(--hero-divider);
524
+ padding-top: 8px;
525
+ margin-bottom: 8px;
526
+ }
527
+ .hero-aside__title { font-size: 10px; letter-spacing: 0.12em; text-transform: uppercase; white-space: nowrap; font-weight: 600; }
528
+ .hero-aside__hint { opacity: 0.6; font-size: 11px; }
529
+ .hero-aside__count { margin-left: auto; font-size: 11px; padding: 1px 7px; background: var(--hero-accent); color: #fff; font-weight: 600; }
530
+ .hero-aside__empty { opacity: 0.6; padding: 10px 0; }
531
+ .hero-attn { display: flex; flex-direction: column; gap: 1px; background: var(--hero-divider); }
532
+ .hero-attn__item, .hero-attn__more {
533
+ display: grid;
534
+ grid-template-columns: 1fr auto;
535
+ gap: 2px 8px;
536
+ padding: 8px 10px;
537
+ font: inherit;
538
+ font-size: 12px;
539
+ text-align: left;
540
+ color: var(--hero-text);
541
+ background: var(--hero-surface);
542
+ border: 0;
543
+ cursor: pointer;
544
+ }
545
+ .hero-attn__item:hover, .hero-attn__more:hover { background: color-mix(in srgb, var(--hero-text) 5%, var(--hero-surface)); }
546
+ .hero-attn__code { color: var(--hero-accent); font-weight: 600; font-size: 11px; }
547
+ .hero-attn__msg { grid-column: 1 / -1; opacity: 0.75; }
548
+ .hero-attn__where { grid-column: 1 / -1; opacity: 0.55; font-size: 11px; }
549
+ .hero-attn__more { display: block; color: var(--hero-accent); font-weight: 600; }
550
+ .hero-drill { margin-bottom: 10px; }
551
+ .hero-drill__client { font-weight: 600; font-size: 12px; display: flex; gap: 8px; }
552
+ .hero-drill__n { opacity: 0.55; font-variant-numeric: tabular-nums; }
553
+ .hero-drill__site {
554
+ display: flex;
555
+ width: 100%;
556
+ gap: 8px;
557
+ align-items: center;
558
+ text-align: left;
559
+ border: 0;
560
+ border-bottom: 1px solid var(--hero-divider);
561
+ padding: 6px 0 6px 12px;
562
+ background: transparent;
563
+ color: var(--hero-text);
564
+ font: inherit;
565
+ font-size: 12px;
566
+ cursor: pointer;
567
+ }
568
+ .hero-drill__site:hover { background: color-mix(in srgb, var(--hero-text) 4%, transparent); }
569
+ .hero-drill__name { flex: 1; }
570
+ .hero-drill__faults { font-size: 10px; padding: 1px 6px; background: var(--hero-accent); color: #fff; font-weight: 600; }
571
+ .hero-drill__go, .hero-go { color: var(--hero-accent); }
572
+
573
+ .hero-back { font: inherit; font-size: 13px; color: var(--hero-accent); background: none; border: 0; padding: 0; cursor: pointer; }
574
+ .hero-alert__code { color: var(--hero-accent); font-weight: 700; }
575
+ .hero-dim { opacity: 0.75; }
576
+ .hero-num { font-variant-numeric: tabular-nums; white-space: nowrap; }
577
+ .hero-note { font-size: 12px; opacity: 0.6; }
578
+
431
579
  /* ----------------------------------------------------------- animations */
432
580
 
433
581
  @keyframes heroScan { from { background-position: 0 -60px; } to { background-position: 0 120%; } }
@@ -0,0 +1,72 @@
1
+ <template>
2
+ <!--
3
+ Faults & alerts: every open fault (and robot not reporting), server-paged.
4
+ Code · Message · Robot · Site · Floor · Since. Floor comes from the robot's
5
+ live state when it is known; otherwise "Floor unknown" - never a guess.
6
+ -->
7
+ <RobotTable
8
+ :headers="headers"
9
+ :items="items"
10
+ :items-length="total"
11
+ :page="page"
12
+ :items-per-page="itemsPerPage"
13
+ :loading="loading"
14
+ noun="faults"
15
+ empty-title="No active faults"
16
+ empty-hint="Alerts appear here and as notifications the moment a robot reports one."
17
+ compact
18
+ hover
19
+ @update:page="emit('update:page', $event)"
20
+ @click:row="onRow"
21
+ >
22
+ <template #item.code="{ item }"><span class="hero-alert__code">{{ attentionText(item).code }}</span></template>
23
+ <template #item.message="{ item }">{{ attentionText(item).message }}</template>
24
+ <template #item.robot="{ item }"><span class="hero-table__name">{{ item.robot?.name }}</span></template>
25
+ <template #item.site="{ item }"><span class="hero-dim">{{ item.client?.name }} · {{ item.site?.name }}</span></template>
26
+ <template #item.floor="{ item }">
27
+ <RobotFloorLabel v-bind="floorOf(item)" />
28
+ </template>
29
+ <template #item.since="{ item }"><span class="hero-dim hero-num">{{ sinceText(item.since, now) }}</span></template>
30
+ <template #item.go><span class="hero-go" aria-hidden="true">›</span></template>
31
+ </RobotTable>
32
+ </template>
33
+
34
+ <script setup lang="ts">
35
+ import RobotFloorLabel from "./FloorLabel.vue";
36
+ import RobotTable from "./Table.vue";
37
+ import { attentionText, sinceText } from "../../utils/robot-display";
38
+
39
+ const props = withDefaults(
40
+ defineProps<{
41
+ /** Rows from `GET /robots/network/faults`. */
42
+ items?: any[];
43
+ total?: number;
44
+ page?: number;
45
+ itemsPerPage?: number;
46
+ loading?: boolean;
47
+ /** Live states by robot id (`useRobotLive`), for the Floor column. */
48
+ states?: Record<string, any>;
49
+ now?: number;
50
+ }>(),
51
+ { items: () => [], total: 0, page: 1, itemsPerPage: 25, loading: false, states: () => ({}), now: () => Date.now() },
52
+ );
53
+ const emit = defineEmits<{ "update:page": [page: number]; open: [item: any] }>();
54
+
55
+ function floorOf(item: any) {
56
+ const s = props.states[String(item?.robot?._id ?? "")];
57
+ return s?.ok ? { floorNo: s.floorNo, floorKnown: s.floorKnown === true } : { floorNo: null, floorKnown: false };
58
+ }
59
+ function onRow(_e: unknown, { item }: { item: any }) {
60
+ emit("open", item);
61
+ }
62
+
63
+ const headers = [
64
+ { title: "Code", key: "code", sortable: false },
65
+ { title: "Message", key: "message", sortable: false },
66
+ { title: "Robot", key: "robot", sortable: false },
67
+ { title: "Site", key: "site", sortable: false },
68
+ { title: "Floor", key: "floor", sortable: false },
69
+ { title: "Since", key: "since", sortable: false },
70
+ { title: "", key: "go", sortable: false, align: "end" as const },
71
+ ];
72
+ </script>
@@ -0,0 +1,21 @@
1
+ <template>
2
+ <!-- The header bell: open faults network-wide; accent while any are open. -->
3
+ <v-btn
4
+ variant="outlined"
5
+ class="hero-bell"
6
+ :class="{ 'hero-bell--on': count > 0 }"
7
+ :aria-label="`${count} open ${count === 1 ? 'fault' : 'faults'}`"
8
+ @click="emit('click')"
9
+ >
10
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
11
+ <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
12
+ <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
13
+ </svg>
14
+ <span>{{ count }}</span>
15
+ </v-btn>
16
+ </template>
17
+
18
+ <script setup lang="ts">
19
+ withDefaults(defineProps<{ count?: number }>(), { count: 0 });
20
+ const emit = defineEmits<{ click: [] }>();
21
+ </script>
@@ -0,0 +1,36 @@
1
+ <template>
2
+ <!-- Clients · drill down: each client, its sites, robots per site and robots with open faults. -->
3
+ <section class="hero-aside" aria-label="Clients drill down">
4
+ <div class="hero-aside__head"><span class="hero-aside__title">Clients · drill down</span></div>
5
+ <div v-for="c in clients" :key="c._id" class="hero-drill">
6
+ <div class="hero-drill__client">
7
+ <span>{{ c.name || "Unknown client" }}</span><span class="hero-drill__n">{{ c.count }}</span>
8
+ </div>
9
+ <button
10
+ v-for="s in c.sites"
11
+ :key="s._id"
12
+ type="button"
13
+ class="hero-drill__site"
14
+ @click="emit('open', { client: c, site: s })"
15
+ >
16
+ <span class="hero-drill__name">{{ s.name || "Unknown site" }}</span>
17
+ <span class="hero-drill__n">{{ s.count }} {{ s.count === 1 ? "robot" : "robots" }}</span>
18
+ <span v-if="(s.faults ?? 0) > 0" class="hero-drill__faults" :aria-label="`${s.faults} with faults`">{{ s.faults }}</span>
19
+ <span class="hero-drill__go" aria-hidden="true">›</span>
20
+ </button>
21
+ </div>
22
+ <div v-if="!clients.length" class="hero-aside__empty">No robots at any client yet.</div>
23
+ </section>
24
+ </template>
25
+
26
+ <script setup lang="ts">
27
+ type TSite = { _id: string; name: string; count: number; faults?: number };
28
+ withDefaults(
29
+ defineProps<{
30
+ /** `[{ _id, name, count, sites: [{ _id, name, count, faults }] }]` */
31
+ clients?: Array<{ _id: string; name: string; count: number; sites: TSite[] }>;
32
+ }>(),
33
+ { clients: () => [] },
34
+ );
35
+ const emit = defineEmits<{ open: [target: { client: any; site: any }] }>();
36
+ </script>
@@ -0,0 +1,18 @@
1
+ <template>
2
+ <!-- "Live · 16:18:15" with a pulsing square; "Connection lost · retrying" when the feed is down. -->
3
+ <div class="hero-live" role="status">
4
+ <span class="hero-live__dot" :class="{ 'hero-live__dot--off': !connected }" aria-hidden="true" />
5
+ <span>{{ connected ? `Live · ${clock}` : "Connection lost · retrying" }}</span>
6
+ </div>
7
+ </template>
8
+
9
+ <script setup lang="ts">
10
+ import { computed, onBeforeUnmount, onMounted, ref } from "vue";
11
+
12
+ withDefaults(defineProps<{ connected?: boolean }>(), { connected: true });
13
+ const now = ref(new Date());
14
+ let timer: ReturnType<typeof setInterval> | undefined;
15
+ onMounted(() => (timer = setInterval(() => (now.value = new Date()), 1000)));
16
+ onBeforeUnmount(() => clearInterval(timer));
17
+ const clock = computed(() => now.value.toTimeString().slice(0, 8));
18
+ </script>
@@ -0,0 +1,56 @@
1
+ <template>
2
+ <!--
3
+ Needs attention (Super Admin network aside): open faults first, then robots
4
+ not reporting, longest-standing first - the order the API returns. Complete
5
+ network-wide: the background sweep records faults whether or not anybody
6
+ is looking.
7
+ -->
8
+ <section class="hero-aside" aria-label="Needs attention">
9
+ <div class="hero-aside__head">
10
+ <span class="hero-aside__title">Needs attention</span>
11
+ <span class="hero-aside__hint">most urgent first</span>
12
+ <span v-if="total > 0" class="hero-aside__count">{{ total }}</span>
13
+ </div>
14
+ <div v-if="loading && !items.length" class="hero-skel" aria-hidden="true">
15
+ <div v-for="i in 3" :key="i" class="hero-skel__row" />
16
+ </div>
17
+ <div v-else-if="!items.length" class="hero-aside__empty">Nothing needs attention.</div>
18
+ <div v-else class="hero-attn">
19
+ <button
20
+ v-for="item in items"
21
+ :key="item._id"
22
+ type="button"
23
+ class="hero-attn__item"
24
+ @click="emit('open', item)"
25
+ >
26
+ <b class="hero-attn__name">{{ item.robot?.name }}</b>
27
+ <span class="hero-attn__code">{{ attentionText(item).code }}</span>
28
+ <span class="hero-attn__msg">{{ attentionText(item).message }}</span>
29
+ <span class="hero-attn__where">
30
+ {{ item.client?.name }} · {{ item.site?.name }} · {{ item.offline ? agoText(item.since, now) : sinceText(item.since, now) }}
31
+ </span>
32
+ </button>
33
+ <button v-if="total > items.length" type="button" class="hero-attn__more" @click="emit('more')">
34
+ {{ total - items.length }} more · Faults &amp; alerts ›
35
+ </button>
36
+ </div>
37
+ </section>
38
+ </template>
39
+
40
+ <script setup lang="ts">
41
+ import { agoText, attentionText, sinceText } from "../../utils/robot-display";
42
+
43
+ withDefaults(
44
+ defineProps<{
45
+ /** Rows from `GET /robots/network/faults`. */
46
+ items?: any[];
47
+ /** Every open fault network-wide (the API's `total`), not just those shown. */
48
+ total?: number;
49
+ loading?: boolean;
50
+ /** Epoch ms the "since" text is measured from (the page's clock tick). */
51
+ now?: number;
52
+ }>(),
53
+ { items: () => [], total: 0, loading: false, now: () => Date.now() },
54
+ );
55
+ const emit = defineEmits<{ open: [item: any]; more: [] }>();
56
+ </script>
@@ -3,7 +3,7 @@
3
3
  <span class="hero-cell__corner hero-cell__corner--tl" aria-hidden="true" />
4
4
  <span class="hero-cell__corner hero-cell__corner--br" aria-hidden="true" />
5
5
  <div class="hero-cell__label"><span class="hero-cell__square" aria-hidden="true" />{{ label }}</div>
6
- <div class="hero-cell__value" :aria-label="`${label}: ${value}`">{{ shown }}</div>
6
+ <div class="hero-cell__value" :aria-label="`${label}: ${unknown ? 'not known yet' : value}`">{{ unknown ? "—" : shown }}</div>
7
7
  <div class="hero-cell__ticks" aria-hidden="true">
8
8
  <span
9
9
  v-for="i in 20"
@@ -24,7 +24,8 @@ import { countUpValue, summaryAlert, summaryTicks } from "../../utils/robot-disp
24
24
  const props = withDefaults(
25
25
  defineProps<{
26
26
  label: string;
27
- value: number;
27
+ /** null = not known (e.g. live counts before the first sweep): shows "—", never 0. */
28
+ value: number | null;
28
29
  /** What the tick bar is a ratio of. */
29
30
  total?: number;
30
31
  /** "faults" / "offline" turn accent when above zero. */
@@ -35,12 +36,13 @@ const props = withDefaults(
35
36
  { total: 0, kind: "", split: "", duration: 900 },
36
37
  );
37
38
 
39
+ const unknown = computed(() => typeof props.value !== "number");
38
40
  const filled = computed(() => summaryTicks(props.value, props.total));
39
41
  const alert = computed(() => summaryAlert(props.kind, props.value));
40
42
 
41
43
  // The count-up and the tick reveal share one clock.
42
44
  const elapsed = ref(0);
43
- const shown = computed(() => countUpValue(props.value, elapsed.value, props.duration));
45
+ const shown = computed(() => countUpValue(props.value ?? 0, elapsed.value, props.duration));
44
46
  const progress = computed(() => Math.min(1, elapsed.value / props.duration));
45
47
 
46
48
  let frame = 0;
@@ -11,7 +11,7 @@ import RobotSummaryCell from "./SummaryCell.vue";
11
11
 
12
12
  withDefaults(
13
13
  defineProps<{
14
- cells?: Array<{ label: string; value: number; total?: number; kind?: string; split?: string }>;
14
+ cells?: Array<{ label: string; value: number | null; total?: number; kind?: string; split?: string }>;
15
15
  label?: string;
16
16
  }>(),
17
17
  { cells: () => [], label: "Fleet summary" },
@@ -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,121 @@
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
+ * `states[id]` for every robot in `ids`, kept live by `feed`. Re-watches when
94
+ * the ids change (a new page, a new filter); stops on unmount.
95
+ */
96
+ export default function useRobotLive(ids: Ref<string[]>, feed: TRobotLiveFeed) {
97
+ const states = ref<Record<string, TLiveRobotState>>({});
98
+ const connected = ref(true);
99
+ const lastAt = ref<Date | null>(null);
100
+ let stop: (() => void) | null = null;
101
+
102
+ watch(
103
+ () => ids.value.join(","),
104
+ () => {
105
+ stop?.();
106
+ const list = [...ids.value];
107
+ stop = feed.watch(
108
+ list,
109
+ (items) => {
110
+ states.value = mergeLiveStates(states.value, items);
111
+ lastAt.value = new Date();
112
+ },
113
+ (up) => (connected.value = up),
114
+ );
115
+ },
116
+ { immediate: true },
117
+ );
118
+ onBeforeUnmount(() => stop?.());
119
+
120
+ return { states, connected, lastAt };
121
+ }
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.30.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
+ }
@@ -514,3 +514,92 @@ export function credentialPlaceholder(saved: unknown): string {
514
514
  export function heroThemeName(appThemeIsDark: unknown): "hero-dark" | "hero-light" {
515
515
  return appThemeIsDark === true ? "hero-dark" : "hero-light";
516
516
  }
517
+
518
+ /* ============================================ network view (HERO phase b) */
519
+
520
+ /** "43 cleaning · 16 security" from `[{ key, count }]`; empty classes are left out. */
521
+ export function splitLine(byType: Array<{ key?: unknown; count?: unknown }> | null | undefined): string {
522
+ return (byType ?? [])
523
+ .filter((t) => typeof t?.count === "number" && (t.count as number) > 0)
524
+ .map((t) => `${t.count} ${t.key}`)
525
+ .join(" · ");
526
+ }
527
+
528
+ /** "0 s ago" / "12 min ago" / "21 h ago" / "3 d ago"; "" when unknown. */
529
+ export function agoText(at: unknown, now: number = Date.now()): string {
530
+ const t = at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : NaN;
531
+ if (!Number.isFinite(t)) return "";
532
+ const s = Math.max(0, Math.round((now - t) / 1000));
533
+ if (s < 60) return `${s} s ago`;
534
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
535
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
536
+ return `${Math.floor(s / 86400)} d ago`;
537
+ }
538
+
539
+ /** "15:58 · 20 min" - when a fault started and how long it has stood (the handoff's Since). */
540
+ export function sinceText(at: unknown, now: number = Date.now()): string {
541
+ const t = at instanceof Date ? at.getTime() : typeof at === "string" || typeof at === "number" ? new Date(at).getTime() : NaN;
542
+ if (!Number.isFinite(t)) return "";
543
+ const clock = new Date(t).toTimeString().slice(0, 5);
544
+ const ago = agoText(t, now).replace(/ ago$/, "").replace(/^(\d+) s$/, "now");
545
+ return `${clock} · ${ago}`;
546
+ }
547
+
548
+ /** A Needs attention / alerts row's code and words: an OFFLINE record reads "Not reporting". */
549
+ export function attentionText(item: { code?: unknown; message?: unknown; offline?: unknown } | null | undefined) {
550
+ if (!item) return { code: "", message: "" };
551
+ if (item.offline === true || item.code === "OFFLINE") return { code: "OFFLINE", message: "Not reporting" };
552
+ return { code: String(item.code ?? ""), message: String(item.message || item.code || "") };
553
+ }
554
+
555
+ export type TLiveRobotState = {
556
+ id: string;
557
+ /** false = the robot's cloud did not answer this poll: show "Reconnecting", never old facts. */
558
+ ok: boolean;
559
+ /** false = its brand has no interface: nothing to show, ever. */
560
+ monitorable?: boolean;
561
+ online?: boolean;
562
+ mode?: string;
563
+ batteryPercent?: number | null;
564
+ floorNo?: number | null;
565
+ floorKnown?: boolean;
566
+ position?: { x: number; y: number; theta: number } | null;
567
+ fault?: { code: string; message?: string; since?: number } | null;
568
+ capabilities?: Record<string, unknown>;
569
+ lastSeenAt?: string | null;
570
+ };
571
+
572
+ /**
573
+ * Fold one poll's answer into the live map. A robot that did not answer
574
+ * REPLACES its old state with `{ ok: false }`: a stale battery or position
575
+ * must never stay on screen as if live. Robots not in this answer keep theirs.
576
+ */
577
+ export function mergeLiveStates(
578
+ prev: Record<string, TLiveRobotState>,
579
+ items: Array<Partial<TLiveRobotState> & { id?: unknown }> | null | undefined,
580
+ ): Record<string, TLiveRobotState> {
581
+ const next = { ...prev };
582
+ for (const item of items ?? []) {
583
+ if (!item || typeof item.id !== "string") continue;
584
+ next[item.id] = item.ok === true ? ({ ...item, ok: true } as TLiveRobotState) : { id: item.id, ok: false, monitorable: item.monitorable !== false };
585
+ }
586
+ return next;
587
+ }
588
+
589
+ /**
590
+ * What the Status cell says for a row: the live mode when read; "Reconnecting"
591
+ * when the last poll got no answer; "Offline" from the stored record while no
592
+ * live answer exists; UNKNOWN (error tone) for a brand with nothing to read -
593
+ * "No interface" is the capability badge's word, never a status; null while
594
+ * still checking. One state per chip.
595
+ */
596
+ export function rowStatus(
597
+ row: { offline?: unknown } | null | undefined,
598
+ live: TLiveRobotState | null | undefined,
599
+ ): { kind: "live" | "reconnecting" | "offline" | "none" | "checking"; mode?: string } {
600
+ if (live?.ok) return live.online === false ? { kind: "live", mode: "UNAVAILABLE" } : { kind: "live", mode: live.mode };
601
+ if (live && live.monitorable === false) return { kind: "none", mode: "UNKNOWN" };
602
+ if (live && !live.ok) return { kind: "reconnecting" };
603
+ if (row?.offline === true) return { kind: "offline" };
604
+ return { kind: "checking" };
605
+ }