@7365admin1/core 3.89.0 → 3.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,11 @@
9
9
  "date": 1789008603082,
10
10
  "name": "logs\\error-2026-09-10.log",
11
11
  "hash": "ea96d42a9881c629d5b87fa8ce141575a177edfc9aef559c47d82848cdc5df47"
12
+ },
13
+ {
14
+ "date": 1790145019990,
15
+ "name": "logs\\error-2026-09-23.log",
16
+ "hash": "6e81a0234c7b52f196d78508cf2167c58491140d446371c3a823b62ace1ed770"
12
17
  }
13
18
  ],
14
19
  "hashType": "sha256"
@@ -9,6 +9,11 @@
9
9
  "date": 1789008603086,
10
10
  "name": "logs\\combined-2026-09-10.log",
11
11
  "hash": "055e77a0887051fb145bef3e749b6db5d193493d5332f359c80c3052d0e9dcea"
12
+ },
13
+ {
14
+ "date": 1790145020005,
15
+ "name": "logs\\combined-2026-09-23.log",
16
+ "hash": "769ffe827dc48bd68cf6b2e69179b7178cf1d9ce0f0e8da27ccbef7208437632"
12
17
  }
13
18
  ],
14
19
  "hashType": "sha256"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@7365admin1/core",
3
3
  "license": "MIT",
4
- "version": "3.89.0",
4
+ "version": "3.90.0",
5
5
  "author": "7365admin1",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
@@ -13,7 +13,7 @@
13
13
  "build": "tsup src/index.ts --format cjs,esm --dts && shx cp -r src/public dist && shx cp -r src/utils/handlebars dist",
14
14
  "release": "yarn run build && changeset publish",
15
15
  "lint": "tsc",
16
- "test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
16
+ "test": "tsup src/config.ts src/utils/building-map.util.ts src/utils/robot-cloud.util.ts src/utils/robot-adapter.util.ts src/utils/png-encoder.util.ts src/services/demo.adapter.ts src/services/ounitech.adapter.ts src/utils/robot-fault.util.ts src/utils/robot-tracking.util.ts src/utils/robot-apps.util.ts src/utils/robot-permission.util.ts src/utils/robot-network.util.ts src/utils/lift-contract.util.ts src/models/robot-building-map.model.ts src/utils/anpr-revoke.util.ts src/utils/anpr-plate.util.ts src/utils/vehicle-request.util.ts src/utils/camera-view.util.ts src/utils/camera-bulk-import.util.ts src/utils/dashboard-metrics.util.ts src/utils/camera-capability.util.ts src/utils/camera-playback.util.ts src/services/camera-device-http.service.ts src/utils/camera-alert.util.ts src/utils/dahua-protocol.util.ts src/utils/site-name.util.ts src/utils/service-provider-invite.util.ts src/utils/notification-category.util.ts src/utils/hid-card.util.ts src/utils/hid-json.util.ts src/utils/hid-access.util.ts src/models/customer-site.model.ts src/models/site-camera.model.ts src/models/member.model.ts src/models/subscription.model.ts src/utils/session-id.util.ts src/utils/occurrence-query.util.ts src/utils/occurrence-book-create.util.ts src/utils/update-result.util.ts src/utils/hid-amico-authz.util.ts src/utils/promo-code-currency.util.ts src/utils/console-audit.util.ts src/utils/org-suspension.util.ts src/utils/session-revoke.util.ts src/models/hid-amico.model.ts src/models/patrol-email.model.ts src/utils/patrol-email-pdf.util.ts src/utils/visitor-status.util.ts src/utils/self-service-email.util.ts src/utils/hid-secret.util.ts src/models/visitor-invite.model.ts src/models/guard-invite.model.ts src/utils/site-timezone.util.ts src/utils/bulletin-service-apps.util.ts src/models/bulletin-board.model.ts src/utils/vehicle-import.util.ts src/utils/expired-vehicle-sweep.util.ts src/models/vehicle.model.ts src/controllers/chat.controller.ts src/utils/file-owner.util.ts src/utils/console-permission.util.ts src/utils/role-scope.util.ts src/utils/org-default-roles.util.ts src/utils/org-modules.util.ts src/utils/site-modules.util.ts src/utils/resident-app-modules.util.ts src/utils/resident-default-role.util.ts src/utils/invite-role-scope.util.ts src/models/personal-emergency-chain.model.ts src/utils/self-signup-files.util.ts src/models/person.model.ts src/utils/module-gate.util.ts src/utils/member-lookup.util.ts src/utils/notification-access.util.ts src/utils/module-access.util.ts src/services/module-gate.service.ts src/controllers/site.controller.ts src/controllers/organization.controller.ts src/controllers/member.controller.ts src/utils/org-owner-repair.util.ts src/utils/socket-session.util.ts src/utils/people-create-gate.util.ts src/utils/service-app-type.util.ts --format esm --out-dir test/.build --no-dts --silent && node --test test/*.test.mjs",
17
17
  "test:camera": "yarn test",
