@7365admin1/layer-common 4.26.0 → 4.26.1-staging.354

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/components/AccessCardAddForm.vue +5 -4
  3. package/components/AccessCardAssignToUnitForm.vue +3 -2
  4. package/components/AccessCardPreviewDialog.vue +4 -3
  5. package/components/Dialog/UpdateMoreAction.vue +11 -1
  6. package/components/DocumentForm.vue +407 -112
  7. package/components/DocumentManagement.vue +213 -12
  8. package/components/EntryPass/QrTemplatePreview.vue +21 -25
  9. package/components/EntryPassInformation.vue +119 -24
  10. package/components/Facility/BookingSetup.vue +63 -0
  11. package/components/HidAccessLogDashboard.vue +29 -5
  12. package/components/HidAccessPermissions.vue +424 -0
  13. package/components/HidIntercomManagement.vue +148 -14
  14. package/components/HidProfileQrCode.vue +323 -0
  15. package/components/HidReaderManagement.vue +26 -0
  16. package/components/HidReaderUserRoster.vue +32 -2
  17. package/components/HidUserEnrollment.vue +833 -152
  18. package/components/InvitationClientForm.vue +19 -1
  19. package/components/Robot/Fleet.vue +3 -0
  20. package/components/Robot/Map3D.vue +761 -37
  21. package/components/RolePermissionFormCreate.vue +163 -19
  22. package/components/RolePermissionFormPreviewUpdate.vue +230 -19
  23. package/components/RolePermissionMain.vue +19 -0
  24. package/components/VisitorManagement.vue +267 -5
  25. package/composables/useAccessManagement.ts +5 -0
  26. package/composables/useDocument.ts +7 -0
  27. package/composables/useFacility.ts +11 -0
  28. package/composables/useHidAmico.ts +117 -0
  29. package/composables/useHidNavigation.ts +25 -1
  30. package/composables/usePeople.ts +19 -0
  31. package/composables/useRobots.ts +88 -0
  32. package/composables/useSiteCategory.ts +45 -0
  33. package/composables/useSiteEntryPassSettings.ts +26 -0
  34. package/composables/useWebUsb.ts +14 -11
  35. package/package.json +1 -1
  36. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  37. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  38. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  39. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  40. package/types/document.d.ts +14 -0
  41. package/types/facility.d.ts +4 -0
  42. package/types/people.d.ts +28 -1
  43. package/utils/building-map.ts +139 -0
  44. package/utils/hid-permission-assignments.ts +190 -0
  45. package/utils/occupancy-role.ts +109 -0
  46. package/utils/permission-labels.ts +30 -0
@@ -4,7 +4,7 @@
4
4
  <template #left>
5
5
  <AppSelect
6
6
  v-model="selectedFloor"
7
- :items="floorOptions"
7
+ :items="editing ? realFloorOptions : floorOptions"
8
8
  item-title="title"
9
9
  item-value="value"
10
10
  label="Level"
@@ -16,8 +16,23 @@
16
16
  <span v-if="wallCount" class="text-caption text-medium-emphasis ml-4">
17
17
  {{ wallCount }} walls found
18
18
  </span>
19
+ <span v-if="savedMap" class="text-caption text-medium-emphasis ml-3">
20
+ · saved layout (version {{ savedMap.version }})
21
+ </span>
22
+ <span v-else-if="savedLoadFailed" class="text-caption text-error ml-3">
23
+ · saved layout could not be loaded
24
+ </span>
19
25
  </template>
20
26
  <template #right>
27
+ <AppButton
28
+ v-if="canEdit && !editing && !savedLoadFailed"
29
+ variant="ghost"
30
+ icon="mdi-pencil-ruler"
31
+ :disabled="loading || !!error"
32
+ @click="startEditing"
33
+ >
34
+ {{ savedMap ? "Edit layout" : "Add doors & lifts" }}
35
+ </AppButton>
21
36
  <AppButton
22
37
  variant="icon"
23
38
  icon="mdi-rotate-left"
@@ -36,14 +51,54 @@
36
51
  variant="icon"
37
52
  :icon="tilted ? 'mdi-cube-outline' : 'mdi-floor-plan'"
38
53
  :aria-label="tilted ? 'Show as a flat plan' : 'Show in 3D'"
39
- :disabled="loading"
54
+ :disabled="loading || editing"
40
55
  @click="toggleTilt"
41
56
  />
42
57
  </template>
43
58
  </CardToolbar>
44
59
 
45
- <div ref="stage" class="robot-map3d">
46
- <canvas ref="canvasEl" class="robot-map3d__canvas" />
60
+ <!--
61
+ Editing happens on the flat plan of one floor, so a click lands exactly
62
+ where it looks like it lands.
63
+ -->
64
+ <div v-if="editing" class="robot-map3d__editbar px-4 py-2">
65
+ <AppSegmented v-model="tool" :options="toolOptions" />
66
+ <v-text-field
67
+ v-model.number="currentHeight"
68
+ type="number"
69
+ step="0.1"
70
+ label="Floor height (m)"
71
+ density="compact"
72
+ hide-details
73
+ style="max-width: 150px"
74
+ />
75
+ <span class="text-caption text-medium-emphasis">{{ toolHint }}</span>
76
+ <v-spacer />
77
+ <AppButton
78
+ v-if="savedMap"
79
+ variant="ghost"
80
+ icon="mdi-delete-outline"
81
+ :disabled="saving"
82
+ @click="removeSaved"
83
+ >
84
+ {{ confirmRemove ? "Confirm remove" : "Remove saved layout" }}
85
+ </AppButton>
86
+ <AppButton variant="ghost" :disabled="saving" @click="cancelEditing">Cancel</AppButton>
87
+ <AppButton icon="mdi-content-save-outline" :disabled="saving" @click="save">
88
+ {{ saving ? "Saving…" : "Save layout" }}
89
+ </AppButton>
90
+ </div>
91
+ <p v-if="editError" class="text-body-2 text-error px-4 pt-2 mb-0">{{ editError }}</p>
92
+
93
+ <div ref="stage" class="robot-map3d" :class="{ 'robot-map3d--placing': editing && tool !== 'select' }">
94
+ <canvas
95
+ ref="canvasEl"
96
+ class="robot-map3d__canvas"
97
+ @pointerdown="onPointerDown"
98
+ @pointermove="onPointerMove"
99
+ @pointerup="onPointerUp"
100
+ @pointercancel="onPointerUp"
101
+ />
47
102
 
