@7365admin1/core 3.90.0 → 3.92.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@7365admin1/core",
3
3
  "license": "MIT",
4
- "version": "3.90.0",
4
+ "version": "3.92.0",
5
5
  "author": "7365admin1",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
@@ -874,7 +874,7 @@ function buildApp(nsu, core) {
874
874
  // mirrors iservice365-API-core/src/routes/robot.route.ts
875
875
  const robots = express.Router();
876
876
  {
877
- const { createRobot, getRobots, updateRobot, deleteRobot } = core.useRobotController();
877
+ const { createRobot, getRobots, getRobot, updateRobot, deleteRobot } = core.useRobotController();
878
878
 
879
879
  // Seven365 console: every robot at every client's site. Mounted before the
880
880
  // id routes, as in API-core.
@@ -884,8 +884,17 @@ function buildApp(nsu, core) {
884
884
  robots.get("/network/faults", requireAuth, n.listNetworkFaults);
885
885
  robots.get("/network/states", requireAuth, n.getNetworkStates);
886
886
 
887
+ // One estate's fleet screens (HERO phase c). Mounted before the id routes.
888
+ const s = core.useRobotSiteController();
889
+ robots.get("/states", requireAuth, s.getSiteStates);
890
+
887
891
  robots.post("/", requireAuth, createRobot);
888
892
  robots.get("/organization/:organization/site/:site", requireAuth, getRobots);
893
+ robots.get("/organization/:organization/site/:site/fleet", requireAuth, s.listSiteFleet);
894
+ robots.get("/organization/:organization/site/:site/summary", requireAuth, s.getSiteSummary);
895
+ robots.post("/organization/:organization/site/:site/demo", requireAuth, s.addDemoRobots);
896
+ robots.delete("/organization/:organization/site/:site/demo", requireAuth, s.removeDemoRobots);
897
+ robots.get("/:id([0-9a-fA-F]{24})", requireAuth, getRobot);
889
898
  robots.patch("/:id([0-9a-fA-F]{24})", requireAuth, updateRobot);
890
899
  robots.delete("/:id([0-9a-fA-F]{24})", requireAuth, deleteRobot);
891
900
 
@@ -908,6 +917,7 @@ function buildApp(nsu, core) {
908
917
  const f = core.useRobotFleetController();
909
918
  robots.get("/:id([0-9a-fA-F]{24})/state", requireAuth, f.getState);
910
919
  robots.post("/:id([0-9a-fA-F]{24})/command", requireAuth, f.sendCommand);
920
+ robots.get("/:id([0-9a-fA-F]{24})/patrol-routes", requireAuth, f.getPatrolRoutes);
911
921
  }
912
922
 
913
923
  // mirrors iservice365-API-core/src/routes/attendance-settings.route.ts
@@ -173,6 +173,13 @@ describe("building maps and the lift queue", { concurrency: 1 }, () => {
173
173
  const now = await h.db.collection("robot-lift-sessions").findOne({ status: "active" });
174
174
  assert.equal(String(now.robotId), String(id.demo2));
175
175
  assert.equal((await h.api(`/robots/lift-sessions/${holder._id}/release`, { method: "POST", sid: managerSid })).status, 409);
176
+ // The ride that just ended is listed under the lift as a recent row.
177
+ const after = await h.api(`/robots/building-maps/${mapId}/lifts`, { sid: managerSid });
178
+ const recent = after.body.items[0].recent;
179
+ assert.equal(recent.length, 1);
180
+ assert.equal(String(recent[0]._id), String(holder._id));
181
+ assert.equal(recent[0].status, "released");
182
+ assert.ok(recent[0].closedAt);
176
183
  assert.ok(await findAudit(h, "robot.lift-released"));
177
184
  assert.ok(await findAudit(h, "robot.lift-requested"));
178
185
  });
@@ -190,6 +197,7 @@ describe("building maps and the lift queue", { concurrency: 1 }, () => {
190
197
  assert.equal(queue.body.items[0].active.robotName, "Demo 1");
191
198
  const expired = await h.db.collection("robot-lift-sessions").findOne({ _id: holder._id });
192
199
  assert.equal(expired.status, "expired");
200
+ assert.ok(queue.body.items[0].recent.some((r) => String(r._id) === String(holder._id) && r.status === "expired"));
193
201
  assert.equal((await h.api(`/robots/lift-sessions/${holder._id}/refresh`, { method: "POST", sid: managerSid })).status, 409);
194
202
  });
195
203
 
@@ -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
+ }