@7365admin1/layer-common 4.32.0 → 4.32.1-staging.365

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 (65) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/assets/css/robot-hero.css +26 -0
  3. package/components/AccessCardAddForm.vue +5 -4
  4. package/components/AccessCardAssignToUnitForm.vue +3 -2
  5. package/components/AccessCardPreviewDialog.vue +4 -3
  6. package/components/Dialog/DeleteConfirmation.vue +17 -2
  7. package/components/Dialog/ReusablePrompt.vue +26 -3
  8. package/components/Dialog/UpdateMoreAction.vue +11 -1
  9. package/components/DocumentForm.vue +407 -112
  10. package/components/DocumentManagement.vue +213 -12
  11. package/components/EntryPass/QrTemplatePreview.vue +21 -25
  12. package/components/EntryPassInformation.vue +119 -24
  13. package/components/Facility/BookingSetup.vue +63 -0
  14. package/components/HidAccessLogDashboard.vue +41 -8
  15. package/components/HidAccessPermissions.vue +424 -0
  16. package/components/HidIntercomManagement.vue +148 -14
  17. package/components/HidProfileQrCode.vue +332 -0
  18. package/components/HidReaderManagement.vue +26 -0
  19. package/components/HidReaderUserRoster.vue +44 -3
  20. package/components/HidUserEnrollment.vue +845 -155
  21. package/components/InvitationClientForm.vue +19 -1
  22. package/components/NotificationBell.vue +39 -3
  23. package/components/Robot/ActivityLog.vue +113 -0
  24. package/components/Robot/AlertsTable.vue +1 -0
  25. package/components/Robot/Detail.vue +8 -5
  26. package/components/Robot/Form.vue +170 -214
  27. package/components/Robot/MiniMap.vue +7 -1
  28. package/components/Robot/SiteAlerts.vue +117 -0
  29. package/components/Robot/SiteScreen.vue +69 -5
  30. package/components/VehicleForm.vue +45 -2
  31. package/components/VehicleManagement.vue +95 -10
  32. package/components/VisitorManagement.vue +267 -5
  33. package/composables/useAccessManagement.ts +5 -0
  34. package/composables/useCleaningPermission.ts +4 -4
  35. package/composables/useCommonPermission.ts +16 -0
  36. package/composables/useDocument.ts +7 -0
  37. package/composables/useFacility.ts +11 -0
  38. package/composables/useHidAmico.ts +117 -0
  39. package/composables/useHidNavigation.ts +25 -1
  40. package/composables/useHidReaderSelection.ts +50 -0
  41. package/composables/useLandscapingPermission.ts +4 -4
  42. package/composables/useMechanicalElectricalPermission.ts +4 -4
  43. package/composables/usePeople.ts +19 -0
  44. package/composables/usePestControlPermission.ts +4 -4
  45. package/composables/usePoolMaintenancePermission.ts +4 -4
  46. package/composables/useRobotBuilding.ts +9 -12
  47. package/composables/useRobots.ts +53 -4
  48. package/composables/useSecurityPermission.ts +4 -10
  49. package/composables/useSiteCategory.ts +45 -0
  50. package/composables/useSiteEntryPassSettings.ts +26 -0
  51. package/composables/useWebUsb.ts +14 -11
  52. package/package.json +1 -1
  53. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  54. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  55. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  56. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  57. package/types/document.d.ts +14 -0
  58. package/types/facility.d.ts +4 -0
  59. package/types/people.d.ts +28 -1
  60. package/utils/hid-permission-assignments.ts +190 -0
  61. package/utils/hid-reader-selection.ts +52 -0
  62. package/utils/notification-target.ts +75 -0
  63. package/utils/occupancy-role.ts +109 -0
  64. package/utils/robot-display.ts +146 -0
  65. package/utils/vehicle-actions.ts +12 -4