48
103
  <div v-if="loading" class="robot-map3d__overlay">
49
104
  <v-progress-circular indeterminate size="28" />
@@ -58,22 +113,126 @@
58
113
  <div v-else-if="error" class="robot-map3d__overlay">
59
114
  <v-icon size="36" class="mb-2">mdi-map-marker-off-outline</v-icon>
60
115
  <p class="text-body-2 mb-3">{{ error }}</p>
61
- <AppButton size="small" variant="outlined" @click="load">Try again</AppButton>
116
+ <AppButton variant="ghost" @click="load">Try again</AppButton>
62
117
  </div>
63
118
 
64
- <div v-else-if="!wallCount" class="robot-map3d__overlay">
119
+ <div v-else-if="!wallCount && !featureCount && !editing" class="robot-map3d__overlay">
65
120
  <v-icon size="36" class="mb-2">mdi-floor-plan</v-icon>
66
121
  <p class="text-body-2 mb-0">
67
122
  No walls could be found in this floor plan.
68
123
  </p>
69
124
  </div>
70
125
  </div>
126
+
127
+ <!-- The feature being edited. -->
128
+ <div v-if="editing && selectedFeature" class="robot-map3d__panel px-4 py-3">
129
+ <v-text-field
130
+ v-model="selectedFeature.name"
131
+ :label="selected?.kind === 'lift' ? 'Lift name' : 'Door name'"
132
+ density="compact"
133
+ hide-details
134
+ maxlength="60"
135
+ style="max-width: 220px"
136
+ />
137
+ <AppSelect
138
+ v-if="selected?.kind === 'door'"
139
+ v-model="doorType"
140
+ :items="doorTypes"
141
+ item-title="title"
142
+ item-value="value"
143
+ label="Type"
144
+ density="compact"
145
+ hide-details
146
+ style="max-width: 160px"
147
+ />
148
+ <AppSelect
149
+ v-if="selected?.kind === 'lift'"
150
+ v-model="liftFloors"
151
+ :items="realFloorOptions"
152
+ item-title="title"
153
+ item-value="value"
154
+ label="Stops at"
155
+ multiple
156
+ chips
157
+ density="compact"
158
+ hide-details
159
+ style="min-width: 260px"
160
+ />
161
+ <v-spacer />
162
+ <AppButton variant="ghost" icon="mdi-delete-outline" @click="removeSelected">Remove</AppButton>
163
+ </div>
164
+
165
+ <!--
166
+ The lift queue. The car is a SIMULATOR - there is no lift driver until
167
+ the lift maker supplies its register map - and the panel says so.
168
+ -->
169
+ <div v-if="!editing && savedMap?.lifts?.length" class="robot-map3d__lifts px-4 py-3">
170
+ <div class="d-flex align-center mb-2">
171
+ <span class="font-weight-medium">Lifts</span>
172
+ <span class="text-caption text-medium-emphasis ml-2">simulated — no real lift is controlled</span>
173
+ </div>
174
+ <p v-if="liftError" class="text-body-2 text-error mb-2">{{ liftError }}</p>
175
+ <div v-for="lift in liftQueue" :key="lift.liftName" class="robot-map3d__lift mb-3">
176
+ <div class="text-body-2">
177
+ <strong>{{ lift.liftName }}</strong>
178
+ — floor {{ lift.state?.currentFloor }}, {{ motionLabel(lift.state) }}, doors {{ doorLabel(lift.state) }}.
179
+ {{ phaseLabel(lift) }}
180
+ </div>
181
+ <div v-if="lift.active" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
182
+ <span>
183
+ In the lift: <strong>{{ lift.active.robotName }}</strong>
184
+ (floor {{ lift.active.fromFloor }} → {{ lift.active.toFloor }}), released automatically
185
+ {{ untilLabel(lift.active.expiresAt) }} unless it finishes first.
186
+ </span>
187
+ <AppButton v-if="canEdit" variant="ghost" @click="release(lift.active)">Release</AppButton>
188
+ </div>
189
+ <div v-for="(row, i) in lift.queue" :key="row._id" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
190
+ <span>Waiting {{ i + 1 }}: {{ row.robotName }} (floor {{ row.fromFloor }} → {{ row.toFloor }})</span>
191
+ <AppButton v-if="canEdit" variant="ghost" @click="release(row)">Remove from queue</AppButton>
192
+ </div>
193
+ <div v-if="!lift.active && !lift.queue?.length" class="text-caption text-medium-emphasis">
194
+ Nobody is waiting.
195
+ </div>
196
+
197
+ <div v-if="canEdit && robotBrand === 'demo' && !thisRobotWaiting" class="d-flex align-center flex-wrap ga-2 mt-2">
198
+ <AppSelect
199
+ v-model="requestFrom[lift.liftName]"
200
+ :items="lift.floors"
201
+ label="From floor"
202
+ density="compact"
203
+ hide-details
204
+ style="max-width: 130px"
205
+ />
206
+ <AppSelect
207
+ v-model="requestTo[lift.liftName]"
208
+ :items="lift.floors"
209
+ label="To floor"
210
+ density="compact"
211
+ hide-details
212
+ style="max-width: 130px"
213
+ />
214
+ <AppButton
215
+ variant="ghost"
216
+ icon="mdi-elevator-passenger-outline"
217
+ :disabled="requesting"
218
+ @click="askForLift(lift)"
219
+ >
220
+ Request lift for {{ robotName || "this robot" }}
221
+ </AppButton>
222
+ </div>
223
+ </div>
224
+ <p v-if="robotBrand !== 'demo'" class="text-caption text-medium-emphasis mb-0">
225
+ Only demo robots can ride a lift for now. Real lifts need the lift maker's driver, which is not available yet.
226
+ </p>
227
+ </div>
71
228
  </AppCard>
