@7365admin1/layer-common 4.28.1-staging.361 → 4.28.1-staging.362

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.
@@ -89,6 +89,24 @@ export function networkStatesFeed(intervalMs = 4000): TRobotLiveFeed {
89
89
  );
90
90
  }
91
91
 
92
+ /**
93
+ * Any estate screen's feed (Property Management, Hygiene, Security, the
94
+ * console's site drill-down, robot detail): `GET /api/robots/states?ids=...`.
95
+ * The API checks every robot against its own site and narrows by the app's
96
+ * `appSlug`, so a robot this screen may not see simply never arrives.
97
+ */
98
+ export function siteStatesFeed(intervalMs = 4000): TRobotLiveFeed {
99
+ const appSlug = useRuntimeConfig().public?.appSlug as string | undefined;
100
+ return robotPollingFeed(
101
+ (ids) =>
102
+ useNuxtApp().$api<{ items: any[] }>("/api/robots/states", {
103
+ method: "GET",
104
+ query: { ids: ids.join(","), appSlug },
105
+ }),
106
+ intervalMs,
107
+ );
108
+ }
109
+
92
110
  /**
93
111
  * `states[id]` for every robot in `ids`, kept live by `feed`. Re-watches when
94
112
  * the ids change (a new page, a new filter); stops on unmount.
@@ -32,6 +32,50 @@ export default function useRobots() {
32
32
  );
33
33
  }
34
34
 
35
+ /**
36
+ * One site's robots for the HERO fleet screen: the stored record plus each
37
+ * robot's open fault / OFFLINE record and last-seen, paged. The answer has
38
+ * `pages` and `total` (read them with `listMeta` - never `totalPages`).
39
+ */
40
+ function getSiteFleet(
41
+ organization: string,
42
+ site: string,
43
+ { page = 1, limit = 25, type = "", search = "" }: { page?: number; limit?: number; type?: string; search?: string } = {},
44
+ ) {
45
+ return useNuxtApp().$api<Record<string, any>>(
46
+ `/api/robots/organization/${organization}/site/${site}/fleet`,
47
+ { method: "GET", query: { page, limit, type: type || undefined, search: search || undefined, appSlug } },
48
+ );
49
+ }
50
+
51
+ /** The site's six summary counts (Total · Online · Working · Charging · Faults · Offline). */
52
+ function getSiteSummary(organization: string, site: string, { type = "" }: { type?: string } = {}) {
53
+ return useNuxtApp().$api<Record<string, any>>(
54
+ `/api/robots/organization/${organization}/site/${site}/summary`,
55
+ { method: "GET", query: { type: type || undefined, appSlug } },
56
+ );
57
+ }
58
+
59
+ /** One robot's record for its detail screen: names, serial, open fault. Never a credential. */
60
+ function getRobot(id: string) {
61
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}`, {
62
+ method: "GET",
63
+ query: { appSlug },
64
+ });
65
+ }
66
+
67
+ /**
68
+ * A security robot's patrol routes (ordered, named checkpoints; the one it is
69
+ * heading for) and their schedule. `supported: false` = the brand has no
70
+ * patrol interface - show "Monitoring not available", never an invented route.
71
+ */
72
+ function getPatrolRoutes(id: string) {
73
+ return useNuxtApp().$api<Record<string, any>>(`/api/robots/${id}/patrol-routes`, {
74
+ method: "GET",
75
+ query: { appSlug },
76
+ });
77
+ }
78
+
35
79
  /**
36
80
  * Register a robot.
37
81
  *
@@ -212,7 +256,10 @@ export default function useRobots() {
212
256
  | { kind: "return" }
213
257
  | { kind: "full"; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
214
258
  | { kind: "area"; areas: string[]; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
215
- | { kind: "spot"; points: Array<{ x: number; y: number }>; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number },
259
+ | { kind: "spot"; points: Array<{ x: number; y: number }>; cleanTimes?: number; modeFlag?: number; subModeFlag?: number; levelFlag?: number }
260
+ | { kind: "pause" | "resume" | "cancel" }
261
+ | { kind: "navigate"; x: number; y: number; theta?: number }
262
+ | { kind: "relocalize"; floorNo: number; x: number; y: number; theta: number },
216
263
  ) {
217
264
  return useNuxtApp().$api<Record<string, any>>(
218
265
  `/api/robots/${id}/command`,
@@ -310,6 +357,10 @@ export default function useRobots() {
310
357
  releaseLiftSession,
311
358
  getRobotLiftSession,
312
359
  getRobots,
360
+ getSiteFleet,
361
+ getSiteSummary,
362
+ getRobot,
363
+ getPatrolRoutes,
313
364
  getRobotBrands,
314
365
  trackRobot,
315
366
  createRobot,
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.28.1-staging.361",
5
+ "version": "4.28.1-staging.362",
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.",
@@ -325,6 +325,13 @@ const REPORTED_FACTS: ReadonlyArray<{ fact: "battery" | "floor" | "position"; ne
325
325
  { fact: "floor", needs: "floorReporting" },
326
326
  { fact: "position", needs: "readLocation" },
327
327
  ];
328
+ /** The "Not reported by" line's words and order (the handoff's): battery, floor, spot clean, live position. */
329
+ const NOT_REPORTED: ReadonlyArray<{ word: string; needs: string; cleaningOnly?: boolean }> = [
330
+ { word: "battery", needs: "battery" },
331
+ { word: "floor", needs: "floorReporting" },
332
+ { word: "spot clean", needs: "spotClean", cleaningOnly: true },
333
+ { word: "live position", needs: "readLocation" },
334
+ ];
328
335
 
329
336
  /** Which facts this brand reports - a fact cell it cannot fill says "Not reported". */
330
337
  export function reportedFacts(capabilities: Record<string, unknown> | null | undefined) {
@@ -336,13 +343,21 @@ export function reportedFacts(capabilities: Record<string, unknown> | null | und
336
343
  }
337
344
 
338
345
  /**
339
- * "Not reported by Ounitech: battery, floor" - shown on robot detail so a
340
- * missing fact reads as the brand's limit, not a fault. The brand's trailing
341
- * model list ("Ounitech (Q3-G / Q3-W)") is dropped. Null when nothing is missing.
346
+ * "Not reported by Ounitech: battery, floor, spot clean" - shown on robot
347
+ * detail so a missing fact reads as the brand's limit, not a fault (the
348
+ * handoff's words and order). Spot clean is a cleaning job, so it is never
349
+ * listed for a security robot. The brand's trailing model list ("Ounitech
350
+ * (Q3-G / Q3-W)") is dropped. Null when nothing is missing.
342
351
  */
343
- export function notReportedLine(brand: unknown, capabilities: Record<string, unknown> | null | undefined): string | null {
344
- const facts = reportedFacts(capabilities);
345
- const missing = REPORTED_FACTS.filter((f) => !facts[f.fact]).map((f) => f.fact);
352
+ export function notReportedLine(
353
+ brand: unknown,
354
+ capabilities: Record<string, unknown> | null | undefined,
355
+ type?: unknown,
356
+ ): string | null {
357
+ const caps = capabilities ?? {};
358
+ const missing = NOT_REPORTED.filter((f) => caps[f.needs] !== true && !(f.cleaningOnly && type === "security")).map(
359
+ (f) => f.word,
360
+ );
346
361
  if (!missing.length) return null;
347
362
  const name = (typeof brand === "string" ? brand : "").replace(/\s*\([^)]*\)\s*$/, "").trim() || "this brand";
348
363
  return `Not reported by ${name}: ${missing.join(", ")}`;
@@ -564,6 +579,11 @@ export type TLiveRobotState = {
564
579
  floorNo?: number | null;
565
580
  floorKnown?: boolean;
566
581
  position?: { x: number; y: number; theta: number } | null;
582
+ /** Where it is on its own floor plan, 0-100 from the top-left; absent when the brand cannot say. */
583
+ planPosition?: { x: number; y: number } | null;
584
+ /** The brand's own status words ("CLEANING_AUTO"), quoted as "Brand status". */
585
+ statusName?: string;
586
+ model?: string;
567
587
  fault?: { code: string; message?: string; since?: number } | null;
568
588
  capabilities?: Record<string, unknown>;
569
589
  lastSeenAt?: string | null;
@@ -603,3 +623,471 @@ export function rowStatus(
603
623
  if (row?.offline === true) return { kind: "offline" };
604
624
  return { kind: "checking" };
605
625
  }
626
+
627
+ /* ============================================ site fleet (HERO phase c) */
628
+
629
+ /** "Cleaning" / "Security"; anything else is cleaning, the class a row written before `type` existed belongs to. */
630
+ export function typeLabel(type: unknown): string {
631
+ return type === "security" ? "Security" : "Cleaning";
632
+ }
633
+
634
+ /**
635
+ * The fleet list's paging, from the API's `{ items, pages, total }`.
636
+ *
637
+ * THE PAGE-1 BUG: the old fleet screen read `totalPages`, which the API has
638
+ * never sent (core's `paginate()` answers `pages` and `pageRange`), so it
639
+ * always believed there was one page and never offered the next. This reads
640
+ * what the API sends: `total`, else the count in `pageRange` ("1-10 of 60"),
641
+ * else the rows in hand; `pages`, else derived from the total.
642
+ */
643
+ export function listMeta(res: Record<string, any> | null | undefined, limit: number): { total: number; pages: number } {
644
+ const size = limit > 0 ? Math.floor(limit) : 10;
645
+ const rows = Array.isArray(res?.items) ? res!.items.length : 0;
646
+ let total = typeof res?.total === "number" && res.total >= 0 ? Math.floor(res.total) : NaN;
647
+ if (!Number.isFinite(total)) {
648
+ const m = /of\s+(\d+)/.exec(String(res?.pageRange ?? ""));
649
+ total = m ? Number(m[1]) : rows;
650
+ }
651
+ const sent = Number(res?.pages ?? res?.totalPages);
652
+ const pages = Number.isFinite(sent) && sent >= 1 ? Math.floor(sent) : Math.ceil(total / size);
653
+ return { total, pages: Math.max(1, pages) };
654
+ }
655
+
656
+ /**
657
+ * The site's six summary cells (README §2): Total · Online · Cleaning|Patrolling
658
+ * · Charging · Faults · Offline. Live counts are null ("—") until the server
659
+ * has read the robots (`live.asOf`); nothing at all is known before the
660
+ * summary arrives. Faults and Offline turn accent when above zero.
661
+ */
662
+ export function siteSummaryCells(summary: Record<string, any> | null | undefined, type: unknown) {
663
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
664
+ const known = !!summary;
665
+ const total = known ? num(summary!.total) ?? 0 : 0;
666
+ const live = known && summary!.live?.asOf ? summary!.live : null;
667
+ return [
668
+ { label: "Total", value: known ? total : null, total },
669
+ { label: "Online", value: live ? num(live.online?.count) : null, total },
670
+ { label: type === "security" ? "Patrolling" : "Cleaning", value: live ? num(live.working?.count) : null, total },
671
+ { label: "Charging", value: live ? num(live.charging?.count) : null, total },
672
+ { label: "Faults", value: known ? num(summary!.faults?.count) ?? 0 : null, total, kind: "faults" },
673
+ { label: "Offline", value: known ? num(summary!.offline?.count) ?? 0 : null, total, kind: "offline" },
674
+ ];
675
+ }
676
+
677
+ /** The empty state: "No cleaning robots at this site" and what to do about it. */
678
+ export function siteEmptyText(type: unknown, canSetup: unknown) {
679
+ return {
680
+ title: `No ${typeLabel(type).toLowerCase()} robots at this site`,
681
+ hint: canSetup === true ? "Add a robot to this site to start monitoring." : "Nothing has been deployed here yet.",
682
+ };
683
+ }
684
+
685
+ /** The header's role tag. Super Admin holds every right; otherwise Manager (may command or set up) or View-only. */
686
+ export function roleLabel(input: { superAdmin?: unknown; canCommand?: unknown; canSetup?: unknown }): string {
687
+ if (input?.superAdmin === true) return "Full rights";
688
+ return input?.canCommand === true || input?.canSetup === true ? "Manager" : "View-only";
689
+ }
690
+
691
+ /**
692
+ * A brand's display name: the build's own (`/robots/brands`) with any
693
+ * trailing model list dropped ("Ounitech (Q3-G / Q3-W)" -> "Ounitech", but
694
+ * "Demo robots (simulated)" keeps its honesty), else a readable form of the
695
+ * stored key - a brand with no adapter here ("sentry") still has a name.
696
+ */
697
+ export function brandName(brand: unknown, brands?: Array<{ brand?: unknown; displayName?: unknown }> | null): string {
698
+ const key = typeof brand === "string" && brand.trim() ? brand.trim() : "ounitech";
699
+ const hit = (brands ?? []).find((b) => b?.brand === key);
700
+ if (typeof hit?.displayName === "string" && hit.displayName) {
701
+ return hit.displayName.replace(/\s*\(([^)]*)\)\s*$/, (m, inner) => (/simulated/i.test(inner) ? m : ""));
702
+ }
703
+ if (key === "demo") return "Demo robots (simulated)";
704
+ return key.charAt(0).toUpperCase() + key.slice(1);
705
+ }
706
+
707
+ /* ------------------------------------------------------------- mini-map */
708
+
709
+ export type TMapRobot = { id: string; name: string; mode?: string; type?: string; left: string; top: string; rot: string };
710
+
711
+ const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
712
+
713
+ /** A robot's point on its floor plan (`planPosition`, 0-100 from top-left) as CSS left/top, or null. */
714
+ export function planPoint(state: { planPosition?: { x?: unknown; y?: unknown } | null } | null | undefined) {
715
+ const p = state?.planPosition;
716
+ if (!p || !finite(p.x) || !finite(p.y)) return null;
717
+ const clamp = (v: number) => Math.min(100, Math.max(0, v));
718
+ return { left: `${clamp(p.x)}%`, top: `${clamp(p.y)}%` };
719
+ }
720
+
721
+ /**
722
+ * The heading as a CSS rotation. `position.theta` is radians in the robot's
723
+ * map frame (y up); the screen's y runs down, so the angle is negated.
724
+ * 0deg (no heading) points right, like the prototype's heading tick.
725
+ */
726
+ export function headingDeg(state: { position?: { theta?: unknown } | null } | null | undefined): number {
727
+ const t = state?.position?.theta;
728
+ if (!finite(t)) return 0;
729
+ return Math.round(((((-t * 180) / Math.PI) % 360) + 360) % 360);
730
+ }
731
+
732
+ /** Is the robot live on a known floor with a plan position - i.e. may it be drawn? */
733
+ function placeable(live: TLiveRobotState | null | undefined) {
734
+ return !!live?.ok && live.online !== false && live.floorKnown === true && finite(live.floorNo) && !!planPoint(live as any);
735
+ }
736
+
737
+ /** The floors the mini-map can show: every floor a robot on screen reports, lowest first. */
738
+ export function mapFloors(ids: string[], states: Record<string, TLiveRobotState>): number[] {
739
+ const floors = new Set<number>();
740
+ for (const id of ids) {
741
+ const s = states[id];
742
+ if (s?.ok && s.floorKnown === true && finite(s.floorNo)) floors.add(s.floorNo);
743
+ }
744
+ return [...floors].sort((a, b) => a - b);
745
+ }
746
+
747
+ /**
748
+ * Which floor the mini-map opens on: the one chosen if it still exists, else
749
+ * the busiest (most robots placed; the handoff's "best floor"), else the lowest.
750
+ */
751
+ export function pickFloor(floors: number[], chosen: unknown, ids: string[], states: Record<string, TLiveRobotState>): number | null {
752
+ if (finite(chosen) && floors.includes(chosen)) return chosen;
753
+ if (!floors.length) return null;
754
+ let best = floors[0]!;
755
+ let most = -1;
756
+ for (const f of floors) {
757
+ const n = ids.filter((id) => placeable(states[id]) && states[id]!.floorNo === f).length;
758
+ if (n > most) {
759
+ most = n;
760
+ best = f;
761
+ }
762
+ }
763
+ return best;
764
+ }
765
+
766
+ /** The robots drawn on `floor`: live, online, on that floor, with a plan position. Never a stale dot. */
767
+ export function mapRobots(
768
+ rows: Array<{ _id?: unknown; name?: unknown; type?: unknown }>,
769
+ states: Record<string, TLiveRobotState>,
770
+ floor: number | null,
771
+ ): TMapRobot[] {
772
+ if (floor === null) return [];
773
+ return rows.flatMap((r) => {
774
+ const id = String(r?._id ?? "");
775
+ const live = states[id];
776
+ if (!placeable(live) || live!.floorNo !== floor) return [];
777
+ const at = planPoint(live as any)!;
778
+ return [{ id, name: String(r.name ?? ""), mode: live!.mode, type: r.type as string, ...at, rot: `rotate(${headingDeg(live)}deg)` }];
779
+ });
780
+ }
781
+
782
+ /** Robots that answer but cannot report a floor - listed, never placed (a guessed floor is worse than none). */
783
+ export function unplacedRobots<T extends { _id?: unknown }>(rows: T[], states: Record<string, TLiveRobotState>): T[] {
784
+ return rows.filter((r) => {
785
+ const live = states[String(r?._id ?? "")];
786
+ return !!live?.ok && live.monitorable !== false && live.floorKnown !== true;
787
+ });
788
+ }
789
+
790
+ /** "2 robots (Ounitech) can't report a floor, so they are listed but not placed on the map." */
791
+ export function unplacedText(brandNames: string[]): string {
792
+ const n = brandNames.length;
793
+ if (!n) return "";
794
+ const brands = [...new Set(brandNames)].join(", ");
795
+ return `${n} ${n === 1 ? "robot" : "robots"} (${brands}) can't report a floor, so ${n === 1 ? "it is" : "they are"} listed but not placed on the map.`;
796
+ }
797
+
798
+ /* -------------------------------------------------------- patrol routes */
799
+
800
+ export type TPatrolRouteView = {
801
+ id: string;
802
+ name: string;
803
+ floorNo: number | null;
804
+ checkpoints: Array<{ name: string; x: number; y: number }>;
805
+ currentCheckpoint: number | null;
806
+ };
807
+
808
+ /** The SVG path of a closed route on a `w` x `h` viewBox (checkpoints are 0-100 shares of the plan). */
809
+ export function routePathD(checkpoints: Array<{ x: number; y: number }>, w = 400, h = 300): string {
810
+ if (!checkpoints?.length) return "";
811
+ return checkpoints.map((p, i) => `${i ? "L" : "M"}${((p.x / 100) * w).toFixed(1)} ${((p.y / 100) * h).toFixed(1)}`).join(" ") + " Z";
812
+ }
813
+
814
+ /** Numbered checkpoint markers for every route; `current` = the one the robot is heading for. */
815
+ export function routeMarks(routes: TPatrolRouteView[]) {
816
+ return routes.flatMap((r) =>
817
+ r.checkpoints.map((c, i) => ({
818
+ key: `${r.id}-${i}`,
819
+ n: i + 1,
820
+ left: `${c.x}%`,
821
+ top: `${c.y}%`,
822
+ label: c.name,
823
+ current: r.currentCheckpoint === i,
824
+ })),
825
+ );
826
+ }
827
+
828
+ /** A route-name tag at each route's first checkpoint. */
829
+ export function routeTags(routes: TPatrolRouteView[]) {
830
+ return routes
831
+ .filter((r) => r.checkpoints.length)
832
+ .map((r) => ({ key: r.id, name: r.name, count: r.checkpoints.length, left: `${r.checkpoints[0]!.x}%`, top: `${r.checkpoints[0]!.y}%` }));
833
+ }
834
+
835
+ const DAY_SHORT = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
836
+
837
+ /**
838
+ * Days as a person says them: every day = "Daily"; a run of three or more
839
+ * = "Mon–Fri"; otherwise a list ("Sat", "Mon, Wed"). 1-7, Monday first.
840
+ */
841
+ export function dayRange(days: unknown): string {
842
+ const list = [...new Set((Array.isArray(days) ? days : []).filter((d) => Number.isInteger(d) && d >= 1 && d <= 7))].sort(
843
+ (a, b) => a - b,
844
+ ) as number[];
845
+ if (!list.length) return "No days set";
846
+ if (list.length === 7) return "Daily";
847
+ const parts: string[] = [];
848
+ for (let i = 0; i < list.length; ) {
849
+ let j = i;
850
+ while (j + 1 < list.length && list[j + 1] === list[j]! + 1) j++;
851
+ if (j - i >= 2) parts.push(`${DAY_SHORT[list[i]! - 1]}–${DAY_SHORT[list[j]! - 1]}`);
852
+ else for (let k = i; k <= j; k++) parts.push(DAY_SHORT[list[k]! - 1]!);
853
+ i = j + 1;
854
+ }
855
+ return parts.join(", ");
856
+ }
857
+
858
+ export type TScheduleRow = { key: string; days: string; time: string; jobs: string };
859
+
860
+ /** A floor number the way a schedule says it: "L1" (the handoff's schedule rows). */
861
+ const levelText = (floorNo: unknown) => (finite(floorNo) ? `L${floorNo}` : "Floor unknown");
862
+ const timeWindow = (start: unknown, end: unknown) => {
863
+ const s = typeof start === "string" ? start : "";
864
+ const e = typeof end === "string" ? end : "";
865
+ return s && e ? `${s}–${e}` : s || e || "No time set";
866
+ };
867
+
868
+ /**
869
+ * Patrol schedule rows (the owner's words): "Daily · 20:00–06:00 · Route A ·
870
+ * Lobby loop · L1 · 4 checkpoints × 6 rounds". A row whose route is not in
871
+ * the plan is dropped rather than shown without a name.
872
+ */
873
+ export function patrolScheduleRows(
874
+ plan: { routes?: TPatrolRouteView[]; schedule?: Array<Record<string, any>> } | null | undefined,
875
+ ): TScheduleRow[] {
876
+ const routes = plan?.routes ?? [];
877
+ return (plan?.schedule ?? []).flatMap((row, i) => {
878
+ const route = routes.find((r) => r.id === row?.routeId);
879
+ if (!route) return [];
880
+ const rounds = finite(row.rounds) ? row.rounds : 1;
881
+ return [
882
+ {
883
+ key: `${route.id}-${i}`,
884
+ days: dayRange(row.days),
885
+ time: timeWindow(row.startTime, row.endTime),
886
+ jobs: `${route.name} · ${levelText(route.floorNo)} · ${route.checkpoints.length} checkpoints × ${rounds} ${rounds === 1 ? "round" : "rounds"}`,
887
+ },
888
+ ];
889
+ });
890
+ }
891
+
892
+ /** Cleaning schedule rows from the brand's plans: "Mon–Fri · 22:00–02:00 · L1 × 2 passes · L2 × 1 pass". */
893
+ export function cleaningScheduleRows(plans: Array<Record<string, any>> | null | undefined): TScheduleRow[] {
894
+ return (plans ?? []).map((plan, i) => ({
895
+ key: String(plan?.planId ?? i),
896
+ days: dayRange(plan?.dateList),
897
+ time: timeWindow(plan?.startTime, plan?.endTime),
898
+ jobs: (Array.isArray(plan?.jobList) ? plan!.jobList : [])
899
+ .map((job: any) => {
900
+ const n = finite(job?.cleanTimes) ? job.cleanTimes : 1;
901
+ return `${levelText(job?.floorNo)} × ${n} ${n === 1 ? "pass" : "passes"}`;
902
+ })
903
+ .join(" · "),
904
+ }));
905
+ }
906
+
907
+ /* ---------------------------------------------------------- robot detail */
908
+
909
+ /** Modes in which a robot moves on its own - its trail grows and its speed is shown. */
910
+ const MOVING: ReadonlySet<string> = new Set(["WORKING", "IN_TRANSIT", "MANUAL"]);
911
+
912
+ /** Is the robot moving on its own (its trail grows)? */
913
+ export function isMoving(mode: unknown): boolean {
914
+ return typeof mode === "string" && MOVING.has(mode);
915
+ }
916
+
917
+ /**
918
+ * The status a command leaves the robot in, shown at once (optimistically)
919
+ * until the next reading confirms or corrects it - the handoff's `send()`.
920
+ */
921
+ export function optimisticMode(kind: unknown, mode: unknown): string {
922
+ switch (kind) {
923
+ case "full":
924
+ case "area":
925
+ case "spot":
926
+ case "resume":
927
+ return "WORKING";
928
+ case "return":
929
+ return "CHARGING_CYCLE";
930
+ case "pause":
931
+ return "PAUSED";
932
+ case "cancel":
933
+ return "IDLE";
934
+ case "navigate":
935
+ return "IN_TRANSIT";
936
+ default:
937
+ return typeof mode === "string" ? mode : "UNKNOWN";
938
+ }
939
+ }
940
+
941
+ /** The command's label ("Clean all"), for the toast "Clean all → HERO-C03". */
942
+ export function commandLabel(kind: unknown): string {
943
+ if (kind === "spot") return "Spot clean";
944
+ return COMMANDS.find((c) => c.kind === kind)?.label ?? String(kind ?? "");
945
+ }
946
+
947
+ /**
948
+ * The POST body for a command-bar button. Go to point / Set position carry a
949
+ * pose; until a point picker exists (building map, phase d) they send the
950
+ * robot's current reported pose. Null when that pose is unknown - the command
951
+ * cannot be sent.
952
+ */
953
+ export function commandBody(kind: TRobotCommandKind, live: TLiveRobotState | null | undefined): Record<string, unknown> | null {
954
+ if (kind !== "navigate" && kind !== "relocalize") return { kind };
955
+ const p = live?.position;
956
+ if (!p || !finite(p.x) || !finite(p.y) || !finite(p.theta)) return null;
957
+ if (kind === "navigate") return { kind, x: p.x, y: p.y, theta: p.theta };
958
+ return finite(live?.floorNo) ? { kind, floorNo: live!.floorNo, x: p.x, y: p.y, theta: p.theta } : null;
959
+ }
960
+
961
+ /**
962
+ * May the plan take spot-clean clicks? A Manager, a cleaning robot, a brand
963
+ * that declares `spotClean`, and a robot confirmed online. (A busy robot keeps
964
+ * the control; the server refuses with its own words.)
965
+ */
966
+ export function showSpotClean(input: {
967
+ canCommand?: unknown;
968
+ capabilities?: Record<string, unknown> | null;
969
+ online?: unknown;
970
+ type?: unknown;
971
+ }): boolean {
972
+ return input?.canCommand === true && input.online === true && input.type !== "security" && input.capabilities?.spotClean === true;
973
+ }
974
+
975
+ /** The breadcrumb trail: newest first, the last `max` positions, no repeat of the same spot. */
976
+ export function trailPush(trail: Array<{ x: number; y: number }>, point: { x: number; y: number } | null, max = 14) {
977
+ if (!point || !finite(point.x) || !finite(point.y)) return trail;
978
+ const head = trail[0];
979
+ if (head && Math.abs(head.x - point.x) < 0.05 && Math.abs(head.y - point.y) < 0.05) return trail;
980
+ return [{ x: point.x, y: point.y }, ...trail].slice(0, max);
981
+ }
982
+
983
+ /** Trail dots with the handoff's fade: newest 0.8, oldest near 0. */
984
+ export function trailDots(trail: Array<{ x: number; y: number }>) {
985
+ return trail.map((p, i) => ({ key: i, left: `${p.x}%`, top: `${p.y}%`, op: Number(((1 - i / trail.length) * 0.8).toFixed(3)) }));
986
+ }
987
+
988
+ /**
989
+ * Speed from two poses in metres with their times (ms): "0.4 m/s". A robot
990
+ * that is not moving, or two poses too close in time to measure, reads "0.0 m/s".
991
+ */
992
+ export function speedText(
993
+ prev: { x: number; y: number; at: number } | null | undefined,
994
+ next: { x: number; y: number; at: number } | null | undefined,
995
+ mode?: unknown,
996
+ ): string {
997
+ if (!prev || !next || !isMoving(mode)) return "0.0 m/s";
998
+ const dt = (next.at - prev.at) / 1000;
999
+ if (!(dt > 0.2)) return "0.0 m/s";
1000
+ const v = Math.hypot(next.x - prev.x, next.y - prev.y) / dt;
1001
+ return `${Math.min(v, 9.9).toFixed(1)} m/s`;
1002
+ }
1003
+
1004
+ /** "x 17.9 · y 34.1 · 53°" (metres, the robot's map frame) - or "Reconnecting", or "Not reported". */
1005
+ export function positionText(live: TLiveRobotState | null | undefined, capabilities: Record<string, unknown> | null | undefined): string {
1006
+ if (capabilities?.readLocation !== true) return "Not reported";
1007
+ const p = live?.position;
1008
+ if (!live?.ok || live.online === false || !p || !finite(p.x) || !finite(p.y)) return "Reconnecting";
1009
+ const deg = finite(p.theta) ? Math.round(((((p.theta * 180) / Math.PI) % 360) + 360) % 360) : 0;
1010
+ return `x ${p.x.toFixed(1)} · y ${p.y.toFixed(1)} · ${deg}°`;
1011
+ }
1012
+
1013
+ export type TRobotFact = { label: string; value: string; dim: boolean };
1014
+
1015
+ /**
1016
+ * The detail screen's facts grid (README §3): Connection · Battery · Floor ·
1017
+ * Live position · Brand status · Model · Serial · Last seen. A fact the brand
1018
+ * cannot report reads "Not reported" at 50%; a brand with no interface
1019
+ * reports nothing live at all.
1020
+ */
1021
+ export function robotFacts(input: {
1022
+ record?: Record<string, any> | null;
1023
+ live?: (TLiveRobotState & { statusName?: string; model?: string }) | null;
1024
+ now?: number;
1025
+ }): TRobotFact[] {
1026
+ const live = input.live ?? null;
1027
+ const record = input.record ?? {};
1028
+ const none = live?.monitorable === false;
1029
+ const caps: Record<string, unknown> | null = none ? {} : live?.ok ? live.capabilities ?? {} : null;
1030
+ const reports = (need: string) => (caps ? caps[need] === true : true);
1031
+ const nr = (label: string): TRobotFact => ({ label, value: "Not reported", dim: true });
1032
+ const fact = (label: string, value: unknown): TRobotFact => ({ label, value: String(value || "—"), dim: false });
1033
+
1034
+ const connection = none
1035
+ ? nr("Connection")
1036
+ : fact("Connection", !live ? "Checking…" : !live.ok ? "Reconnecting" : live.online === false ? "Offline" : "Online");
1037
+ const battery = !reports("battery") ? nr("Battery") : fact("Battery", batteryReading(live?.batteryPercent)?.text);
1038
+ const floor = !reports("floorReporting")
1039
+ ? nr("Floor")
1040
+ : fact("Floor", live?.ok ? floorLabel({ floorNo: live.floorNo, floorKnown: live.floorKnown }) : "");
1041
+ const position = !reports("readLocation")
1042
+ ? nr("Live position")
1043
+ : fact("Live position", live ? positionText(live, caps ?? { readLocation: true }) : "");
1044
+ return [
1045
+ connection,
1046
+ battery,
1047
+ floor,
1048
+ position,
1049
+ none ? nr("Brand status") : fact("Brand status", live?.ok ? live.statusName : ""),
1050
+ fact("Model", live?.ok ? live.model : ""),
1051
+ fact("Serial", record.robotSn),
1052
+ fact("Last seen", agoText(live?.lastSeenAt ?? record.lastSeenAt, input.now)),
1053
+ ];
1054
+ }
1055
+
1056
+ /**
1057
+ * Fold a live-stream event (`/robots/:id/track`) into the robot's state: a
1058
+ * pose moves it (and its plan point, when the stream carries one); anything
1059
+ * else leaves the polled state alone - the poll decides "Reconnecting".
1060
+ */
1061
+ export function mergePose(
1062
+ live: TLiveRobotState | null | undefined,
1063
+ event: { type?: unknown; pose?: { x?: unknown; y?: unknown; theta?: unknown; mode?: unknown } | null; planPosition?: unknown } | null | undefined,
1064
+ ): TLiveRobotState | null {
1065
+ if (!live || !live.ok || event?.type !== "pose" || !event.pose) return live ?? null;
1066
+ const { x, y, theta, mode } = event.pose;
1067
+ if (!finite(x) || !finite(y)) return live;
1068
+ const plan = event.planPosition as { x?: unknown; y?: unknown } | null | undefined;
1069
+ return {
1070
+ ...live,
1071
+ position: { x, y, theta: finite(theta) ? theta : live.position?.theta ?? 0 },
1072
+ ...(plan && finite(plan.x) && finite(plan.y) ? { planPosition: { x: plan.x, y: plan.y } } : {}),
1073
+ ...(typeof mode === "string" && mode ? { mode } : {}),
1074
+ } as TLiveRobotState;
1075
+ }
1076
+
1077
+ /**
1078
+ * Spot-clean points picked on the plan (0-100 shares) as the polygon the spot
1079
+ * command takes, in the robot's plan-image pixels. Three or more points are
1080
+ * the polygon itself; one or two become a small square around their centre
1081
+ * (a polygon needs three corners).
1082
+ */
1083
+ export function spotPixels(points: Array<{ x: number; y: number }>, size: { width: number; height: number }) {
1084
+ if (!points?.length || !(size?.width > 0) || !(size?.height > 0)) return [];
1085
+ const px = points.map((p) => ({
1086
+ x: Math.round((Math.min(100, Math.max(0, p.x)) / 100) * (size.width - 1)),
1087
+ y: Math.round((Math.min(100, Math.max(0, p.y)) / 100) * (size.height - 1)),
1088
+ }));
1089
+ if (px.length >= 3) return px;
1090
+ const cx = px.reduce((s, p) => s + p.x, 0) / px.length;
1091
+ const cy = px.reduce((s, p) => s + p.y, 0) / px.length;
1092
+ return spotPolygon(cx, cy, size);
1093
+ }