@7365admin1/core 3.96.1-staging.366 → 3.96.1-staging.368

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,40 @@
1
+ ---
2
+ "@7365admin1/core": minor
3
+ ---
4
+
5
+ Return the owner's block, level and unit with each HID SIP account.
6
+
7
+ `listSipAccounts` answered a name, email and extension per account, which is
8
+ enough to say who holds an extension but not which home it reaches. Two
9
+ residents called Harris were indistinguishable in the intercom contact picker,
10
+ and the contact saved onto the reader carried no address at all — so the door
11
+ panel's contact list named a person without saying whose unit was being rung.
12
+
13
+ Each row now carries `unitLabel`, the readable `Blk 1/Level 1/Unit 1`. The three
14
+ stored values are ObjectIds into `buildings`, `building-levels` and
15
+ `building-units`, so every one is resolved to its name; joining the raw values
16
+ would stamp `665f.../665f.../665f...` onto the reader. A block carries both a
17
+ number and an optional descriptive name and the short number wins, because the
18
+ label is read off a door panel.
19
+
20
+ The address comes from `site.people` first — where it is edited, and the source
21
+ `loadPermissionSubjects` already trusts for a resident's subtitle — and falls
22
+ back to the copy `person.service` keeps on `users`, for an account whose owner
23
+ has no active person row on the site.
24
+
25
+ An owner with neither does not live here, so `unitLabel` carries their
26
+ membership type instead — "Security Agency" rather than nothing — read from a
27
+ live `members` row on the SAME site. A user can hold several memberships (the
28
+ unique index is `org_1_siteId_1_user_1_type_1`), so a non-organization row is
29
+ preferred: "organization" names the company that employs them, not what they are
30
+ at this door. It is still used when it is the only membership there is. A `type`
31
+ of 24 hex characters is dropped rather than printed — `MMember` accepts an
32
+ organisation id in that field, and stamping one onto the reader's contact list
33
+ would be the same defect as joining the raw block and level ids.
34
+
35
+ `""` only when the site knows neither, which the picker reads as "no suffix" and
36
+ leaves the bare name.
37
+
38
+ Four id-keyed lookups for the whole list, not one per row, and the `members`
39
+ read is skipped entirely when every owner already has an address. The response
40
+ still never contains a SIP password.
package/dist/index.d.ts CHANGED
@@ -16674,6 +16674,7 @@ declare function useHidAmicoRepo(): {
16674
16674
  registration?: string;
16675
16675
  cardNo?: string;
16676
16676
  }) => Promise<mongodb.WithId<bson.Document> | null>;
