@7365admin1/layer-common 4.21.4-staging.347 → 4.21.4-staging.348

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.
@@ -0,0 +1,329 @@
1
+ <template>
2
+ <PageHeader :title="title">
3
+ <template #actions>
4
+ <AppButton v-if="canAdd" @click="dialog = true">Add Robot</AppButton>
5
+ </template>
6
+ </PageHeader>
7
+
8
+ <v-row no-gutters>
9
+ <v-col cols="12">
10
+ <AppCard class="table-card">
11
+ <CardToolbar :count="pageRange">
12
+ <template #left>
13
+ <AppButton
14
+ variant="icon"
15
+ icon="mdi-refresh"
16
+ aria-label="Refresh"
17
+ :loading="loading"
18
+ @click="load()"
19
+ />
20
+ <AppField
21
+ v-model="search"
22
+ search
23
+ compact
24
+ placeholder="Search robots"
25
+ klass="app-toolbar__search"
26
+ @update:model-value="onSearch"
27
+ />
28
+ </template>
29
+ <template #right>
30
+ <LocalPagination v-model="page" :length="pages" @update:model-value="load()" />
31
+ </template>
32
+ </CardToolbar>
33
+
34
+ <!--
35
+ The empty state distinguishes "nothing registered yet" from "we could
36
+ not load" - the two look identical if you only render an empty table,
37
+ and they need opposite actions from the person looking at the screen.
38
+ -->
39
+ <v-alert
40
+ v-if="error"
41
+ type="error"
42
+ variant="tonal"
43
+ class="ma-4"
44
+ :text="error"
45
+ />
46
+
47
+ <div v-else-if="!loading && !items.length" class="robot-empty">
48
+ <v-icon size="56" class="mb-3">mdi-robot-outline</v-icon>
49
+ <p class="text-subtitle-1 font-weight-medium mb-1">No robots yet</p>
50
+ <p class="text-body-2 text-medium-emphasis mb-4">
51
+ {{
52
+ canAdd
53
+ ? "Add a robot to see it here and send it to clean."
54
+ : "No robots have been added to this site yet."
55
+ }}
56
+ </p>
57
+ <AppButton v-if="canAdd" @click="dialog = true">Add Robot</AppButton>
58
+ </div>
59
+
60
+ <div v-else class="app-table-scroll">
61
+ <v-data-table
62
+ :loading="loading"
63
+ :headers="headers"
64
+ :items="items"
65
+ :items-per-page="limit"
66
+ fixed-header
67
+ hide-default-footer
68
+ style="max-height: calc(100vh - 200px)"
69
+ >
70
+ <template #item.name="{ item }">
71
+ <div class="d-flex align-center">
72
+ <v-icon size="20" color="primary" class="mr-3">mdi-robot-outline</v-icon>
73
+ <div>
74
+ <div class="font-weight-medium">{{ item.name }}</div>
75
+ <div class="text-caption text-medium-emphasis">
76
+ {{ item.robotSn || "Serial not yet known" }}
77
+ </div>
78
+ </div>
79
+ </div>
80
+ </template>
81
+
82
+ <template #item.state="{ item }">
83
+ <!--
84
+ Live state is fetched per robot AFTER the list renders. The list
85
+ itself comes from our database and is fast; each state call
86
+ crosses to the vendor's cloud. Blocking the table on the slowest
87
+ robot would make the whole screen feel broken.
88
+ -->
89
+ <v-chip v-if="!states[item._id]" size="small" label variant="tonal">
90
+ <v-progress-circular indeterminate size="12" width="2" class="mr-2" />
91
+ Checking
92
+ </v-chip>
93
+ <v-chip
94
+ v-else
95
+ size="small"
96
+ label
97
+ :color="display(item).color"
98
+ variant="tonal"
99
+ >
100
+ <v-icon start size="16">{{ display(item).icon }}</v-icon>
101
+ {{ display(item).label }}
102
+ </v-chip>
103
+ </template>
104
+
105
+ <template #item.floor="{ item }">
106
+ <span class="text-body-2 text-medium-emphasis">
107
+ {{ floorLabel(states[item._id]) }}
108
+ </span>
109
+ </template>
110
+
111
+ <template #item.actions="{ item }">
112
+ <div class="d-flex justify-end ga-2">
113
+ <AppButton
114
+ v-if="canCommand"
115
+ size="small"
116
+ variant="outlined"
117
+ :disabled="!canDispatch(states[item._id]) || busy === item._id"
118
+ :loading="busy === item._id && lastCommand === 'full'"
119
+ @click="send(item, { kind: 'full' }, 'full')"
120
+ >
121
+ Clean
122
+ </AppButton>
123
+ <AppButton
124
+ v-if="canCommand"
125
+ size="small"
126
+ variant="text"
127
+ :disabled="!canRecall(states[item._id]) || busy === item._id"
128
+ :loading="busy === item._id && lastCommand === 'return'"
129
+ @click="send(item, { kind: 'return' }, 'return')"
130
+ >
131
+ Return to dock
132
+ </AppButton>
133
+ </div>
134
+ </template>
135
+
136
+ <template #bottom />
137
+ </v-data-table>
138
+ </div>
139
+ </AppCard>
140
+ </v-col>
141
+ </v-row>
142
+
143
+ <Snackbar v-model="toast" :text="toastText" :color="toastColor" />
144
+
145
+ <v-dialog v-model="dialog" width="460" persistent>
146
+ <RobotForm
147
+ :organization="organization"
148
+ :site="site"
149
+ :type="robotType"
150
+ @cancel="dialog = false"
151
+ @created="onCreated"
152
+ />
153
+ </v-dialog>
154
+ </template>
155
+
156
+ <script lang="ts" setup>
157
+ /**
158
+ * The fleet screen, shared by every application that shows robots.
159
+ *
160
+ * One component rather than a copy per app, so Property Management, Hygiene,
161
+ * the Seven365 console and the two mobile apps cannot drift into describing the
162
+ * same robot four different ways.
163
+ *
164
+ * What each app changes is only what it passes in: which robot `type` it
165
+ * presents, and which actions its user holds a permission for. The API narrows
166
+ * the result again on its own side, so a cleaning app asking for security robots
167
+ * gets nothing back rather than being trusted.
168
+ */
169
+ import {
170
+ canDispatch,
171
+ canRecall,
172
+ floorLabel,
173
+ robotDisplay,
174
+ robotErrorMessage,
175
+ } from "../../utils/robot-display";
176
+
177
+ const props = withDefaults(
178
+ defineProps<{
179
+ organization: string;
180
+ site: string;
181
+ /** Which class of robot this application presents. */
182
+ robotType?: "cleaning" | "security";
183
+ title?: string;
184
+ canAdd?: boolean;
185
+ /** Whether this user may dispatch. Reads and writes are separate grants. */
186
+ canCommand?: boolean;
187
+ }>(),
188
+ { robotType: "cleaning", title: "Robots", canAdd: false, canCommand: false },
189
+ );
190
+
191
+ const { getRobots, getRobotState, sendRobotCommand } = useRobots();
192
+
193
+ // The house pattern is a local Snackbar with local state, as
194
+ // `AccessCardPreviewDialog.vue` does - there is no global toast composable.
195
+ const toast = ref(false);
196
+ const toastText = ref("");
197
+ const toastColor = ref<"success" | "error">("success");
198
+
199
+ function showToast(message: string, color: "success" | "error") {
200
+ toastText.value = message;
201
+ toastColor.value = color;
202
+ toast.value = true;
203
+ }
204
+
205
+ const items = ref<Array<Record<string, any>>>([]);
206
+ const states = ref<Record<string, any>>({});
207
+ const loading = ref(false);
208
+ const error = ref("");
209
+ const search = ref("");
210
+ const page = ref(1);
211
+ const pages = ref(1);
212
+ const limit = 10;
213
+ const dialog = ref(false);
214
+ const busy = ref("");
215
+ const lastCommand = ref("");
216
+
217
+ const headers = [
218
+ { title: "Robot", value: "name", sortable: false },
219
+ { title: "Status", value: "state", sortable: false },
220
+ { title: "Floor", value: "floor", sortable: false },
221
+ { title: "", value: "actions", sortable: false, align: "end" as const },
222
+ ];
223
+
224
+ const pageRange = computed(() => {
225
+ if (!items.value.length) return "0 of 0";
226
+ const from = (page.value - 1) * limit + 1;
227
+ return `${from} - ${from + items.value.length - 1}`;
228
+ });
229
+
230
+ const display = (item: Record<string, any>) =>
231
+ robotDisplay(states.value[item._id]?.mode);
232
+
233
+ async function load() {
234
+ loading.value = true;
235
+ error.value = "";
236
+ try {
237
+ const res = await getRobots({
238
+ organization: props.organization,
239
+ site: props.site,
240
+ search: search.value,
241
+ page: page.value,
242
+ limit,
243
+ type: props.robotType,
244
+ });
245
+ items.value = res?.items ?? [];
246
+ pages.value = Math.max(1, Number(res?.totalPages ?? 1));
247
+ // Deliberately not awaited: the table renders from our own database
248
+ // immediately, and each robot's chip fills in as its cloud call returns.
249
+ loadStates();
250
+ } catch (e) {
251
+ error.value = robotErrorMessage(e, "Could not load the robots for this site.");
252
+ items.value = [];
253
+ } finally {
254
+ loading.value = false;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * One state call per robot, each failing on its own.
260
+ *
261
+ * `allSettled`, not `all`: one robot that is off must not blank the status of
262
+ * every other robot on the site.
263
+ */
264
+ async function loadStates() {
265
+ states.value = {};
266
+ await Promise.allSettled(
267
+ items.value.map(async (robot) => {
268
+ try {
269
+ states.value = { ...states.value, [robot._id]: await getRobotState(robot._id) };
270
+ } catch {
271
+ states.value = {
272
+ ...states.value,
273
+ [robot._id]: { mode: "UNAVAILABLE", online: false, dispatchable: false },
274
+ };
275
+ }
276
+ }),
277
+ );
278
+ }
279
+
280
+ async function send(robot: Record<string, any>, command: any, kind: string) {
281
+ busy.value = robot._id;
282
+ lastCommand.value = kind;
283
+ try {
284
+ await sendRobotCommand(robot._id, command);
285
+ showToast(
286
+ kind === "return"
287
+ ? `${robot.name} is returning to its dock.`
288
+ : `${robot.name} has been sent to clean.`,
289
+ "success",
290
+ );
291
+ // Re-read rather than assume: the API returns no job id, so the robot's own
292
+ // state is the only truthful confirmation that anything happened.
293
+ states.value = { ...states.value, [robot._id]: await getRobotState(robot._id) };
294
+ } catch (e) {
295
+ showToast(robotErrorMessage(e), "error");
296
+ } finally {
297
+ busy.value = "";
298
+ lastCommand.value = "";
299
+ }
300
+ }
301
+
302
+ let searchTimer: ReturnType<typeof setTimeout> | undefined;
303
+ function onSearch() {
304
+ clearTimeout(searchTimer);
305
+ searchTimer = setTimeout(() => {
306
+ page.value = 1;
307
+ load();
308
+ }, 350);
309
+ }
310
+
311
+ function onCreated() {
312
+ dialog.value = false;
313
+ page.value = 1;
314
+ load();
315
+ }
316
+
317
+ onMounted(load);
318
+ </script>
319
+
320
+ <style scoped>
321
+ .robot-empty {
322
+ display: flex;
323
+ flex-direction: column;
324
+ align-items: center;
325
+ justify-content: center;
326
+ text-align: center;
327
+ padding: 56px 16px;
328
+ }
329
+ </style>
@@ -0,0 +1,170 @@
1
+ <template>
2
+ <v-card width="100%">
3
+ <v-toolbar density="comfortable" class="pl-4 py-2">
4
+ <span class="font-weight-medium text-h6">Add {{ typeLabel }} robot</span>
5
+ </v-toolbar>
6
+
7
+ <v-card-text class="pa-0" style="max-height: 70vh; overflow-y: auto">
8
+ <v-form ref="form" @submit.prevent="submit">
9
+ <v-row no-gutters class="px-6 pt-4">
10
+ <v-col cols="12" class="mb-2">
11
+ <p class="text-body-2 text-medium-emphasis">
12
+ The app key and token come from your robot supplier. They are used
13
+ to talk to the robot and are never shown again once saved.
14
+ </p>
15
+ </v-col>
16
+
17
+ <v-col cols="12">
18
+ <InputLabel class="font-weight-bold" title="Name" required />
19
+ <v-text-field
20
+ v-model="name"
21
+ density="comfortable"
22
+ placeholder="e.g. Cleaner 02"
23
+ :rules="[requiredRule]"
24
+ :disabled="saving"
25
+ />
26
+ </v-col>
27
+
28
+ <v-col cols="12">
29
+ <InputLabel class="font-weight-bold" title="App key" required />
30
+ <v-text-field
31
+ v-model="appKey"
32
+ density="comfortable"
33
+ autocomplete="off"
34
+ :rules="[requiredRule]"
35
+ :disabled="saving"
36
+ />
37
+ </v-col>
38
+
39
+ <v-col cols="12">
40
+ <InputLabel class="font-weight-bold" title="App token" required />
41
+ <!--
42
+ Masked like a password because that is what it is: this token signs
43
+ every command sent to the estate's robots. It is never returned by
44
+ any read, so it cannot be recovered from the screen later either.
45
+ -->
46
+ <v-text-field
47
+ v-model="appToken"
48
+ density="comfortable"
49
+ autocomplete="off"
50
+ :type="reveal ? 'text' : 'password'"
51
+ :append-inner-icon="reveal ? 'mdi-eye-off-outline' : 'mdi-eye-outline'"
52
+ :rules="[requiredRule]"
53
+ :disabled="saving"
54
+ @click:append-inner="reveal = !reveal"
55
+ />
56
+ </v-col>
57
+
58
+ <v-col cols="12">
59
+ <InputLabel class="font-weight-bold" title="Serial number" />
60
+ <v-text-field
61
+ v-model="robotSn"
62
+ density="comfortable"
63
+ placeholder="Optional — found automatically if left blank"
64
+ :disabled="saving"
65
+ />
66
+ <p class="text-caption text-medium-emphasis mt-n3 mb-2">
67
+ Leave this blank unless the same key covers more than one robot.
68
+ </p>
69
+ </v-col>
70
+
71
+ <v-col cols="12" v-if="error">
72
+ <v-alert type="error" variant="tonal" class="mb-3" :text="error" />
73
+ </v-col>
74
+ </v-row>
75
+ </v-form>
76
+ </v-card-text>
77
+
78
+ <v-toolbar density="compact">
79
+ <v-row no-gutters>
80
+ <v-col cols="6">
81
+ <v-btn
82
+ tile block variant="flat" size="48"
83
+ class="text-none" color="#EFEFEF"
84
+ :disabled="saving"
85
+ @click="$emit('cancel')"
86
+ >
87
+ Close
88
+ </v-btn>
89
+ </v-col>
90
+ <v-col cols="6">
91
+ <v-btn
92
+ tile block variant="flat" size="48"
93
+ class="text-none" color="primary"
94
+ :loading="saving"
95
+ @click="submit"
96
+ >
97
+ Add robot
98
+ </v-btn>
99
+ </v-col>
100
+ </v-row>
101
+ </v-toolbar>
102
+ </v-card>
103
+ </template>
104
+
105
+ <script lang="ts" setup>
106
+ /**
107
+ * Register a robot against a site.
108
+ *
109
+ * The credential pair travels up once and is never returned by any read, so
110
+ * there is deliberately no edit-credentials path here: a wrong key is fixed by
111
+ * removing the robot and adding it again, which is honest about the fact that
112
+ * the old value is gone.
113
+ *
114
+ * The serial is optional because the supplier's Add-Robot flow has never asked
115
+ * for one. When it is blank the server finds it from the robot cloud — and
116
+ * refuses rather than guessing if the key covers more than one machine, which is
117
+ * exactly when the person filling this in should type it themselves.
118
+ */
119
+ import { robotErrorMessage } from "../../utils/robot-display";
120
+
121
+ const props = withDefaults(
122
+ defineProps<{
123
+ organization: string;
124
+ site: string;
125
+ type?: "cleaning" | "security";
126
+ }>(),
127
+ { type: "cleaning" },
128
+ );
129
+
130
+ const emit = defineEmits<{ cancel: []; created: [] }>();
131
+
132
+ const { createRobot } = useRobots();
133
+ const { requiredRule } = useUtils();
134
+
135
+ const form = ref();
136
+ const name = ref("");
137
+ const appKey = ref("");
138
+ const appToken = ref("");
139
+ const robotSn = ref("");
140
+ const reveal = ref(false);
141
+ const saving = ref(false);
142
+ const error = ref("");
143
+
144
+ const typeLabel = computed(() => (props.type === "security" ? "security" : "cleaning"));
145
+
146
+ async function submit() {
147
+ const { valid } = await form.value?.validate?.() ?? { valid: false };
148
+ if (!valid) return;
149
+
150
+ saving.value = true;
151
+ error.value = "";
152
+ try {
153
+ await createRobot({
154
+ name: name.value.trim(),
155
+ appKey: appKey.value.trim(),
156
+ appToken: appToken.value.trim(),
157
+ type: props.type,
158
+ // Sent only when the person typed one; an empty string would otherwise be
159
+ // stored and stop the server ever discovering the real serial.
160
+ ...(robotSn.value.trim() ? { robotSn: robotSn.value.trim() } : {}),
161
+ metadata: { orgId: props.organization, siteId: props.site },
162
+ });
163
+ emit("created");
164
+ } catch (e) {
165
+ error.value = robotErrorMessage(e, "Could not add the robot.");
166
+ } finally {
167
+ saving.value = false;
168
+ }
169
+ }
170
+ </script>
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The cleaning robots at a site.
3
+ *
4
+ * Two halves, matching the API. `/api/robots` manages the RECORD — register a
5
+ * robot, list an estate's robots. `/api/robots/:id/*` manages the ROBOT itself,
6
+ * and every one of those calls reaches the vendor's cloud, so they are slower
7
+ * and they can fail for reasons that have nothing to do with us (the robot is
8
+ * off, the cloud is unreachable, the credentials were rotated). Screens should
9
+ * show what the failure was rather than an empty list.
10
+ *
11
+ * `appSlug` is sent on the reads so the API narrows the result to the robot
12
+ * types this application presents: a cleaning app never sees a security patrol.
13
+ * It is a visibility rule, not a security boundary — the boundary is the session
14
+ * and the permission — but sending it consistently is what keeps the screens
15
+ * honest.
16
+ */
17
+ export default function useRobots() {
18
+ const appSlug = useRuntimeConfig().public?.appSlug as string | undefined;
19
+
20
+ /** The estate's robots. Credentials are never in this response. */
21
+ async function getRobots({
22
+ organization = "",
23
+ site = "",
24
+ search = "",
25
+ page = 1,
26
+ limit = 10,
27
+ type = "",
28
+ } = {}) {
29
+ return useNuxtApp().$api<Record<string, any>>(
30
+ `/api/robots/organization/${organization}/site/${site}`,
31
+ { method: "GET", query: { search, page, limit, type, appSlug } },
32
+ );
33
+ }
34
+
35
+ /**
36
+ * Register a robot.
37
+ *
38
+ * `appKey` and `appToken` are the vendor cloud credentials. They go up once,
39
+ * are never returned by any read, and must never be put into a query string,
40
+ * a log line or a toast.
41
+ */
42
+ function createRobot(payload: {
43
+ name: string;
44
+ appKey: string;
45
+ appToken: string;
46
+ type?: "cleaning" | "security";
47
+ robotSn?: string;
48
+ metadata: { orgId: string; siteId: string; administratorId?: string };
49
+ }) {
50
+ return useNuxtApp().$api<Record<string, any>>("/api/robots", {
51
+ method: "POST",
52
+ body: payload,
53
+ });
54
+ }
55
+
56
+ /** Live state — mode, online, whether it can take a job right now. */
57
+ function getRobotState(id: string) {
58
+ return useNuxtApp().$api<Record<string, any>>(
59
+ `/api/robots/${id}/state`,
60
+ { method: "GET", query: { appSlug } },
61
+ );
62
+ }
63
+
64
+ /** The robot's floors, their areas and their metre/pixel transform. */
65
+ function getRobotMaps(id: string) {
66
+ return useNuxtApp().$api<Record<string, any>>(
67
+ `/api/robots/${id}/maps`,
68
+ { method: "GET", query: { appSlug } },
69
+ );
70
+ }
71
+
72
+ /**
73
+ * Signed image URLs for a map's layers.
74
+ *
75
+ * Fetched at the moment of display and never stored: the vendor signs them for
76
+ * about an hour, so a URL kept in a record is a URL that stops working. If a
77
+ * floor plan has gone blank, ask for the URLs again rather than caching harder.
78
+ */
79
+ function getRobotMapImages(id: string, fileKeys: string[]) {
80
+ return useNuxtApp().$api<Record<string, any>>(
81
+ `/api/robots/${id}/map-images`,
82
+ { method: "POST", query: { appSlug }, body: { fileKeys } },
83
+ );
84
+ }
85
+
86
+ /** The cleaning schedule the vendor cloud holds for this robot. */
87
+ function getRobotPlans(id: string) {
88
+ return useNuxtApp().$api<Record<string, any>>(
89
+ `/api/robots/${id}/plans`,
90
+ { method: "GET", query: { appSlug } },
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Send the robot to work, or bring it home.
96
+ *
97
+ * The API accepts exactly one outstanding job per robot and returns no job id,
98
+ * so a screen cannot track a command after sending it — it re-reads the state.
99
+ * A robot that is not idle is refused by the server with a readable reason;
100
+ * show that reason rather than a generic failure.
101
+ */
102
+ function sendRobotCommand(
103
+ id: string,
104
+ command:
105
+ | { kind: "return" }
106
+ | { kind: "full"; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
107
+ | { kind: "area"; areas: string[]; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
108
+ | { kind: "spot"; points: Array<{ x: number; y: number }>; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number },
109
+ ) {
110
+ return useNuxtApp().$api<Record<string, any>>(
111
+ `/api/robots/${id}/command`,
112
+ { method: "POST", query: { appSlug }, body: command },
113
+ );
114
+ }
115
+
116
+ return {
117
+ getRobots,
118
+ createRobot,
119
+ getRobotState,
120
+ getRobotMaps,
121
+ getRobotMapImages,
122
+ getRobotPlans,
123
+ sendRobotCommand,
124
+ };
125
+ }
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.21.4-staging.347",
5
+ "version": "4.21.4-staging.348",
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.",
@@ -36,7 +36,7 @@
36
36
  "build": "nuxt build .playground",
37
37
  "generate": "nuxt generate .playground",
38
38
  "preview": "nuxt preview .playground",
39
- "test": "esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
39
+ "test": "esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && esbuild utils/robot-display.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-display.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
40
40
  "test:units": "node --experimental-strip-types --test \"utils/*.test.ts\"",
41
41
  "release": "yarn run build && changeset publish"
42
42
  },
@@ -0,0 +1,123 @@
1
+ /**
2
+ * How a robot's state is shown to a person.
3
+ *
4
+ * The API answers with a mode from a fixed vocabulary; every screen turns that
5
+ * into the same words and the same colour, so a cleaner on a phone and a manager
6
+ * on a desktop are never looking at two different descriptions of one robot.
7
+ *
8
+ * Pure on purpose: the interesting part is the failure wording, and none of it
9
+ * needs Nuxt, a network or a robot to test.
10
+ */
11
+
12
+ export type TRobotMode =
13
+ | "IDLE"
14
+ | "CHARGED"
15
+ | "WORKING"
16
+ | "PAUSED"
17
+ | "CHARGING_CYCLE"
18
+ | "MAINTENANCE"
19
+ | "IN_TRANSIT"
20
+ | "MANUAL"
21
+ | "UNAVAILABLE";
22
+
23
+ export type TRobotDisplay = {
24
+ /** What the person reads. */
25
+ label: string;
26
+ /** A Vuetify colour token, not a hex — the theme decides the shade. */
27
+ color: string;
28
+ icon: string;
29
+ /** True only when the robot could be given a job this moment. */
30
+ ready: boolean;
31
+ };
32
+
33
+ const DISPLAY: Readonly<Record<TRobotMode, TRobotDisplay>> = {
34
+ IDLE: { label: "Ready", color: "success", icon: "mdi-check-circle-outline", ready: true },
35
+ CHARGED: { label: "Charged", color: "success", icon: "mdi-battery-charging-100", ready: true },
36
+ WORKING: { label: "Cleaning", color: "primary", icon: "mdi-broom", ready: false },
37
+ PAUSED: { label: "Paused", color: "warning", icon: "mdi-pause-circle-outline", ready: false },
38
+ CHARGING_CYCLE: { label: "Charging", color: "info", icon: "mdi-battery-charging", ready: false },
39
+ MAINTENANCE: { label: "Maintenance", color: "warning", icon: "mdi-wrench-outline", ready: false },
40
+ IN_TRANSIT: { label: "Changing floor", color: "info", icon: "mdi-elevator-passenger-outline", ready: false },
41
+ MANUAL: { label: "Manual control", color: "warning", icon: "mdi-hand-back-right-outline", ready: false },
42
+ UNAVAILABLE: { label: "Unavailable", color: "error", icon: "mdi-alert-circle-outline", ready: false },
43
+ };
44
+
45
+ const UNKNOWN: TRobotDisplay = {
46
+ label: "Unknown",
47
+ color: "error",
48
+ icon: "mdi-help-circle-outline",
49
+ ready: false,
50
+ };
51
+
52
+ /**
53
+ * A mode we do not recognise shows as "Unknown" and is NEVER ready.
54
+ *
55
+ * The branch that matters. A firmware state this build has not seen must not
56
+ * render as a green "Ready" chip with a Clean button beside it — a person would
57
+ * press it, and the robot would refuse, and the screen would look broken.
58
+ */
59
+ export function robotDisplay(mode: unknown): TRobotDisplay {
60
+ if (typeof mode !== "string") return UNKNOWN;
61
+ return DISPLAY[mode as TRobotMode] ?? UNKNOWN;
62
+ }
63
+
64
+ /**
65
+ * May the Clean / Return buttons be offered?
66
+ *
67
+ * Offline beats everything: a robot we cannot reach cannot be commanded,
68
+ * whatever its last known mode said.
69
+ */
70
+ export function canDispatch(state: {
71
+ online?: unknown;
72
+ dispatchable?: unknown;
73
+ mode?: unknown;
74
+ } | null | undefined): boolean {
75
+ if (!state) return false;
76
+ if (state.online === false) return false;
77
+ // The server already decided this; the client agrees rather than re-deriving,
78
+ // so the two can never disagree about whether a button should be there.
79
+ return state.dispatchable === true;
80
+ }
81
+
82
+ /**
83
+ * Return-to-dock is offered even when a robot is busy.
84
+ *
85
+ * It is how an operator recovers a robot, so it has to be reachable precisely
86
+ * when the robot is doing something wrong. Only an unreachable robot hides it.
87
+ */
88
+ export function canRecall(state: { online?: unknown } | null | undefined): boolean {
89
+ if (!state) return false;
90
+ return state.online !== false;
91
+ }
92
+
93
+ /**
94
+ * The floor to show, when the robot does not report one.
95
+ *
96
+ * The vendor's tracking stream carries no floor, so anything claiming to know it
97
+ * must say how sure it is. An unknown floor is shown as unknown rather than
98
+ * guessed — a robot displayed on the wrong storey is worse than one displayed
99
+ * on no storey.
100
+ */
101
+ export function floorLabel(state: {
102
+ floorNo?: unknown;
103
+ floorKnown?: unknown;
104
+ } | null | undefined): string {
105
+ if (!state || state.floorKnown !== true) return "Floor unknown";
106
+ return typeof state.floorNo === "number" ? `Floor ${state.floorNo}` : "Floor unknown";
107
+ }
108
+
109
+ /**
110
+ * Turn a failed fleet call into something worth reading.
111
+ *
112
+ * These calls cross to the vendor's cloud, so the useful message is usually the
113
+ * server's own — "Robot X is Cleaning and cannot take a new job" tells an
114
+ * operator what to do; "Request failed" does not.
115
+ */
116
+ export function robotErrorMessage(error: unknown, fallback = "Could not reach the robot."): string {
117
+ const e = error as any;
118
+ const fromServer =
119
+ e?.data?.message ?? e?.response?._data?.message ?? e?.data?.msg;
120
+ if (typeof fromServer === "string" && fromServer.trim()) return fromServer.trim();
121
+ if (typeof e?.message === "string" && e.message.trim()) return e.message.trim();
122
+ return fallback;
123
+ }