@7365admin1/layer-common 4.25.0 → 4.27.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.
@@ -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>>(
@@ -199,11 +220,101 @@ export default function useRobots() {
199
220
  );
200
221
  }
201
222
 
223
+ /* ---------------------------------------- building maps and lifts */
224
+
225
+ /**
226
+ * A robot's saved building maps, newest first (a summary; `getBuildingMap`
227
+ * has the full layout). No saved map is normal - the 3D view then shows the
228
+ * robot's own floor plans exactly as before.
229
+ */
230
+ function listBuildingMaps(robotId: string, { page = 1, limit = 10 } = {}) {
231
+ return useNuxtApp().$api<Record<string, any>>("/api/robots/building-maps", {
232
+ method: "GET",
233
+ query: { robot: robotId, page, limit, appSlug },
234
+ });
235
+ }
236
+
237
+ function getBuildingMap(mapId: string) {
238
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/building-maps/${mapId}`, {
239
+ method: "GET",
240
+ });
241
+ }
242
+
243
+ /** Save a first map for a robot's building. The estate comes from the robot. */
244
+ function createBuildingMap(payload: Record<string, any> & { robotId: string }) {
245
+ return useNuxtApp().$api<Record<string, any>>("/api/robots/building-maps", {
246
+ method: "POST",
247
+ query: { appSlug },
248
+ body: payload,
249
+ });
250
+ }
251
+
252
+ /**
253
+ * Save an edited map. `version` is the one the editor loaded; if somebody
254
+ * else saved since, the server refuses (409) rather than overwrite them.
255
+ */
256
+ function updateBuildingMap(mapId: string, payload: Record<string, any> & { version: number }) {
257
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/building-maps/${mapId}`, {
258
+ method: "PATCH",
259
+ body: payload,
260
+ });
261
+ }
262
+
263
+ function deleteBuildingMap(mapId: string) {
264
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/building-maps/${mapId}`, {
265
+ method: "DELETE",
266
+ });
267
+ }
268
+
269
+ /** Every lift on the map: the (simulated) car, who holds it, who is waiting. */
270
+ function getLiftQueue(mapId: string) {
271
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/building-maps/${mapId}/lifts`, {
272
+ method: "GET",
273
+ });
274
+ }
275
+
276
+ function requestLift(
277
+ mapId: string,
278
+ liftName: string,
279
+ payload: { robotId: string; fromFloor: number; toFloor: number },
280
+ ) {
281
+ return useNuxtApp().$api<Record<string, any>>(
282
+ `/api/robots/building-maps/${mapId}/lifts/${encodeURIComponent(liftName)}/sessions`,
283
+ { method: "POST", query: { appSlug }, body: payload },
284
+ );
285
+ }
286
+
287
+ /** Give the lift back, or leave the queue. */
288
+ function releaseLiftSession(sessionId: string) {
289
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/lift-sessions/${sessionId}/release`, {
290
+ method: "POST",
291
+ });
292
+ }
293
+
294
+ /** This robot's open lift request and its place in the queue, or null. */
295
+ function getRobotLiftSession(robotId: string) {
296
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${robotId}/lift-session`, {
297
+ method: "GET",
298
+ query: { appSlug },
299
+ });
300
+ }
301
+
202
302
  return {
303
+ listBuildingMaps,
304
+ getBuildingMap,
305
+ createBuildingMap,
306
+ updateBuildingMap,
307
+ deleteBuildingMap,
308
+ getLiftQueue,
309
+ requestLift,
310
+ releaseLiftSession,
311
+ getRobotLiftSession,
203
312
  getRobots,
204
313
  getRobotBrands,
205
314
  trackRobot,
206
315
  createRobot,
316
+ updateRobot,
317
+ deleteRobot,
207
318
  getRobotState,
208
319
  getRobotMaps,
209
320
  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.25.0",
5
+ "version": "4.27.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.",
@@ -47,6 +47,8 @@ export type TWallSolid = {
47
47
  thicknessM: number;
48
48
  heightM: number;
49
49
  yaw: number;
50
+ /** What the box is, so the renderer can colour it. Absent = a wall. */
51
+ kind?: "wall" | "door" | "lift" | "car";
50
52
  };
51
53
 
52
54
  /* ------------------------------------------------- image to occupancy grid */
@@ -333,12 +335,23 @@ export function fitView(
333
335
  const bounds = solidsBounds(solids);
334
336
  if (!bounds) return base;
335
337
 
336
- const projected = [
338
+ // Heights count too: a stacked building's top storey must fit on the canvas,
339
+ // not just its footprint. A single level spans 0..wall height as before.
340
+ let minZ = Infinity;
341
+ let maxZ = -Infinity;
342
+ for (const w of solids) {
343
+ minZ = Math.min(minZ, w.centre.z - w.heightM / 2);
344
+ maxZ = Math.max(maxZ, w.centre.z + w.heightM / 2);
345
+ }
346
+ const corners = [
337
347
  { x: bounds.minX, y: bounds.minY },
338
348
  { x: bounds.maxX, y: bounds.minY },
339
349
  { x: bounds.maxX, y: bounds.maxY },
340
350
  { x: bounds.minX, y: bounds.maxY },
341
- ].map((p) => projectPoint(p.x, p.y, 0, { ...base, zoom: 1, originPx: { x: 0, y: 0 } }));
351
+ ];
352
+ const projected = [0, minZ, maxZ].flatMap((z) =>
353
+ corners.map((p) => projectPoint(p.x, p.y, z, { ...base, zoom: 1, originPx: { x: 0, y: 0 } })),
354
+ );
342
355
 
343
356
  const spanX = Math.max(...projected.map((p) => p.x)) - Math.min(...projected.map((p) => p.x));
344
357
  const spanY = Math.max(...projected.map((p) => p.y)) - Math.min(...projected.map((p) => p.y));
@@ -350,12 +363,12 @@ export function fitView(
350
363
  ? Math.min(usableW / spanX, usableH / spanY)
351
364
  : base.zoom;
352
365
 
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
- );
366
+ const unit = { ...base, zoom, originPx: { x: 0, y: 0 } };
367
+ const all = [0, minZ, maxZ].flatMap((z) => corners.map((p) => projectPoint(p.x, p.y, z, unit)));
368
+ const centre = {
369
+ x: (Math.min(...all.map((p) => p.x)) + Math.max(...all.map((p) => p.x))) / 2,
370
+ y: (Math.min(...all.map((p) => p.y)) + Math.max(...all.map((p) => p.y))) / 2,
371
+ };
359
372
 
360
373
  return {
361
374
  rotation,
@@ -364,3 +377,161 @@ export function fitView(
364
377
  originPx: { x: canvas.width / 2 - centre.x, y: canvas.height / 2 - centre.y },
365
378
  };
366
379
  }
380
+
381
+ /** Storey height used to stack levels when the plans carry no elevation. */
382
+ export const STOREY_HEIGHT_M = 4;
383
+
384
+ /**
385
+ * Where each floor sits when the building is shown stacked.
386
+ *
387
+ * The robot's maps give a floor NUMBER and nothing about height, so floors are
388
+ * stacked in number order one storey apart. Missing numbers do not leave gaps:
389
+ * a robot mapping floors 1 and 5 shows two levels, not five.
390
+ *
391
+ * ponytail: equal storeys. Real heights need building-map persistence, which
392
+ * is an owner decision still open.
393
+ */
394
+ export function stackedElevations(
395
+ floorNos: number[],
396
+ storeyM = STOREY_HEIGHT_M,
397
+ ): Map<number, number> {
398
+ const ordered = [...new Set(floorNos.filter((n) => Number.isFinite(n)))].sort((a, b) => a - b);
399
+ return new Map(ordered.map((floorNo, i) => [floorNo, i * storeyM]));
400
+ }
401
+
402
+ /* ------------------------------------------------ saved map features */
403
+
404
+ /**
405
+ * The saved building map's editable features, in site metres - the shapes
406
+ * `@7365admin1/core` validates in `robot-building-map.model.ts`.
407
+ */
408
+ export type TMapPointM = { x: number; y: number };
409
+ export type TMapDoor = {
410
+ name: string;
411
+ floorNo: number;
412
+ type: "hinged" | "sliding";
413
+ start: TMapPointM;
414
+ end: TMapPointM;
415
+ };
416
+ export type TMapLift = {
417
+ name: string;
418
+ x: number;
419
+ y: number;
420
+ widthM: number;
421
+ depthM: number;
422
+ floors: number[];
423
+ };
424
+
425
+ /** A door is shorter than a wall and sits in it. */
426
+ export const DOOR_HEIGHT_M = 2.1;
427
+ export const DOOR_THICKNESS_M = 0.18;
428
+
429
+ /**
430
+ * Each floor's height: the saved elevation where somebody set one, otherwise
431
+ * one storey above the floor below. So a building with no saved heights stacks
432
+ * exactly as it did before a map was saved.
433
+ */
434
+ export function levelElevations(
435
+ floorNos: number[],
436
+ saved: Array<{ floorNo: number; elevationM?: number | null }> = [],
437
+ storeyM = STOREY_HEIGHT_M,
438
+ ): Map<number, number> {
439
+ const out = new Map<number, number>();
440
+ for (const [floorNo, z] of stackedElevations(floorNos, storeyM)) {
441
+ const set = saved.find((l) => l.floorNo === floorNo)?.elevationM;
442
+ out.set(floorNo, typeof set === "number" && Number.isFinite(set) ? set : z);
443
+ }
444
+ return out;
445
+ }
446
+
447
+ /** A door as a box standing in its wall. Null for a zero-length door. */
448
+ export function doorSolid(door: TMapDoor, elevationM: number): TWallSolid | null {
449
+ const lengthM = Math.hypot(door.end.x - door.start.x, door.end.y - door.start.y);
450
+ if (!(lengthM > 0)) return null;
451
+ return {
452
+ kind: "door",
453
+ centre: {
454
+ x: (door.start.x + door.end.x) / 2,
455
+ y: (door.start.y + door.end.y) / 2,
456
+ z: elevationM + DOOR_HEIGHT_M / 2,
457
+ },
458
+ lengthM,
459
+ thicknessM: DOOR_THICKNESS_M,
460
+ heightM: DOOR_HEIGHT_M,
461
+ yaw: Math.atan2(door.end.y - door.start.y, door.end.x - door.start.x),
462
+ };
463
+ }
464
+
465
+ /**
466
+ * A lift shaft as one box from the lowest floor it serves to the top of the
467
+ * highest - through every storey in between, which is the point of drawing it.
468
+ * With `onlyFloor`, just that storey's slice (single-level view); null when
469
+ * the shaft does not stop there.
470
+ */
471
+ export function liftSolid(
472
+ lift: TMapLift,
473
+ elevations: Map<number, number>,
474
+ onlyFloor?: number,
475
+ ): TWallSolid | null {
476
+ if (onlyFloor !== undefined && !lift.floors.includes(onlyFloor)) return null;
477
+ const zs = onlyFloor !== undefined
478
+ ? [0]
479
+ : lift.floors.filter((f) => elevations.has(f)).map((f) => elevations.get(f) ?? 0);
480
+ if (!zs.length) return null;
481
+ const bottom = Math.min(...zs);
482
+ const top = Math.max(...zs) + WALL_HEIGHT_M;
483
+ return {
484
+ kind: "lift",
485
+ centre: { x: lift.x, y: lift.y, z: (bottom + top) / 2 },
486
+ lengthM: lift.widthM,
487
+ thicknessM: lift.depthM,
488
+ heightM: top - bottom,
489
+ yaw: 0,
490
+ };
491
+ }
492
+
493
+ /**
494
+ * A screen point back to site metres, on the horizontal plane at height `z` -
495
+ * the exact inverse of `projectPoint`. The editor uses it to place what the
496
+ * pointer clicked; it always edits in the flat plan view.
497
+ */
498
+ export function unprojectPoint(
499
+ sx: number,
500
+ sy: number,
501
+ view: TView,
502
+ z = 0,
503
+ ): { x: number; y: number } {
504
+ const rx = (sx - view.originPx.x) / view.zoom;
505
+ const ry =
506
+ (sy - view.originPx.y + z * view.zoom * Math.sin(view.tilt)) /
507
+ (view.zoom * Math.cos(view.tilt));
508
+ const cos = Math.cos(view.rotation);
509
+ const sin = Math.sin(view.rotation);
510
+ return { x: rx * cos + ry * sin, y: -rx * sin + ry * cos };
511
+ }
512
+
513
+ /** Distance from a point to a segment, metres. The editor's door hit test. */
514
+ export function distanceToSegment(p: TMapPointM, a: TMapPointM, b: TMapPointM): number {
515
+ const dx = b.x - a.x;
516
+ const dy = b.y - a.y;
517
+ const len2 = dx * dx + dy * dy;
518
+ const t = len2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)) : 0;
519
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
520
+ }
521
+
522
+ /** Is the point inside the lift's footprint? */
523
+ export function insideLift(p: TMapPointM, lift: TMapLift): boolean {
524
+ return Math.abs(p.x - lift.x) <= lift.widthM / 2 && Math.abs(p.y - lift.y) <= lift.depthM / 2;
525
+ }
526
+
527
+ /** The next free default name: Lift A, Lift B, ... / Door 1, Door 2, ... */
528
+ export function nextFeatureName(existing: string[], kind: "lift" | "door"): string {
529
+ const taken = new Set(existing);
530
+ for (let i = 0; i < 500; i++) {
531
+ const name = kind === "lift"
532
+ ? `Lift ${i < 26 ? String.fromCharCode(65 + i) : i + 1}`
533
+ : `Door ${i + 1}`;
534
+ if (!taken.has(name)) return name;
535
+ }
536
+ return `${kind === "lift" ? "Lift" : "Door"} ${existing.length + 1}`;
537
+ }
@@ -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
+ }