18
18
  "test:e2e": "yarn build && node --test --test-concurrency=1 --test-timeout=600000 \"test/e2e/*.test.mjs\""
19
19
  },
@@ -881,6 +881,8 @@ function buildApp(nsu, core) {
881
881
  const n = core.useRobotNetworkController();
882
882
  robots.get("/network", requireAuth, n.listNetworkRobots);
883
883
  robots.get("/network/summary", requireAuth, n.getNetworkSummary);
884
+ robots.get("/network/faults", requireAuth, n.listNetworkFaults);
885
+ robots.get("/network/states", requireAuth, n.getNetworkStates);
884
886
 
885
887
  robots.post("/", requireAuth, createRobot);
886
888
  robots.get("/organization/:organization/site/:site", requireAuth, getRobots);
@@ -0,0 +1,307 @@
1
+ // End-to-end proof of the network fault record (owner approval 2026-09-23:
2
+ // a NEW `robot-faults` collection; Needs attention and Faults & alerts must be
3
+ // complete network-wide, and each fault occurrence notifies ONCE).
4
+ //
5
+ // The sweep's robot reader and the notifier are injected, so no vendor cloud is
6
+ // contacted and every notification is counted exactly. Everything else - the
7
+ // collection, its unique partial index, the atomic notifiedAt claim, the HTTP
8
+ // gate and pipelines - is the real code against the in-process MongoDB.
9
+ //
10
+ // Run with: yarn test:e2e
11
+
12
+ import { after, before, describe, it } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { ObjectId } from "mongodb";
15
+
16
+ import { startHarness } from "./harness.mjs";
17
+
18
+ const PASSWORD = "Robot-Passw0rd!";
19
+ const STAFF = "flt-staff@e2e.example.com"; // Seven365 super admin (seeded shape: permissions [])
20
+ const PARTIAL = "flt-partial@e2e.example.com"; // Seven365 staff without the cross-client grant
21
+ const MANAGER = "flt-manager@e2e.example.com"; // client A's manager, role "*"
22
+
23
+ describe("robot faults - stored, deduped, network-wide", { concurrency: 1 }, () => {
24
+ let h;
25
+ const id = {};
26
+ const sid = {};
27
+ // What each robot "reports" to the sweep; changed between steps.
28
+ const reports = {};
29
+ const notified = [];
30
+ const notifyFn = async (p) => { notified.push(`${p.robotName}:${p.fault.code}`); };
31
+ const readState = async (robot) => {
32
+ const r = reports[robot.name];
33
+ if (r instanceof Error) throw r;
34
+ return r ?? { online: true, fault: null };
35
+ };
36
+ const cfg = { enabled: true, seconds: 60, cron: "", concurrency: 2, timeoutMs: 2000, offlineAlertMinutes: 10 };
37
+ const alerts = [];
38
+ const connectionNotifyFn = async (p) => { alerts.push(`${p.robotName}:${p.online ? "online" : "offline"}`); };
39
+ const sweeper = () => h.core.useRobotFaultSweep({ readState, notifyFn, connectionNotifyFn, config: cfg });
40
+ const open = () => h.db.collection("robot-faults").find({ clearedAt: null }).toArray();
41
+
42
+ before(async () => {
43
+ h = await startHarness();
44
+ await h.core.useRobotFaultRepo().createIndex();
45
+ Object.assign(id, await seed(h));
46
+ for (const [k, email] of Object.entries({ STAFF, PARTIAL, MANAGER })) sid[k] = await h.login(email, PASSWORD);
47
+ }, { timeout: 300000 });
48
+
49
+ after(async () => {
50
+ if (h) await h.stop();
51
+ });
52
+
53
+ const get = (path, who = "STAFF") => h.api(path, { sid: sid[who] });
54
+
55
+ it("1. the gate: no session 401; a client's manager and staff without the cross-client grant are refused", async () => {
56
+ for (const p of ["/robots/network/faults", `/robots/network/states?ids=${id.jam}`]) {
57
+ assert.equal((await h.api(p)).status, 401, p);
58
+ assert.equal((await get(p, "MANAGER")).status, 401, p);
59
+ assert.equal((await get(p, "PARTIAL")).status, 401, p);
60
+ }
61
+ });
62
+
63
+ it("2. two sweeps racing (two instances) open ONE record per fault and notify ONCE", async () => {
64
+ Object.assign(reports, {
65
+ "A jam": { online: true, fault: { code: "JAM", message: "Side brush jammed", since: Date.now() - 60000 } },
66
+ "A fine": { online: true, fault: null },
67
+ "B off": { online: false, fault: null },
68
+ "B silent": new Error('Robot "B silent" did not answer after 2000 ms'),
69
+ });
70
+ const [r1, r2] = await Promise.all([sweeper()(), sweeper()()]);
71
+ assert.equal(r1.skipped || r2.skipped, false, "both instances swept");
72
+ const rows = await open();
73
+ assert.deepEqual(rows.map((r) => `${r.code}`).sort(), ["JAM", "OFFLINE", "OFFLINE"]);
74
+ assert.deepEqual(notified, ["A jam:JAM"], "one notification, from whichever instance won");
75
+ assert.equal(r1.notified + r2.notified, 1);
76
+ const jam = rows.find((r) => r.code === "JAM");
77
+ assert.ok(jam.notifiedAt instanceof Date);
78
+ assert.equal(String(jam.orgId), String(id.orgA));
79
+ assert.equal(String(jam.siteId), String(id.siteA));
80
+ const silent = rows.find((r) => String(r.robotId) === String(id.silent));
81
+ assert.match(silent.message, /^Not reporting: Robot "B silent" did not answer/);
82
+ // offline is not a staff notification, and a robot with no adapter is not offline
83
+ assert.equal(rows.some((r) => String(r.robotId) === String(id.noInterface)), false);
84
+ });
85
+
86
+ it("3. the database, not the process, enforces one open record per robot and code", async () => {
87
+ await assert.rejects(
88
+ h.db.collection("robot-faults").insertOne({ robotId: id.jam, code: "JAM", clearedAt: null, since: new Date() }),
89
+ (e) => e.code === 11000,
90
+ );
91
+ });
92
+
93
+ it("4. a state read seeing the same fault does not notify again (the sweep already did)", async () => {
94
+ const robot = await h.db.collection("robots").findOne({ _id: id.jam });
95
+ await h.core.notifyRobotFault(robot, reports["A jam"].fault, { notifyFn });
96
+ assert.deepEqual(notified, ["A jam:JAM"]);
97
+ });
98
+
99
+ it("5. the faults list: real faults first, then offline, longest-standing first; filters", async () => {
100
+ const res = await get("/robots/network/faults");
101
+ assert.equal(res.status, 200, JSON.stringify(res.body));
102
+ assert.equal(res.body.total, 3);
103
+ assert.deepEqual(res.body.items.map((f) => f.code), ["JAM", "OFFLINE", "OFFLINE"]);
104
+ const first = res.body.items[0];
105
+ assert.equal(first.robot.name, "A jam");
106
+ assert.equal(first.client.name, "Flt Client A");
107
+ assert.equal(first.site.name, "Flt Site A");
108
+ assert.equal(first.offline, false);
109
+ assert.equal(res.body.items[1].offline, true);
110
+ assert.equal(JSON.stringify(res.body).includes("e2e-fake"), false);
111
+
112
+ assert.equal((await get("/robots/network/faults?code=JAM")).body.total, 1);
113
+ assert.equal((await get(`/robots/network/faults?org=${id.orgB}`)).body.total, 2);
114
+ assert.equal((await get("/robots/network/faults?type=security")).body.total, 1);
115
+ assert.equal((await get("/robots/network/faults?limit=500")).status, 400);
116
+ });
117
+
118
+ it("6. the list filters faults-only / offline-only server-side; the summary counts them", async () => {
119
+ const faults = await get("/robots/network?faultsOnly=true&limit=50");
120
+ assert.deepEqual(faults.body.items.map((r) => r.name), ["A jam"]);
121
+ assert.equal(faults.body.items[0].fault.code, "JAM");
122
+ const offline = await get("/robots/network?offlineOnly=true&limit=50");
123
+ assert.deepEqual(offline.body.items.map((r) => r.name).sort(), ["B off", "B silent"]);
124
+ assert.ok(offline.body.items.every((r) => r.offline === true && r.offlineSince));
125
+ const all = await get("/robots/network?limit=50");
126
+ assert.equal(all.body.items.find((r) => r.name === "A fine").fault, null);
127
+
128
+ const sum = await get("/robots/network/summary");
129
+ assert.equal(sum.body.faults.count, 1);
130
+ assert.equal(sum.body.offline.count, 2);
131
+ assert.deepEqual(sum.body.offline.byType, [{ key: "cleaning", count: 1 }, { key: "security", count: 1 }]);
132
+ assert.deepEqual(sum.body.faults.bySite, [{ key: String(id.siteA), count: 1 }]);
133
+ const siteA = sum.body.bySite.find((x) => x._id === String(id.siteA));
134
+ assert.equal(siteA.name, "Flt Site A");
135
+ assert.equal(siteA.client, String(id.orgA));
136
+ // the sweep's snapshot: A jam, A fine, A demo live read online
137
+ assert.equal(sum.body.live.online.count, 3);
138
+ });
139
+
140
+ it("7. cleared when it goes away; re-opened later = a new record and a second notification", async () => {
141
+ reports["A jam"] = { online: true, fault: null };
142
+ reports["B off"] = { online: true, fault: null };
143
+ await sweeper()();
144
+ let rows = await open();
145
+ assert.deepEqual(rows.map((r) => String(r.robotId)), [String(id.silent)], "JAM and B off cleared");
146
+ const cleared = await h.db.collection("robot-faults").findOne({ code: "JAM" });
147
+ assert.ok(cleared.clearedAt instanceof Date);
148
+
149
+ reports["A jam"] = { online: true, fault: { code: "JAM", message: "Side brush jammed", since: Date.now() } };
150
+ await sweeper()();
151
+ rows = await open();
152
+ assert.equal(rows.filter((r) => r.code === "JAM").length, 1);
153
+ assert.equal(await h.db.collection("robot-faults").countDocuments({ code: "JAM" }), 2, "history kept");
154
+ assert.deepEqual(notified, ["A jam:JAM", "A jam:JAM"]);
155
+ });
156
+
157
+ it("7b. a flicker (missed on one read, back with the same start) re-opens WITHOUT notifying again", async () => {
158
+ const same = reports["A jam"].fault;
159
+ reports["A jam"] = { online: true, fault: null };
160
+ await sweeper()();
161
+ reports["A jam"] = { online: true, fault: same };
162
+ await sweeper()();
163
+ const reopened = await h.db.collection("robot-faults").findOne({ code: "JAM", clearedAt: null });
164
+ assert.ok(reopened.notifiedAt instanceof Date, "notification carried over");
165
+ assert.deepEqual(notified, ["A jam:JAM", "A jam:JAM"], "no third notification");
166
+ });
167
+
168
+ it("7c. a robot going offline keeps its own fault open (no re-notify when it returns)", async () => {
169
+ const same = reports["A jam"].fault;
170
+ reports["A jam"] = { online: false, fault: null };
171
+ await sweeper()();
172
+ const rows = (await open()).filter((r) => String(r.robotId) === String(id.jam)).map((r) => r.code).sort();
173
+ assert.deepEqual(rows, ["JAM", "OFFLINE"]);
174
+ reports["A jam"] = { online: true, fault: same };
175
+ await sweeper()();
176
+ assert.deepEqual((await open()).filter((r) => String(r.robotId) === String(id.jam)).map((r) => r.code), ["JAM"]);
177
+ assert.deepEqual(notified, ["A jam:JAM", "A jam:JAM"]);
178
+ });
179
+
180
+ it("8. a removed robot's open records are cleared by the next sweep", async () => {
181
+ await h.db.collection("robots").updateOne({ _id: id.silent }, { $set: { deletedAt: new Date() } });
182
+ await sweeper()();
183
+ assert.equal((await open()).some((r) => String(r.robotId) === String(id.silent)), false);
184
+ });
185
+
186
+ it("9. live states for on-screen rows: bounded, validated, no credentials", async () => {
187
+ const res = await get(`/robots/network/states?ids=${id.demo},${id.noInterface}`);
188
+ assert.equal(res.status, 200, JSON.stringify(res.body));
189
+ const demo = res.body.items.find((i) => i.id === String(id.demo));
190
+ assert.equal(demo.ok, true);
191
+ assert.equal(typeof demo.online, "boolean");
192
+ assert.ok(demo.capabilities);
193
+ assert.deepEqual(res.body.items.find((i) => i.id === String(id.noInterface)), {
194
+ id: String(id.noInterface), ok: false, monitorable: false,
195
+ });
196
+ assert.equal(JSON.stringify(res.body).includes("e2e-fake"), false);
197
+
198
+ assert.equal((await get("/robots/network/states?ids=nope")).status, 400);
199
+ const many = Array.from({ length: 51 }, () => new ObjectId().toString()).join(",");
200
+ assert.equal((await get(`/robots/network/states?ids=${many}`)).status, 400);
201
+ });
202
+
203
+ it("10. offline alerts: a blip alerts nobody; 10+ minutes alerts ONCE; back online alerts ONCE", async () => {
204
+ const offRec = () => h.db.collection("robot-faults").findOne({ robotId: id.off, code: "OFFLINE", clearedAt: null });
205
+ const backdate = async (min) => h.db.collection("robot-faults").updateOne(
206
+ { robotId: id.off, code: "OFFLINE", clearedAt: null }, { $set: { since: new Date(Date.now() - min * 60000) } });
207
+ assert.deepEqual(alerts, [], "nothing alerted by the earlier steps (all blips)");
208
+
209
+ // blip under the threshold: the record opens (Needs attention) but nobody is told
210
+ reports["B off"] = { online: false, fault: null };
211
+ await sweeper()();
212
+ assert.ok(await offRec(), "OFFLINE opens at the first missed report");
213
+ await backdate(9);
214
+ await sweeper()();
215
+ assert.deepEqual(alerts, []);
216
+ // ...and its recovery is silent too (never alerted)
217
+ reports["B off"] = { online: true, fault: null };
218
+ await sweeper()();
219
+ assert.equal(await offRec(), null);
220
+ assert.deepEqual(alerts, []);
221
+
222
+ // offline past the threshold: two racing instances plus a later sweep = one alert
223
+ reports["B off"] = { online: false, fault: null };
224
+ await sweeper()();
225
+ await backdate(10);
226
+ await Promise.all([sweeper()(), sweeper()()]);
227
+ await sweeper()();
228
+ assert.deepEqual(alerts, ["B off:offline"]);
229
+ assert.ok((await offRec()).offlineNotifiedAt instanceof Date);
230
+
231
+ // back online: two racing instances = one "back online"; a later sweep adds nothing
232
+ reports["B off"] = { online: true, fault: null };
233
+ await Promise.all([sweeper()(), sweeper()()]);
234
+ await sweeper()();
235
+ assert.deepEqual(alerts, ["B off:offline", "B off:online"]);
236
+ const last = await h.db.collection("robot-faults").find({ robotId: id.off, code: "OFFLINE" }).sort({ createdAt: -1 }).limit(1).next();
237
+ assert.ok(last.clearedAt instanceof Date && last.recoveryNotifiedAt instanceof Date);
238
+ assert.deepEqual(notified.filter((n) => n.startsWith("B off")), [], "offline is never a fault notice");
239
+ });
240
+ });
241
+
242
+ async function seed(h) {
243
+ const now = new Date().toISOString();
244
+ const orgA = new ObjectId();
245
+ const orgB = new ObjectId();
246
+ const siteA = new ObjectId();
247
+ const siteB = new ObjectId();
248
+ const staffRole = new ObjectId();
249
+ const partialRole = new ObjectId();
250
+ const managerRole = new ObjectId();
251
+
252
+ await h.db.collection("organizations").insertMany([
253
+ { _id: orgA, name: "Flt Client A", email: "flta@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
254
+ { _id: orgB, name: "Flt Client B", email: "fltb@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
255
+ ]);
256
+ await h.db.collection("sites").insertMany([
257
+ { _id: siteA, name: "Flt Site A", org: orgA, orgId: orgA, status: "active" },
258
+ { _id: siteB, name: "Flt Site B", org: orgB, orgId: orgB, status: "active" },
259
+ ]);
260
+ await h.db.collection("roles").insertMany([
261
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
262
+ { _id: partialRole, name: "Promo desk", type: "admin", permissions: ["promo-codes:see-all-promo-codes"], status: "active" },
263
+ { _id: managerRole, name: "Manager A", org: orgA, type: "organization", permissions: ["*"], status: "active" },
264
+ ]);
265
+
266
+ const emails = [STAFF, PARTIAL, MANAGER];
267
+ const users = await h.db.collection("users").insertMany(
268
+ emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })),
269
+ );
270
+ const hashed = await h.hashPassword(PASSWORD);
271
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
272
+ const [staff, partial, manager] = [0, 1, 2].map((i) => users.insertedIds[i]);
273
+
274
+ await h.db.collection("members").insertMany([
275
+ { user: staff, type: "admin", role: staffRole, status: "active" },
276
+ { user: partial, type: "admin", role: partialRole, status: "active" },
277
+ { user: manager, org: orgA, type: "organization", role: managerRole, status: "active" },
278
+ ]);
279
+
280
+ const robot = (name, org, site, extra = {}) => ({
281
+ name,
282
+ appKey: "e2e-fake-key",
283
+ appToken: "e2e-fake-token",
284
+ createdBy: manager,
285
+ robotSn: "",
286
+ metadata: { orgId: org, siteId: site, administratorId: "" },
287
+ status: "",
288
+ createdAt: new Date(),
289
+ deletedAt: "",
290
+ type: "cleaning",
291
+ brand: "demo",
292
+ ...extra,
293
+ });
294
+
295
+ const res = await h.db.collection("robots").insertMany([
296
+ robot("A jam", orgA, siteA),
297
+ robot("A fine", orgA, siteA),
298
+ robot("B off", orgB, siteB),
299
+ robot("B silent", orgB, siteB, { type: "security" }),
300
+ robot("B no interface", orgB, siteB, { type: "security", brand: "no-such-brand" }),
301
+ robot("A demo live", orgA, siteA, { robotSn: "DEMO-0001" }),
302
+ ]);
303
+ const ids = res.insertedIds;
304
+ // "A demo live" is only read by test 9 (real demo adapter); the sweep's
305
+ // injected reader would not know it, so it answers like a healthy robot.
306
+ return { orgA, orgB, siteA, siteB, jam: ids[0], off: ids[2], silent: ids[3], noInterface: ids[4], demo: ids[5] };
307
+ }
@@ -131,7 +131,7 @@ describe("robot network view - Seven365 super admin only", { concurrency: 1 }, (
131
131
  assert.equal((await list("?sort=appKey")).status, 400);
132
132
  });
