@7365admin1/layer-common 4.22.0 → 4.22.1-staging.353

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 +712 -0
  20. package/components/Robot/Form.vue +256 -0
  21. package/components/Robot/Map3D.vue +1145 -0
  22. package/components/Robot/Plans.vue +63 -0
  23. package/components/Robot/SpotClean.vue +174 -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 +324 -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 +2 -2
  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 +537 -0
  44. package/utils/hid-permission-assignments.ts +190 -0
  45. package/utils/occupancy-role.ts +109 -0
  46. package/utils/robot-display.ts +212 -0
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.22.0",
5
+ "version": "4.22.1-staging.353",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -36,7 +36,7 @@
36
36
  "build": "nuxt build .playground",
37
37
  "generate": "nuxt generate .playground",
38
38
  "preview": "nuxt preview .playground",
39
- "test": "esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
39
+ "test": "esbuild composables/useVisitorSocket.ts --format=esm --outfile=test/.build/useVisitorSocket.mjs --log-level=error && esbuild composables/usePlateToastWindow.ts --format=esm --outfile=test/.build/usePlateToastWindow.mjs --log-level=error && esbuild utils/client-invite-modules.ts --bundle --platform=node --format=esm --outfile=test/.build/client-invite-modules.mjs --log-level=error && esbuild utils/robot-display.ts --bundle --platform=node --format=esm --outfile=test/.build/robot-display.mjs --log-level=error && esbuild utils/building-map.ts --bundle --platform=node --format=esm --outfile=test/.build/building-map.mjs --log-level=error && node --experimental-strip-types --test \"test/*.test.mjs\" && yarn test:units",
40
40
  "test:units": "node --experimental-strip-types --test \"utils/*.test.ts\"",
41
41
  "release": "yarn run build && changeset publish"
42
42
  },
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing HID users."
7
7
  >
8
- <HidUserEnrollment :site="siteId" />
8
+ <HidUserEnrollment :site="siteId" :org="orgId" />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing physical HID cards."
7
7
  >
8
- <HidUserEnrollment :site="siteId" card-management />
8
+ <HidUserEnrollment :site="siteId" :org="orgId" card-management />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -0,0 +1,23 @@
1
+ <template>
2
+ <v-container fluid>
3
+ <HidEnabledGate
4
+ :site="siteId"
5
+ :org="orgId"
6
+ message="Enable HID as a service for this site before generating a QR code."
7
+ >
8
+ <HidProfileQrCode :site="siteId" />
9
+ </HidEnabledGate>
10
+ </v-container>
11
+ </template>
12
+
13
+ <script setup lang="ts">
14
+ definePageMeta({
15
+ layout: "default",
16
+ middleware: ["01-auth", "02-org"],
17
+ memberOnly: true,
18
+ });
19
+
20
+ const route = useRoute();
21
+ const siteId = computed(() => String(route.params.site ?? ""));
22
+ const orgId = computed(() => String(route.params.org ?? ""));
23
+ </script>
@@ -5,7 +5,7 @@
5
5
  :org="orgId"
6
6
  message="Enable HID as a service for this site before managing HID readers."
7
7
  >
8
- <HidReaderManagement :site="siteId" />
8
+ <HidReaderManagement :site="siteId" :org="orgId" />
9
9
  </HidEnabledGate>
10
10
  </v-container>
11
11
  </template>
@@ -3,4 +3,18 @@ declare type TDocument = {
3
3
  name: string;
4
4
  attachment: string;
5
5
  type: string;
6
+ /**
7
+ * Set at upload or renewal, absent when the document never expires.
8
+ *
9
+ * An ISO instant on the way out of the API and a `YYYY-MM-DD` string on the
10
+ * way back in, which is what `InputDatePicker` binds to - hence the loose
11
+ * type rather than `string`.
12
+ */
13
+ expiryDate?: string | Date | null;
14
+ remarks?: string;
15
+ size?: number;
16
+ parentId?: string | null;
17
+ createdAt?: string | Date;
18
+ updatedAt?: string | Date;
19
+ status?: string;
6
20
  };