@@ -0,0 +1,190 @@
1
+ /**
2
+ * WHO IS ASSIGNED TO A HID READER — the editing model behind the permissions
3
+ * dialog.
4
+ *
5
+ * This is the step that actually grants access. Enrolling a person gives the
6
+ * reader a face, a card or a PIN it can RECOGNISE; it puts nobody in the group
7
+ * the access rule is attached to, so a recognised person is still refused at
8
+ * the door (access log event 6). `PUT /sites/:siteId/permissions` is the only
9
+ * call in the system that writes that group membership.
10
+ *
11
+ * Two contracts make this file necessary rather than inlining the logic in the
12
+ * component:
13
+ *
14
+ * 1. **The PUT REPLACES the whole assignment set for the reader.** The server
15
+ * keeps other readers' rows and overwrites this reader's with exactly what
16
+ * is sent. The candidate list, however, is fetched ONE CATEGORY AT A TIME.
17
+ * Saving from the tab in front of you while sending only that tab's people
18
+ * would silently revoke every resident if you were looking at the service
19
+ * providers tab. So the edit state is held for the whole reader and the
20
+ * payload is always built from all of it.
21
+ *
22
+ * 2. **The body schema accepts three keys and nothing else.**
23
+ * `hidPermissionAssignmentSchema` is `{ subjectId, category, intercom }`,
24
+ * and Joi rejects unknown keys rather than stripping them. The candidate
25
+ * rows carry `name`, `subtitle`, `location` and friends for display, so the
26
+ * payload has to be narrowed deliberately — passing a candidate straight
27
+ * through is a 400.
28
+ */
29
+
30
+ /** The three real categories. `intercom` is a candidate FILTER, never a category. */
31
+ export const HID_PERMISSION_CATEGORIES: THidPermissionCategory[] = [
32
+ "resident",
33
+ "property_management",
34
+ "service_provider",
35
+ ];
36
+
37
+ export type HidAssignmentState = Map<string, { category: THidPermissionCategory; intercom: boolean }>;
38
+
39
+ /** Body row for `updateSitePermissions` — exactly the keys Joi allows. */
40
+ export type HidAssignmentPayload = {
41
+ subjectId: string;
42
+ category: THidPermissionCategory;
43
+ intercom: boolean;
44
+ };
45
+
46
+ function isRealCategory(value: unknown): value is THidPermissionCategory {
47
+ return HID_PERMISSION_CATEGORIES.includes(value as THidPermissionCategory);
48
+ }
49
+
50
+ /**
51
+ * The reader's CURRENT assignments, as the edit state.
52
+ *
53
+ * Seeded from `getSitePermissions`, which returns every category at once —
54
+ * that is what makes a whole-reader payload possible from a one-category view.
55
+ * Rows with an unrecognised category are dropped rather than carried: sending
56
+ * one back fails the enum check and takes the entire save with it.
57
+ */
58
+ export function seedAssignments(
59
+ assignments: readonly THidPermissionAssignment[] | undefined | null,
60
+ ): HidAssignmentState {
61
+ const state: HidAssignmentState = new Map();
62
+ if (!Array.isArray(assignments)) return state;
63
+ for (const assignment of assignments) {
64
+ const subjectId = String(assignment?.subjectId ?? "");
65
+ if (!subjectId || !isRealCategory(assignment?.category)) continue;
66
+ state.set(subjectId, {
67
+ category: assignment.category,
68
+ intercom: assignment.intercom === true,
69
+ });
70
+ }
71
+ return state;
72
+ }
73
+
74
+ /**
75
+ * Add or remove one person.
76
+ *
77
+ * `saved` is the state the dialog opened with, and it is consulted for one
78
+ * reason: the `intercom` flag. Nothing here edits that flag, but
79
+ * `userHasSiteIntercomPermission` reads it off these same rows, so it must
80
+ * survive a round trip through the checkbox.
81
+ *
82
+ * - **Untick then save** drops it, which is right — an unassigned person
83
+ * holding a dangling intercom right would keep answering the door panel
84
+ * after losing the door.
85
+ * - **Untick then re-tick, without saving** must restore it. Removing from the
86
+ * draft forgets the flag, so re-adding recovers it from `saved`; otherwise a
87
+ * misclick corrected a second later would silently revoke intercom on the
88
+ * next save, with nothing on screen to show it had happened.
89
+ */
90
+ export function setAssignment(
91
+ state: HidAssignmentState,
92
+ saved: HidAssignmentState,
93
+ subjectId: string,
94
+ category: THidPermissionCategory,
95
+ selected: boolean,
96
+ ): HidAssignmentState {
97
+ const next: HidAssignmentState = new Map(state);
98
+ const id = String(subjectId ?? "");
99
+ if (!id || !isRealCategory(category)) return next;
100
+ if (!selected) {
101
+ next.delete(id);
102
+ return next;
103
+ }
104
+ const intercom = next.get(id)?.intercom ?? saved.get(id)?.intercom ?? false;
105
+ next.set(id, { category, intercom: intercom === true });
106
+ return next;
107
+ }
108
+
109
+ /** The whole reader's assignments, narrowed to the three keys the API accepts. */
110
+ export function toAssignmentPayload(state: HidAssignmentState): HidAssignmentPayload[] {
111
+ return [...state.entries()].map(([subjectId, value]) => ({
112
+ subjectId,
113
+ category: value.category,
114
+ intercom: value.intercom === true,
115
+ }));
116
+ }
117
+
118
+ /**
119
+ * The server sends `selected` with each candidate, describing what is SAVED.
120
+ * Once the dialog is open the local edit state is the truth, so the flag is
121
+ * recomputed rather than trusted — otherwise paging or searching would redraw
122
+ * a row with the saved value and quietly discard an unsaved tick.
123
+ */
124
+ export function applySelection(
125
+ candidates: readonly THidPermissionCandidate[] | undefined | null,
126
+ state: HidAssignmentState,
127
+ ): THidPermissionCandidate[] {
128
+ if (!Array.isArray(candidates)) return [];
129
+ return candidates.map((candidate) => ({
130
+ ...candidate,
131
+ selected: state.has(String(candidate?.subjectId ?? "")),
132
+ }));
133
+ }
134
+
135
+ /** Per-category totals for the dialog header, counted over the whole reader. */
136
+ export function countByCategory(state: HidAssignmentState): Record<THidPermissionCategory, number> {
137
+ const counts = { resident: 0, property_management: 0, service_provider: 0 } as Record<
138
+ THidPermissionCategory,
139
+ number
140
+ >;
141
+ for (const value of state.values()) counts[value.category] += 1;
142
+ return counts;
143
+ }
144
+
145
+ /** Has anything changed since the dialog opened? Drives the Save button. */
146
+ export function hasChanges(saved: HidAssignmentState, draft: HidAssignmentState): boolean {
147
+ if (saved.size !== draft.size) return true;
148
+ for (const [subjectId, value] of draft) {
149
+ const before = saved.get(subjectId);
150
+ if (!before) return true;
151
+ if (before.category !== value.category) return true;
152
+ if (before.intercom !== value.intercom) return true;
153
+ }
154
+ return false;
155
+ }
156
+
157
+ /**
158
+ * What a listing response tells us: the rows, and how many pages exist.
159
+ *
160
+ * It deliberately does NOT return the current page, and the caller must keep
161
+ * owning that. `paginate` in `@7365admin1/node-server-utils` returns only
162
+ * `{ items, pages, pageRange }` — it never echoes the page it was asked for. A
163
+ * caller that read one back therefore got a default on every fetch and pinned
164
+ * itself to page one, so the pager moved and the rows never did.
165
+ *
166
+ * `items` sits at the root on some of these endpoints and under `data` on
167
+ * others, so both are read.
168
+ */
169
+ export function readCandidatePage(response: unknown): {
170
+ items: THidPermissionCandidate[];
171
+ pages: number;
172
+ pageRange: string;
173
+ } {
174
+ const source = (response && typeof response === "object" ? response : {}) as Record<string, unknown>;
175
+ const nested = (source.data && typeof source.data === "object" ? source.data : {}) as Record<string, unknown>;
176
+ const items = Array.isArray(source.items)
177
+ ? source.items
178
+ : Array.isArray(nested.items)
179
+ ? nested.items
180
+ : [];
181
+ const pages = Number(source.pages ?? nested.pages ?? 1);
182
+ // `paginate` builds this ("1-10 of 37") and the table renders it verbatim.
183
+ // Without it the pager draws its placeholder, "-- - -- of --".
184
+ const pageRange = String(source.pageRange ?? nested.pageRange ?? "");
185
+ return {
186
+ items: items as THidPermissionCandidate[],
187
+ pages: Number.isFinite(pages) && pages > 0 ? pages : 1,
188
+ pageRange,
189
+ };
190
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * WHICH HID READER THE OPERATOR IS WORKING ON — the one rule behind it.
3
+ *
4
+ * Every HID screen used to hold its own `ref("")` and default it to
5
+ * `readers[0]`, so picking HID 2 on HID Reader Users and clicking through to
6
+ * HID Cards put you back on HID 1. They are separate PAGES, so the component
7
+ * unmounted and the ref was rebuilt from scratch every time — there was no way
8
+ * to make a choice stick. "I am working on HID 2" is a mode, not a per-screen
9
+ * preference.
10
+ *
11
+ * Navigation between those pages is a route change rather than a page load
12
+ * (`NavigationItem.vue` renders the menu's `route` through `:to`), so the
13
+ * module-scoped ref in `useHidReaderSelection` survives it. This file holds the
14
+ * part worth testing: deciding whether a remembered choice may still be used.
15
+ */
16
+
17
+ export type HidReaderChoice = { siteId: string; readerId: string };
18
+
19
+ /** Anything with an id — the four screens all carry a different reader shape. */
20
+ type ReaderLike = { _id?: unknown };
21
+
22
+ export const EMPTY_HID_READER_CHOICE: HidReaderChoice = { siteId: "", readerId: "" };
23
+
24
+ /**
25
+ * The reader a screen should show, given what this site actually has.
26
+ *
27
+ * A remembered id is honoured ONLY when it belongs to this site and is still in
28
+ * the list. That single condition covers every way it goes stale:
29
+ *
30
+ * - the operator switched site, so the id belongs to a site they have left
31
+ * - the reader was deleted or deactivated since they chose it
32
+ * - nothing has been chosen yet
33
+ *
34
+ * In all three the first reader is returned instead. The alternative — using
35
+ * the id anyway — sends requests for a reader the site does not own, which come
36
+ * back empty and read on screen as a reader with no users, no cards and no
37
+ * logs, rather than as the mistake it is.
38
+ */
39
+ export function resolveHidReaderId(
40
+ siteId: string,
41
+ readers: readonly ReaderLike[] | null | undefined,
42
+ choice: HidReaderChoice = EMPTY_HID_READER_CHOICE,
43
+ ): string {
44
+ const ids = (Array.isArray(readers) ? readers : [])
45
+ .map((reader) => String(reader?._id ?? ""))
46
+ .filter(Boolean);
47
+
48
+ if (choice.siteId === String(siteId ?? "") && ids.includes(choice.readerId)) {
49
+ return choice.readerId;
50
+ }
51
+ return ids[0] ?? "";
52
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Where a notification takes you when you click it.
3
+ *
4
+ * Kept free of Vue and Nuxt so the decision is unit-tested directly
5
+ * (`utils/notification-target.test.ts`); `NotificationBell.vue` does nothing
6
+ * with the answer but hand it to the router.
7
+ *
8
+ * WHY THE BELL NEEDED THIS AT ALL
9
+ * The bell has drawn rows since it shipped and clicking one only ever marked it
10
+ * read. For an expiring document that is survivable — the row says what it says.
11
+ * For a marketplace order it is not: "A new marketplace order has reached your
12
+ * company" is a message whose entire point is the order, and a vendor who taps
13
+ * the push on their phone and then goes looking in the org app had nowhere to
14
+ * land.
15
+ *
16
+ * WHAT THE ROW ACTUALLY CARRIES
17
+ * `iservice365-API-core`'s marketplace senders store `module` as the display
18
+ * tag and the record's id in `params.id` — for the vendor rows that id is the
19
+ * SUB-order, which is the same id the vendor's order queue routes on. `screen`
20
+ * is deliberately empty on those rows (it is a mobile deep-link path, and no
21
+ * mobile screen exists), so the module is what we route on, not `screen`.
22
+ *
23
+ * WHY AN APP-SPECIFIC ROUTE NAME LIVES IN THE SHARED LAYER
24
+ * Eleven web apps render this bell and only `iservice365-web-app-org` has an
25
+ * order queue. Rather than make eleven apps configure a map, the name is
26
+ * written down once here and the bell asks its own router whether the route
27
+ * exists before pushing — so in the ten apps without the page the click stays
28
+ * exactly what it was: mark as read, go nowhere.
29
+ */
30
+
31
+ /** Only the fields a destination is decided from. */
32
+ export type TTargetRow = {
33
+ module?: string;
34
+ params?: { id?: string } | null;
35
+ };
36
+
37
+ /** What the surrounding app knows that the stored row does not. */
38
+ export type TTargetContext = {
39
+ /** The organization in the current URL. Org routes are all nested under it. */
40
+ organization?: string;
41
+ };
42
+
43
+ export type TNotificationTarget = {
44
+ name: string;
45
+ params: Record<string, string>;
46
+ };
47
+
48
+ /** Nuxt's generated names for `pages/org/[organization]/marketplace/orders/`. */
49
+ export const ORDER_QUEUE_ROUTE = "org-organization-marketplace-orders";
50
+ export const ORDER_DETAIL_ROUTE = "org-organization-marketplace-orders-id";
51
+
52
+ /** The stored `module` tag on a row sent to a vendor's staff. */
53
+ export const VENDOR_ORDER_MODULE = "marketplace-vendor-order";
54
+
55
+ export function notificationTarget(
56
+ item: TTargetRow | null | undefined,
57
+ context: TTargetContext = {},
58
+ ): TNotificationTarget | null {
59
+ const organization = String(context.organization ?? "").trim();
60
+
61
+ if (String(item?.module ?? "") !== VENDOR_ORDER_MODULE) return null;
62
+
63
+ // Every order route is nested under the organization. Without one there is no
64
+ // URL to build, and guessing an organization for somebody who belongs to
65
+ // several is worse than leaving the click as it was.
66
+ if (!organization) return null;
67
+
68
+ const id = String(item?.params?.id ?? "").trim();
69
+
70
+ // No id — an older row, or one whose params were dropped — still has an
71
+ // honest destination: the queue the order is sitting in.
72
+ if (!id) return { name: ORDER_QUEUE_ROUTE, params: { organization } };
73
+
74
+ return { name: ORDER_DETAIL_ROUTE, params: { organization, id } };
75
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * OWNER / OCCUPANT / PERSON IN CHARGE - the three standings a business
3
+ * tenancy has, and everything the product says about them.
4
+ *
5
+ * One list, because three screens read it: the form that asks the question
6
+ * (`PeopleFormMgmt`), the list and preview that print the answer back, and
7
+ * the row menu that reassigns it (`people-mgmt`). The values are the ones the
8
+ * server stores and validates - `OccupancyRoles` in core's `person.model.ts`
9
+ * - so a value added on one side has to be added on the other.
10
+ */
11
+ export const OCCUPANCY_ROLE_OPTIONS: TOccupancyRoleOption[] = [
12
+ {
13
+ value: "owner",
14
+ title: "Owner",
15
+ action: "Assign Owner",
16
+ prompt: "Assign Owner",
17
+ description:
18
+ "The legal titleholder or primary deed owner of the property.",
19
+ },
20
+ {
21
+ value: "occupant",
22
+ title: "Occupant",
23
+ action: "Assign Occupant",
24
+ prompt: "Assign Occupant",
25
+ description:
26
+ "The person currently living in, renting, or utilizing the physical unit.",
27
+ },
28
+ {
29
+ value: "person-in-charge",
30
+ title: "Person in Charge",
31
+ action: "Assign Person in Charge",
32
+ prompt: "Assign Person in Charge (PIC)",
33
+ description:
34
+ "The designated manager responsible for maintenance, emergencies, and daily operations.",
35
+ },
36
+ ];
37
+
38
+ /**
39
+ * The same three, in the order the ROW MENU draws them, which is not the
40
+ * order the form's radio does. Derived rather than re-typed so the wording
41
+ * cannot drift between the two.
42
+ */
43
+ export const OCCUPANCY_ROLE_ACTIONS: TOccupancyRoleOption[] = (
44
+ ["person-in-charge", "owner", "occupant"] as TOccupancyRole[]
45
+ ).map(
46
+ (value) =>
47
+ OCCUPANCY_ROLE_OPTIONS.find(
48
+ (option) => option.value === value,
49
+ ) as TOccupancyRoleOption,
50
+ );
51
+
52
+ /**
53
+ * The label for a stored role, or "" for a person who was never asked - which
54
+ * is everyone on a residential site and everyone saved before the question
55
+ * existed. Callers decide what to print instead; nobody should print a raw
56
+ * `person-in-charge` at a user.
57
+ */
58
+ export function occupancyRoleLabel(role?: string | null): string {
59
+ return (
60
+ OCCUPANCY_ROLE_OPTIONS.find((option) => option.value === role)?.title ?? ""
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Does this person hold OWNER at their unit?
66
+ *
67
+ * The role when there is one, `isOwner` when there is not - the same test the
68
+ * server applies (`holdsUnitOwner` in core's `unit-owner.util.ts`). A person
69
+ * recorded before the role existed carries only the flag, and the people list
70
+ * already prints them as "Owner".
71
+ */
72
+ export function holdsUnitOwner(person?: {
73
+ occupancyRole?: string | null;
74
+ isOwner?: boolean;
75
+ }): boolean {
76
+ if (!person) return false;
77
+
78
+ if (person.occupancyRole) return person.occupancyRole === "owner";
79
+
80
+ return person.isOwner === true;
81
+ }
82
+
83
+ /**
84
+ * MUST THIS PERSON HAND THE UNIT OVER BEFORE THEY CAN BE DEACTIVATED?
85
+ *
86
+ * The owner of a unit does not leave while they still own it - the standing
87
+ * moves to another tenant at the same block, level and unit first.
88
+ *
89
+ * Keyed to the ROLE and never to `isOwner`, exactly as the server keys it
90
+ * (`mustHandOverBeforeDeactivating` in core): the flag is on every resident in
91
+ * the estate, and no residential screen can change it, so a rule keyed to it
92
+ * would trap records that can never satisfy it.
93
+ */
94
+ export function mustHandOverBeforeDeactivating(person?: {
95
+ occupancyRole?: string | null;
96
+ }): boolean {
97
+ return person?.occupancyRole === "owner";
98
+ }
99
+
100
+ /**
101
+ * Why a deactivation was held back. The SERVER carries the enforcing copy of
102
+ * this rule and of these words (core `unit-owner.util.ts`); this one exists so
103
+ * the console can say it before the round trip rather than after.
104
+ */
105
+ export function ownerHandoverRequiredMessage(name?: string): string {
106
+ const who = name?.trim() ? `"${name.trim()}"` : "This person";
107
+
108
+ return `${who} is the owner of this unit. Assign the owner role to another tenant at the same block, level and unit before deactivating them.`;
109
+ }
@@ -1114,3 +1114,149 @@ export function spotPixels(points: Array<{ x: number; y: number }>, size: { widt
1114
1114
  const cy = px.reduce((s, p) => s + p.y, 0) / px.length;
1115
1115
  return spotPolygon(cx, cy, size);
1116
1116
  }
1117
+
1118
+ /* ================================= alerts, activity log, add / edit (HERO phase e) */
1119
+
1120
+ /** The Activity log's "When": "14:02 · 4 min" / "14:02 · just now" (the prototype's fmtSince). */
1121
+ export function activityWhen(at: unknown, now: number = Date.now()): string {
1122
+ return sinceText(at, now).replace(/· now$/, "· just now");
1123
+ }
1124
+
1125
+ /**
1126
+ * One console-audit row (`GET /robots/activity`) as the Activity log reads it
1127
+ * (README §7; the prototype's words): Who · Action · Target, e.g.
1128
+ * "Mei Lin" · "sent Clean all to" · "HERO-C03". Only the allow-listed audit
1129
+ * fields are read (names, command kind, lift floors) - never a credential,
1130
+ * which is never in the row either.
1131
+ */
1132
+ export function activityRow(entry: Record<string, any> | null | undefined, now: number = Date.now()) {
1133
+ const a = (entry?.after ?? {}) as Record<string, any>;
1134
+ const b = (entry?.before ?? {}) as Record<string, any>;
1135
+ const name = String(a.name || b.name || "");
1136
+ const lift = () => `${a.liftName ?? "the lift"} (${floorName(a.fromFloor)} → ${floorName(a.toFloor)})`;
1137
+ let action: string;
1138
+ switch (entry?.action) {
1139
+ case "robot.added":
1140
+ action = "added robot";
1141
+ break;
1142
+ case "robot.updated":
1143
+ action = a.credentialsReplaced
1144
+ ? "replaced the credentials of"
1145
+ : a.name && b.name && a.name !== b.name
1146
+ ? `renamed ${b.name} to`
1147
+ : "edited robot";
1148
+ break;
1149
+ case "robot.removed":
1150
+ action = "removed robot";
1151
+ break;
1152
+ case "robot.commanded":
1153
+ action = `sent ${commandLabel(a.command)} to`;
1154
+ break;
1155
+ case "robot.map-saved":
1156
+ action = "saved building map";
1157
+ break;
1158
+ case "robot.map-updated":
1159
+ action = "edited building map";
1160
+ break;
1161
+ case "robot.map-removed":
1162
+ action = "removed building map";
1163
+ break;
1164
+ case "robot.lift-requested":
1165
+ action = `requested ${lift()} for`;
1166
+ break;
1167
+ case "robot.lift-released":
1168
+ action = `released ${lift()} for`;
1169
+ break;
1170
+ default:
1171
+ action = String(entry?.label ?? entry?.action ?? "").toLowerCase();
1172
+ }
1173
+ return {
1174
+ id: String(entry?.id ?? ""),
1175
+ when: activityWhen(entry?.when, now),
1176
+ who: String(entry?.actor?.name || "Someone"),
1177
+ action,
1178
+ target: name || "—",
1179
+ };
1180
+ }
1181
+
1182
+ /**
1183
+ * The Add robot dialog's Brand options for a type (README §8: "filtered by
1184
+ * type; option shows capability"): only brands that make that class (a brand
1185
+ * declaring no `types` makes cleaning robots), as "Ounitech · Basic control".
1186
+ */
1187
+ export function brandOptions(
1188
+ brands: Array<Record<string, any>> | null | undefined,
1189
+ type: unknown,
1190
+ ): Array<{ value: string; label: string; capabilities: Record<string, unknown> }> {
1191
+ return (brands ?? [])
1192
+ .filter((b) => (Array.isArray(b?.types) && b.types.length ? b.types : ["cleaning"]).includes(type))
1193
+ .map((b) => ({
1194
+ value: String(b.brand),
1195
+ label: `${brandName(b.brand, brands as any)} · ${capabilityLabel(b.capabilities)}`,
1196
+ capabilities: (b.capabilities ?? {}) as Record<string, unknown>,
1197
+ }));
1198
+ }
1199
+
1200
+ /**
1201
+ * "Basic control — no battery, floor or spot clean" (README §8), derived from
1202
+ * the brand's manifest: the command level, then what it cannot report (spot
1203
+ * clean only matters for a cleaning robot).
1204
+ */
1205
+ export function capabilityNote(capabilities: Record<string, unknown> | null | undefined, type?: unknown): string {
1206
+ const caps = capabilities ?? {};
1207
+ const label = capabilityLabel(caps);
1208
+ if (label === "No interface") return `${label} — listed only, no monitoring`;
1209
+ if (label === "Read-only") return `${label} — reports only, takes no commands`;
1210
+ const missing = [
1211
+ caps.battery !== true && "battery",
1212
+ caps.floorReporting !== true && "floor",
1213
+ type !== "security" && caps.spotClean !== true && "spot clean",
1214
+ ].filter(Boolean) as string[];
1215
+ if (!missing.length) return label === "Full control" ? `${label} — all commands available` : `${label} — some commands only`;
1216
+ const list = missing.length > 1 ? `${missing.slice(0, -1).join(", ")} or ${missing[missing.length - 1]}` : missing[0];
1217
+ return `${label} — no ${list}`;
1218
+ }
1219
+
1220
+ /**
1221
+ * The note under the credentials. The handoff says "stored encrypted"; they
1222
+ * are not encrypted at rest today (see HERO-PENDING_INTEGRATIONS), so the note
1223
+ * says only what is true: they are never shown again.
1224
+ */
1225
+ export const CREDENTIALS_NOTE = "Credentials are never shown again after saving.";
1226
+
1227
+ /**
1228
+ * What the dialog sends for the credentials. Adding needs both. Editing sends
1229
+ * them ONLY when replaced - both typed; neither typed leaves the stored pair
1230
+ * alone; one without the other is refused before anything is sent.
1231
+ */
1232
+ export function credentialPatch(
1233
+ appKey: unknown,
1234
+ appToken: unknown,
1235
+ editing: boolean,
1236
+ ): { ok: true; body: { appKey?: string; appToken?: string } } | { ok: false; message: string } {
1237
+ const key = typeof appKey === "string" ? appKey.trim() : "";
1238
+ const token = typeof appToken === "string" ? appToken.trim() : "";
1239
+ if (key && token) return { ok: true, body: { appKey: key, appToken: token } };
1240
+ if (editing && !key && !token) return { ok: true, body: {} };
1241
+ return {
1242
+ ok: false,
1243
+ message: editing
1244
+ ? "Enter both the app key and the token to replace them, or leave both empty."
1245
+ : "Enter the app key and the token from the brand portal.",
1246
+ };
1247
+ }
1248
+
1249
+ /**
1250
+ * Keep a robot's name tag inside the mini-map plan: flip it to the robot's
1251
+ * left near the right edge, and below the robot near the top edge.
1252
+ * ponytail: width estimated from the text (10px Archivo 600) against the
1253
+ * smallest plan (320px wide, 240 tall); measure if a tag must be exact.
1254
+ */
1255
+ export function nameTagSide(left: unknown, top: unknown, name: unknown, planW = 320, planH = 240) {
1256
+ const pct = (v: unknown) => (typeof v === "string" ? parseFloat(v) : typeof v === "number" ? v : 0) || 0;
1257
+ const width = String(name ?? "").length * 6.2 + 8;
1258
+ return {
1259
+ flipX: (pct(left) / 100) * planW + 10 + width > planW,
1260
+ below: (pct(top) / 100) * planH < 20,
1261
+ };
1262
+ }
@@ -96,9 +96,12 @@ export function vehiclePlateActions(
96
96
  });
97
97
  }
98
98
 
99
- // Restore is deliberately NOT gated on `canUpdateVehicle`: it was ungated
100
- // before and narrowing a gate is a separate, role-data decision.
101
- if (isRestorable) {
99
+ // Restore goes through the approve endpoint (`submitRestore` ->
100
+ // `approveVehicle`), which the server gates on "Approve Vehicle" and refuses
101
+ // with "You do not have permission to approve vehicles." without it. It
102
+ // used to be offered to everyone, so a role without the right saw Restore,
103
+ // pressed it and was refused - and it could not be hidden on that refusal.
104
+ if (permissions.canApproveVehicle && isRestorable) {
102
105
  actions.push({
103
106
  key: "restore",
104
107
  title: "Restore",
@@ -110,7 +113,12 @@ export function vehiclePlateActions(
110
113
  // Any record that is not already blocked (and is not waiting for approval)
111
114
  // can be blocked - including an unblocked or deleted one, which is how the
112
115
  // same plate is blocked again without a second record.
113
- if (canUpdate && (isAllowed || isUnblocked || isRestorable)) {
116
+ // A deleted BLOCKLIST plate (Block Listed tab) is not offered Block: Restore
117
+ // already puts it back on every camera's blocklist, so the two would do the
118
+ // same thing. A deleted whitelist plate keeps Block - that turns it into a
119
+ // blocked plate, which Restore (back to allowed) does not.
120
+ const restoresToBlocked = isRestorable && type === "blocklist";
121
+ if (canUpdate && (isAllowed || isUnblocked || (isRestorable && !restoresToBlocked))) {
114
122
  actions.push({
115
123
  key: "block",
116
124
  title: "Block",