72
229
  </template>
73
230
 
74
231
  <script lang="ts" setup>
75
232
  /**
76
- * The building, in 3D, generated from the robot's own floor plan.
233
+ * The building, in 3D, generated from the robot's own floor plan - plus the
234
+ * saved layout: doors, lift shafts and floor heights, which the floor plan
235
+ * cannot say by itself.
77
236
  *
78
237
  * Nobody draws walls. The robot's map image is a SLAM occupancy grid — walls
79
238
  * are already dark pixels — so it is fetched into a canvas, thresholded, traced
@@ -81,6 +240,13 @@
81
240
  * annotated plan; this skips the annotation because the robot has surveyed the
82
241
  * building already.
83
242
  *
243
+ * ## The saved layout
244
+ *
245
+ * Doors and lift shafts are placed by hand in edit mode (flat plan, one floor)
246
+ * and saved to the building map (`/api/robots/building-maps`). With no saved
247
+ * map the view is exactly what it was before - the saved map only adds. A lift
248
+ * shaft runs through every floor it stops at, which the stacked view shows.
249
+ *
84
250
  * ## Why the image is fetched every time
85
251
  *
86
252
  * The vendor signs its map URLs for about an hour. A URL kept in a record is a
@@ -100,13 +266,22 @@
100
266
  */
101
267
  import {
102
268
  depthOf,
269
+ distanceToSegment,
270
+ doorSolid,
103
271
  fitView,
104
272
  gridFromImageData,
273
+ insideLift,
274
+ levelElevations,
105
275
  levelSolids,
276
+ liftSolid,
277
+ nextFeatureName,
106
278
  projectPoint,
107
- stackedElevations,
279
+ unprojectPoint,
108
280
  wallCorners,
109
281
  wallsFromOccupancyGrid,
282
+ type TMapDoor,
283
+ type TMapLift,
284
+ type TMapPointM,
110
285
  type TView,
111
286
  type TWallSolid,
112
287
  } from "../../utils/building-map";
@@ -117,43 +292,74 @@ const props = defineProps<{
117
292
  robotId: string;
118
293
  /** Drawn on the plan when its position and floor are both known. */
119
294
  robotState?: Record<string, any> | null;
295
+ /** May this person save the layout and use the lift (`update-robot`)? */
296
+ canEdit?: boolean;
297
+ robotName?: string;
298
+ /** Only the demo brand can ride the simulated lift. */
299
+ robotBrand?: string;
120
300
  }>();
121
301
 
122
- const { getRobotMaps, getRobotMapImages } = useRobots();
302
+ const {
303
+ getRobotMaps,
304
+ getRobotMapImages,
305
+ listBuildingMaps,
306
+ getBuildingMap,
307
+ createBuildingMap,
308
+ updateBuildingMap,
309
+ deleteBuildingMap,
310
+ getLiftQueue,
311
+ requestLift,
312
+ releaseLiftSession,
313
+ } = useRobots();
123
314
 
124
315
  const stage = ref<HTMLElement | null>(null);
125
316
  const canvasEl = ref<HTMLCanvasElement | null>(null);
126
317
 
127
318
  const maps = ref<Array<Record<string, any>>>([]);
128
319
  const selectedFloor = ref<number | null>(null);
129
- const solids = ref<TWallSolid[]>([]);
130
- const imageHeight = ref(0);
320
+ const wallSolids = ref<TWallSolid[]>([]);
131
321
  const loading = ref(true);
132
322
  const error = ref("");
133
323
  const rotation = ref(Math.PI / 5);
134
324
  const tilted = ref(true);
135
325
 
136
- const wallCount = computed(() => solids.value.length);
326
+ /* The saved layout, and the working copy the editor changes. */
327
+ const savedMap = ref<Record<string, any> | null>(null);
328
+ const savedLoadFailed = ref(false);
329
+ const doors = ref<TMapDoor[]>([]);
330
+ const lifts = ref<TMapLift[]>([]);
331
+ const heights = ref<Record<number, number | undefined>>({});
332
+
333
+ const wallCount = computed(() => wallSolids.value.length);
334
+ const featureCount = computed(() => doors.value.length + lifts.value.length);
137
335
 
138
336
  /**
139
- * "All levels" stacks every floor the robot has mapped, one storey apart.
337
+ * "All levels" stacks every floor the robot has mapped.
140
338
  * A sentinel rather than null, because null already means "nothing chosen".
141
339
  */
142
340
  const ALL_LEVELS = -1_000_000;
143
341
 
144
- const floorOptions = computed(() => {
145
- const floors = maps.value
146
- .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: m.floorNo }))
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
- });
342
+ const realFloorOptions = computed(() =>
343
+ maps.value
344
+ .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: Number(m.floorNo) }))
345
+ .sort((a, b) => a.value - b.value),
346
+ );
347
+
348
+ const floorOptions = computed(() =>
349
+ realFloorOptions.value.length > 1
350
+ ? [...realFloorOptions.value, { title: "All levels (stacked)", value: ALL_LEVELS }]
351
+ : realFloorOptions.value,
352
+ );
152
353
 
153
354
  const stacked = computed(() => selectedFloor.value === ALL_LEVELS);
