@7365admin1/core 3.89.0 → 3.91.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.
@@ -0,0 +1,360 @@
1
+ // End-to-end proof for the HERO site fleet endpoints (phase c):
2
+ //
3
+ // GET /api/robots/organization/:org/site/:site/fleet the site's robots, paged
4
+ // GET /api/robots/organization/:org/site/:site/summary the six counts
5
+ // GET /api/robots/states?ids= live state, per robot
6
+ // GET /api/robots/:id one robot's record
7
+ // GET /api/robots/:id/patrol-routes a security robot's patrol
8
+ //
9
+ // Four rules, each proved both ways:
10
+ // 1. no session, no answer (401);
11
+ // 2. the estate is checked against the session - a manager reaches their own
12
+ // client's site and never another's, and on `/states` (no site in the
13
+ // request) a robot at an unreachable site is simply left out;
14
+ // 3. `appSlug` narrows every answer to the classes that app presents -
15
+ // Hygiene never learns a security robot exists (rows, counts, states,
16
+ // record, patrol), Security never learns of a cleaning one;
17
+ // 4. no credential is ever in a response.
18
+ // Plus the fleet list pages past page 1 (the known HERO bug was a client
19
+ // reading `totalPages`; the API answers `pages` and `total`), the demo patrol
20
+ // contract, and pause / resume reaching a demo patrol robot.
21
+ //
22
+ // Everything is created and thrown away: an in-process MongoDB replica set, a
23
+ // loopback Redis, a loopback mail sink. Only DEMO / unregistered brands are
24
+ // read, so no vendor cloud is contacted. Run with: yarn test:e2e
25
+
26
+ import { after, before, describe, it } from "node:test";
27
+ import assert from "node:assert/strict";
28
+ import { ObjectId } from "mongodb";
29
+
30
+ import { startHarness } from "./harness.mjs";
31
+
32
+ const PASSWORD = "Robot-Passw0rd!";
33
+ const MANAGER_A = "site-manager-a@e2e.example.com"; // client A's manager, role "*"
34
+ const MANAGER_B = "site-manager-b@e2e.example.com"; // client B's manager, role "*"
35
+ const STAFF = "site-staff@e2e.example.com"; // Seven365 super admin
36
+
37
+ const HYGIENE = "iservice365-web-app-hygiene";
38
+ const SECURITY = "iservice365-web-app-security";
39
+ const PM = "iservice365-web-app-property-management";
40
+
41
+ describe("robot site fleet endpoints - estate and app scoped", { concurrency: 1 }, () => {
42
+ let h;
43
+ const id = {};
44
+ const sid = {};
45
+
46
+ before(async () => {
47
+ h = await startHarness();
48
+ Object.assign(id, await seed(h));
49
+ for (const [k, email] of Object.entries({ MANAGER_A, MANAGER_B, STAFF })) {
50
+ sid[k] = await h.login(email, PASSWORD);
51
+ }
52
+ }, { timeout: 300000 });
53
+
54
+ after(async () => {
55
+ if (h) await h.stop();
56
+ });
57
+
58
+ const fleet = (qs = "", who = "MANAGER_A", org = id.orgA, site = id.siteA) =>
59
+ h.api(`/robots/organization/${org}/site/${site}/fleet${qs}`, { sid: sid[who] });
60
+ const summary = (qs = "", who = "MANAGER_A", org = id.orgA, site = id.siteA) =>
61
+ h.api(`/robots/organization/${org}/site/${site}/summary${qs}`, { sid: sid[who] });
62
+ const states = (ids, qs = "", who = "MANAGER_A") =>
63
+ h.api(`/robots/states?ids=${ids.join(",")}${qs}`, { sid: sid[who] });
64
+ const noCredentials = (body) => {
65
+ const text = JSON.stringify(body);
66
+ assert.equal(text.includes("appKey"), false, "appKey leaked");
67
+ assert.equal(text.includes("appToken"), false, "appToken leaked");
68
+ assert.equal(text.includes("e2e-fake"), false, "a credential value leaked");
69
+ };
70
+
71
+ it("1. no session is a 401 on every new route", async () => {
72
+ for (const path of [
73
+ `/robots/organization/${id.orgA}/site/${id.siteA}/fleet`,
74
+ `/robots/organization/${id.orgA}/site/${id.siteA}/summary`,
75
+ `/robots/states?ids=${id.cleanA1}`,
76
+ `/robots/${id.cleanA1}`,
77
+ `/robots/${id.patrolA}/patrol-routes`,
78
+ ]) {
79
+ assert.equal((await h.api(path)).status, 401, path);
80
+ }
81
+ });
82
+
83
+ it("2. a manager lists their own site - both classes when no app narrows - with no credentials", async () => {
84
+ const res = await fleet("?limit=50");
85
+ assert.equal(res.status, 200, JSON.stringify(res.body));
86
+ assert.deepEqual(res.body.items.map((r) => r.name).sort(), ["A clean 1", "A clean 2", "A clean 3", "A patrol", "A sentry"]);
87
+ assert.equal(res.body.total, 5);
88
+ assert.equal(res.body.items[0].site.name, "Site A");
89
+ noCredentials(res.body);
90
+ });
91
+
92
+ it("3. the list pages past page 1 (pages + total, never totalPages)", async () => {
93
+ const p1 = await fleet("?limit=2&page=1");
94
+ const p3 = await fleet("?limit=2&page=3");
95
+ assert.equal(p1.body.pages, 3);
96
+ assert.equal(p1.body.total, 5);
97
+ assert.equal(p1.body.items.length, 2);
98
+ assert.equal(p3.body.items.length, 1);
99
+ const all = [...p1.body.items, ...(await fleet("?limit=2&page=2")).body.items, ...p3.body.items].map((r) => r.name);
100
+ assert.equal(new Set(all).size, 5, "every robot on exactly one page");
101
+ });
102
+
103
+ it("4. another client's site is refused - list and summary", async () => {
104
+ const list = await fleet("", "MANAGER_A", id.orgB, id.siteB);
105
+ const sum = await summary("", "MANAGER_A", id.orgB, id.siteB);
106
+ assert.notEqual(list.status, 200);
107
+ assert.notEqual(sum.status, 200);
108
+ assert.equal(JSON.stringify(list.body).includes("B clean"), false);
109
+ });
110
+
111
+ it("5. appSlug narrows the list: Hygiene cleaning only, Security security only, PM both", async () => {
112
+ const names = async (slug, extra = "") => (await fleet(`?limit=50&appSlug=${slug}${extra}`)).body.items.map((r) => r.type);
113
+ assert.deepEqual([...new Set(await names(HYGIENE))], ["cleaning"]);
114
+ assert.deepEqual([...new Set(await names(SECURITY))], ["security"]);
115
+ assert.deepEqual([...new Set(await names(PM))].sort(), ["cleaning", "security"]);
116
+ // Hygiene asking for security gets NOTHING, not everything.
117
+ assert.deepEqual(await names(HYGIENE, "&type=security"), []);
118
+ // A slug nobody declared sees no robots at all (fails closed).
119
+ assert.deepEqual(await names("iservice365-web-app-landscape"), []);
120
+ });
121
+
122
+ it("6. the summary counts the same robots the list shows, narrowed the same way", async () => {
123
+ const all = await summary();
124
+ assert.equal(all.status, 200, JSON.stringify(all.body));
125
+ assert.equal(all.body.total, 5);
126
+ assert.equal(all.body.faults.count, 0);
127
+ assert.equal(all.body.offline.count, 0);
128
+ // The heading's names come with it, so an empty site still has a title.
129
+ assert.deepEqual([all.body.client.name, all.body.site.name], ["Client A", "Site A"]);
130
+ assert.equal((await summary(`?appSlug=${HYGIENE}`)).body.total, 3);
131
+ assert.equal((await summary(`?appSlug=${SECURITY}`)).body.total, 2);
132
+ assert.equal((await summary(`?appSlug=${HYGIENE}&type=security`)).body.total, 0);
133
+ });
134
+
135
+ it("7. /states answers only robots at a reachable site, and only the app's classes", async () => {
136
+ const res = await states([id.cleanA1, id.patrolA, id.sentryA, id.cleanB]);
137
+ assert.equal(res.status, 200, JSON.stringify(res.body));
138
+ const byId = Object.fromEntries(res.body.items.map((x) => [x.id, x]));
139
+ assert.equal(byId[String(id.cleanB)], undefined, "a robot at another client's site is left out");
140
+ assert.equal(byId[String(id.cleanA1)].ok, true);
141
+ assert.equal(byId[String(id.cleanA1)].online, true);
142
+ assert.equal(typeof byId[String(id.cleanA1)].batteryPercent, "number");
143
+ assert.equal(byId[String(id.cleanA1)].model, "Demo S1");
144
+ assert.equal(typeof byId[String(id.cleanA1)].planPosition.x, "number");
145
+ assert.equal(byId[String(id.patrolA)].mode, "WORKING");
146
+ // An unregistered brand is "No interface": nothing to read.
147
+ assert.deepEqual(byId[String(id.sentryA)], { id: String(id.sentryA), ok: false, monitorable: false });
148
+ noCredentials(res.body);
149
+
150
+ const hyg = await states([id.cleanA1, id.patrolA, id.sentryA], `&appSlug=${HYGIENE}`);
151
+ assert.deepEqual(hyg.body.items.map((x) => x.id), [String(id.cleanA1)]);
152
+ const sec = await states([id.cleanA1, id.patrolA], `&appSlug=${SECURITY}`);
153
+ assert.deepEqual(sec.body.items.map((x) => x.id), [String(id.patrolA)]);
154
+
155
+ assert.equal((await states([])).status, 400);
156
+ assert.equal((await h.api(`/robots/states?ids=nope`, { sid: sid.MANAGER_A })).status, 400);
157
+ });
158
+
159
+ it("8. after a read the summary's live counts are known", async () => {
160
+ const res = await summary();
161
+ assert.ok(res.body.live.asOf, "live.asOf set after /states read the robots");
162
+ assert.equal(res.body.live.online.count, 2, JSON.stringify(res.body.live)); // the two monitorable robots /states read
163
+ assert.ok(res.body.live.working.count >= 1, "the demo patrol robot is working");
164
+ });
165
+
166
+ it("9. GET /:id is the record with names and no credentials; scoped like every robot route", async () => {
167
+ const own = await h.api(`/robots/${id.patrolA}`, { sid: sid.MANAGER_A });
168
+ assert.equal(own.status, 200, JSON.stringify(own.body));
169
+ assert.equal(own.body.name, "A patrol");
170
+ assert.equal(own.body.type, "security");
171
+ assert.equal(own.body.client.name, "Client A");
172
+ assert.equal(own.body.site.name, "Site A");
173
+ assert.equal(own.body.robotSn, "DEMO-S-003");
174
+ noCredentials(own.body);
175
+ assert.notEqual((await h.api(`/robots/${id.cleanB}`, { sid: sid.MANAGER_A })).status, 200);
176
+ assert.notEqual((await h.api(`/robots/${id.patrolA}?appSlug=${HYGIENE}`, { sid: sid.MANAGER_A })).status, 200);
177
+ });
178
+
179
+ it("10. patrol routes: the demo security robot has the full contract", async () => {
180
+ const res = await h.api(`/robots/${id.patrolA}/patrol-routes?appSlug=${SECURITY}`, { sid: sid.MANAGER_A });
181
+ assert.equal(res.status, 200, JSON.stringify(res.body));
182
+ assert.equal(res.body.supported, true);
183
+ const [route] = res.body.routes;
184
+ assert.equal(route.name, "Route A · Lobby loop");
185
+ assert.deepEqual(route.checkpoints.map((c) => c.name), ["Lobby", "Lift lobby", "Corridor B", "Fire exit"]);
186
+ assert.ok(Number.isInteger(route.currentCheckpoint) && route.currentCheckpoint >= 0 && route.currentCheckpoint < 4);
187
+ assert.deepEqual(res.body.schedule, [{ routeId: "route-a", days: [1, 2, 3, 4, 5, 6, 7], startTime: "20:00", endTime: "06:00", rounds: 6 }]);
188
+ });
189
+
190
+ it("11. patrol routes: a cleaning robot and a no-interface brand are 'not supported'; Hygiene cannot ask", async () => {
191
+ const clean = await h.api(`/robots/${id.cleanA1}/patrol-routes`, { sid: sid.MANAGER_A });
192
+ assert.deepEqual(clean.body, { supported: false, routes: [], schedule: [] });
193
+ const sentry = await h.api(`/robots/${id.sentryA}/patrol-routes`, { sid: sid.MANAGER_A });
194
+ assert.equal(sentry.status, 200, JSON.stringify(sentry.body));
195
+ assert.deepEqual(sentry.body, { supported: false, routes: [], schedule: [] });
196
+ assert.notEqual((await h.api(`/robots/${id.patrolA}/patrol-routes?appSlug=${HYGIENE}`, { sid: sid.MANAGER_A })).status, 200);
197
+ assert.notEqual((await h.api(`/robots/${id.patrolA}/patrol-routes`, { sid: sid.MANAGER_B })).status, 200);
198
+ });
199
+
200
+ it("12. pause / resume / cancel reach a demo patrol robot; resume while not paused is refused", async () => {
201
+ const cmd = (kind, extra = {}) =>
202
+ h.api(`/robots/${id.patrolA}/command`, { method: "POST", sid: sid.MANAGER_A, body: { kind, ...extra } });
203
+ assert.equal((await cmd("resume")).status, 400, "not paused yet");
204
+ assert.equal((await cmd("pause")).status, 202);
205
+ const paused = await states([id.patrolA]);
206
+ assert.equal(paused.body.items[0].mode, "PAUSED");
207
+ assert.equal((await cmd("resume")).status, 202);
208
+ assert.equal((await cmd("cancel")).status, 202);
209
+ assert.equal((await cmd("pause", { x: 1 })).status, 400, "a bare command takes no fields");
210
+ });
211
+
212
+ it("14. the site is the estate: a robot registered from another organisation's app at this site lists too", async () => {
213
+ const contractorOrg = new ObjectId();
214
+ await h.db.collection("robots").insertOne({
215
+ name: "A contractor bot", type: "cleaning", brand: "demo", robotSn: "DEMO-0003",
216
+ appKey: "e2e-fake-key", appToken: "e2e-fake-token", createdBy: "x", createdByName: "x",
217
+ metadata: { orgId: contractorOrg, siteId: id.siteA, administratorId: "" }, status: "", createdAt: new Date(), deletedAt: "",
218
+ });
219
+ const res = await fleet("?limit=50");
220
+ assert.ok(res.body.items.some((r) => r.name === "A contractor bot"), "listed at its site");
221
+ assert.equal((await summary()).body.total, 6);
222
+ // ...and the heading names the site's own client, whichever app asks.
223
+ assert.equal((await summary()).body.client.name, "Client A");
224
+ // Another client's manager still cannot open this site.
225
+ assert.notEqual((await fleet("", "MANAGER_B")).status, 200);
226
+ });
227
+
228
+ it("13. super admin reaches any client's site", async () => {
229
+ const res = await fleet("?limit=50", "STAFF", id.orgB, id.siteB);
230
+ assert.equal(res.status, 200, JSON.stringify(res.body));
231
+ assert.deepEqual(res.body.items.map((r) => r.name), ["B clean"]);
232
+ const st = await states([id.cleanB], "", "STAFF");
233
+ assert.equal(st.body.items.length, 1);
234
+ });
235
+
236
+ // ---- "Add demo robots" / "Remove demo robots": Super Admin only ----------
237
+
238
+ const demo = (method, who, body, site = id.siteB, org = id.orgB) =>
239
+ h.api(`/robots/organization/${org}/site/${site}/demo`, { method, sid: sid[who], body });
240
+
241
+ it("15. adding demo robots: only the super-admin membership; demo brand only, whatever the body says", async () => {
242
+ assert.equal((await h.api(`/robots/organization/${id.orgB}/site/${id.siteB}/demo`, { method: "POST", body: {} })).status, 401);
243
+ // A client's own manager - even at their own site - is refused before anything is written.
244
+ const refused = await demo("POST", "MANAGER_B", { cleaning: 1, security: 1 });
245
+ assert.notEqual(refused.status, 201);
246
+ assert.equal(await h.db.collection("robots").countDocuments({ robotSn: /^DEMO-[CS]-/, "metadata.siteId": id.siteB }), 0);
247
+
248
+ const res = await demo("POST", "STAFF", { cleaning: 2, security: 1, brand: "ounitech", robotSn: "EVIL", name: "Real robot" });
249
+ assert.equal(res.status, 201, JSON.stringify(res.body));
250
+ assert.deepEqual(res.body.created.map((r) => [r.type, r.robotSn, r.name]), [
251
+ ["cleaning", "DEMO-C-001", "Demo Cleaner 001"],
252
+ ["cleaning", "DEMO-C-002", "Demo Cleaner 002"],
253
+ // DEMO-S-003 is already taken at site A, so security numbering goes on from it.
254
+ ["security", "DEMO-S-004", "Demo Patrol 004"],
255
+ ]);
256
+ const rows = await h.db.collection("robots").find({ robotSn: /^DEMO-[CS]-00[124]$/, "metadata.siteId": id.siteB }).toArray();
257
+ assert.equal(rows.length, 3);
258
+ for (const r of rows) {
259
+ assert.equal(r.brand, "demo");
260
+ assert.match(r.name, /^Demo /);
261
+ // The robot belongs to the site's own client.
262
+ assert.equal(String(r.metadata.orgId), String(id.orgB));
263
+ }
264
+ // Console-audit: one row per robot added.
265
+ assert.equal(await h.db.collection("console-audit").countDocuments({ action: "robot.added", target: { $in: res.body.created.map((r) => r._id) } }), 3);
266
+ // They list at the site, and live.
267
+ const list = await fleet("?limit=50", "STAFF", id.orgB, id.siteB);
268
+ assert.equal(list.body.total, 4);
269
+ // A second press numbers on - never the same serial twice.
270
+ const again = await demo("POST", "STAFF", { cleaning: 1, security: 0 });
271
+ assert.deepEqual(again.body.created.map((r) => r.robotSn), ["DEMO-C-003"]);
272
+ // Bounds.
273
+ assert.equal((await demo("POST", "STAFF", { cleaning: 0, security: 0 })).status, 400);
274
+ assert.equal((await demo("POST", "STAFF", { cleaning: 21 })).status, 400);
275
+ assert.notEqual((await demo("POST", "STAFF", {}, String(new ObjectId()))).status, 201, "an unknown site");
276
+ });
277
+
278
+ it("16. removing demo robots touches demo robots only, and only for the super admin", async () => {
279
+ assert.notEqual((await demo("DELETE", "MANAGER_B")).status, 200);
280
+ const res = await demo("DELETE", "STAFF");
281
+ assert.equal(res.status, 200, JSON.stringify(res.body));
282
+ // Site B had "B clean" (demo brand, registered normally) + the four demo robots added.
283
+ assert.equal(res.body.removed, 5);
284
+ const left = await h.db.collection("robots").find({ "metadata.siteId": id.siteB, deletedAt: { $in: ["", null] } }).toArray();
285
+ assert.deepEqual(left, []);
286
+ // A real (non-demo) robot elsewhere is untouched: the Sentry robot at site A is still listed.
287
+ const a = await fleet("?limit=50", "STAFF");
288
+ assert.ok(a.body.items.some((r) => r.name === "A sentry"));
289
+ assert.equal(await h.db.collection("console-audit").countDocuments({ action: "robot.removed" }) >= 5, true);
290
+ });
291
+ });
292
+
293
+ async function seed(h) {
294
+ const now = new Date().toISOString();
295
+ const orgA = new ObjectId();
296
+ const orgB = new ObjectId();
297
+ const siteA = new ObjectId();
298
+ const siteB = new ObjectId();
299
+ const staffRole = new ObjectId();
300
+ const managerA = new ObjectId();
301
+ const managerB = new ObjectId();
302
+
303
+ await h.db.collection("organizations").insertMany([
304
+ { _id: orgA, name: "Client A", email: "sca@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
305
+ { _id: orgB, name: "Client B", email: "scb@e2e.example.com", type: "org", nature: "property_management_agency", status: "active", createdAt: now },
306
+ ]);
307
+ await h.db.collection("sites").insertMany([
308
+ { _id: siteA, name: "Site A", org: orgA, orgId: orgA, status: "active" },
309
+ { _id: siteB, name: "Site B", org: orgB, orgId: orgB, status: "active" },
310
+ ]);
311
+ await h.db.collection("roles").insertMany([
312
+ { _id: staffRole, name: "Super Admin", type: "admin", default: true, permissions: [], status: "active" },
313
+ { _id: managerA, name: "Manager A", org: orgA, type: "organization", permissions: ["*"], status: "active" },
314
+ { _id: managerB, name: "Manager B", org: orgB, type: "organization", permissions: ["*"], status: "active" },
315
+ ]);
316
+
317
+ const emails = [MANAGER_A, MANAGER_B, STAFF];
318
+ const users = await h.db.collection("users").insertMany(
319
+ emails.map((email) => ({ email, name: email.split("@")[0], status: "active", createdAt: now })),
320
+ );
321
+ const hashed = await h.hashPassword(PASSWORD);
322
+ await h.db.collection("users").updateMany({ email: { $in: emails } }, { $set: { password: hashed } });
323
+ const [ua, ub, us] = [0, 1, 2].map((i) => users.insertedIds[i]);
324
+ await h.db.collection("members").insertMany([
325
+ { user: ua, org: orgA, type: "organization", role: managerA, status: "active" },
326
+ { user: ub, org: orgB, type: "organization", role: managerB, status: "active" },
327
+ { user: us, type: "admin", role: staffRole, status: "active" },
328
+ ]);
329
+
330
+ const robot = (name, org, site, extra = {}) => ({
331
+ name,
332
+ appKey: "e2e-fake-key",
333
+ appToken: "e2e-fake-token",
334
+ createdBy: ua,
335
+ createdByName: "site-manager-a",
336
+ robotSn: "",
337
+ metadata: { orgId: org, siteId: site, administratorId: "" },
338
+ status: "",
339
+ createdAt: new Date(),
340
+ deletedAt: "",
341
+ ...extra,
342
+ });
343
+
344
+ const res = await h.db.collection("robots").insertMany([
345
+ robot("A clean 1", orgA, siteA, { type: "cleaning", brand: "demo", robotSn: "DEMO-0001" }),
346
+ robot("A clean 2", orgA, siteA, { type: "cleaning", brand: "demo", robotSn: "DEMO-0003" }),
347
+ robot("A clean 3", orgA, siteA, { type: "cleaning", brand: "demo", robotSn: "DEMO-0002" }),
348
+ robot("A patrol", orgA, siteA, { type: "security", brand: "demo", robotSn: "DEMO-S-003" }),
349
+ robot("A sentry", orgA, siteA, { type: "security", brand: "sentry", robotSn: "SP-1" }),
350
+ robot("B clean", orgB, siteB, { type: "cleaning", brand: "demo", robotSn: "DEMO-0001" }),
351
+ ]);
352
+
353
+ return {
354
+ orgA, orgB, siteA, siteB,
355
+ cleanA1: res.insertedIds[0],
356
+ patrolA: res.insertedIds[3],
357
+ sentryA: res.insertedIds[4],
358
+ cleanB: res.insertedIds[5],
359
+ };
360
+ }
@@ -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
+ });