@@ -73,6 +73,10 @@ declare type TFacility = {
73
73
  hourInterval?: number;
74
74
  isBookingFeeEnabled: boolean;
75
75
  isGuestEnabled: boolean;
76
+ /** Residents may complete this facility's checklist themselves. */
77
+ isResidentChecklistEnabled?: boolean;
78
+ /** Security may complete it. Mutually exclusive with the above. */
79
+ isSecurityChecklistEnabled?: boolean;
76
80
  bookingAmount: number | null;
77
81
  peakBookingFeeAmount?: number | null;
78
82
  bookingFeeGuestAmount?: number | null;
package/types/people.d.ts CHANGED
@@ -22,11 +22,38 @@ declare type TPeople = {
22
22
  email?: string;
23
23
  files?: { name: string, id: string }[];
24
24
  isOwner?: boolean;
25
+ /**
26
+ * Owner / occupant / person-in-charge, as the BUSINESS people form asks it.
27
+ * Absent on everyone else - `isOwner` is still the flag that decides unit
28
+ * ownership, and the server derives it from this when it is sent. See
29
+ * `OccupancyRoles` in core's `person.model.ts`.
30
+ */
31
+ occupancyRole?: TOccupancyRole;
32
+ // Link to this person's `users` row. Empty for the person types that carry
33
+ // no login, and empty for a resident whose account was never written.
34
+ user?: string;
35
+ };
36
+
37
+ declare type TOccupancyRole = "owner" | "occupant" | "person-in-charge";
38
+
39
+ /** One standing and everything the product says about it. See `utils/occupancy-role.ts`. */
40
+ declare type TOccupancyRoleOption = {
41
+ value: TOccupancyRole;
42
+ /** The label a stored role is printed with. */
43
+ title: string;
44
+ /** The row menu's wording. */
45
+ action: string;
46
+ /** The confirmation's heading and its sentence. */
47
+ prompt: string;
48
+ description: string;
25
49
  };
26
50
 
27
51
  declare type TPlateNumber = { plateNumber: string, recNo?: string, _id?: string, status: TVehicleStatus, type: TVehicleType, anprCameras?: TVehicleAnprCamera[] };
28
52
 
29
53
 
30
- declare type TPeoplePayload = Pick<TGuest, "name" | "block" | "level" | "unit" | "unitName" | "contact" | "plateNumber" | "nric" | "contact" | "remarks" | "org" | "site" | "start" | "end" | "type" | "isOwner"> & { status?: string }
54
+ // `""` is the FORM's "nothing picked yet" - it is stripped from the payload
55
+ // before it is sent, because absence is what the server reads as "never
56
+ // asked". See `PeopleFormMgmt.vue`.
57
+ declare type TPeoplePayload = Pick<TGuest, "name" | "block" | "level" | "unit" | "unitName" | "contact" | "plateNumber" | "nric" | "contact" | "remarks" | "org" | "site" | "start" | "end" | "type" | "isOwner"> & { status?: string; user?: string; occupancyRole?: TOccupancyRole | "" }
31
58
 
32
59
  declare type TPeopleType = "guest" | "resident" | "tenant"
@@ -0,0 +1,537 @@
1
+ /**
2
+ * Floor plan to 3D layout, in the browser.
3
+ *
4
+ * This is a deliberate copy of the same logic in `@7365admin1/core`, for the
5
+ * same reason `robot-display.ts` is: core is a backend package and a browser
6
+ * cannot import it. The wall extraction has to run where the floor plan image
7
+ * is — the vendor signs its map URLs for about an hour, so the picture is
8
+ * fetched into a canvas at the moment of display and never stored, and the
9
+ * pixels only exist client-side.
10
+ *
11
+ * The two copies must agree, and the agreement is held by the same tests on
12
+ * both sides.
13
+ *
14
+ * ## Why there is no 3D library here
15
+ *
16
+ * The scene is extruded boxes standing on flat floors. A projection and a
17
+ * back-to-front draw order render that correctly in a few hundred lines, and
18
+ * `layer-common` is consumed by eleven web apps — a 3D engine is a large thing
19
+ * to put in all of them for a shape this simple.
20
+ *
21
+ * ponytail: painter's algorithm with a fixed camera. No lighting model, no
22
+ * textures, no orbit. If any of those matter later, swap Three.js in behind
23
+ * `levelSolids` / `projectPoint` — the geometry above them does not change.
24
+ */
25
+
26
+ /** `traffic_editor`'s defaults, matched so our layout and RMF's agree. */
27
+ export const WALL_HEIGHT_M = 2.5;
28
+ export const WALL_THICKNESS_M = 0.1;
29
+ export const DEFAULT_SCALE_M_PER_PX = 0.05;
30
+
31
+ export type TMapVertex = { x: number; y: number; name?: string };
32
+ export type TMapWall = { start: number; end: number; heightM?: number; thicknessM?: number };
33
+
34
+ export type TPlanLevel = {
35
+ name: string;
36
+ elevationM: number;
37
+ scaleMPerPx: number;
38
+ originXM: number;
39
+ originYM: number;
40
+ vertices: TMapVertex[];
41
+ walls: TMapWall[];
42
+ };
43
+
44
+ export type TWallSolid = {
45
+ centre: { x: number; y: number; z: number };
46
+ lengthM: number;
47
+ thicknessM: number;
48
+ heightM: number;
49
+ yaw: number;
50
+ /** What the box is, so the renderer can colour it. Absent = a wall. */
51
+ kind?: "wall" | "door" | "lift" | "car";
52
+ };
53
+
54
+ /* ------------------------------------------------- image to occupancy grid */
55
+
56
+ export type TOccupancyGrid = { data: Uint8Array; width: number; height: number };
57
+
58
+ /**
59
+ * Turn canvas RGBA into one luminance value per pixel.
60
+ *
61
+ * A fully transparent pixel is treated as FREE space, not dark. Map PNGs are
62
+ * commonly transparent outside the surveyed area, and reading alpha 0 as black
63
+ * would wrap the whole plan in a wall.
64
+ */
65
+ export function gridFromImageData(
66
+ rgba: ArrayLike<number>,
67
+ width: number,
68
+ height: number,
69
+ ): TOccupancyGrid {
70
+ const data = new Uint8Array(width * height);
71
+ for (let i = 0, p = 0; p < width * height; i += 4, p++) {
72
+ const alpha = Number(rgba[i + 3]);
73
+ if (alpha === 0) {
74
+ data[p] = 255;
75
+ continue;
76
+ }
77
+ // Rec. 601 luma — close enough for "is this pixel dark", and cheap.
78
+ data[p] =
79
+ (0.299 * Number(rgba[i]) + 0.587 * Number(rgba[i + 1]) + 0.114 * Number(rgba[i + 2])) | 0;
80
+ }
81
+ return { data, width, height };
82
+ }
83
+
84
+ /**
85
+ * Trace walls out of a floor plan, so nobody has to draw them.
86
+ *
87
+ * Horizontal runs first, then vertical runs from what those did not cover, so a
88
+ * long wall is one segment rather than one per pixel. Corners are de-duplicated
89
+ * so the result stays editable afterwards.
90
+ */
91
+ export function wallsFromOccupancyGrid(
92
+ grid: TOccupancyGrid,
93
+ options?: { threshold?: number; minRunPx?: number },
94
+ ): { vertices: TMapVertex[]; walls: TMapWall[] } {
95
+ const threshold = options?.threshold ?? 100;
96
+ const minRun = Math.max(2, options?.minRunPx ?? 6);
97
+ const { data, width, height } = grid;
98
+
99
+ if (!width || !height || !data || data.length < width * height) {
100
+ return { vertices: [], walls: [] };
101
+ }
102
+
103
+ const occupied = (x: number, y: number) => Number(data[y * width + x]) <= threshold;
104
+ const consumed = new Uint8Array(width * height);
105
+ const vertices: TMapVertex[] = [];
106
+ const walls: TMapWall[] = [];
107
+ const index = new Map<string, number>();
108
+
109
+ const vertexAt = (x: number, y: number) => {
110
+ const key = `${x}:${y}`;
111
+ const found = index.get(key);
112
+ if (found !== undefined) return found;
113
+ vertices.push({ x, y });
114
+ index.set(key, vertices.length - 1);
115
+ return vertices.length - 1;
116
+ };
117
+
118
+ for (let y = 0; y < height; y++) {
119
+ let run = 0;
120
+ for (let x = 0; x <= width; x++) {
121
+ if (x < width && occupied(x, y)) {
122
+ run++;
123
+ continue;
124
+ }
125
+ if (run >= minRun) {
126
+ const startX = x - run;
127
+ walls.push({ start: vertexAt(startX, y), end: vertexAt(x - 1, y) });
128
+ for (let i = startX; i < x; i++) consumed[y * width + i] = 1;
129
+ }
130
+ run = 0;
131
+ }
132
+ }
133
+
134
+ for (let x = 0; x < width; x++) {
135
+ let run = 0;
136
+ for (let y = 0; y <= height; y++) {
137
+ if (y < height && occupied(x, y) && !consumed[y * width + x]) {
138
+ run++;
139
+ continue;
140
+ }
141
+ if (run >= minRun) {
142
+ walls.push({ start: vertexAt(x, y - run), end: vertexAt(x, y - 1) });
143
+ }
144
+ run = 0;
145
+ }
146
+ }
147
+
148
+ return { vertices, walls };
149
+ }
150
+
151
+ /* ------------------------------------------------------------- geometry */
152
+
153
+ export function levelScale(level: TPlanLevel): number {
154
+ return level.scaleMPerPx > 0 ? level.scaleMPerPx : DEFAULT_SCALE_M_PER_PX;
155
+ }
156
+
157
+ /**
158
+ * A drawing pixel in site metres.
159
+ *
160
+ * The vertical flip is the occupancy-grid convention: image origin top-left,
161
+ * map origin bottom-left. Without it the building renders mirrored, which reads
162
+ * as "the robot is in the wrong room" rather than as a transform bug.
163
+ */
164
+ export function levelPixelToMetres(
165
+ level: TPlanLevel,
166
+ px: number,
167
+ py: number,
168
+ imageHeightPx: number,
169
+ ): { x: number; y: number } {
170
+ const scale = levelScale(level);
171
+ return {
172
+ x: level.originXM + px * scale,
173
+ y: level.originYM + (imageHeightPx - py) * scale,
174
+ };
175
+ }
176
+
177
+ /** Extrude a level's walls into boxes a renderer can place. */
178
+ export function levelSolids(level: TPlanLevel, imageHeightPx: number): TWallSolid[] {
179
+ const solids: TWallSolid[] = [];
180
+ for (const wall of level.walls ?? []) {
181
+ const a = level.vertices[wall.start];
182
+ const b = level.vertices[wall.end];
183
+ if (!a || !b) continue;
184
+
185
+ const pa = levelPixelToMetres(level, a.x, a.y, imageHeightPx);
186
+ const pb = levelPixelToMetres(level, b.x, b.y, imageHeightPx);
187
+ const lengthM = Math.hypot(pb.x - pa.x, pb.y - pa.y);
188
+ // A zero-length wall renders as a flickering sliver that looks like a
189
+ // graphics fault rather than a map mistake.
190
+ if (lengthM <= 0) continue;
191
+
192
+ const heightM = wall.heightM ?? WALL_HEIGHT_M;
193
+ solids.push({
194
+ centre: {
195
+ x: (pa.x + pb.x) / 2,
196
+ y: (pa.y + pb.y) / 2,
197
+ // Boxes are centred, so a wall standing ON the floor sits at half its
198
+ // own height above the level's elevation.
199
+ z: level.elevationM + heightM / 2,
200
+ },
201
+ lengthM,
202
+ thicknessM: wall.thicknessM ?? WALL_THICKNESS_M,
203
+ heightM,
204
+ yaw: Math.atan2(pb.y - pa.y, pb.x - pa.x),
205
+ });
206
+ }
207
+ return solids;
208
+ }
209
+
210
+ /* ----------------------------------------------------------- projection */
211
+
212
+ export type TView = {
213
+ /** Radians. How far the scene is turned about the vertical axis. */
214
+ rotation: number;
215
+ /** Radians. 0 is a plan view looking straight down; ~0.9 reads as 3D. */
216
+ tilt: number;
217
+ /** Screen pixels per metre. */
218
+ zoom: number;
219
+ /** Where the site origin lands on the canvas. */
220
+ originPx: { x: number; y: number };
221
+ };
222
+
223
+ /**
224
+ * A point in site metres, on the canvas.
225
+ *
226
+ * An axonometric projection: rotate about the vertical axis, then foreshorten
227
+ * the depth axis by the tilt. Parallel, so there is no perspective distortion
228
+ * and a wall is the same size wherever it sits — which is what you want for a
229
+ * floor plan, and is why a full camera is not needed.
230
+ *
231
+ * Screen y grows downward, so height is SUBTRACTED: a taller wall draws further
232
+ * up the canvas.
233
+ */
234
+ export function projectPoint(
235
+ x: number,
236
+ y: number,
237
+ z: number,
238
+ view: TView,
239
+ ): { x: number; y: number } {
240
+ const cos = Math.cos(view.rotation);
241
+ const sin = Math.sin(view.rotation);
242
+
243
+ const rx = x * cos - y * sin;
244
+ const ry = x * sin + y * cos;
245
+
246
+ return {
247
+ x: view.originPx.x + rx * view.zoom,
248
+ y: view.originPx.y + ry * view.zoom * Math.cos(view.tilt) - z * view.zoom * Math.sin(view.tilt),
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Back-to-front order, so nearer walls are drawn over farther ones.
254
+ *
255
+ * Painter's algorithm: with no depth buffer, draw order IS the depth test. Sort
256
+ * by the rotated depth axis, lowest first — get this backwards and the building
257
+ * renders inside out, which looks like a rendering bug and is really a sort.
258
+ */
259
+ export function depthOf(point: { x: number; y: number }, view: TView): number {
260
+ return point.x * Math.sin(view.rotation) + point.y * Math.cos(view.rotation);
261
+ }
262
+
263
+ /** The eight corners of a wall box, in site metres. */
264
+ export function wallCorners(solid: TWallSolid): Array<{ x: number; y: number; z: number }> {
265
+ const hl = solid.lengthM / 2;
266
+ const ht = solid.thicknessM / 2;
267
+ const hh = solid.heightM / 2;
268
+ const cos = Math.cos(solid.yaw);
269
+ const sin = Math.sin(solid.yaw);
270
+
271
+ const corners: Array<{ x: number; y: number; z: number }> = [];
272
+ for (const dz of [-hh, hh]) {
273
+ for (const [dl, dt] of [
274
+ [-hl, -ht],
275
+ [hl, -ht],
276
+ [hl, ht],
277
+ [-hl, ht],
278
+ ] as const) {
279
+ corners.push({
280
+ x: solid.centre.x + dl * cos - dt * sin,
281
+ y: solid.centre.y + dl * sin + dt * cos,
282
+ z: solid.centre.z + dz,
283
+ });
284
+ }
285
+ }
286
+ return corners;
287
+ }
288
+
289
+ /**
290
+ * How big the site is, so a view can be framed without anyone choosing numbers.
291
+ *
292
+ * Returns null for an empty scene rather than a zero-size box: a caller must be
293
+ * able to tell "nothing to show" from "everything is at the origin".
294
+ */
295
+ export function solidsBounds(solids: TWallSolid[]): {
296
+ minX: number; maxX: number; minY: number; maxY: number;
297
+ } | null {
298
+ if (!solids.length) return null;
299
+
300
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
301
+ for (const s of solids) {
302
+ for (const c of wallCorners(s)) {
303
+ if (c.x < minX) minX = c.x;
304
+ if (c.x > maxX) maxX = c.x;
305
+ if (c.y < minY) minY = c.y;
306
+ if (c.y > maxY) maxY = c.y;
307
+ }
308
+ }
309
+ return { minX, maxX, minY, maxY };
310
+ }
311
+
312
+ /**
313
+ * A view that fits the whole site on the canvas.
314
+ *
315
+ * Falls back to a sane zoom for a degenerate scene — a single wall has zero
316
+ * extent on one axis, and dividing by it would give an infinite zoom and a
317
+ * blank canvas.
318
+ */
319
+ export function fitView(
320
+ solids: TWallSolid[],
321
+ canvas: { width: number; height: number },
322
+ options?: { rotation?: number; tilt?: number; paddingPx?: number },
323
+ ): TView {
324
+ const rotation = options?.rotation ?? Math.PI / 5;
325
+ const tilt = options?.tilt ?? 0.95;
326
+ const padding = options?.paddingPx ?? 32;
327
+
328
+ const base: TView = {
329
+ rotation,
330
+ tilt,
331
+ zoom: 20,
332
+ originPx: { x: canvas.width / 2, y: canvas.height / 2 },
333
+ };
334
+
335
+ const bounds = solidsBounds(solids);
336
+ if (!bounds) return base;
337
+
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 = [
347
+ { x: bounds.minX, y: bounds.minY },
348
+ { x: bounds.maxX, y: bounds.minY },
349
+ { x: bounds.maxX, y: bounds.maxY },
350
+ { x: bounds.minX, y: bounds.maxY },
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
+ );
355
+
356
+ const spanX = Math.max(...projected.map((p) => p.x)) - Math.min(...projected.map((p) => p.x));
357
+ const spanY = Math.max(...projected.map((p) => p.y)) - Math.min(...projected.map((p) => p.y));
358
+
359
+ const usableW = Math.max(1, canvas.width - padding * 2);
360
+ const usableH = Math.max(1, canvas.height - padding * 2);
361
+ const zoom =
362
+ spanX > 0 && spanY > 0
363
+ ? Math.min(usableW / spanX, usableH / spanY)
364
+ : base.zoom;
365
+
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
+ };
372
+
373
+ return {
374
+ rotation,
375
+ tilt,
376
+ zoom,
377
+ originPx: { x: canvas.width / 2 - centre.x, y: canvas.height / 2 - centre.y },
378
+ };
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
+ }