154
355
 
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))));
356
+ /** Each floor's height: saved where set, otherwise one storey apart. */
357
+ const elevations = computed(() =>
358
+ levelElevations(
359
+ maps.value.map((m) => Number(m.floorNo)),
360
+ Object.entries(heights.value).map(([f, h]) => ({ floorNo: Number(f), elevationM: h })),
361
+ ),
362
+ );
157
363
 
158
364
  /* ------------------------------------------------------------------ load */
159
365
 
@@ -170,6 +376,7 @@ async function load() {
170
376
  }
171
377
  selectedFloor.value = floorOptions.value[0]?.value ?? null;
172
378
  }
379
+ await loadSaved();
173
380
  await buildLevel();
174
381
  } catch (e) {
175
382
  error.value = robotErrorMessage(e, "Could not load this building's floor plan.");
@@ -178,17 +385,45 @@ async function load() {
178
385
  }
179
386
  }
180
387
 
388
+ /**
389
+ * The newest saved map, if any. Never fails the view: without a saved map the
390
+ * building shows exactly as it always did. A map that exists but could not be
391
+ * read turns editing OFF - saving blind would create a second map beside it.
392
+ */
393
+ async function loadSaved() {
394
+ savedLoadFailed.value = false;
395
+ try {
396
+ const list = await listBuildingMaps(props.robotId, { limit: 1 });
397
+ const first = list?.items?.[0];
398
+ savedMap.value = first ? await getBuildingMap(String(first._id)) : null;
399
+ } catch {
400
+ savedMap.value = null;
401
+ savedLoadFailed.value = true;
402
+ }
403
+ applySaved(savedMap.value);
404
+ pollLifts();
405
+ }
406
+
407
+ function applySaved(map: Record<string, any> | null) {
408
+ const copy = (v: unknown) => JSON.parse(JSON.stringify(v ?? []));
409
+ doors.value = copy(map?.doors);
410
+ lifts.value = copy(map?.lifts);
411
+ const h: Record<number, number | undefined> = {};
412
+ for (const level of map?.levels ?? []) {
413
+ if (typeof level.elevationM === "number") h[Number(level.floorNo)] = level.elevationM;
414
+ }
415
+ heights.value = h;
416
+ }
417
+
181
418
  /**
182
419
  * 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.
420
+ * walls and extrude them.
186
421
  */
187
422
  async function buildLevel() {
188
- solids.value = [];
423
+ wallSolids.value = [];
189
424
  const chosen = stacked.value
190
425
  ? [...maps.value].sort((a, b) => a.floorNo - b.floorNo)
191
- : maps.value.filter((m) => m.floorNo === selectedFloor.value);
426
+ : maps.value.filter((m) => Number(m.floorNo) === selectedFloor.value);
192
427
 
193
428
  if (!chosen.length || chosen.some((m) => !m.backgroundFileKey)) {
194
429
  error.value = "This floor has no plan image.";
@@ -205,12 +440,13 @@ async function buildLevel() {
205
440
  error.value = "The floor plan image could not be fetched.";
206
441
  return;
207
442
  }
208
- const level = await traceLevel(map, url, stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0);
443
+ const z = stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0;
444
+ const level = await traceLevel(map, url, z);
209
445
  if (!level) return;
210
446
  built.push(...level);
211
447
  }
212
448
 
213
- solids.value = built;
449
+ wallSolids.value = built;
214
450
  draw();
215
451
  }
216
452
 