133
133
 
134
- it("10. the summary counts stored data and claims no fault count", async () => {
134
+ it("10. the summary counts stored data; faults come from robot-faults", async () => {
135
135
  const res = await h.api("/robots/network/summary", { sid: sid.STAFF });
136
136
  assert.equal(res.status, 200);
137
137
  assert.equal(res.body.total, 4);
@@ -142,7 +142,10 @@ describe("robot network view - Seven365 super admin only", { concurrency: 1 }, (
142
142
  res.body.byClient.map((c) => [c.name, c.count, c.sites]),
143
143
  [["Net Client A", 2, 1], ["Net Client B", 2, 1]],
144
144
  );
145
- assert.deepEqual(res.body.faults, { live: false, count: null });
145
+ // counted from robot-faults (none recorded in this suite)
146
+ assert.equal(res.body.faults.live, true);
147
+ assert.equal(res.body.faults.count, 0);
148
+ assert.equal(res.body.offline.count, 0);
146
149
  });
147
150
 
148
151
  // ---- Super Admin holds every robot right at ANY client's site ----------
@@ -237,3 +237,12 @@ test("re-registering a brand replaces it rather than duplicating", () => {
237
237
  assert.equal(registeredRobotBrands().length, 1);
238
238
  assert.equal(robotBrandFor("brand-a").displayName, "Two");
239
239
  });
240
+
241
+ test("Ounitech manifest: only proven commands are offered; pause/resume/cancel are recorded as pending", async () => {
242
+ const { OUNITECH_CAPABILITIES, OUNITECH_PENDING_COMMANDS } = await import("./.build/services/ounitech.adapter.mjs");
243
+ const offered = ["full", "area", "spot", "return", "pause", "resume", "cancel", "navigate", "relocalize"]
244
+ .filter((k) => commandSupported(OUNITECH_CAPABILITIES, k));
245
+ assert.deepEqual(offered, ["full", "area", "return"]);
246
+ assert.deepEqual(OUNITECH_PENDING_COMMANDS, ["pause", "resume", "cancel"].map((kind) => ({ kind, reason: "awaiting Ounitech confirmation" })));
247
+ assert.ok(OUNITECH_PENDING_COMMANDS.every((p) => !commandSupported(OUNITECH_CAPABILITIES, p.kind)), "pending is never offered");
248
+ });
@@ -3,9 +3,15 @@ import { test } from "node:test";
3
3
 
4
4
  import {
5
5
  claimFaultOnce,
6
+ OFFLINE_FAULT_CODE,
7
+ planFaultChanges,
6
8
  robotFaultKey,
9
+ robotFaultSweepConfig,
10
+ runBounded,
11
+ withTimeout,
7
12
  robotFaultNotifyEnabled,
8
13
  robotFaultText,
14
+ robotConnectionText,
9
15
  } from "./.build/utils/robot-fault.util.mjs";
10
16
 
11
17
  test("the same fault occurrence is claimed once per process", async () => {
@@ -37,3 +43,77 @@ test("the text names the robot and the fault", () => {
37
43
  assert.match(body, /Cleaner 02/);
38
44
  assert.match(body, /Side brush jammed/);
39
45
  });
46
+
47
+ /* ------------------------------------------- the stored record (phase b) */
48
+
49
+ const rec = (code, since = 1000, _id = code) => ({ _id, code, since: new Date(since) });
50
+
51
+ test("plan: a new fault opens; the same fault on every read changes nothing", () => {
52
+ const fault = { code: "JAM", message: "Brush jammed", since: 1000 };
53
+ assert.deepEqual(planFaultChanges([], { ok: true, online: true, fault }), { open: [fault], clear: [] });
54
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault }), { open: [], clear: [] });
55
+ // a brand that cannot say when it started: the open record stands
56
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: { code: "JAM" } }), { open: [], clear: [] });
57
+ });
58
+
59
+ test("plan: a fault that goes away is cleared; coming back later is a new occurrence", () => {
60
+ assert.deepEqual(planFaultChanges([rec("JAM")], { ok: true, online: true, fault: null }), { open: [], clear: ["JAM"] });
61
+ const again = planFaultChanges([rec("JAM", 1000)], { ok: true, online: true, fault: { code: "JAM", message: "m", since: 90000 } });
62
+ assert.deepEqual(again.clear, ["JAM"]);
63
+ assert.equal(again.open[0].code, "JAM");
64
+ });
65
+
66
+ test("plan: offline / not reporting is an OFFLINE record; a failed read cannot clear robot faults", () => {
67
+ const off = planFaultChanges([], { ok: true, online: false, fault: null });
68
+ assert.deepEqual(off.open, [{ code: OFFLINE_FAULT_CODE, message: "Not reporting" }]);
69
+ const failed = planFaultChanges([rec("JAM")], { ok: false, error: "Robot X did not answer after 10000 ms" });
70
+ assert.deepEqual(failed.clear, [], "JAM is kept - we could not see it");
71
+ assert.equal(failed.open[0].code, OFFLINE_FAULT_CODE);
72
+ assert.match(failed.open[0].message, /^Not reporting: Robot X did not answer/);
73
+ // back online: OFFLINE clears, the robot's own fault is judged on the fresh read
74
+ const back = planFaultChanges([rec(OFFLINE_FAULT_CODE), rec("JAM")], { ok: true, online: true, fault: null });
75
+ assert.deepEqual(back.clear.sort(), ["JAM", OFFLINE_FAULT_CODE].sort());
76
+ // still offline: nothing new
77
+ assert.deepEqual(planFaultChanges([rec(OFFLINE_FAULT_CODE)], { ok: true, online: false }), { open: [], clear: [] });
78
+ // going offline does NOT clear the robot's own fault (it would re-notify on return)
79
+ const wentOff = planFaultChanges([rec("JAM")], { ok: true, online: false, fault: null });
80
+ assert.deepEqual(wentOff.clear, []);
81
+ assert.deepEqual(wentOff.open.map((f) => f.code), [OFFLINE_FAULT_CODE]);
82
+ });
83
+
84
+ test("sweep config: on by default every 60 s; off with no deploy; values clamped", () => {
85
+ const d = robotFaultSweepConfig({});
86
+ assert.deepEqual(d, { enabled: true, seconds: 60, cron: "0 */1 * * * *", concurrency: 4, timeoutMs: 10000, offlineAlertMinutes: 10 });
87
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP: " Off " }).enabled, false);
88
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_SECONDS: "30" }).cron, "*/30 * * * * *");
89
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_SECONDS: "300" }).cron, "0 */5 * * * *");
90
+ // steps that divide evenly: 45 -> 30 s, 90 -> 60 s, 25 min -> 20 min
91
+ assert.deepEqual([45, 90, 1500].map((v) => robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_SECONDS: String(v) }).seconds), [30, 60, 1200]);
92
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_SECONDS: "1" }).seconds, 10);
93
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_SECONDS: "abc" }).seconds, 60);
94
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_CONCURRENCY: "99" }).concurrency, 16);
95
+ assert.equal(robotFaultSweepConfig({ ROBOT_FAULT_SWEEP_TIMEOUT_MS: "5" }).timeoutMs, 1000);
96
+ assert.equal(robotFaultSweepConfig({ ROBOT_OFFLINE_ALERT_MINUTES: "15" }).offlineAlertMinutes, 15);
97
+ assert.equal(robotFaultSweepConfig({ ROBOT_OFFLINE_ALERT_MINUTES: "0" }).offlineAlertMinutes, 1);
98
+ assert.equal(robotFaultSweepConfig({ ROBOT_OFFLINE_ALERT_MINUTES: "x" }).offlineAlertMinutes, 10);
99
+ });
100
+
101
+ test("offline / back-online alert text names the robot and the threshold", () => {
102
+ assert.deepEqual(robotConnectionText("Cleaner 02", false, 10), { title: "Robot offline", body: "Cleaner 02 has not reported for 10 minutes." });
103
+ assert.deepEqual(robotConnectionText("", true, 10), { title: "Robot back online", body: "A robot is reporting again." });
104
+ });
105
+
106
+ test("bounded: never more than the limit in flight, one failure does not stop the rest; a hang times out", async () => {
107
+ let inFlight = 0, peak = 0, done = 0;
108
+ await runBounded([1, 2, 3, 4, 5, 6, 7], 3, async (n) => {
109
+ inFlight++; peak = Math.max(peak, inFlight);
110
+ await new Promise((r) => setTimeout(r, 5));
111
+ inFlight--;
112
+ if (n === 2) throw new Error("boom");
113
+ done++;
114
+ });
115
+ assert.equal(peak, 3);
116
+ assert.equal(done, 6);
117
+ await assert.rejects(withTimeout(new Promise(() => {}), 20, "slow"), /slow after 20 ms/);
118
+ assert.equal(await withTimeout(Promise.resolve(7), 20), 7);
119
+ });
@@ -7,6 +7,9 @@ import {
7
7
  networkListPipeline,
8
8
  networkMatch,
9
9
  networkSummaryPipeline,
10
+ networkFaultsPipeline,
11
+ networkFaultJoin,
12
+ shapeFaultCounts,
10
13
  shapeNetworkSummary,
11
14
  } from "./.build/utils/robot-network.util.mjs";
