@7365admin1/core 3.122.5 → 3.123.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/dist/index.js CHANGED
@@ -266,6 +266,7 @@ __export(src_exports, {
266
266
  PADBOT_BRAND_DEFINITION: () => PADBOT_BRAND_DEFINITION,
267
267
  PADBOT_CAPABILITIES: () => PADBOT_CAPABILITIES,
268
268
  PADBOT_DISPLAY_NAME: () => PADBOT_DISPLAY_NAME,
269
+ PADBOT_FAILURE_SHOW_MS: () => PADBOT_FAILURE_SHOW_MS,
269
270
  PADBOT_LIVE_POSE_MS: () => PADBOT_LIVE_POSE_MS,
270
271
  PADBOT_MAKER_APP_ONLY: () => PADBOT_MAKER_APP_ONLY,
271
272
  PADBOT_MODELS: () => PADBOT_MODELS,
@@ -612,12 +613,14 @@ __export(src_exports, {
612
613
  padbotCanReachMap: () => padbotCanReachMap,
613
614
  padbotChargingPoint: () => padbotChargingPoint,
614
615
  padbotCheckpointVisit: () => padbotCheckpointVisit,
616
+ padbotCommandBlock: () => padbotCommandBlock,
615
617
  padbotCommandLog: () => padbotCommandLog,
616
618
  padbotCurrentMap: () => padbotCurrentMap,
617
619
  padbotDriveBlock: () => padbotDriveBlock,
618
620
  padbotDriveLimits: () => padbotDriveLimits,
619
621
  padbotDriveSignal: () => padbotDriveSignal,
620
622
  padbotErrorText: () => padbotErrorText,
623
+ padbotFailureText: () => padbotFailureText,
621
624
  padbotLinkUp: () => padbotLinkUp,
622
625
  padbotLive: () => padbotLive,
623
626
  padbotManualDriveEnabled: () => padbotManualDriveEnabled,
@@ -626,6 +629,8 @@ __export(src_exports, {
626
629
  padbotPatrolPlan: () => padbotPatrolPlan,
627
630
  padbotPatrolRecord: () => padbotPatrolRecord,
628
631
  padbotPlanShare: () => padbotPlanShare,
632
+ padbotReactionPoint: () => padbotReactionPoint,
633
+ padbotReadiness: () => padbotReadiness,
629
634
  padbotSignature: () => padbotSignature,
630
635
  padbotSignedRequest: () => padbotSignedRequest,
631
636
  parseCameraChannel: () => parseCameraChannel,
@@ -65321,6 +65326,64 @@ function padbotMode(states, now = Date.now()) {
65321
65326
  const base = phase || (charging ? "Charging" : patrolling ? "Patrolling" : work.workState === 1 ? "Working on a task" : "Standing by");
65322
65327
  return { online: true, mode, statusName: `${base}${networkText(states["1107"])}` };
65323
65328
  }
65329
+ var MOVING_COMMANDS = /* @__PURE__ */ new Set(["full", "area", "patrol-resume", "return", "navigate", "go-to-point"]);
65330
+ function padbotCommandBlock(states, kind, now = Date.now()) {
65331
+ if (!MOVING_COMMANDS.has(kind))
65332
+ return null;
65333
+ if (!states || !padbotMode(states, now).online)
65334
+ return "The robot is not reporting to PadBot, so it cannot take a command. Check it is switched on and connected.";
65335
+ if (states["1006"]?.emergencyStopState === 1)
65336
+ return "The robot's emergency stop button is pressed. Release the red button on the robot, then try again.";
65337
+ const battery = num(states["1001"]?.batteryPercent);
65338
+ if (kind !== "return" && battery !== null && battery < 10)
65339
+ return `The battery is at ${battery}%. PadBot robots do not start jobs under 10%; send it to charge first.`;
65340
+ if (kind === "return" && [1, 2].includes(states["1002"]?.chargingState))
65341
+ return "The robot is already on its charger.";
65342
+ return null;
65343
+ }
65344
+ function padbotReadiness(states, now = Date.now()) {
65345
+ const st = states ?? {};
65346
+ const nav = st["1003"] ?? {};
65347
+ const es = st["1006"] ?? {};
65348
+ const charging = st["1002"]?.chargingState;
65349
+ const notes = [];
65350
+ if (es.wheelLockState === 1)
65351
+ notes.push("PadBot reports the wheel motor lock ON (1006 wheelLockState 1). PadBot's v4.0 document does not say whether this stops navigation - asked PadBot.");
65352
+ if (charging === 2)
65353
+ notes.push("Charging state 2 is not in PadBot's v4.0 document (only 0 and 1) - asked PadBot what it means.");
65354
+ return {
65355
+ online: padbotMode(st, now).online,
65356
+ heartbeatAt: st["1000"]?.updatedAt ?? null,
65357
+ emergencyStopPressed: es.emergencyStopState === 1,
65358
+ wheelLockState: es.wheelLockState ?? null,
65359
+ batteryPercent: num(st["1001"]?.batteryPercent),
65360
+ chargingState: charging ?? null,
65361
+ map: { id: st["1007"]?.mapId ?? null, name: st["1007"]?.mapDisplayName ?? null, floor: st["1007"]?.floor ?? null },
65362
+ navigation: { actionType: nav.actionType ?? null, actionState: nav.actionState ?? null, message: nav.message ?? null, updatedAt: nav.updatedAt ?? null },
65363
+ work: { workState: st["1010"]?.workState ?? null, taskType: st["1010"]?.taskType ?? null, updatedAt: st["1010"]?.updatedAt ?? null },
65364
+ blocker: padbotCommandBlock(st, "go-to-point", now),
65365
+ notes
65366
+ };
65367
+ }
65368
+ function padbotReactionPoint(states) {
65369
+ const st = states ?? {};
65370
+ const nav = st["1003"] ?? {};
65371
+ return {
65372
+ action: Number(nav.actionType) || 0,
65373
+ state: Number(nav.actionState) || 0,
65374
+ target: nav.finalTargetPointName ?? nav.nextTargetPointName ?? null,
65375
+ message: nav.message ?? null,
65376
+ work: Number(st["1010"]?.workState) || 0,
65377
+ charging: st["1002"]?.chargingState ?? null,
65378
+ estop: st["1006"]?.emergencyStopState ?? null,
65379
+ wheelLock: st["1006"]?.wheelLockState ?? null
65380
+ };
65381
+ }
65382
+ function padbotFailureText(p) {
65383
+ if (p.state !== 6)
65384
+ return null;
65385
+ return `Could not reach ${p.target || "its destination"}${p.message ? ` (${p.message})` : ""}`;
65386
+ }
65324
65387
  function networkText(net) {
65325
65388
  const say = (label2, v) => v < 0 ? ` \xB7 ${label2} ${v} dBm` : ` \xB7 ${label2} signal ${v}`;
65326
65389
  const wifi = num(net?.wifi?.signalStrength);
@@ -65488,7 +65551,7 @@ function createPadbotClient(credentials, options = {}) {
65488
65551
  const baseUrl = (options.baseUrl ?? padbotBaseUrl()).replace(/\/+$/, "");
65489
65552
  const doFetch = options.fetch ?? ((url2, init) => fetch(url2, init));
65490
65553
  const timeoutMs = options.timeoutMs ?? 8e3;
65491
- async function call(path5, body = {}) {
65554
+ async function call(path5, body = {}, meta) {
65492
65555
  const req = padbotSignedRequest({ path: path5, body, accessKeyId: credentials.appid, accessKeySecret: credentials.secret, now: options.now });
65493
65556
  let res;
65494
65557
  try {
@@ -65508,6 +65571,10 @@ function createPadbotClient(credentials, options = {}) {
65508
65571
  } catch {
65509
65572
  throw new import_node_server_utils162.AppError("PadBot's cloud sent an answer that is not JSON.", 502);
65510
65573
  }
65574
+ if (meta) {
65575
+ meta.message = typeof json?.message === "string" ? json.message.slice(0, 200) : "";
65576
+ meta.requestId = typeof json?.requestId === "string" ? json.requestId.slice(0, 64) : "";
65577
+ }
65511
65578
  if (json?.code !== 0) {
65512
65579
  const e = new import_node_server_utils162.BadRequestError(padbotErrorText(Number(json?.code)));
65513
65580
  e.vendorCode = Number(json?.code);
@@ -65584,6 +65651,7 @@ function clearPadbotCache() {
65584
65651
  cache2.clear();
65585
65652
  live.clear();
65586
65653
  commandLog.clear();
65654
+ lastFailure.clear();
65587
65655
  }
65588
65656
  function forgetPadbotMaps(appid, robotSn) {
65589
65657
  for (const key of cache2.keys())
@@ -65610,6 +65678,8 @@ function logCommand(accountKey, robotSn, entry) {
65610
65678
  commandLog.set(k, [entry, ...commandLog.get(k) ?? []].slice(0, 10));
65611
65679
  }
65612
65680
  var padbotCommandLog = (accountKey, robotSn) => commandLog.get(`${accountKey}:${robotSn}`) ?? [];
65681
+ var lastFailure = /* @__PURE__ */ new Map();
65682
+ var PADBOT_FAILURE_SHOW_MS = 3 * 6e4;
65613
65683
  async function readPadbotStates(credentials, robotSn, stateTypes) {
65614
65684
  const list = await createPadbotClient(credentials).call(PADBOT_PATHS.states, { serialNumbers: [robotSn], stateTypes });
65615
65685
  const entry = (list ?? []).find((e) => e?.serialNumber === robotSn);
@@ -65635,6 +65705,11 @@ async function listPadbotAlarmsSince(credentials, serials, startTime) {
65635
65705
  }
65636
65706
  function createPadbotAdapter(credentials, options = {}) {
65637
65707
  const { call, raw } = createPadbotClient(credentials, options);
65708
+ const watch = options.watch === void 0 ? { everyMs: 2e3, forMs: 3e4 } : options.watch;
65709
+ const sleep3 = options.sleep ?? ((ms2) => new Promise((resolve) => {
65710
+ const t = setTimeout(resolve, ms2);
65711
+ t?.unref?.();
65712
+ }));
65638
65713
  const now = options.now ?? Date.now;
65639
65714
  const ns = `${credentials.appid}@${options.baseUrl ?? padbotBaseUrl()}`;
65640
65715
  const account = padbotAccountKey(credentials);
@@ -65656,13 +65731,15 @@ function createPadbotAdapter(credentials, options = {}) {
65656
65731
  const heard = padbotLive(account, robotSn);
65657
65732
  const restBatteryAt = ms(st["1001"]?.updatedAt);
65658
65733
  const battery = heard?.batteryPercent !== void 0 && (!Number.isFinite(restBatteryAt) || (heard.batteryAt ?? 0) > restBatteryAt) ? heard.batteryPercent : num(st["1001"]?.batteryPercent);
65734
+ const failed = lastFailure.get(`${account}:${robotSn}`);
65735
+ const showFailure = online && failed && now() - failed.at < PADBOT_FAILURE_SHOW_MS && /^(Standing by|Charging)/.test(statusName);
65659
65736
  const robot = {
65660
65737
  robotSn,
65661
65738
  name: info?.robotName,
65662
65739
  model: info?.robotModel ? `PadBot ${info.robotModel}` : void 0,
65663
65740
  online,
65664
65741
  mode,
65665
- statusName,
65742
+ statusName: showFailure ? `${failed.text} \xB7 ${statusName}` : statusName,
65666
65743
  batteryPercent: battery,
65667
65744
  floorNo: Number.isInteger(floor) ? floor : null,
65668
65745
  floorKnown: Number.isInteger(floor),
@@ -65751,13 +65828,56 @@ function createPadbotAdapter(credentials, options = {}) {
65751
65828
  }
65752
65829
  return String(rawRoute.pathId);
65753
65830
  }
65831
+ async function watchReaction(robotSn, entry, sentAt) {
65832
+ if (!watch)
65833
+ return;
65834
+ const r = entry.reaction = { watching: true, points: [], failure: null, moved: false };
65835
+ let last = "";
65836
+ try {
65837
+ for (let waited = 0; waited < watch.forMs; ) {
65838
+ await sleep3(watch.everyMs);
65839
+ waited += watch.everyMs;
65840
+ const st = await states(robotSn).catch(() => null);
65841
+ if (!st)
65842
+ continue;
65843
+ const p = padbotReactionPoint(st);
65844
+ const key = JSON.stringify(p);
65845
+ if (key !== last && r.points.length < 20)
65846
+ r.points.push({ ...p, afterSeconds: Math.round((now() - sentAt) / 1e3) });
65847
+ last = key;
65848
+ if (p.state >= 1 && p.state <= 4)
65849
+ r.moved = true;
65850
+ const failure = padbotFailureText(p);
65851
+ if (failure) {
65852
+ r.failure = failure;
65853
+ lastFailure.set(`${account}:${robotSn}`, { at: now(), text: failure });
65854
+ break;
65855
+ }
65856
+ if (p.state === 5)
65857
+ break;
65858
+ }
65859
+ } finally {
65860
+ r.watching = false;
65861
+ }
65862
+ }
65754
65863
  async function sendCommand2(robotSn, command) {
65755
65864
  const sn = { serialNumber: robotSn };
65865
+ if (MOVING_COMMANDS.has(command.kind)) {
65866
+ const block = padbotCommandBlock(await states(robotSn), command.kind, now());
65867
+ if (block)
65868
+ throw new import_node_server_utils162.BadRequestError(block);
65869
+ lastFailure.delete(`${account}:${robotSn}`);
65870
+ }
65756
65871
  const call2 = async (path5, body) => {
65757
65872
  const at2 = new Date(now()).toISOString();
65873
+ const meta = {};
65758
65874
  try {
65759
- await callRaw(path5, body);
65760
- logCommand(account, robotSn, { at: at2, command: command.kind, path: path5, body, ok: true });
65875
+ await callRaw(path5, body, meta);
65876
+ const entry = { at: at2, command: command.kind, path: path5, body, ok: true, vendorCode: 0, vendorMessage: meta.message, requestId: meta.requestId };
65877
+ logCommand(account, robotSn, entry);
65878
+ if (MOVING_COMMANDS.has(command.kind))
65879
+ void watchReaction(robotSn, entry, now()).catch(() => {
65880
+ });
65761
65881
  } catch (e) {
65762
65882
  logCommand(account, robotSn, {
65763
65883
  at: at2,
@@ -65854,6 +65974,8 @@ function createPadbotAdapter(credentials, options = {}) {
65854
65974
  steps.push({ step, path: path5, body, httpStatus: r.httpStatus, code: r.code, message: r.message, ms: r.ms, data: r.code === 0 ? shape(r.data) : r.data });
65855
65975
  };
65856
65976
  await run("states (4.2)", PADBOT_PATHS.states, { serialNumbers: [robotSn] });
65977
+ const stEntry = (Array.isArray(steps[0]?.data) ? steps[0].data : []).find((e) => e?.serialNumber === robotSn);
65978
+ const ready = padbotReadiness(stEntry ? statesByType(stEntry) : null, now());
65857
65979
  await run("location (4.3)", PADBOT_PATHS.location, sn);
65858
65980
  await run("maps (5.1)", PADBOT_PATHS.maps, sn, (d) => Array.isArray(d) ? d.slice(0, 100).map(mapSummary) : d);
65859
65981
  await run("patrol routes (6.1)", PADBOT_PATHS.patrolRoutes, sn, (d) => Array.isArray(d) ? d.slice(0, 50) : d);
@@ -65861,6 +65983,7 @@ function createPadbotAdapter(credentials, options = {}) {
65861
65983
  await run("patrol records (6.7)", PADBOT_PATHS.records, { serialNumbers: [robotSn], pageNumber: 1, pageSize: 3 });
65862
65984
  const replies = padbotCommandLog(account, robotSn);
65863
65985
  steps.push({ step: "recent commands (this server)", path: "", body: null, httpStatus: 200, code: 0, message: replies.length ? `${replies.length} kept` : "none since this server started", ms: 0, data: replies });
65986
+ steps.push({ step: "can it move now? (from 4.2)", path: "", body: null, httpStatus: 200, code: 0, message: ready.blocker ?? (ready.notes.length ? "No documented blocker; see notes" : "No blocker"), ms: 0, data: ready });
65864
65987
  return steps;
65865
65988
  },
65866
65989
  async getPatrolRoutes(robotSn) {
@@ -90141,7 +90264,7 @@ function useNewDashboardRepo() {
90141
90264
  },
90142
90265
  activePatrolItems
90143
90266
  };
90144
- return data;
90267
+ return { ...data, ...await inventorySupplyTile(siteIdObj, "security_agency") };
90145
90268
  }
90146
90269
  async function getPropertyManagementDashboard(siteId, period = "today" /* TODAY */, type, facility) {
90147
90270
  const siteIdObj = (0, import_node_server_utils261.toObjectId)(siteId);
@@ -90580,7 +90703,7 @@ function useNewDashboardRepo() {
90580
90703
  todayReminders,
90581
90704
  todayAttentions
90582
90705
  };
90583
- return data;
90706
+ return { ...data, ...await inventorySupplyTile(siteIdObj, "property_management_agency") };
90584
90707
  }
90585
90708
  function areaChecklistScheduleLookup(site, serviceType, createdAtRange) {
90586
90709
  return [
@@ -90605,24 +90728,38 @@ function useNewDashboardRepo() {
90605
90728
  { $unwind: { path: "$scheduleDoc", preserveNullAndEmptyArrays: false } }
90606
90729
  ];
90607
90730
  }
90731
+ async function inventoryLowStock(site, serviceType) {
90732
+ const natures = serviceType === "property_management_agency" ? ["property_management_agency", "real_estate_developer"] : [serviceType];
90733
+ const siteStores = await db2.collection("inventory.stores").find({ sites: site, status: "active" }, { projection: { _id: 1, org: 1 } }).toArray();
90734
+ if (!siteStores.length)
90735
+ return null;
90736
+ const ownOrgs = new Set(
90737
+ (await db2.collection("organizations").find(
90738
+ { _id: { $in: siteStores.map((store) => store.org) }, nature: { $in: natures } },
90739
+ { projection: { _id: 1 } }
90740
+ ).toArray()).map((org) => org._id.toString())
90741
+ );
90742
+ const stores = siteStores.filter((store) => ownOrgs.has(String(store.org)));
90743
+ if (!stores.length)
90744
+ return null;
90745
+ return db2.collection("inventory.items").aggregate([
90746
+ {
90747
+ $match: {
90748
+ store: { $in: stores.map((store) => store._id) },
90749
+ status: "active",
90750
+ reorderLevel: { $gt: 0 },
90751
+ $expr: { $lte: ["$onHand", "$reorderLevel"] }
90752
+ }
90753
+ },
90754
+ { $sort: { onHand: 1 } },
90755
+ { $limit: 5 },
90756
+ { $project: { _id: 1, name: 1, qty: "$onHand" } }
90757
+ ]).toArray();
90758
+ }
90608
90759
  async function lowStockItems(site, serviceType) {
90609
- const stores = await db2.collection("inventory.stores").find({ sites: site, status: "active" }, { projection: { _id: 1 } }).toArray();
90610
- if (stores.length) {
90611
- const items2 = await db2.collection("inventory.items").aggregate([
90612
- {
90613
- $match: {
90614
- store: { $in: stores.map((store) => store._id) },
90615
- status: "active",
90616
- reorderLevel: { $gt: 0 },
90617
- $expr: { $lte: ["$onHand", "$reorderLevel"] }
90618
- }
90619
- },
90620
- { $sort: { onHand: 1 } },
90621
- { $limit: 5 },
90622
- { $project: { _id: 1, name: 1, qty: "$onHand" } }
90623
- ]).toArray();
90624
- return { items: items2, basis: SUPPLY_BASIS_BELOW_ALERT_LEVEL };
90625
- }
90760
+ const inventory = await inventoryLowStock(site, serviceType);
90761
+ if (inventory)
90762
+ return { items: inventory, basis: SUPPLY_BASIS_BELOW_ALERT_LEVEL };
90626
90763
  const items = await supplyCollection.aggregate([
90627
90764
  { $match: { site, serviceType, status: "active" } },
90628
90765
  { $sort: { qty: 1 } },
@@ -90631,6 +90768,10 @@ function useNewDashboardRepo() {
90631
90768
  ]).toArray();
90632
90769
  return { items, basis: SUPPLY_BASIS_LOWEST_QUANTITY };
90633
90770
  }
90771
+ async function inventorySupplyTile(site, serviceType) {
90772
+ const items = await inventoryLowStock(site, serviceType);
90773
+ return items ? { supplyAlert: { items: items.map((item) => ({ name: item.name, qty: item.qty })), basis: SUPPLY_BASIS_BELOW_ALERT_LEVEL } } : {};
90774
+ }
90634
90775
  async function getServiceDashboard({
90635
90776
  site,
90636
90777
  serviceType,
@@ -104950,6 +105091,7 @@ function usePersonalEmergencyChainController() {
104950
105091
  PADBOT_BRAND_DEFINITION,
104951
105092
  PADBOT_CAPABILITIES,
104952
105093
  PADBOT_DISPLAY_NAME,
105094
+ PADBOT_FAILURE_SHOW_MS,
104953
105095
  PADBOT_LIVE_POSE_MS,
104954
105096
  PADBOT_MAKER_APP_ONLY,
104955
105097
  PADBOT_MODELS,
@@ -105296,12 +105438,14 @@ function usePersonalEmergencyChainController() {
105296
105438
  padbotCanReachMap,
105297
105439
  padbotChargingPoint,
105298
105440
  padbotCheckpointVisit,
105441
+ padbotCommandBlock,
105299
105442
  padbotCommandLog,
105300
105443
  padbotCurrentMap,
105301
105444
  padbotDriveBlock,
105302
105445
  padbotDriveLimits,
105303
105446
  padbotDriveSignal,
105304
105447
  padbotErrorText,
105448
+ padbotFailureText,
105305
105449
  padbotLinkUp,
105306
105450
  padbotLive,
105307
105451
  padbotManualDriveEnabled,
@@ -105310,6 +105454,8 @@ function usePersonalEmergencyChainController() {
105310
105454
  padbotPatrolPlan,
105311
105455
  padbotPatrolRecord,
105312
105456
  padbotPlanShare,
105457
+ padbotReactionPoint,
105458
+ padbotReadiness,
105313
105459
  padbotSignature,
105314
105460
  padbotSignedRequest,
105315
105461
  parseCameraChannel,