@7365admin1/layer-common 4.24.0 → 4.26.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,41 @@
1
1
  # @iservice365/layer-common
2
2
 
3
+ ## 4.26.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a4e0317: Robots: edit and remove, schedule, spot clean on the floor plan, faults, stacked levels
8
+
9
+ - `RobotFleet` gains a row menu: Schedule (read-only view of the robot's plans),
10
+ Spot clean (only for brands whose state reports `capabilities.spotClean`),
11
+ Edit (name, serial) and Remove, behind new `canEdit` / `canDelete` props.
12
+ - A robot's reported fault is shown under its status chip.
13
+ - `RobotMap3D` offers "All levels (stacked)" when a robot maps more than one
14
+ floor; the view fits the whole stack.
15
+ - `useRobots` gains `updateRobot` and `deleteRobot`.
16
+
17
+ ## 4.25.0
18
+
19
+ ### Minor Changes
20
+
21
+ - a227cdf: Robot screens: brand picker, live positions, and cleaning by area
22
+
23
+ The Add Robot form now asks which brand a robot is, offering each with what its
24
+ protocol actually allows in plain words. There is no safe default — sending a
25
+ robot a command in another brand's protocol is the one mistake the adapter layer
26
+ exists to prevent — so a brand is preselected only when there is no choice.
27
+
28
+ The fleet screen follows each robot's position while it is open, via the
29
+ `/track` stream, and stops every stream on unmount: the server holds one
30
+ connection to the robot cloud for each open one.
31
+
32
+ Losing a stream marks a robot `UNAVAILABLE` rather than leaving its last known
33
+ mode, which would advertise it as ready for work forever.
34
+
35
+ Adds "Clean area", so zones can be chosen from the robot's own maps rather than
36
+ cleaning everything. Battery is shown only when the brand reports one — a brand
37
+ that cannot measure it must not render as 0%, which reads as flat.
38
+
3
39
  ## 4.24.0
4
40
 
5
41
  ### Minor Changes
@@ -1301,11 +1337,11 @@
1301
1337
  `utils/console-tier.ts` + `composables/useConsoleTier.ts` mirror the server's
1302
1338
  own rule from two endpoints the console already calls, unprojected:
1303
1339
 
1304
- GET /api/members/user/:user/app/admin the Seven365 staff membership
1305
- GET /api/roles/id/:role that membership's role document
1340
+ GET /api/members/user/:user/app/admin the Seven365 staff membership
1341
+ GET /api/roles/id/:role that membership's role document
1306
1342
 
1307
- owner = member.type === "admin" && role.type === "admin" && role.default === true
1308
- staff = member.type === "admin" && role.type === "admin"
1343
+ owner = member.type === "admin" && role.type === "admin" && role.default === true
1344
+ staff = member.type === "admin" && role.type === "admin"
1309
1345
 
1310
1346
  `role.default` is the marker because it is the only property of a platform
1311
1347
  staff role no API caller can set - `role.controller.ts` validates create and
@@ -100,12 +100,31 @@
100
100
  <v-icon start size="16">{{ display(item).icon }}</v-icon>
101
101
  {{ display(item).label }}
102
102
  </v-chip>
103
+ <!-- The robot's own fault, in its words, under the chip. -->
104
+ <div
105
+ v-if="robotFaultText(states[item._id])"
106
+ class="text-caption text-error mt-1"
107
+ >
108
+ {{ robotFaultText(states[item._id]) }}
109
+ </div>
103
110
  </template>
104
111
 
105
112
  <template #item.floor="{ item }">
106
- <span class="text-body-2 text-medium-emphasis">
107
- {{ floorLabel(states[item._id]) }}
108
- </span>
113
+ <div class="d-flex flex-column">
114
+ <span class="text-body-2 text-medium-emphasis">
115
+ {{ floorLabel(states[item._id]) }}
116
+ </span>
117
+ <!--
118
+ Battery is shown only when the brand reports one. A brand that
119
+ cannot measure it must not render as 0% - which reads as flat.
120
+ -->
121
+ <span
122
+ v-if="typeof states[item._id]?.batteryPercent === 'number'"
123
+ class="text-caption text-medium-emphasis"
124
+ >
125
+ {{ states[item._id].batteryPercent }}% battery
126
+ </span>
127
+ </div>
109
128
  </template>
110
129
 
111
130
  <template #item.actions="{ item }">
@@ -130,9 +149,50 @@
130
149
  >
131
150
  Return to dock
132
151
  </AppButton>
152
+ <AppButton
153
+ v-if="canCommand"
154
+ size="small"
155
+ variant="text"
156
+ :disabled="!canDispatch(states[item._id]) || busy === item._id"
157
+ @click="openAreas(item)"
158
+ >
159
+ Clean area
160
+ </AppButton>
133
161
  <AppButton size="small" variant="text" @click="openMap(item)">
134
162
  View layout
135
163
  </AppButton>
164
+ <v-menu location="bottom end">
165
+ <template #activator="{ props: menu }">
166
+ <AppButton
167
+ v-bind="menu"
168
+ variant="icon"
169
+ icon="mdi-dots-vertical"
170
+ :aria-label="`More actions for ${item.name}`"
171
+ />
172
+ </template>
173
+ <v-list density="compact">
174
+ <v-list-item title="Schedule" prepend-icon="mdi-calendar-clock" @click="openPlans(item)" />
175
+ <!--
176
+ Only for a brand that can take a click on the plan. A brand
177
+ without it gets no control, not one the server refuses.
178
+ -->
179
+ <v-list-item
180
+ v-if="canCommand && brandSpotCleans(states[item._id])"
181
+ title="Spot clean"
182
+ prepend-icon="mdi-target"
183
+ :disabled="!canSpotClean(states[item._id])"
184
+ @click="openSpot(item)"
185
+ />
186
+ <v-list-item v-if="canEdit" title="Edit" prepend-icon="mdi-pencil-outline" @click="openEdit(item)" />
187
+ <v-list-item
188
+ v-if="canDelete"
189
+ title="Remove"
190
+ prepend-icon="mdi-delete-outline"
191
+ base-color="error"
192
+ @click="openRemove(item)"
193
+ />
194
+ </v-list>
195
+ </v-menu>
136
196
  </div>
137
197
  </template>
138
198
 
@@ -166,6 +226,55 @@
166
226
  </AppCard>
167
227
  </v-dialog>
168
228
 
229
+ <!--
230
+ Choosing zones rather than cleaning everything. The areas come from the
231
+ robot's own maps, so the names are the ones its operator already knows.
232
+ -->
233
+ <v-dialog v-model="areaDialog" width="520" scrollable>
234
+ <AppCard class="pa-0">
235
+ <v-toolbar density="comfortable" class="pl-4">
236
+ <span class="font-weight-medium text-h6">Clean areas — {{ areaRobot?.name }}</span>
237
+ </v-toolbar>
238
+ <v-card-text style="max-height: 55vh">
239
+ <div v-if="loadingAreas" class="py-6 text-center">
240
+ <v-progress-circular indeterminate size="28" />
241
+ </div>
242
+ <v-alert v-else-if="areaError" type="error" variant="tonal" :text="areaError" />
243
+ <div v-else-if="!areaOptions.length" class="py-6 text-center text-body-2 text-medium-emphasis">
244
+ This robot's maps define no cleaning areas.
245
+ </div>
246
+ <template v-else>
247
+ <p class="text-body-2 text-medium-emphasis mb-3">
248
+ Pick the areas to clean. The robot cleans them in the order shown.
249
+ </p>
250
+ <v-checkbox
251
+ v-for="area in areaOptions"
252
+ :key="area.value"
253
+ v-model="chosenAreas"
254
+ :value="area.value"
255
+ :label="area.title"
256
+ density="compact"
257
+ hide-details
258
+ />
259
+ </template>
260
+ </v-card-text>
261
+ <v-toolbar density="compact">
262
+ <v-row no-gutters>
263
+ <v-col cols="6">
264
+ <v-btn tile block variant="flat" size="48" class="text-none" color="#EFEFEF"
265
+ :disabled="sendingAreas" @click="areaDialog = false">Close</v-btn>
266
+ </v-col>
267
+ <v-col cols="6">
268
+ <v-btn tile block variant="flat" size="48" class="text-none" color="primary"
269
+ :loading="sendingAreas" :disabled="!chosenAreas.length" @click="sendAreas">
270
+ Clean {{ chosenAreas.length || "" }}
271
+ </v-btn>
272
+ </v-col>
273
+ </v-row>
274
+ </v-toolbar>
275
+ </AppCard>
276
+ </v-dialog>
277
+
169
278
  <v-dialog v-model="dialog" width="460" persistent>
170
279
  <RobotForm
171
280
  :organization="organization"
@@ -175,6 +284,68 @@
175
284
  @created="onCreated"
176
285
  />
177
286
  </v-dialog>
287
+
288
+ <v-dialog v-model="editDialog" width="460" persistent>
289
+ <RobotForm
290
+ v-if="editDialog && actionRobot"
291
+ :key="actionRobot._id"
292
+ :organization="organization"
293
+ :site="site"
294
+ :type="robotType"
295
+ :robot="actionRobot"
296
+ @cancel="editDialog = false"
297
+ @saved="onSaved"
298
+ />
299
+ </v-dialog>
300
+
301
+ <v-dialog v-model="plansDialog" width="560" scrollable>
302
+ <AppCard class="pa-0">
303
+ <v-toolbar density="comfortable" class="pl-4">
304
+ <span class="font-weight-medium text-h6">Schedule — {{ actionRobot?.name }}</span>
305
+ <v-spacer />
306
+ <AppButton variant="icon" icon="mdi-close" aria-label="Close" @click="plansDialog = false" />
307
+ </v-toolbar>
308
+ <RobotPlans v-if="plansDialog && actionRobot" :key="actionRobot._id" :robot-id="actionRobot._id" />
309
+ </AppCard>
310
+ </v-dialog>
311
+
312
+ <v-dialog v-model="spotDialog" width="720" scrollable>
313
+ <AppCard class="pa-0">
314
+ <v-toolbar density="comfortable" class="pl-4">
315
+ <span class="font-weight-medium text-h6">Spot clean — {{ actionRobot?.name }}</span>
316
+ </v-toolbar>
317
+ <RobotSpotClean
318
+ v-if="spotDialog && actionRobot"
319
+ :key="actionRobot._id"
320
+ :robot-id="actionRobot._id"
321
+ :robot-name="actionRobot.name"
322
+ @close="spotDialog = false"
323
+ @sent="onSpotSent"
324
+ />
325
+ </AppCard>
326
+ </v-dialog>
327
+
328
+ <ConfirmDialog v-model="removeDialog" :loading="removing">
329
+ <template #title>Remove {{ actionRobot?.name }}?</template>
330
+ <template #description>
331
+ It stops appearing here and can no longer be sent to clean. To use it
332
+ again, add it back with its app key and token.
333
+ </template>
334
+ <template #footer>
335
+ <v-row no-gutters class="w-100">
336
+ <v-col cols="6" class="pr-2">
337
+ <v-btn block variant="outlined" class="text-none" :disabled="removing" @click="removeDialog = false">
338
+ Cancel
339
+ </v-btn>
340
+ </v-col>
341
+ <v-col cols="6" class="pl-2">
342
+ <v-btn block variant="flat" color="error" class="text-none" :loading="removing" @click="confirmRemove">
343
+ Remove
344
+ </v-btn>
345
+ </v-col>
346
+ </v-row>
347
+ </template>
348
+ </ConfirmDialog>
178
349
  </template>
179
350
 
180
351
  <script lang="ts" setup>
@@ -191,11 +362,14 @@
191
362
  * gets nothing back rather than being trusted.
192
363
  */
193
364
  import {
365
+ brandSpotCleans,
194
366
  canDispatch,
195
367
  canRecall,
368
+ canSpotClean,
196
369
  floorLabel,
197
370
  robotDisplay,
198
371
  robotErrorMessage,
372
+ robotFaultText,
199
373
  } from "../../utils/robot-display";
200
374
 
201
375
  const props = withDefaults(
@@ -208,11 +382,84 @@ const props = withDefaults(
208
382
  canAdd?: boolean;
209
383
  /** Whether this user may dispatch. Reads and writes are separate grants. */
210
384
  canCommand?: boolean;
385
+ /** `robot-mgmt:update-robot` - rename a robot or set its serial. */
386
+ canEdit?: boolean;
387
+ /** `robot-mgmt:delete-robot` - remove a robot. */
388
+ canDelete?: boolean;
211
389
  }>(),
212
- { robotType: "cleaning", title: "Robots", canAdd: false, canCommand: false },
390
+ {
391
+ robotType: "cleaning",
392
+ title: "Robots",
393
+ canAdd: false,
394
+ canCommand: false,
395
+ canEdit: false,
396
+ canDelete: false,
397
+ },
213
398
  );
214
399
 
215
- const { getRobots, getRobotState, sendRobotCommand } = useRobots();
400
+ const { getRobots, getRobotState, sendRobotCommand, getRobotMaps, trackRobot, deleteRobot } =
401
+ useRobots();
402
+
403
+ /* ---- the row menu: schedule, spot clean, edit, remove ------------------ */
404
+
405
+ const actionRobot = ref<Record<string, any> | null>(null);
406
+ const plansDialog = ref(false);
407
+ const spotDialog = ref(false);
408
+ const editDialog = ref(false);
409
+ const removeDialog = ref(false);
410
+ const removing = ref(false);
411
+
412
+ function openPlans(robot: Record<string, any>) {
413
+ actionRobot.value = robot;
414
+ plansDialog.value = true;
415
+ }
416
+ function openSpot(robot: Record<string, any>) {
417
+ actionRobot.value = robot;
418
+ spotDialog.value = true;
419
+ }
420
+ function openEdit(robot: Record<string, any>) {
421
+ actionRobot.value = robot;
422
+ editDialog.value = true;
423
+ }
424
+ function openRemove(robot: Record<string, any>) {
425
+ actionRobot.value = robot;
426
+ removeDialog.value = true;
427
+ }
428
+
429
+ async function onSpotSent(message: string) {
430
+ spotDialog.value = false;
431
+ showToast(message, "success");
432
+ const robot = actionRobot.value;
433
+ if (!robot) return;
434
+ // Re-read: the API returns no job id, so the robot's own state is the proof.
435
+ try {
436
+ states.value = { ...states.value, [robot._id]: await getRobotState(robot._id) };
437
+ } catch {
438
+ // The command was accepted; a failed re-read only leaves the old chip.
439
+ }
440
+ }
441
+
442
+ function onSaved() {
443
+ editDialog.value = false;
444
+ showToast("Robot saved.", "success");
445
+ load();
446
+ }
447
+
448
+ async function confirmRemove() {
449
+ const robot = actionRobot.value;
450
+ if (!robot) return;
451
+ removing.value = true;
452
+ try {
453
+ await deleteRobot(robot._id);
454
+ removeDialog.value = false;
455
+ showToast(`${robot.name} has been removed.`, "success");
456
+ load();
457
+ } catch (e) {
458
+ showToast(robotErrorMessage(e, "Could not remove the robot."), "error");
459
+ } finally {
460
+ removing.value = false;
461
+ }
462
+ }
216
463
 
217
464
  // The house pattern is a local Snackbar with local state, as
218
465
  // `AccessCardPreviewDialog.vue` does - there is no global toast composable.
@@ -238,6 +485,107 @@ const dialog = ref(false);
238
485
  const mapDialog = ref(false);
239
486
  const mapRobot = ref<Record<string, any> | null>(null);
240
487
 
488
+ const areaDialog = ref(false);
489
+ const areaRobot = ref<Record<string, any> | null>(null);
490
+ const areaOptions = ref<Array<{ title: string; value: string }>>([]);
491
+ const chosenAreas = ref<string[]>([]);
492
+ const loadingAreas = ref(false);
493
+ const sendingAreas = ref(false);
494
+ const areaError = ref("");
495
+
496
+ /** One open stream per robot, so they can all be stopped on unmount. */
497
+ const streams = new Map<string, { stop: () => void }>();
498
+
499
+ async function openAreas(robot: Record<string, any>) {
500
+ areaRobot.value = robot;
501
+ chosenAreas.value = [];
502
+ areaOptions.value = [];
503
+ areaError.value = "";
504
+ areaDialog.value = true;
505
+ loadingAreas.value = true;
506
+ try {
507
+ const res = await getRobotMaps(robot._id);
508
+ // Areas are per floor, and the same name can appear on more than one, so
509
+ // they are labelled with their floor rather than silently de-duplicated.
510
+ const options: Array<{ title: string; value: string }> = [];
511
+ for (const map of res?.items ?? []) {
512
+ for (const area of map.areaList ?? []) {
513
+ options.push({
514
+ title: `${area.areaName} — ${map.mapName?.trim() || `Floor ${map.floorNo}`}`,
515
+ value: area.areaName,
516
+ });
517
+ }
518
+ }
519
+ areaOptions.value = options;
520
+ } catch (e) {
521
+ areaError.value = robotErrorMessage(e, "Could not load this robot's areas.");
522
+ } finally {
523
+ loadingAreas.value = false;
524
+ }
525
+ }
526
+
527
+ async function sendAreas() {
528
+ const robot = areaRobot.value;
529
+ if (!robot || !chosenAreas.value.length) return;
530
+ sendingAreas.value = true;
531
+ try {
532
+ await sendRobotCommand(robot._id, { kind: "area", areas: [...chosenAreas.value] });
533
+ showToast(`${robot.name} has been sent to clean ${chosenAreas.value.length} area(s).`, "success");
534
+ areaDialog.value = false;
535
+ // Re-read rather than assume: the API returns no job id, so the robot's own
536
+ // state is the only truthful confirmation anything happened.
537
+ states.value = { ...states.value, [robot._id]: await getRobotState(robot._id) };
538
+ } catch (e) {
539
+ showToast(robotErrorMessage(e), "error");
540
+ } finally {
541
+ sendingAreas.value = false;
542
+ }
543
+ }
544
+
545
+ /**
546
+ * Follow each robot's position while this screen is open.
547
+ *
548
+ * The server holds one connection to the robot cloud for as long as each of
549
+ * these is open, so they are all stopped on unmount - leaving them running
550
+ * would consume the vendor's stream budget for a screen nobody is looking at.
551
+ */
552
+ function watchRobots() {
553
+ stopWatching();
554
+ for (const robot of items.value) {
555
+ streams.set(
556
+ robot._id,
557
+ trackRobot(robot._id, (event) => {
558
+ if (event?.type === "pose" && event.pose) {
559
+ const current = states.value[robot._id] ?? {};
560
+ states.value = {
561
+ ...states.value,
562
+ [robot._id]: {
563
+ ...current,
564
+ mode: event.pose.mode ?? current.mode,
565
+ position: { x: event.pose.x, y: event.pose.y, theta: event.pose.theta },
566
+ },
567
+ };
568
+ return;
569
+ }
570
+ if (event?.type === "lost") {
571
+ // Losing the stream is not the same as the robot being idle: the last
572
+ // known mode would keep it advertised as ready for work forever.
573
+ const current = states.value[robot._id] ?? {};
574
+ states.value = {
575
+ ...states.value,
576
+ [robot._id]: { ...current, mode: "UNAVAILABLE", dispatchable: false },
577
+ };
578
+ }
579
+ }),
580
+ );
581
+ }
582
+ }
583
+
584
+ function stopWatching() {
585
+ for (const stream of streams.values()) stream.stop();
586
+ streams.clear();
587
+ }
588
+
241
589
  function openMap(robot: Record<string, any>) {
242
590
  mapRobot.value = robot;
243
591
  mapDialog.value = true;
@@ -277,7 +625,7 @@ async function load() {
277
625
  pages.value = Math.max(1, Number(res?.totalPages ?? 1));
278
626
  // Deliberately not awaited: the table renders from our own database
279
627
  // immediately, and each robot's chip fills in as its cloud call returns.
280
- loadStates();
628
+ loadStates().then(watchRobots);
281
629
  } catch (e) {
282
630
  error.value = robotErrorMessage(e, "Could not load the robots for this site.");
283
631
  items.value = [];
@@ -346,6 +694,7 @@ function onCreated() {
346
694
  }
347
695
 
348
696
  onMounted(load);
697
+ onBeforeUnmount(stopWatching);
349
698
  </script>
350
699
 
351
700
  <style scoped>
@@ -1,14 +1,20 @@
1
1
  <template>
2
2
  <v-card width="100%">
3
3
  <v-toolbar density="comfortable" class="pl-4 py-2">
4
- <span class="font-weight-medium text-h6">Add {{ typeLabel }} robot</span>
4
+ <span class="font-weight-medium text-h6">
5
+ {{ editing ? `Edit ${robot?.name ?? "robot"}` : `Add ${typeLabel} robot` }}
6
+ </span>
5
7
  </v-toolbar>
6
8
 
7
9
  <v-card-text class="pa-0" style="max-height: 70vh; overflow-y: auto">
8
10
  <v-form ref="form" @submit.prevent="submit">
9
11
  <v-row no-gutters class="px-6 pt-4">
10
12
  <v-col cols="12" class="mb-2">
11
- <p class="text-body-2 text-medium-emphasis">
13
+ <p v-if="editing" class="text-body-2 text-medium-emphasis">
14
+ Rename the robot or set its serial. To change its brand or its app
15
+ key and token, remove the robot and add it again.
16
+ </p>
17
+ <p v-else class="text-body-2 text-medium-emphasis">
12
18
  The app key and token come from your robot supplier. They are used
13
19
  to talk to the robot and are never shown again once saved.
14
20
  </p>
@@ -25,7 +31,24 @@
25
31
  />
26
32
  </v-col>
27
33
 
28
- <v-col cols="12">
34
+ <v-col v-if="!editing" cols="12">
35
+ <InputLabel class="font-weight-bold" title="Brand" required />
36
+ <AppSelect
37
+ v-model="brand"
38
+ :items="brands"
39
+ item-title="label"
40
+ item-value="brand"
41
+ density="comfortable"
42
+ :loading="loadingBrands"
43
+ :rules="[requiredRule]"
44
+ :disabled="saving"
45
+ />
46
+ <p class="text-caption text-medium-emphasis mt-n3 mb-2">
47
+ {{ brandHint }}
48
+ </p>
49
+ </v-col>
50
+
51
+ <v-col v-if="!editing" cols="12">
29
52
  <InputLabel class="font-weight-bold" title="App key" required />
30
53
  <v-text-field
31
54
  v-model="appKey"
@@ -36,7 +59,7 @@
36
59
  />
37
60
  </v-col>
38
61
 
39
- <v-col cols="12">
62
+ <v-col v-if="!editing" cols="12">
40
63
  <InputLabel class="font-weight-bold" title="App token" required />
41
64
  <!--
42
65
  Masked like a password because that is what it is: this token signs
@@ -94,7 +117,7 @@
94
117
  :loading="saving"
95
118
  @click="submit"
96
119
  >
97
- Add robot
120
+ {{ editing ? "Save" : "Add robot" }}
98
121
  </v-btn>
99
122
  </v-col>
100
123
  </v-row>
@@ -123,35 +146,98 @@ const props = withDefaults(
123
146
  organization: string;
124
147
  site: string;
125
148
  type?: "cleaning" | "security";
149
+ /** When given, the form edits this robot instead of adding one. */
150
+ robot?: Record<string, any> | null;
126
151
  }>(),
127
- { type: "cleaning" },
152
+ { type: "cleaning", robot: null },
128
153
  );
129
154
 
130
- const emit = defineEmits<{ cancel: []; created: [] }>();
155
+ const emit = defineEmits<{ cancel: []; created: []; saved: [] }>();
131
156
 
132
- const { createRobot } = useRobots();
157
+ const { createRobot, updateRobot, getRobotBrands } = useRobots();
158
+ const editing = computed(() => !!props.robot?._id);
133
159
  const { requiredRule } = useUtils();
134
160
 
135
161
  const form = ref();
136
- const name = ref("");
162
+ const name = ref(props.robot?.name ?? "");
163
+ const brand = ref("");
164
+ const brands = ref<Array<Record<string, any>>>([]);
165
+ const loadingBrands = ref(false);
137
166
  const appKey = ref("");
138
167
  const appToken = ref("");
139
- const robotSn = ref("");
168
+ const robotSn = ref(props.robot?.robotSn ?? "");
140
169
  const reveal = ref(false);
141
170
  const saving = ref(false);
142
171
  const error = ref("");
143
172
 
144
173
  const typeLabel = computed(() => (props.type === "security" ? "security" : "cleaning"));
145
174
 
175
+ /**
176
+ * What each brand's protocol will actually allow, in plain words.
177
+ *
178
+ * The tier comes from Open-RMF's published categories, so this is not a Seven365
179
+ * opinion - and somebody choosing a brand should know before they commit that
180
+ * one of them cannot be paused or told where to go.
181
+ */
182
+ const TIER_HINT: Record<string, string> = {
183
+ "full-control": "Full control — position, battery, navigation, pause and resume.",
184
+ "traffic-light": "Position, battery, and pause/resume. No navigation to a point.",
185
+ "read-only": "Position only. This brand cannot be given jobs through its API.",
186
+ "no-interface":
187
+ "Limited: the published API does not yet report battery or progress. Cleaning and return-to-dock work.",
188
+ };
189
+
190
+ const brandHint = computed(() => {
191
+ const chosen = brands.value.find((b) => b.brand === brand.value);
192
+ return chosen ? TIER_HINT[chosen.tier] ?? "" : "Which robot this is. Ask your supplier if unsure.";
193
+ });
194
+
195
+ async function loadBrands() {
196
+ loadingBrands.value = true;
197
+ try {
198
+ const res = await getRobotBrands();
199
+ brands.value = (res?.items ?? []).map((b: any) => ({
200
+ ...b,
201
+ label: b.displayName ?? b.brand,
202
+ }));
203
+ // Only preselect when there is no choice to make. Guessing a brand is how a
204
+ // robot ends up being sent commands in a protocol it does not speak.
205
+ if (brands.value.length === 1) brand.value = brands.value[0].brand;
206
+ } catch {
207
+ brands.value = [];
208
+ } finally {
209
+ loadingBrands.value = false;
210
+ }
211
+ }
212
+
213
+ onMounted(() => {
214
+ if (!editing.value) loadBrands();
215
+ });
216
+
146
217
  async function submit() {
147
218
  const { valid } = await form.value?.validate?.() ?? { valid: false };
148
219
  if (!valid) return;
149
220
 
150
221
  saving.value = true;
151
222
  error.value = "";
223
+ if (editing.value) {
224
+ try {
225
+ await updateRobot(props.robot!._id, {
226
+ name: name.value.trim(),
227
+ robotSn: robotSn.value.trim(),
228
+ });
229
+ emit("saved");
230
+ } catch (e) {
231
+ error.value = robotErrorMessage(e, "Could not save the robot.");
232
+ } finally {
233
+ saving.value = false;
234
+ }
235
+ return;
236
+ }
152
237
  try {
153
238
  await createRobot({
154
239
  name: name.value.trim(),
240
+ brand: brand.value,
155
241
  appKey: appKey.value.trim(),
156
242
  appToken: appToken.value.trim(),
157
243
  type: props.type,
@@ -104,6 +104,7 @@ import {
104
104
  gridFromImageData,
105
105
  levelSolids,
106
106
  projectPoint,
107
+ stackedElevations,
107
108
  wallCorners,
108
109
  wallsFromOccupancyGrid,
109
110
  type TView,
@@ -134,15 +135,25 @@ const tilted = ref(true);
134
135
 
135
136
  const wallCount = computed(() => solids.value.length);
136
137
 
137
- const floorOptions = computed(() =>
138
- maps.value
138
+ /**
139
+ * "All levels" stacks every floor the robot has mapped, one storey apart.
140
+ * A sentinel rather than null, because null already means "nothing chosen".
141
+ */
142
+ const ALL_LEVELS = -1_000_000;
143
+
144
+ const floorOptions = computed(() => {
145
+ const floors = maps.value
139
146
  .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: m.floorNo }))
140
- .sort((a, b) => a.value - b.value),
141
- );
147
+ .sort((a, b) => a.value - b.value);
148
+ return floors.length > 1
149
+ ? [...floors, { title: "All levels (stacked)", value: ALL_LEVELS }]
150
+ : floors;
151
+ });
152
+
153
+ const stacked = computed(() => selectedFloor.value === ALL_LEVELS);
142
154
 
143
- const currentMap = computed(() =>
144
- maps.value.find((m) => m.floorNo === selectedFloor.value) ?? null,
145
- );
155
+ /** Each floor's height in the stack; a single floor sits at zero. */
156
+ const elevations = computed(() => stackedElevations(maps.value.map((m) => Number(m.floorNo))));
146
157
 
147
158
  /* ------------------------------------------------------------------ load */
148
159
 
@@ -167,22 +178,48 @@ async function load() {
167
178
  }
168
179
  }
169
180
 
170
- /** Fetch this floor's plan, trace its walls, and extrude them. */
181
+ /**
182
+ * Fetch the selected floor's plan - or every floor's, stacked - trace the
183
+ * walls and extrude them. Stacking uses only what the robot's maps already
184
+ * return (floor number, plan image, scale, origin); floors sit one storey
185
+ * apart because the maps carry no height.
186
+ */
171
187
  async function buildLevel() {
172
- const map = currentMap.value;
173
188
  solids.value = [];
174
- if (!map?.backgroundFileKey) {
189
+ const chosen = stacked.value
190
+ ? [...maps.value].sort((a, b) => a.floorNo - b.floorNo)
191
+ : maps.value.filter((m) => m.floorNo === selectedFloor.value);
192
+
193
+ if (!chosen.length || chosen.some((m) => !m.backgroundFileKey)) {
175
194
  error.value = "This floor has no plan image.";
176
195
  return;
177
196
  }
178
197
 
179
- const files = await getRobotMapImages(props.robotId, [map.backgroundFileKey]);
180
- const url = files?.items?.find((f: any) => f.fileKey === map.backgroundFileKey)?.url;
181
- if (!url) {
182
- error.value = "The floor plan image could not be fetched.";
183
- return;
198
+ const keys = chosen.map((m) => m.backgroundFileKey);
199
+ const files = await getRobotMapImages(props.robotId, keys);
200
+
201
+ const built: TWallSolid[] = [];
202
+ for (const map of chosen) {
203
+ const url = files?.items?.find((f: any) => f.fileKey === map.backgroundFileKey)?.url;
204
+ if (!url) {
205
+ error.value = "The floor plan image could not be fetched.";
206
+ return;
207
+ }
208
+ const level = await traceLevel(map, url, stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0);
209
+ if (!level) return;
210
+ built.push(...level);
184
211
  }
185
212
 
213
+ solids.value = built;
214
+ draw();
215
+ }
216
+
217
+ /** One floor plan image to extruded wall boxes, at a given height. */
218
+ async function traceLevel(
219
+ map: Record<string, any>,
220
+ url: string,
221
+ elevationM: number,
222
+ ): Promise<TWallSolid[] | null> {
186
223
  const image = await loadImage(url);
187
224
  imageHeight.value = image.height;
188
225
 
@@ -192,7 +229,7 @@ async function buildLevel() {
192
229
  const wctx = work.getContext("2d", { willReadFrequently: true });
193
230
  if (!wctx) {
194
231
  error.value = "This browser could not read the floor plan image.";
195
- return;
232
+ return null;
196
233
  }
197
234
  wctx.drawImage(image, 0, 0);
198
235
 
@@ -200,10 +237,10 @@ async function buildLevel() {
200
237
  const grid = gridFromImageData(data, image.width, image.height);
201
238
  const { vertices, walls } = wallsFromOccupancyGrid(grid, { minRunPx: 6 });
202
239
 
203
- solids.value = levelSolids(
240
+ return levelSolids(
204
241
  {
205
242
  name: map.mapName ?? `L${map.floorNo}`,
206
- elevationM: 0,
243
+ elevationM,
207
244
  scaleMPerPx: Number(map.resolution) || 0.05,
208
245
  originXM: Number(map.originX) || 0,
209
246
  originYM: Number(map.originY) || 0,
@@ -212,8 +249,6 @@ async function buildLevel() {
212
249
  },
213
250
  image.height,
214
251
  );
215
-
216
- draw();
217
252
  }
218
253
 
219
254
  /**
@@ -257,8 +292,10 @@ function draw() {
257
292
  });
258
293
 
259
294
  // Painter's algorithm: with no depth buffer, draw order IS the depth test.
295
+ // Lower storeys first when stacked - seen from above, a floor hides the one
296
+ // beneath it, never the other way round.
260
297
  const ordered = [...solids.value].sort(
261
- (a, b) => depthOf(a.centre, view) - depthOf(b.centre, view),
298
+ (a, b) => a.centre.z - b.centre.z || depthOf(a.centre, view) - depthOf(b.centre, view),
262
299
  );
263
300
 
264
301
  for (const solid of ordered) drawBox(ctx, solid, view);
@@ -301,10 +338,12 @@ function drawRobot(ctx: CanvasRenderingContext2D, view: TView) {
301
338
  const state = props.robotState;
302
339
  const pos = state?.position;
303
340
  if (!pos || state?.floorKnown !== true) return;
304
- if (state.floorNo !== selectedFloor.value) return;
341
+ if (!stacked.value && state.floorNo !== selectedFloor.value) return;
305
342
 
306
- const base = projectPoint(pos.x, pos.y, 0, view);
307
- const top = projectPoint(pos.x, pos.y, 0.9, view);
343
+ // Stacked, the robot stands on its own storey.
344
+ const z = stacked.value ? elevations.value.get(Number(state.floorNo)) ?? 0 : 0;
345
+ const base = projectPoint(pos.x, pos.y, z, view);
346
+ const top = projectPoint(pos.x, pos.y, z + 0.9, view);
308
347
 
309
348
  ctx.beginPath();
310
349
  ctx.moveTo(base.x, base.y);
@@ -0,0 +1,63 @@
1
+ <template>
2
+ <div class="pa-4">
3
+ <div v-if="loading" class="py-6 text-center">
4
+ <v-progress-circular indeterminate size="28" />
5
+ </div>
6
+ <v-alert v-else-if="error" type="error" variant="tonal" :text="error" />
7
+ <div v-else-if="!plans.length" class="py-6 text-center text-body-2 text-medium-emphasis">
8
+ This robot has no cleaning schedule.
9
+ </div>
10
+ <v-list v-else density="compact" class="pa-0">
11
+ <v-list-item v-for="(plan, i) in plans" :key="plan.planId ?? i" class="px-0">
12
+ <v-list-item-title class="font-weight-medium">
13
+ {{ plan.summary.days }} · {{ plan.summary.time }}
14
+ <v-chip
15
+ size="x-small"
16
+ label
17
+ variant="tonal"
18
+ class="ml-2"
19
+ :color="plan.summary.enabled ? 'success' : 'default'"
20
+ >
21
+ {{ plan.summary.enabled ? "On" : "Off" }}
22
+ </v-chip>
23
+ </v-list-item-title>
24
+ <v-list-item-subtitle>
25
+ {{ plan.summary.jobs.join(" · ") || "No jobs in this plan" }}
26
+ </v-list-item-subtitle>
27
+ </v-list-item>
28
+ </v-list>
29
+ <!--
30
+ Read-only on purpose: the schedule lives in the robot maker's cloud, and no
31
+ brand's adapter offers editing it through this platform yet.
32
+ -->
33
+ <p class="text-caption text-medium-emphasis mt-3 mb-0">
34
+ Schedules are set in the robot maker's own app and shown here as they are.
35
+ </p>
36
+ </div>
37
+ </template>
38
+
39
+ <script lang="ts" setup>
40
+ /** The cleaning schedule a robot's cloud holds, shown read-only. */
41
+ import { planSummary, robotErrorMessage } from "../../utils/robot-display";
42
+
43
+ const props = defineProps<{ robotId: string }>();
44
+ const { getRobotPlans } = useRobots();
45
+
46
+ const plans = ref<Array<Record<string, any>>>([]);
47
+ const loading = ref(true);
48
+ const error = ref("");
49
+
50
+ onMounted(async () => {
51
+ try {
52
+ const res = await getRobotPlans(props.robotId);
53
+ plans.value = (res?.items ?? []).map((p: Record<string, any>) => ({
54
+ ...p,
55
+ summary: planSummary(p),
56
+ }));
57
+ } catch (e) {
58
+ error.value = robotErrorMessage(e, "Could not load this robot's schedule.");
59
+ } finally {
60
+ loading.value = false;
61
+ }
62
+ });
63
+ </script>
@@ -0,0 +1,174 @@
1
+ <template>
2
+ <div class="pa-4">
3
+ <AppSelect
4
+ v-if="maps.length > 1"
5
+ v-model="floorNo"
6
+ :items="floorOptions"
7
+ item-title="title"
8
+ item-value="value"
9
+ label="Level"
10
+ density="compact"
11
+ hide-details
12
+ class="mb-3"
13
+ style="max-width: 220px"
14
+ />
15
+ <div v-if="loading" class="py-6 text-center">
16
+ <v-progress-circular indeterminate size="28" />
17
+ </div>
18
+ <v-alert v-else-if="error" type="error" variant="tonal" :text="error" />
19
+ <template v-else>
20
+ <p class="text-body-2 text-medium-emphasis mb-2">
21
+ Click the spot on the floor plan you want cleaned.
22
+ </p>
23
+ <div class="spot-plan">
24
+ <img
25
+ ref="img"
26
+ :src="imageUrl"
27
+ alt="Floor plan"
28
+ class="spot-plan__img"
29
+ @click="pick"
30
+ />
31
+ <div
32
+ v-if="picked"
33
+ class="spot-plan__marker"
34
+ :style="{ left: `${picked.left}%`, top: `${picked.top}%` }"
35
+ />
36
+ </div>
37
+ </template>
38
+ <div class="d-flex justify-end ga-2 mt-3">
39
+ <AppButton variant="text" :disabled="sending" @click="$emit('close')">Close</AppButton>
40
+ <AppButton :loading="sending" :disabled="!picked" @click="send">Clean this spot</AppButton>
41
+ </div>
42
+ </div>
43
+ </template>
44
+
45
+ <script lang="ts" setup>
46
+ /**
47
+ * Spot cleaning by clicking the robot's own floor plan.
48
+ *
49
+ * The click is taken in the plan's PIXELS - the frame the spot command uses -
50
+ * so no metre conversion happens here. Offered only for brands declaring
51
+ * `spotClean`; the server refuses the rest by name as well.
52
+ */
53
+ import { robotErrorMessage, spotPolygon } from "../../utils/robot-display";
54
+
55
+ const props = defineProps<{ robotId: string; robotName?: string }>();
56
+ const emit = defineEmits<{ close: []; sent: [message: string] }>();
57
+
58
+ const { getRobotMaps, getRobotMapImages, sendRobotCommand } = useRobots();
59
+
60
+ const maps = ref<Array<Record<string, any>>>([]);
61
+ const floorNo = ref<number | null>(null);
62
+ const imageUrl = ref("");
63
+ const img = ref<HTMLImageElement | null>(null);
64
+ const picked = ref<{ x: number; y: number; left: number; top: number } | null>(null);
65
+ const loading = ref(true);
66
+ const sending = ref(false);
67
+ const error = ref("");
68
+
69
+ const floorOptions = computed(() =>
70
+ maps.value.map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: m.floorNo })),
71
+ );
72
+
73
+ async function loadImage() {
74
+ const map = maps.value.find((m) => m.floorNo === floorNo.value);
75
+ picked.value = null;
76
+ imageUrl.value = "";
77
+ if (!map?.backgroundFileKey) {
78
+ error.value = "This floor has no plan image.";
79
+ return;
80
+ }
81
+ const files = await getRobotMapImages(props.robotId, [map.backgroundFileKey]);
82
+ imageUrl.value = files?.items?.find((f: any) => f.fileKey === map.backgroundFileKey)?.url ?? "";
83
+ if (!imageUrl.value) error.value = "The floor plan image could not be fetched.";
84
+ }
85
+
86
+ onMounted(async () => {
87
+ try {
88
+ const res = await getRobotMaps(props.robotId);
89
+ maps.value = res?.items ?? [];
90
+ if (!maps.value.length) {
91
+ error.value = "This robot has no floor maps yet.";
92
+ return;
93
+ }
94
+ floorNo.value = maps.value[0].floorNo;
95
+ await loadImage();
96
+ } catch (e) {
97
+ error.value = robotErrorMessage(e, "Could not load this robot's floor plan.");
98
+ } finally {
99
+ loading.value = false;
100
+ }
101
+ });
102
+
103
+ watch(floorNo, async (next, prev) => {
104
+ if (prev === null || next === prev) return;
105
+ loading.value = true;
106
+ error.value = "";
107
+ try {
108
+ await loadImage();
109
+ } catch (e) {
110
+ error.value = robotErrorMessage(e, "Could not load this floor.");
111
+ } finally {
112
+ loading.value = false;
113
+ }
114
+ });
115
+
116
+ /** Screen point to plan pixel: the image is scaled to fit, its pixels are not. */
117
+ function pick(event: MouseEvent) {
118
+ const el = img.value;
119
+ if (!el || !el.naturalWidth) return;
120
+ const rect = el.getBoundingClientRect();
121
+ const fx = (event.clientX - rect.left) / rect.width;
122
+ const fy = (event.clientY - rect.top) / rect.height;
123
+ picked.value = {
124
+ x: fx * el.naturalWidth,
125
+ y: fy * el.naturalHeight,
126
+ left: fx * 100,
127
+ top: fy * 100,
128
+ };
129
+ }
130
+
131
+ async function send() {
132
+ const el = img.value;
133
+ if (!picked.value || !el) return;
134
+ sending.value = true;
135
+ try {
136
+ await sendRobotCommand(props.robotId, {
137
+ kind: "spot",
138
+ points: spotPolygon(picked.value.x, picked.value.y, {
139
+ width: el.naturalWidth,
140
+ height: el.naturalHeight,
141
+ }),
142
+ });
143
+ emit("sent", `${props.robotName ?? "The robot"} has been sent to clean that spot.`);
144
+ } catch (e) {
145
+ error.value = robotErrorMessage(e);
146
+ } finally {
147
+ sending.value = false;
148
+ }
149
+ }
150
+ </script>
151
+
152
+ <style scoped>
153
+ .spot-plan {
154
+ position: relative;
155
+ width: 100%;
156
+ }
157
+ .spot-plan__img {
158
+ display: block;
159
+ width: 100%;
160
+ cursor: crosshair;
161
+ image-rendering: pixelated;
162
+ border: 1px solid rgba(0, 0, 0, 0.12);
163
+ }
164
+ .spot-plan__marker {
165
+ position: absolute;
166
+ width: 14px;
167
+ height: 14px;
168
+ margin: -7px 0 0 -7px;
169
+ border-radius: 50%;
170
+ background: #ff5a1f;
171
+ box-shadow: 0 0 0 3px rgba(255, 90, 31, 0.3);
172
+ pointer-events: none;
173
+ }
174
+ </style>
@@ -53,6 +53,27 @@ export default function useRobots() {
53
53
  });
54
54
  }
55
55
 
56
+ /**
57
+ * Rename a robot, or set its serial. The brand and the credentials are not
58
+ * editable: a wrong credential is replaced by removing the robot and adding
59
+ * it again, because the old value is never shown.
60
+ */
61
+ function updateRobot(id: string, payload: { name?: string; robotSn?: string }) {
62
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}`, {
63
+ method: "PATCH",
64
+ query: { appSlug },
65
+ body: payload,
66
+ });
67
+ }
68
+
69
+ /** Remove a robot. It stops listing and answering; the record is kept. */
70
+ function deleteRobot(id: string) {
71
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}`, {
72
+ method: "DELETE",
73
+ query: { appSlug },
74
+ });
75
+ }
76
+
56
77
  /** Live state — mode, online, whether it can take a job right now. */
57
78
  function getRobotState(id: string) {
58
79
  return useNuxtApp().$api<Record<string, any>>(
@@ -83,6 +104,92 @@ export default function useRobots() {
83
104
  );
84
105
  }
85
106
 
107
+ /**
108
+ * The robot brands this platform can talk to.
109
+ *
110
+ * A robot record has to name its brand and there is no safe default - sending
111
+ * a robot a command in another brand's protocol is the one mistake the
112
+ * adapter layer exists to prevent. Each brand reports its Open-RMF tier, so
113
+ * somebody choosing one can see what that protocol allows before committing.
114
+ */
115
+ function getRobotBrands() {
116
+ return useNuxtApp().$api<Record<string, any>>("/api/robots/brands", {
117
+ method: "GET",
118
+ });
119
+ }
120
+
121
+ /**
122
+ * Watch one robot's position.
123
+ *
124
+ * `fetch` with a stream reader rather than `EventSource`, because EventSource
125
+ * cannot carry the headers `$api` adds - it would be an unauthenticated
126
+ * request that simply 401s.
127
+ *
128
+ * Returns a `stop`. Calling it aborts the request, which closes the upstream
129
+ * connection to the robot cloud - the server holds one for as long as this
130
+ * one is open, so leaving it running is not free.
131
+ */
132
+ function trackRobot(
133
+ id: string,
134
+ onEvent: (event: Record<string, any>) => void,
135
+ ): { stop: () => void } {
136
+ const controller = new AbortController();
137
+ const base = useRuntimeConfig().public?.apiBase ?? "";
138
+ const query = appSlug ? `?appSlug=${encodeURIComponent(appSlug)}` : "";
139
+
140
+ (async () => {
141
+ try {
142
+ const response = await fetch(`${base}/api/robots/${id}/track${query}`, {
143
+ method: "GET",
144
+ headers: { Accept: "text/event-stream" },
145
+ credentials: "include",
146
+ signal: controller.signal,
147
+ });
148
+ if (!response.ok || !response.body) {
149
+ onEvent({ type: "lost", reason: `The robot stream refused (${response.status}).` });
150
+ return;
151
+ }
152
+
153
+ const reader = response.body.getReader();
154
+ const decoder = new TextDecoder();
155
+ let buffer = "";
156
+
157
+ // Events do not respect chunk boundaries: whatever follows the last
158
+ // blank line stays buffered for the next read, or a pose arriving in
159
+ // two pieces is dropped.
160
+ for (;;) {
161
+ const { done, value } = await reader.read();
162
+ if (done) break;
163
+
164
+ buffer += decoder.decode(value, { stream: true });
165
+ buffer = buffer.replace(/\r\n|\r/g, "\n");
166
+
167
+ const frames = buffer.split("\n\n");
168
+ buffer = frames.pop() ?? "";
169
+
170
+ for (const frame of frames) {
171
+ for (const line of frame.split("\n")) {
172
+ // A line starting ":" is a keep-alive comment, not an event.
173
+ if (!line.startsWith("data:")) continue;
174
+ try {
175
+ onEvent(JSON.parse(line.slice(5).trim()));
176
+ } catch {
177
+ // One malformed frame must not tear down a stream that is
178
+ // otherwise delivering good poses.
179
+ }
180
+ }
181
+ }
182
+ }
183
+ onEvent({ type: "lost", reason: "The robot stream ended." });
184
+ } catch (error: any) {
185
+ if (error?.name === "AbortError") return;
186
+ onEvent({ type: "lost", reason: error?.message ?? "The robot stream failed." });
187
+ }
188
+ })();
189
+
190
+ return { stop: () => controller.abort() };
191
+ }
192
+
86
193
  /** The cleaning schedule the vendor cloud holds for this robot. */
87
194
  function getRobotPlans(id: string) {
88
195
  return useNuxtApp().$api<Record<string, any>>(
@@ -115,7 +222,11 @@ export default function useRobots() {
115
222
 
116
223
  return {
117
224
  getRobots,
225
+ getRobotBrands,
226
+ trackRobot,
118
227
  createRobot,
228
+ updateRobot,
229
+ deleteRobot,
119
230
  getRobotState,
120
231
  getRobotMaps,
121
232
  getRobotMapImages,
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.24.0",
5
+ "version": "4.26.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.",
@@ -333,12 +333,23 @@ export function fitView(
333
333
  const bounds = solidsBounds(solids);
334
334
  if (!bounds) return base;
335
335
 
336
- const projected = [
336
+ // Heights count too: a stacked building's top storey must fit on the canvas,
337
+ // not just its footprint. A single level spans 0..wall height as before.
338
+ let minZ = Infinity;
339
+ let maxZ = -Infinity;
340
+ for (const w of solids) {
341
+ minZ = Math.min(minZ, w.centre.z - w.heightM / 2);
342
+ maxZ = Math.max(maxZ, w.centre.z + w.heightM / 2);
343
+ }
344
+ const corners = [
337
345
  { x: bounds.minX, y: bounds.minY },
338
346
  { x: bounds.maxX, y: bounds.minY },
339
347
  { x: bounds.maxX, y: bounds.maxY },
340
348
  { x: bounds.minX, y: bounds.maxY },
341
- ].map((p) => projectPoint(p.x, p.y, 0, { ...base, zoom: 1, originPx: { x: 0, y: 0 } }));
349
+ ];
350
+ const projected = [0, minZ, maxZ].flatMap((z) =>
351
+ corners.map((p) => projectPoint(p.x, p.y, z, { ...base, zoom: 1, originPx: { x: 0, y: 0 } })),
352
+ );
342
353
 
343
354
  const spanX = Math.max(...projected.map((p) => p.x)) - Math.min(...projected.map((p) => p.x));
344
355
  const spanY = Math.max(...projected.map((p) => p.y)) - Math.min(...projected.map((p) => p.y));
@@ -350,12 +361,12 @@ export function fitView(
350
361
  ? Math.min(usableW / spanX, usableH / spanY)
351
362
  : base.zoom;
352
363
 
353
- const centre = projectPoint(
354
- (bounds.minX + bounds.maxX) / 2,
355
- (bounds.minY + bounds.maxY) / 2,
356
- 0,
357
- { ...base, zoom, originPx: { x: 0, y: 0 } },
358
- );
364
+ const unit = { ...base, zoom, originPx: { x: 0, y: 0 } };
365
+ const all = [0, minZ, maxZ].flatMap((z) => corners.map((p) => projectPoint(p.x, p.y, z, unit)));
366
+ const centre = {
367
+ x: (Math.min(...all.map((p) => p.x)) + Math.max(...all.map((p) => p.x))) / 2,
368
+ y: (Math.min(...all.map((p) => p.y)) + Math.max(...all.map((p) => p.y))) / 2,
369
+ };
359
370
 
360
371
  return {
361
372
  rotation,
@@ -364,3 +375,24 @@ export function fitView(
364
375
  originPx: { x: canvas.width / 2 - centre.x, y: canvas.height / 2 - centre.y },
365
376
  };
366
377
  }
378
+
379
+ /** Storey height used to stack levels when the plans carry no elevation. */
380
+ export const STOREY_HEIGHT_M = 4;
381
+
382
+ /**
383
+ * Where each floor sits when the building is shown stacked.
384
+ *
385
+ * The robot's maps give a floor NUMBER and nothing about height, so floors are
386
+ * stacked in number order one storey apart. Missing numbers do not leave gaps:
387
+ * a robot mapping floors 1 and 5 shows two levels, not five.
388
+ *
389
+ * ponytail: equal storeys. Real heights need building-map persistence, which
390
+ * is an owner decision still open.
391
+ */
392
+ export function stackedElevations(
393
+ floorNos: number[],
394
+ storeyM = STOREY_HEIGHT_M,
395
+ ): Map<number, number> {
396
+ const ordered = [...new Set(floorNos.filter((n) => Number.isFinite(n)))].sort((a, b) => a - b);
397
+ return new Map(ordered.map((floorNo, i) => [floorNo, i * storeyM]));
398
+ }
@@ -121,3 +121,92 @@ export function robotErrorMessage(error: unknown, fallback = "Could not reach th
121
121
  if (typeof e?.message === "string" && e.message.trim()) return e.message.trim();
122
122
  return fallback;
123
123
  }
124
+
125
+ /**
126
+ * May the "Spot clean" control be offered?
127
+ *
128
+ * Only when the robot could take a job now AND its brand says it can take a
129
+ * click on the plan (`spotClean`). A brand without it - Ounitech, until its
130
+ * pixel frame is verified - gets no control rather than one the server refuses.
131
+ */
132
+ export function canSpotClean(state: {
133
+ online?: unknown;
134
+ dispatchable?: unknown;
135
+ capabilities?: Record<string, unknown> | null;
136
+ } | null | undefined): boolean {
137
+ return canDispatch(state) && state?.capabilities?.spotClean === true;
138
+ }
139
+
140
+ /** Whether the brand can take a spot at all, busy or not - decides if the control exists. */
141
+ export function brandSpotCleans(state: { capabilities?: Record<string, unknown> | null } | null | undefined) {
142
+ return state?.capabilities?.spotClean === true;
143
+ }
144
+
145
+ /** The fault the robot is reporting, in its own words, or null. */
146
+ export function robotFaultText(state: { fault?: { message?: unknown; code?: unknown } | null } | null | undefined): string | null {
147
+ const fault = state?.fault;
148
+ if (!fault) return null;
149
+ const text = typeof fault.message === "string" && fault.message.trim()
150
+ ? fault.message.trim()
151
+ : typeof fault.code === "string" ? fault.code : "";
152
+ return text ? `Fault: ${text}` : null;
153
+ }
154
+
155
+ /**
156
+ * A small square around a clicked pixel, as the polygon a spot command takes.
157
+ *
158
+ * A spot command needs at least three points (a single point encloses
159
+ * nothing). Clamped to the image so a click on the edge stays on the plan.
160
+ */
161
+ export function spotPolygon(
162
+ x: number,
163
+ y: number,
164
+ size: { width: number; height: number },
165
+ half = 10,
166
+ ): Array<{ x: number; y: number }> {
167
+ const cx = (v: number) => Math.round(Math.min(Math.max(v, 0), Math.max(size.width - 1, 0)));
168
+ const cy = (v: number) => Math.round(Math.min(Math.max(v, 0), Math.max(size.height - 1, 0)));
169
+ return [
170
+ { x: cx(x - half), y: cy(y - half) },
171
+ { x: cx(x + half), y: cy(y - half) },
172
+ { x: cx(x + half), y: cy(y + half) },
173
+ { x: cx(x - half), y: cy(y + half) },
174
+ ];
175
+ }
176
+
177
+ const DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
178
+
179
+ /**
180
+ * A cleaning schedule, as a person reads it.
181
+ *
182
+ * The vendor's `dateList` is 1-7, Monday first. An unknown day number is
183
+ * dropped rather than shown as a blank - but a plan with NO valid days says so,
184
+ * instead of reading like "every day".
185
+ */
186
+ export function planSummary(plan: Record<string, any> | null | undefined) {
187
+ const days = [...new Set((Array.isArray(plan?.dateList) ? plan!.dateList : [])
188
+ .filter((d: unknown) => Number.isInteger(d) && (d as number) >= 1 && (d as number) <= 7))]
189
+ .sort((a: any, b: any) => a - b) as number[];
190
+
191
+ const dayText =
192
+ days.length === 7 ? "Every day"
193
+ : days.length ? days.map((d) => DAY_NAMES[d - 1]).join(", ")
194
+ : "No days set";
195
+
196
+ const start = typeof plan?.startTime === "string" ? plan.startTime : "";
197
+ const end = typeof plan?.endTime === "string" ? plan.endTime : "";
198
+ const time = start && end ? `${start}–${end}` : start || end || "No time set";
199
+
200
+ const jobs = (Array.isArray(plan?.jobList) ? plan!.jobList : []).map((job: any) => {
201
+ const floor = typeof job?.floorNo === "number" ? `Floor ${job.floorNo}` : "Floor unknown";
202
+ const passes = typeof job?.cleanTimes === "number" ? `${job.cleanTimes} pass${job.cleanTimes === 1 ? "" : "es"}` : "";
203
+ return [floor, passes].filter(Boolean).join(" · ");
204
+ });
205
+
206
+ return {
207
+ days: dayText,
208
+ time,
209
+ enabled: plan?.enableFlag === true || plan?.enableFlag === 1,
210
+ jobs,
211
+ };
212
+ }