12
15
 
@@ -72,7 +75,7 @@ test("paging is bounded and the default order groups by client then site", () =>
72
75
  assert.deepEqual(bySite, { "site.name": -1, _id: 1 });
73
76
  });
74
77
 
75
- test("the summary never claims a fault count it did not measure", () => {
78
+ test("the stored-data summary carries no fault count of its own (counted from robot-faults)", () => {
76
79
  const s = shapeNetworkSummary({
77
80
  total: [{ n: 5 }],
78
81
  sites: [{ n: 2 }],
@@ -85,9 +88,66 @@ test("the summary never claims a fault count it did not measure", () => {
85
88
  assert.deepEqual(s.byType, [{ key: "cleaning", count: 4 }, { key: "security", count: 1 }]);
86
89
  assert.equal(s.demo, 3);
87
90
  assert.equal(s.byClient[0].name, "Client A");
88
- assert.deepEqual(s.faults, { live: false, count: null });
91
+ assert.equal(s.faults, undefined);
89
92
  // empty collection: zeros, not a crash
90
93
  const empty = shapeNetworkSummary(undefined);
91
94
  assert.equal(empty.total, 0);
92
95
  assert.deepEqual(empty.byType.map((t) => t.count), [0, 0]);
93
96
  });
97
+
98
+ /* ------------------------------------------- robot-faults (phase b) */
99
+
100
+ test("list: every row carries its open fault / offline record; filters are server-side", () => {
101
+ const plain = networkListPipeline({});
102
+ assert.ok(plain.some((st) => st.$lookup?.from === "robot-faults"), "fault join present");
103
+ assert.equal(plain.some((st) => st.$match?.offline === true || st.$match?.fault), false);
104
+ const faults = networkListPipeline({ faultsOnly: true });
105
+ assert.ok(faults.some((st) => st.$match?.fault?.$ne === null));
106
+ const offline = networkListPipeline({ offlineOnly: true });
107
+ assert.ok(offline.some((st) => st.$match?.offline === true));
108
+ // the join reads OPEN records only, and paging comes after the filter
109
+ const join = networkFaultJoin()[0].$lookup;
110
+ assert.deepEqual(join.pipeline[0], { $match: { clearedAt: null } });
111
+ const iFacet = faults.findIndex((st) => st.$facet);
112
+ const iFilter = faults.findIndex((st) => st.$match?.fault);
113
+ assert.ok(iFilter < iFacet);
114
+ assert.equal(NETWORK_PROJECTION.fault, 1);
115
+ assert.equal(NETWORK_PROJECTION.offline, 1);
116
+ });
117
+
118
+ test("list: the status filter narrows to the snapshot's ids (invalid ids dropped, empty list = nothing)", () => {
119
+ assert.equal(networkMatch({ ids: [ORG, "nope"] })._id.$in.length, 1);
120
+ assert.deepEqual(networkMatch({ ids: [] })._id, { $in: [] });
121
+ });
122
+
123
+ test("faults list: open only, faults before offline, longest-standing first, removed robots dropped", () => {
124
+ const p = networkFaultsPipeline({ org: ORG, code: "E1", type: "security", page: 2, limit: 10 });
125
+ assert.equal(p[0].$match.clearedAt, null);
126
+ assert.equal(String(p[0].$match.orgId), ORG);
127
+ assert.equal(p[0].$match.code, "E1");
128
+ assert.deepEqual(p[1].$lookup.pipeline[0], { $match: { deletedAt: { $in: ["", null] } } });
129
+ assert.ok(p.some((st) => st.$match?.["_r.type"] === "security"));
130
+ assert.deepEqual(p.find((st) => st.$sort).$sort, { _rank: 1, since: 1, _id: 1 });
131
+ const items = p.find((st) => st.$facet).$facet.items;
132
+ assert.deepEqual(items.slice(0, 2), [{ $skip: 10 }, { $limit: 10 }]);
133
+ const raw = JSON.stringify(items);
134
+ assert.equal(raw.includes("appKey") || raw.includes("appToken"), false);
135
+ assert.deepEqual(networkFaultsPipeline({ limit: 1000 }).find((st) => st.$facet).$facet.items[1], { $limit: 100 });
136
+ });
137
+
138
+ test("fault counts: robots per class, faults and offline apart, zeros when none", () => {
139
+ const c = shapeFaultCounts({
140
+ byType: [
141
+ { _id: { offline: false, type: "cleaning" }, count: 3 },
142
+ { _id: { offline: false, type: "security" }, count: 1 },
143
+ { _id: { offline: true, type: "cleaning" }, count: 2 },
144
+ ],
145
+ bySite: [{ _id: ORG, count: 4 }],
146
+ });
147
+ assert.deepEqual(c.faults, {
148
+ live: true, count: 4, byType: [{ key: "cleaning", count: 3 }, { key: "security", count: 1 }], bySite: [{ key: ORG, count: 4 }],
149
+ });
150
+ assert.deepEqual(c.offline, { count: 2, byType: [{ key: "cleaning", count: 2 }, { key: "security", count: 0 }] });
151
+ assert.equal(shapeFaultCounts().faults.count, 0);
152
+ assert.deepEqual(shapeFaultCounts(undefined).faults.bySite, []);
153
+ });