@@ -221,7 +457,6 @@ async function traceLevel(
221
457
  elevationM: number,
222
458
  ): Promise<TWallSolid[] | null> {
223
459
  const image = await loadImage(url);
224
- imageHeight.value = image.height;
225
460
 
226
461
  const work = document.createElement("canvas");
227
462
  work.width = image.width;
@@ -268,6 +503,52 @@ function loadImage(url: string): Promise<HTMLImageElement> {
268
503
 
269
504
  /* ------------------------------------------------------------------ draw */
270
505
 
506
+ /** Solids that are the thing being edited, so they draw highlighted. */
507
+ let highlighted = new WeakSet<TWallSolid>();
508
+
509
+ /** Doors, lift shafts and the simulated car, for the current view. */
510
+ function featureSolids(): TWallSolid[] {
511
+ highlighted = new WeakSet();
512
+ const out: TWallSolid[] = [];
513
+ const elev = elevations.value;
514
+ const floor = selectedFloor.value ?? undefined;
515
+
516
+ doors.value.forEach((door, i) => {
517
+ if (stacked.value ? !elev.has(door.floorNo) : door.floorNo !== floor) return;
518
+ const solid = doorSolid(door, stacked.value ? elev.get(door.floorNo) ?? 0 : 0);
519
+ if (!solid) return;
520
+ if (selected.value?.kind === "door" && selected.value.index === i) highlighted.add(solid);
521
+ out.push(solid);
522
+ });
523
+
524
+ lifts.value.forEach((lift, i) => {
525
+ const solid = stacked.value ? liftSolid(lift, elev) : liftSolid(lift, elev, floor);
526
+ if (!solid) return;
527
+ if (selected.value?.kind === "lift" && selected.value.index === i) highlighted.add(solid);
528
+ out.push(solid);
529
+ });
530
+
531
+ // The simulated car, on the floor it is at - stacked only, where floors differ.
532
+ if (stacked.value && !editing.value) {
533
+ for (const q of liftQueue.value) {
534
+ const lift = lifts.value.find((l) => l.name === q.liftName);
535
+ const at = Number(q.state?.currentFloor);
536
+ if (!lift || !elev.has(at)) continue;
537
+ out.push({
538
+ kind: "car",
539
+ centre: { x: lift.x, y: lift.y, z: (elev.get(at) ?? 0) + 1.1 },
540
+ lengthM: lift.widthM * 0.8,
541
+ thicknessM: lift.depthM * 0.8,
542
+ heightM: 2.2,
543
+ yaw: 0,
544
+ });
545
+ }
546
+ }
547
+ return out;
548
+ }
549
+
550
+ let lastView: TView | null = null;
551
+
271
552
  function draw() {
272
553
  const canvas = canvasEl.value;
273
554
  const host = stage.value;
@@ -286,22 +567,48 @@ function draw() {
286
567
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
287
568
  ctx.clearRect(0, 0, width, height);
288
569
 
289
- const view: TView = fitView(solids.value, { width, height }, {
570
+ const features = featureSolids();
571
+ const scene = [...wallSolids.value, ...features];
572
+
573
+ // Framed on the walls when there are any, so adding or dragging a feature
574
+ // does not move the whole picture under the pointer.
575
+ const view: TView = fitView(wallSolids.value.length ? wallSolids.value : scene, { width, height }, {
290
576
  rotation: rotation.value,
291
577
  tilt: tilted.value ? 0.95 : 0,
292
578
  });
579
+ lastView = view;
293
580
 
294
581
  // Painter's algorithm: with no depth buffer, draw order IS the depth test.
295
582
  // Lower storeys first when stacked - seen from above, a floor hides the one
296
583
  // beneath it, never the other way round.
297
- const ordered = [...solids.value].sort(
584
+ const ordered = [...scene].sort(
298
585
  (a, b) => a.centre.z - b.centre.z || depthOf(a.centre, view) - depthOf(b.centre, view),
299
586
  );
300
587
 
301
588
  for (const solid of ordered) drawBox(ctx, solid, view);
589
+ drawPending(ctx, view);
302
590
  drawRobot(ctx, view);
303
591
  }
304
592
 
593
+ /** Fill colour per kind of box; the face shade multiplies it. */
594
+ function fillFor(solid: TWallSolid, shade: number): string {
595
+ const lit = highlighted.has(solid) ? 1.15 : 1;
596
+ const c = (r: number, g: number, b: number, a = 1) =>
597
+ `rgba(${Math.min(255, Math.round(r * shade * lit))},${Math.min(255, Math.round(g * shade * lit))},${Math.min(255, Math.round(b * shade * lit))},${a})`;
598
+ switch (solid.kind) {
599
+ case "door":
600
+ return c(196, 128, 66);
601
+ case "lift":
602
+ return c(60, 130, 230, highlighted.has(solid) ? 0.45 : 0.28);
603
+ case "car":
604
+ return c(255, 150, 40);
605
+ default: {
606
+ const v = Math.round(150 * shade + 60);
607
+ return `rgb(${v},${v + 4},${v + 8})`;
608
+ }
609
+ }
610
+ }
611
+
305
612
  /** The three visible faces of a box: top, and two sides. */
306
613
  function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView) {
307
614
  const c = wallCorners(solid).map((p) => projectPoint(p.x, p.y, p.z, view));
@@ -318,15 +625,25 @@ function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView)
318
625
  ctx.beginPath();
319
626
  face.idx.forEach((i, n) => (n === 0 ? ctx.moveTo(c[i].x, c[i].y) : ctx.lineTo(c[i].x, c[i].y)));
320
627
  ctx.closePath();
321
- const v = Math.round(150 * face.shade + 60);
322
- ctx.fillStyle = `rgb(${v},${v + 4},${v + 8})`;
628
+ ctx.fillStyle = fillFor(solid, face.shade);
323
629
  ctx.fill();
324
- ctx.strokeStyle = "rgba(20,28,38,0.22)";
325
- ctx.lineWidth = 0.6;
630
+ ctx.strokeStyle = highlighted.has(solid) ? "rgba(255,90,31,0.9)" : "rgba(20,28,38,0.22)";
631
+ ctx.lineWidth = highlighted.has(solid) ? 1.4 : 0.6;
326
632
  ctx.stroke();
327
633
  }
328
634
  }
329
635
 
636
+ /** The first click of a door being drawn. */
637
+ function drawPending(ctx: CanvasRenderingContext2D, view: TView) {
638
+ const p = pendingDoorStart.value;
639
+ if (!editing.value || !p) return;
640
+ const s = projectPoint(p.x, p.y, 0, view);
641
+ ctx.beginPath();
642
+ ctx.arc(s.x, s.y, 5, 0, Math.PI * 2);
643
+ ctx.fillStyle = "#C48042";
644
+ ctx.fill();
645
+ }
646
+
330
647
  /**
331
648
  * The robot, only when its position AND its floor are both known.
332
649
  *
@@ -370,7 +687,380 @@ function toggleTilt() {
370
687
  draw();
371
688
  }
372
689
 
690
+ /* ------------------------------------------------------------------- edit */
691
+
692
+ const editing = ref(false);
693
+ const tool = ref<"select" | "door" | "lift">("select");
694
+ const selected = ref<{ kind: "door" | "lift"; index: number } | null>(null);
695
+ const pendingDoorStart = ref<TMapPointM | null>(null);
696
+ const saving = ref(false);
697
+ const editError = ref("");
698
+ const confirmRemove = ref(false);
699
+ let dragging: { kind: "door" | "lift"; index: number; last: TMapPointM } | null = null;
700
+
701
+ const toolOptions = [
702
+ { label: "Select / move", value: "select" },
703
+ { label: "Add door", value: "door" },
704
+ { label: "Add lift shaft", value: "lift" },
705
+ ];
706
+ const doorTypes = [
707
+ { title: "Hinged", value: "hinged" },
708
+ { title: "Sliding", value: "sliding" },
709
+ ];
710
+
711
+ const toolHint = computed(() => {
712
+ if (tool.value === "door") {
713
+ return pendingDoorStart.value ? "Click where the door ends." : "Click where the door starts.";
714
+ }
715
+ if (tool.value === "lift") return "Click the middle of the lift shaft.";
716
+ return "Click a door or lift to select it; drag to move it.";
717
+ });
718
+
719
+ const selectedFeature = computed<TMapDoor | TMapLift | null>(() => {
720
+ const s = selected.value;
721
+ if (!s) return null;
722
+ return (s.kind === "door" ? doors.value[s.index] : lifts.value[s.index]) ?? null;
723
+ });
724
+
725
+ /* The selected door's type and the selected lift's floors, as plain models. */
726
+ const doorType = computed<string>({
727
+ get: () => (selected.value?.kind === "door" ? doors.value[selected.value.index]?.type ?? "hinged" : "hinged"),
728
+ set: (v) => {
729
+ const s = selected.value;
730
+ if (s?.kind === "door" && doors.value[s.index]) doors.value[s.index].type = v === "sliding" ? "sliding" : "hinged";
731
+ },
732
+ });
733
+ const liftFloors = computed<number[]>({
734
+ get: () => (selected.value?.kind === "lift" ? lifts.value[selected.value.index]?.floors ?? [] : []),
735
+ set: (v) => {
736
+ const s = selected.value;
737
+ if (s?.kind === "lift" && lifts.value[s.index]) {
738
+ lifts.value[s.index].floors = [...new Set(v.map(Number))].sort((a, b) => a - b);
739
+ draw();
740
+ }
741
+ },
742
+ });
743
+
744
+ /** The selected floor's saved height, editable. Blank = one storey above. */
745
+ const currentHeight = computed<number | string>({
746
+ get: () => (selectedFloor.value !== null ? heights.value[selectedFloor.value] ?? "" : ""),
747
+ set: (v) => {
748
+ if (selectedFloor.value === null) return;
749
+ const n = typeof v === "number" ? v : parseFloat(String(v));
750
+ heights.value = { ...heights.value, [selectedFloor.value]: Number.isFinite(n) ? n : undefined };
751
+ },
752
+ });
753
+
754
+ function startEditing() {
755
+ editing.value = true;
756
+ editError.value = "";
757
+ confirmRemove.value = false;
758
+ tool.value = "select";
759
+ selected.value = null;
760
+ tilted.value = false;
761
+ if (stacked.value) selectedFloor.value = realFloorOptions.value[0]?.value ?? null;
762
+ else draw();
763
+ }
764
+
765
+ function stopEditing() {
766
+ editing.value = false;
767
+ selected.value = null;
768
+ pendingDoorStart.value = null;
769
+ dragging = null;
770
+ draw();
771
+ }
772
+
773
+ function cancelEditing() {
774
+ applySaved(savedMap.value);
775
+ stopEditing();
776
+ }
777
+
778
+ function worldAt(e: PointerEvent): TMapPointM | null {
779
+ const canvas = canvasEl.value;
780
+ if (!canvas || !lastView) return null;
781
+ const r = canvas.getBoundingClientRect();
782
+ return unprojectPoint(e.clientX - r.left, e.clientY - r.top, lastView, 0);
783
+ }
784
+
785
+ /** The feature under the pointer on this floor, lifts first (they are bigger). */
786
+ function hitTest(p: TMapPointM): { kind: "door" | "lift"; index: number } | null {
787
+ const tolerance = lastView ? 10 / lastView.zoom : 0.5;
788
+ const floor = selectedFloor.value;
789
+ const li = lifts.value.findIndex((l) => l.floors.includes(floor ?? NaN) && insideLift(p, l));
790
+ if (li >= 0) return { kind: "lift", index: li };
791
+ const di = doors.value.findIndex(
792
+ (d) => d.floorNo === floor && distanceToSegment(p, d.start, d.end) <= tolerance,
793
+ );
794
+ return di >= 0 ? { kind: "door", index: di } : null;
795
+ }
796
+
797
+ const round = (n: number) => Math.round(n * 100) / 100;
798
+ const roundPoint = (p: TMapPointM) => ({ x: round(p.x), y: round(p.y) });
799
+
800
+ function onPointerDown(e: PointerEvent) {
801
+ if (!editing.value || selectedFloor.value === null) return;
802
+ const p = worldAt(e);
803
+ if (!p) return;
804
+ editError.value = "";
805
+
806
+ if (tool.value === "door") {
807
+ const start = pendingDoorStart.value;
808
+ if (!start) {
809
+ pendingDoorStart.value = roundPoint(p);
810
+ } else {
811
+ pendingDoorStart.value = null;
812
+ if (Math.hypot(p.x - start.x, p.y - start.y) >= 0.3) {
813
+ doors.value.push({
814
+ name: nextFeatureName(doors.value.map((d) => d.name), "door"),
815
+ floorNo: selectedFloor.value,
816
+ type: "hinged",
817
+ start,
818
+ end: roundPoint(p),
819
+ });
820
+ selected.value = { kind: "door", index: doors.value.length - 1 };
821
+ } else {
822
+ editError.value = "A door must be at least 30 cm wide.";
823
+ }
824
+ }
825
+ draw();
826
+ return;
827
+ }
828
+
829
+ if (tool.value === "lift") {
830
+ const floors = realFloorOptions.value.map((f) => f.value);
831
+ if (floors.length < 2) {
832
+ editError.value = "A lift shaft needs at least two floors on this robot's map.";
833
+ return;
834
+ }
835
+ lifts.value.push({
836
+ name: nextFeatureName(lifts.value.map((l) => l.name), "lift"),
837
+ ...roundPoint(p),
838
+ widthM: 2,
839
+ depthM: 2,
840
+ floors,
841
+ });
842
+ selected.value = { kind: "lift", index: lifts.value.length - 1 };
843
+ tool.value = "select";
844
+ draw();
845
+ return;
846
+ }
847
+
848
+ selected.value = hitTest(p);
849
+ if (selected.value) {
850
+ dragging = { ...selected.value, last: p };
851
+ canvasEl.value?.setPointerCapture?.(e.pointerId);
852
+ }
853
+ draw();
854
+ }
855
+
856
+ function onPointerMove(e: PointerEvent) {
857
+ if (!dragging) return;
858
+ const p = worldAt(e);
859
+ if (!p) return;
860
+ const dx = p.x - dragging.last.x;
861
+ const dy = p.y - dragging.last.y;
862
+ dragging.last = p;
863
+ if (dragging.kind === "lift") {
864
+ const lift = lifts.value[dragging.index];
865
+ lift.x = round(lift.x + dx);
866
+ lift.y = round(lift.y + dy);
867
+ } else {
868
+ const door = doors.value[dragging.index];
869
+ door.start = roundPoint({ x: door.start.x + dx, y: door.start.y + dy });
870
+ door.end = roundPoint({ x: door.end.x + dx, y: door.end.y + dy });
871
+ }
872
+ draw();
873
+ }
874
+
875
+ function onPointerUp() {
876
+ dragging = null;
877
+ }
878
+
879
+ function removeSelected() {
880
+ const s = selected.value;
881
+ if (!s) return;
882
+ if (s.kind === "door") doors.value.splice(s.index, 1);
883
+ else lifts.value.splice(s.index, 1);
884
+ selected.value = null;
885
+ draw();
886
+ }
887
+
888
+ /** What gets saved. Drawn walls and zones already on the map are kept as they are. */
889
+ function payload() {
890
+ const savedLevels: Array<Record<string, any>> = savedMap.value?.levels ?? [];
891
+ const floorNos = [
892
+ ...new Set([...maps.value.map((m) => Number(m.floorNo)), ...savedLevels.map((l) => Number(l.floorNo))]),
893
+ ].sort((a, b) => a - b);
894
+
895
+ const levels = floorNos.map((floorNo) => {
896
+ const saved = savedLevels.find((l) => Number(l.floorNo) === floorNo) ?? {};
897
+ const robotMap = maps.value.find((m) => Number(m.floorNo) === floorNo);
898
+ const level: Record<string, any> = {
899
+ floorNo,
900
+ name: robotMap?.mapName?.trim() || saved.name || "",
901
+ };
902
+ if (saved.walls?.length) level.walls = saved.walls;
903
+ if (saved.zones?.length) level.zones = saved.zones;
904
+ const h = heights.value[floorNo];
905
+ if (typeof h === "number" && Number.isFinite(h)) level.elevationM = h;
906
+ return level;
907
+ });
908
+
909
+ return {
910
+ name: savedMap.value?.name || `${props.robotName || "Robot"} building`,
911
+ levels,
912
+ doors: doors.value.map((d) => ({ ...d, name: d.name.trim() || "Door" })),
913
+ lifts: lifts.value.map((l) => ({ ...l, name: l.name.trim() || "Lift" })),
914
+ };
915
+ }
916
+
917
+ async function save() {
918
+ const body = payload();
919
+ const short = body.lifts.find((l) => l.floors.length < 2);
920
+ if (short) {
921
+ editError.value = `${short.name} must stop at two floors or more.`;
922
+ return;
923
+ }
924
+ saving.value = true;
925
+ editError.value = "";
926
+ try {
927
+ if (savedMap.value?._id) {
928
+ await updateBuildingMap(String(savedMap.value._id), { ...body, version: savedMap.value.version });
929
+ savedMap.value = await getBuildingMap(String(savedMap.value._id));
930
+ } else {
931
+ const res = await createBuildingMap({ ...body, robotId: props.robotId });
932
+ savedMap.value = await getBuildingMap(String(res.id));
933
+ }
934
+ applySaved(savedMap.value);
935
+ stopEditing();
936
+ // Heights may have changed the stack.
937
+ if (stacked.value) await buildLevel();
938
+ pollLifts();
939
+ } catch (e) {
940
+ editError.value = robotErrorMessage(e, "Could not save the layout.");
941
+ } finally {
942
+ saving.value = false;
943
+ }
944
+ }
945
+
946
+ let confirmTimer: ReturnType<typeof setTimeout> | undefined;
947
+ async function removeSaved() {
948
+ if (!savedMap.value?._id) return;
949
+ if (!confirmRemove.value) {
950
+ confirmRemove.value = true;
951
+ clearTimeout(confirmTimer);
952
+ confirmTimer = setTimeout(() => (confirmRemove.value = false), 4000);
953
+ return;
954
+ }
955
+ saving.value = true;
956
+ try {
957
+ await deleteBuildingMap(String(savedMap.value._id));
958
+ savedMap.value = null;
959
+ liftQueue.value = [];
960
+ applySaved(null);
961
+ stopEditing();
962
+ } catch (e) {
963
+ editError.value = robotErrorMessage(e, "Could not remove the layout.");
964
+ } finally {
965
+ saving.value = false;
966
+ confirmRemove.value = false;
967
+ }
968
+ }
969
+
970
+ /* ------------------------------------------------------------------ lifts */
971
+
972
+ const liftQueue = ref<Array<Record<string, any>>>([]);
973
+ const liftError = ref("");
974
+ const requesting = ref(false);
975
+ const requestFrom = ref<Record<string, number>>({});
976
+ const requestTo = ref<Record<string, number>>({});
977
+
978
+ const thisRobotWaiting = computed(() =>
979
+ liftQueue.value.some(
980
+ (l) =>
981
+ String(l.active?.robotId ?? "") === props.robotId ||
982
+ (l.queue ?? []).some((q: any) => String(q.robotId) === props.robotId),
983
+ ),
984
+ );
985
+
986
+ async function pollLifts() {
987
+ const id = savedMap.value?._id;
988
+ if (!id || !savedMap.value?.lifts?.length || editing.value) return;
989
+ try {
990
+ const res = await getLiftQueue(String(id));
991
+ liftQueue.value = res?.items ?? [];
992
+ liftError.value = "";
993
+ for (const lift of liftQueue.value) {
994
+ requestFrom.value[lift.liftName] ??= lift.floors?.[0];
995
+ requestTo.value[lift.liftName] ??= lift.floors?.[lift.floors.length - 1];
996
+ }
997
+ if (stacked.value) draw();
998
+ } catch (e) {
999
+ liftError.value = robotErrorMessage(e, "Could not read the lift queue.");
1000
+ }
1001
+ }
1002
+
1003
+ async function askForLift(lift: Record<string, any>) {
1004
+ if (!savedMap.value?._id) return;
1005
+ requesting.value = true;
1006
+ liftError.value = "";
1007
+ try {
1008
+ await requestLift(String(savedMap.value._id), lift.liftName, {
1009
+ robotId: props.robotId,
1010
+ fromFloor: Number(requestFrom.value[lift.liftName]),
1011
+ toFloor: Number(requestTo.value[lift.liftName]),
1012
+ });
1013
+ await pollLifts();
1014
+ } catch (e) {
1015
+ liftError.value = robotErrorMessage(e, "Could not request the lift.");
1016
+ } finally {
1017
+ requesting.value = false;
1018
+ }
1019
+ }
1020
+
1021
+ async function release(row: Record<string, any>) {
1022
+ liftError.value = "";
1023
+ try {
1024
+ await releaseLiftSession(String(row._id));
1025
+ await pollLifts();
1026
+ } catch (e) {
1027
+ liftError.value = robotErrorMessage(e, "Could not release the lift.");
1028
+ }
1029
+ }
1030
+
1031
+ function motionLabel(state: any) {
1032
+ return ["stopped", "going up", "going down", "position unknown"][state?.motionState] ?? "position unknown";
1033
+ }
1034
+ function doorLabel(state: any) {
1035
+ return ["closed", "moving", "open"][state?.doorState] ?? "unknown";
1036
+ }
1037
+ function phaseLabel(lift: any) {
1038
+ const a = lift.active;
1039
+ switch (lift.phase) {
1040
+ case "to-pickup":
1041
+ return `Going to floor ${a?.fromFloor} to collect ${a?.robotName}.`;
1042
+ case "boarding":
1043
+ return `${a?.robotName} is getting in.`;
1044
+ case "to-destination":
1045
+ return `Carrying ${a?.robotName} to floor ${a?.toFloor}.`;
1046
+ case "arrived":
1047
+ return `${a?.robotName} can get out at floor ${a?.toFloor}.`;
1048
+ default:
1049
+ return "Free.";
1050
+ }
1051
+ }
1052
+ function untilLabel(when: string) {
1053
+ const ms = new Date(when).getTime() - Date.now();
1054
+ if (!Number.isFinite(ms) || ms <= 0) return "now";
1055
+ const s = Math.round(ms / 1000);
1056
+ return `in ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
1057
+ }
1058
+
1059
+ /* ---------------------------------------------------------------- watches */
1060
+
373
1061
  watch(selectedFloor, async () => {
1062
+ selected.value = null;
1063
+ pendingDoorStart.value = null;
374
1064
  if (!maps.value.length) return;
375
1065
  loading.value = true;
376
1066
  error.value = "";
@@ -383,16 +1073,27 @@ watch(selectedFloor, async () => {
383
1073
  }
384
1074
  });
385
1075
 
1076
+ watch(tool, () => {
1077
+ pendingDoorStart.value = null;
1078
+ draw();
1079
+ });
1080
+
386
1081
  watch(() => props.robotState, draw, { deep: true });
387
1082
 
388
1083
  let onResize: (() => void) | undefined;
1084
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
389
1085
  onMounted(() => {
390
1086
  load();
391
1087
  onResize = () => draw();
392
1088
  window.addEventListener("resize", onResize);
1089
+ // The queue moves on its own (leases run out, the car travels), so it is
1090
+ // re-read while the layout is open - and only then.
1091
+ pollTimer = setInterval(pollLifts, 3000);
393
1092
  });
394
1093
  onBeforeUnmount(() => {
395
1094
  if (onResize) window.removeEventListener("resize", onResize);
1095
+ clearInterval(pollTimer);
1096
+ clearTimeout(confirmTimer);
396
1097
  });
397
1098
  </script>
398
1099
 
@@ -403,10 +1104,14 @@ onBeforeUnmount(() => {
403
1104
  height: 460px;
404
1105
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.02), rgba(0, 0, 0, 0.06));
405
1106
  }
1107
+ .robot-map3d--placing .robot-map3d__canvas {
1108
+ cursor: crosshair;
1109
+ }
406
1110
  .robot-map3d__canvas {
407
1111
  display: block;
408
1112
  width: 100%;
409
1113
  height: 100%;
1114
+ touch-action: none;
410
1115
  }
411
1116
  .robot-map3d__overlay {
412
1117
  position: absolute;
@@ -417,5 +1122,24 @@ onBeforeUnmount(() => {
417
1122
  justify-content: center;
418
1123
  text-align: center;
419
1124
  padding: 24px;
1125
+ pointer-events: none;
1126
+ }
1127
+ .robot-map3d__overlay :deep(button) {
1128
+ pointer-events: auto;
1129
+ }
1130
+ .robot-map3d__editbar,
1131
+ .robot-map3d__panel {
1132
+ display: flex;
1133
+ flex-wrap: wrap;
1134
+ align-items: center;
1135
+ gap: 12px;
1136
+ border-bottom: 1px solid rgba(0, 0, 0, 0.08);
1137
+ }
1138
+ .robot-map3d__panel {
1139
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
1140
+ border-bottom: none;
1141
+ }
1142
+ .robot-map3d__lifts {
1143
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
420
1144
  }
421
1145
  </style>