16677
+ listFacialEnrolledHidUserIds: (readerId: string | ObjectId) => Promise<string[]>;
16677
16678
  findExistingIdentity: (value: {
16678
16679
  reader: string | ObjectId;
16679
16680
  hidUserId?: string | number;
@@ -16765,6 +16766,7 @@ declare function useHidAmicoRepo(): {
16765
16766
  userId: string;
16766
16767
  name: string;
16767
16768
  email: string;
16769
+ unitLabel: string;
16768
16770
  extension: string;
16769
16771
  username: string;
16770
16772
  status: string;
@@ -17494,6 +17496,7 @@ declare function useHidAmicoService(): {
17494
17496
  userId: string;
17495
17497
  name: string;
17496
17498
  email: string;
17499
+ unitLabel: string;
17497
17500
  extension: string;
17498
17501
  username: string;
17499
17502
  status: string;
package/dist/index.js CHANGED
@@ -47747,6 +47747,17 @@ function useHidAmicoRepo() {
47747
47747
  session
47748
47748
  );
47749
47749
  }
47750
+ async function listFacialEnrolledHidUserIds(readerId) {
47751
+ const rows = await identities().find(
47752
+ {
47753
+ reader: toId4(readerId, "reader ID"),
47754
+ status: { $ne: "deleted" },
47755
+ "metadata.facialEnrolled": true
47756
+ },
47757
+ { projection: { hidUserId: 1 } }
47758
+ ).toArray();
47759
+ return rows.map((row) => String(row.hidUserId ?? "").trim()).filter(Boolean);
47760
+ }
47750
47761
  async function findIdentity(value) {
47751
47762
  const or = buildIdentityKeyQuery(value);
47752
47763
  if (!or.length) {
@@ -47891,10 +47902,104 @@ function useHidAmicoRepo() {
47891
47902
  status: { $ne: "disabled" }
47892
47903
  });
47893
47904
  }
47905
+ function memberTypeLabel(value) {
47906
+ const type = String(value ?? "").trim();
47907
+ if (!type || /^[a-fA-F0-9]{24}$/.test(type))
47908
+ return "";
47909
+ return type.split(/[_\s]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
47910
+ }
47911
+ function isOrganizationMemberType(value) {
47912
+ return String(value ?? "").trim().toLowerCase() === "organization";
47913
+ }
47914
+ async function loadUnitLabels(siteId, userIds, userMap) {
47915
+ const labels = /* @__PURE__ */ new Map();
47916
+ if (!userIds.length)
47917
+ return labels;
47918
+ const people = await db2().collection("site.people").find({
47919
+ site: siteId,
47920
+ user: { $in: userIds },
47921
+ status: "active"
47922
+ }, {
47923
+ projection: { user: 1, block: 1, level: 1, unit: 1, unitName: 1 }
47924
+ }).toArray();
47925
+ const peopleMap = new Map(people.map((row) => [String(row.user), row]));
47926
+ const addressOf = (key) => {
47927
+ const person = peopleMap.get(key);
47928
+ if (person) {
47929
+ return {
47930
+ block: optionalObjectId2(person.block),
47931
+ level: optionalObjectId2(person.level),
47932
+ unit: optionalObjectId2(person.unit),
47933
+ unitName: String(person.unitName || "")
47934
+ };
47935
+ }
47936
+ const user = userMap.get(key);
47937
+ return {
47938
+ block: optionalObjectId2(user?.block),
47939
+ level: optionalObjectId2(user?.level),
47940
+ unit: optionalObjectId2(user?.unitId),
47941
+ unitName: String(user?.unitName || "")
47942
+ };
47943
+ };
47944
+ const addresses = new Map(userIds.map((userId) => {
47945
+ const key = String(userId);
47946
+ return [key, addressOf(key)];
47947
+ }));
47948
+ const collect = (pick) => {
47949
+ const seen2 = /* @__PURE__ */ new Map();
47950
+ for (const address of addresses.values()) {
47951
+ const id = pick(address);
47952
+ if (id)
47953
+ seen2.set(String(id), id);
47954
+ }
47955
+ return [...seen2.values()];
47956
+ };
47957
+ const lookup = async (collection, ids2, projection) => {
47958
+ if (!ids2.length)
47959
+ return /* @__PURE__ */ new Map();
47960
+ const rows = await db2().collection(collection).find(
47961
+ { _id: { $in: ids2 } },
47962
+ { projection }
47963
+ ).toArray();
47964
+ return new Map(rows.map((row) => [String(row._id), row]));
47965
+ };
47966
+ const [blocks, levels, units] = await Promise.all([
47967
+ lookup("buildings", collect((address) => address.block), { block: 1, name: 1 }),
47968
+ lookup("building-levels", collect((address) => address.level), { name: 1 }),
47969
+ lookup("building-units", collect((address) => address.unit), { name: 1 })
47970
+ ]);
47971
+ for (const [key, address] of addresses) {
47972
+ const blockRow = address.block ? blocks.get(String(address.block)) : void 0;
47973
+ const blockLabel = blockRow ? blockRow.block ? `Blk ${String(blockRow.block)}` : String(blockRow.name || "") : "";
47974
+ const levelLabel = address.level ? String(levels.get(String(address.level))?.name || "") : "";
47975
+ const unitLabel = (address.unit ? String(units.get(String(address.unit))?.name || "") : "") || address.unitName;
47976
+ labels.set(key, [blockLabel, levelLabel, unitLabel].filter(Boolean).join("/"));
47977
+ }
47978
+ const withoutAddress = userIds.filter((userId) => !labels.get(String(userId)));
47979
+ if (!withoutAddress.length)
47980
+ return labels;
47981
+ const members = await db2().collection("members").find({
47982
+ siteId,
47983
+ user: { $in: withoutAddress },
47984
+ status: "active"
47985
+ }, {
47986
+ projection: { user: 1, type: 1 }
47987
+ }).toArray();
47988
+ const ordered = [...members].sort((left, right) => Number(isOrganizationMemberType(left.type)) - Number(isOrganizationMemberType(right.type)));
47989
+ for (const member of ordered) {
47990
+ const key = String(member.user);
47991
+ const label2 = memberTypeLabel(member.type);
47992
+ if (!label2 || labels.get(key))
47993
+ continue;
47994
+ labels.set(key, label2);
47995
+ }
47996
+ return labels;
47997
+ }
47894
47998
  async function listSipAccounts(orgIdValue, siteValue) {
47999
+ const siteId = toId4(siteValue, "site ID");
47895
48000
  const accounts = await sipAccounts().find({
47896
48001
  orgId: toId4(orgIdValue, "organization ID"),
47897
- site: toId4(siteValue, "site ID"),
48002
+ site: siteId,
47898
48003
  status: { $ne: "disabled" }
47899
48004
  }, {
47900
48005
  projection: { user: 1, extension: 1, username: 1, status: 1, provisionedAt: 1 }
@@ -47902,9 +48007,10 @@ function useHidAmicoRepo() {
47902
48007
  const userIds = accounts.map((account) => optionalObjectId2(account.user)).filter((value) => Boolean(value));
47903
48008
  const users = userIds.length ? await db2().collection("users").find(
47904
48009
  { _id: { $in: userIds } },
47905
- { projection: { name: 1, email: 1 } }
48010
+ { projection: { name: 1, email: 1, block: 1, level: 1, unitId: 1, unitName: 1 } }
47906
48011
  ).toArray() : [];
47907
48012
  const userMap = new Map(users.map((user) => [String(user._id), user]));
48013
+ const unitLabels = await loadUnitLabels(siteId, userIds, userMap);
47908
48014
  return accounts.map((account) => {
47909
48015
  const user = userMap.get(String(account.user));
47910
48016
  return {
@@ -47912,6 +48018,7 @@ function useHidAmicoRepo() {
47912
48018
  userId: String(account.user),
47913
48019
  name: String(user?.name || user?.email || ""),
47914
48020
  email: String(user?.email || ""),
48021
+ unitLabel: unitLabels.get(String(account.user)) || "",
47915
48022
  extension: String(account.extension || ""),
47916
48023
  username: String(account.username || ""),
47917
48024
  status: String(account.status || ""),
@@ -48421,6 +48528,7 @@ function useHidAmicoRepo() {
48421
48528
  updateIdentity,
48422
48529
  deleteIdentity,
48423
48530
  findIdentity,
48531
+ listFacialEnrolledHidUserIds,
48424
48532
  findExistingIdentity,
48425
48533
  findIdentityBySubject,
48426
48534
  findProfileIdentity,
@@ -48764,6 +48872,7 @@ function deriveKey(secret) {
48764
48872
  // src/services/hid-amico.service.ts
48765
48873
  var PASSWORD_PREFIX = "v1";
48766
48874
  var HID_READER_NOT_FOUND = "HID Amico reader not found.";
48875
+ var HID_KEEP_USER_IMAGE = "0";
48767
48876
  var PJSIP_CONFIGURATION_KEYS = [
48768
48877
  "enabled",
48769
48878
  "server_ip",
@@ -49876,9 +49985,7 @@ var HidAmicoClient = class {
49876
49985
  }
49877
49986
  await this.setConfiguration({
49878
49987
  identifier: { face_identification_enabled: "1" },
49879
- // iService365 reads the image back for enrollment verification and user
49880
- // avatars. HID defaults to keeping it, but make that dependency explicit.
49881
- general: { keep_user_image: "1" }
49988
+ general: { keep_user_image: HID_KEEP_USER_IMAGE }
49882
49989
  });
49883
49990
  const facialConfiguration = await this.getConfiguration({
49884
49991
  identifier: ["face_identification_enabled"],
@@ -49887,7 +49994,7 @@ var HidAmicoClient = class {
49887
49994
  const configuration = isUnknownRecord2(facialConfiguration) ? facialConfiguration : {};
49888
49995
  const identifier = isUnknownRecord2(configuration.identifier) ? configuration.identifier : {};
49889
49996
  const general = isUnknownRecord2(configuration.general) ? configuration.general : {};
49890
- if (String(identifier.face_identification_enabled ?? "") !== "1" || String(general.keep_user_image ?? "") !== "1") {
49997
+ if (String(identifier.face_identification_enabled ?? "") !== "1" || String(general.keep_user_image ?? "") !== HID_KEEP_USER_IMAGE) {
49891
49998
  throw new import_node_server_utils143.BadRequestError(
49892
49999
  "The HID reader did not retain facial identification configuration."
49893
50000
  );
@@ -49904,24 +50011,6 @@ var HidAmicoClient = class {
49904
50011
  const res = await this.postBinary(path5, image, "application/octet-stream");
49905
50012
  const result = res.data;
49906
50013
  assertSuccessfulFacialResult(result, "enrollment");
49907
- const verificationPath = this.url(
49908
- `/user_get_image.fcgi?user_id=${numericUserId}&get_timestamp=1`
49909
- );
49910
- const verificationResponse = await this.get(verificationPath, "arraybuffer");
49911
- const verificationBuffer = Buffer.from(verificationResponse.data);
49912
- let verification;
49913
- try {
49914
- verification = JSON.parse(verificationBuffer.toString("utf8"));
49915
- } catch {
49916
- throw new import_node_server_utils143.BadRequestError(
49917
- "The HID reader did not return facial enrollment verification data."
49918
- );
49919
- }
49920
- if (!isUnknownRecord2(verification) || Number(verification.timestamp) !== timestamp || typeof verification.image !== "string" || !verification.image.length) {
49921
- throw new import_node_server_utils143.BadRequestError(
49922
- "The HID reader did not retain the facial image or enrollment timestamp."
49923
- );
49924
- }
49925
50014
  return {
49926
50015
  ...isUnknownRecord2(result) ? result : {},
49927
50016
  success: true,
@@ -51497,7 +51586,15 @@ function useHidAmicoService() {
51497
51586
  });
51498
51587
  return getHidObjectRows(roleResponse, "user_roles").length > 0;
51499
51588
  })),
51500
- readerSupportsFacial(reader) ? client.listUserImageIds().catch(() => []) : Promise.resolve([])
51589
+ /*
51590
+ * Who is facially enrolled comes from OUR records now, not from the
51591
+ * reader's photo list.
51592
+ *
51593
+ * The reader no longer keeps photographs — only the facial template,
51594
+ * which cannot be listed — so asking the device would report nobody as
51595
+ * enrolled and every resident would look un-enrolled on screen.
51596
+ */
51597
+ readerSupportsFacial(reader) ? repo.listFacialEnrolledHidUserIds(readerId).catch(() => []) : Promise.resolve([])
51501
51598
  ]);
51502
51599
  const facialUserIdSet = new Set(facialUserIds.map(String));
51503
51600
  const items = rows.map((row, index) => {
@@ -52567,43 +52664,14 @@ function useHidAmicoService() {
52567
52664
  await client.logout();
52568
52665
  }
52569
52666
  }
52570
- async function getReaderFacialUserIds(client) {
52571
- try {
52572
- return await client.listUserImageIds();
52573
- } catch {
52574
- const usersResponse = await client.loadObjects({
52575
- object: "users",
52576
- where: { users: {} },
52577
- limit: 500,
52578
- offset: 0,
52579
- order: ["id", "ascending"]
52580
- });
52581
- const userIds = getHidObjectRows(usersResponse, "users").map((user) => Number(user.id)).filter((userId) => Number.isSafeInteger(userId) && userId > 0);
52582
- const facialUserIds = [];
52583
- const batchSize = 4;
52584
- for (let offset = 0; offset < userIds.length; offset += batchSize) {
52585
- const batch = userIds.slice(offset, offset + batchSize);
52586
- const results = await Promise.all(batch.map(async (userId) => {
52587
- try {
52588
- const image = await client.getUserImage(userId);
52589
- return image.base64 ? userId : null;
52590
- } catch {
52591
- return null;
52592
- }
52593
- }));
52594
- facialUserIds.push(...results.filter((userId) => userId !== null));
52595
- }
52596
- return facialUserIds;
52597
- }
52598
- }
52599
52667
  async function syncReaderFacialData(readerId) {
52600
52668
  const reader = await getActiveReader(readerId);
52601
52669
  assertReaderCapability(reader, "facial");
52602
52670
  const client = new HidAmicoClient(reader);
52603
52671
  try {
52604
52672
  await client.login();
52605
- const facialUserIds = await getReaderFacialUserIds(client);
52606
- const message = facialUserIds.length ? `Found ${facialUserIds.length} Amico user(s) with facial data. Facial status and images are read directly from the reader.` : "No facial enrollments found on the HID reader.";
52673
+ const facialUserIds = await repo.listFacialEnrolledHidUserIds(readerId);
52674
+ const message = facialUserIds.length ? `${facialUserIds.length} user(s) are facially enrolled on this reader, as recorded by iService365.` : "No facial enrollments recorded for this HID reader.";
52607
52675
  await repo.updateById(readerId, { status: "active", lastSeenAt: /* @__PURE__ */ new Date() });
52608
52676
  await repo.addEvent({
52609
52677
  reader: readerId,
@@ -52611,7 +52679,7 @@ function useHidAmicoService() {
52611
52679
  type: "facial_sync",
52612
52680
  payload: {
52613
52681
  facialDetected: facialUserIds.length,
52614
- source: "amico",
52682
+ source: "iservice365",
52615
52683
  hidUserIds: facialUserIds
52616
52684
  }
52617
52685
  });