@7365admin1/core 3.129.0 → 3.129.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @iservice365/core
2
2
 
3
+ ## 3.129.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 5453144: Roles: an owner grant chosen before the inventory permission split still covers the keys it granted (full inventory access covers every inventory key, request-stock covers record-usage, view/approve cover view-reports), so the inventory presets can be saved. Role-save rule refusals (module not given, owner grant, console permission, shared template) now answer 403 with their message instead of 401.
8
+
9
+ ## 3.129.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 6323620: Visitor list search is fast on large sites: block/level/unit and pass/key names are resolved to ids first instead of joining five collections onto every visitor row (staging 120k-row site: 20 s -> 0.2 s with the default one-month range, 84 s -> 0.7 s all-time). Same matches as before.
14
+
3
15
  ## 3.129.0
4
16
 
5
17
  ### Minor Changes
package/dist/index.js CHANGED
@@ -6549,10 +6549,25 @@ function boundToOwnerGrant(ceiling, next, previous) {
6549
6549
  return { permissions: [...ceiling], refused: [] };
6550
6550
  const held = new Set(previous ?? []);
6551
6551
  const refused = list.filter(
6552
- (p) => !held.has(p) && !ceiling.includes(p) && !ALWAYS_ALLOWED.includes(p.split(":")[0])
6552
+ (p) => !held.has(p) && !ceilingCovers(ceiling, p) && !ALWAYS_ALLOWED.includes(p.split(":")[0])
6553
6553
  );
6554
6554
  return { permissions: list, refused };
6555
6555
  }
6556
+ var PERMISSION_COVERS = Object.freeze({
6557
+ "inventory:manage-inventory": ["inventory:*"],
6558
+ "inventory:request-stock": ["inventory:record-usage"],
6559
+ "inventory:view-inventory": ["inventory:view-reports"],
6560
+ "inventory:approve-requests": ["inventory:view-reports"]
6561
+ });
6562
+ function ceilingCovers(ceiling, permission) {
6563
+ if (ceiling.includes(permission))
6564
+ return true;
6565
+ const moduleWide = `${permission.split(":")[0]}:*`;
6566
+ return ceiling.some((granted) => {
6567
+ const covers = PERMISSION_COVERS[granted];
6568
+ return !!covers && (covers.includes(permission) || covers.includes(moduleWide));
6569
+ });
6570
+ }
6556
6571
 
6557
6572
  // src/models/site.model.ts
6558
6573
  var import_node_server_utils22 = require("@7365admin1/node-server-utils");
@@ -6604,6 +6619,9 @@ function permissionsOutsideModules2(effective, next, previous) {
6604
6619
  if (!Array.isArray(next) || !next.length || next.includes("*"))
6605
6620
  return [];
6606
6621
  const held = new Set(Array.isArray(previous) ? previous : []);
6622
+ const heldModules = new Set(
6623
+ [...held].map((p) => typeof p === "string" ? p.split(":")[0]?.trim() : "").filter(Boolean)
6624
+ );
6607
6625
  const allowed = normaliseModules(effective);
6608
6626
  const refused = [];
6609
6627
  for (const permission of next) {
@@ -6612,6 +6630,8 @@ function permissionsOutsideModules2(effective, next, previous) {
6612
6630
  if (held.has(permission))
6613
6631
  continue;
6614
6632
  const resource = permission.split(":")[0]?.trim();
6633
+ if (resource && heldModules.has(resource))
6634
+ continue;
6615
6635
  if (!resource)
6616
6636
  continue;
6617
6637
  if (!orgAllowsModule(allowed, resource))
@@ -6623,8 +6643,9 @@ function requireWithinModules(effective, next, previous) {
6623
6643
  const refused = permissionsOutsideModules2(effective, next, previous);
6624
6644
  if (!refused.length)
6625
6645
  return;
6626
- throw new import_node_server_utils21.UnauthorizedError(
6627
- "This site has not been given " + refused.join(", ") + ". Ask Seven365 to add the module to the organisation first."
6646
+ throw new import_node_server_utils21.AppError(
6647
+ "This site has not been given " + refused.join(", ") + ". Ask Seven365 to add the module to the organisation first.",
6648
+ 403
6628
6649
  );
6629
6650
  }
6630
6651
 
@@ -16065,7 +16086,8 @@ function useVisitorTransactionRepo() {
16065
16086
  throw new import_node_server_utils48.InternalServerError("Unable to connect to server.");
16066
16087
  }
16067
16088
  const collection = db2.collection(visitors_namespace_collection);
16068
- function buildSearchStages(search) {
16089
+ const searchDb = db2;
16090
+ async function buildSearchStages(search, siteIds) {
16069
16091
  const text2 = normaliseVisitorSearch(search);
16070
16092
  if (!text2)
16071
16093
  return [];
@@ -16079,98 +16101,78 @@ function useVisitorTransactionRepo() {
16079
16101
  $regex: `(^|\\s)${escape(value)}$`,
16080
16102
  $options: "i"
16081
16103
  });
16082
- const nameLookup = (from, localField, as) => ({
16083
- $lookup: {
16084
- from,
16085
- localField,
16086
- foreignField: "_id",
16087
- pipeline: [{ $project: { _id: 0, name: 1 } }],
16088
- as
16089
- }
16090
- });
16091
- const keyNameLookup = (localField, as) => ({
16092
- $lookup: {
16093
- from: "keys",
16094
- localField,
16095
- foreignField: "_id",
16096
- pipeline: [
16097
- {
16098
- $lookup: {
16099
- from: "qr-code-templates",
16100
- localField: "template",
16101
- foreignField: "_id",
16102
- pipeline: [{ $project: { prefixPass: 1 } }],
16103
- as: "template"
16104
- }
16105
- },
16106
- {
16107
- $project: {
16108
- _id: 0,
16109
- prefixAndName: {
16110
- $concat: [
16111
- { $ifNull: [{ $arrayElemAt: ["$template.prefixPass", 0] }, ""] },
16112
- { $ifNull: ["$name", ""] }
16113
- ]
16114
- }
16115
- }
16116
- }
16117
- ],
16118
- as
16119
- }
16120
- });
16121
- const locationLookups = [
16122
- nameLookup("buildings", "block", "_searchBlock"),
16123
- nameLookup("building-levels", "level", "_searchLevel"),
16124
- nameLookup("building-units", "unit", "_searchUnit")
16125
- ];
16126
- const cleanup = {
16127
- $project: {
16128
- _searchBlock: 0,
16129
- _searchLevel: 0,
16130
- _searchUnit: 0,
16131
- _searchPass: 0,
16132
- _searchKeys: 0
16133
- }
16134
- };
16135
- const unitMatch = (value, match = like) => ({
16136
- $or: [{ "_searchUnit.name": match(value) }, { unitName: match(value) }]
16137
- });
16104
+ const onSites = siteIds ? { site: { $in: siteIds } } : {};
16105
+ const levelOnSites = siteIds ? { $or: [{ site: { $in: siteIds } }, { site: null }, { site: "" }] } : {};
16106
+ const idsOf = (from, filter) => searchDb.collection(from).distinct("_id", filter);
16107
+ const inIds = (field, ids2) => ids2.length ? [{ [field]: { $in: ids2 } }] : [];
16138
16108
  const parts = text2.split("/").map((part) => part.trim());
16139
16109
  if (parts.length >= 2 && parts.length <= 3 && parts.every(Boolean)) {
16140
16110
  const [block, level2, unit] = parts;
16111
+ const [blockIds2, levelIds2, unitIds2] = await Promise.all([
16112
+ idsOf("buildings", { ...onSites, name: blockName(block) }),
16113
+ idsOf("building-levels", { ...levelOnSites, name: exact(level2) }),
16114
+ unit ? idsOf("building-units", { ...onSites, name: exact(unit) }) : []
16115
+ ]);
16141
16116
  return [
16142
- ...locationLookups,
16143
16117
  {
16144
16118
  $match: {
16145
- "_searchBlock.name": blockName(block),
16146
- "_searchLevel.name": exact(level2),
16147
- ...unit && unitMatch(unit, exact)
16119
+ block: { $in: blockIds2 },
16120
+ level: { $in: levelIds2 },
16121
+ ...unit && {
16122
+ $or: [...inIds("unit", unitIds2), { unitName: exact(unit) }]
16123
+ }
16148
16124
  }
16149
- },
16150
- cleanup
16125
+ }
16151
16126
  ];
16152
16127
  }
16153
16128
  const compact = text2.replace(/\s+/g, "");
16129
+ const [blockIds, levelIds, unitIds, keyIds] = await Promise.all([
16130
+ idsOf("buildings", { ...onSites, name: like(text2) }),
16131
+ idsOf("building-levels", { ...levelOnSites, name: like(text2) }),
16132
+ idsOf("building-units", { ...onSites, name: like(text2) }),
16133
+ compact ? matchingKeyIds(compact) : []
16134
+ ]);
16154
16135
  return [
16155
- ...locationLookups,
16156
- keyNameLookup("visitorPass.keyId", "_searchPass"),
16157
- keyNameLookup("passKeys.keyId", "_searchKeys"),
16158
16136
  {
16159
16137
  $match: {
16160
16138
  $or: [
16161
16139
  // name, company, purpose, NRIC, types, members; plates ignoring
16162
16140
  // spaces/hyphens/case; phones by digits - visitor-search.util.
16163
16141
  ...visitorRowSearchOr(text2),
16164
- { "_searchBlock.name": like(text2) },
16165
- { "_searchLevel.name": like(text2) },
16166
- unitMatch(text2),
16167
- { "_searchPass.prefixAndName": like(compact) },
16168
- { "_searchKeys.prefixAndName": like(compact) }
16142
+ ...inIds("block", blockIds),
16143
+ ...inIds("level", levelIds),
16144
+ ...inIds("unit", unitIds),
16145
+ { unitName: like(text2) },
16146
+ ...inIds("visitorPass.keyId", keyIds),
16147
+ ...inIds("passKeys.keyId", keyIds)
16169
16148
  ]
16170
16149
  }
16171
- },
16172
- cleanup
16150
+ }
16151
+ ];
16152
+ }
16153
+ async function matchingKeyIds(compact) {
16154
+ const t = compact.toLowerCase();
16155
+ const templates = await searchDb.collection("qr-code-templates").find({ prefixPass: { $nin: [null, ""] } }, { projection: { prefixPass: 1 } }).toArray();
16156
+ const or = [
16157
+ { name: { $regex: escapeRegex2(compact), $options: "i" } }
16173
16158
  ];
16159
+ for (const tpl of templates) {
16160
+ const prefix = String(tpl.prefixPass).toLowerCase();
16161
+ const template = { $in: [tpl._id, String(tpl._id)] };
16162
+ if (prefix.includes(t)) {
16163
+ or.push({ template });
16164
+ continue;
16165
+ }
16166
+ for (let i = 1; i < t.length; i++) {
16167
+ if (prefix.endsWith(t.slice(0, i))) {
16168
+ or.push({
16169
+ template,
16170
+ name: { $regex: `^${escapeRegex2(compact.slice(i))}`, $options: "i" }
16171
+ });
16172
+ }
16173
+ }
16174
+ }
16175
+ return await searchDb.collection("keys").distinct("_id", { $or: or });
16174
16176
  }
16175
16177
  async function createTextIndex() {
16176
16178
  try {
@@ -16274,10 +16276,11 @@ function useVisitorTransactionRepo() {
16274
16276
  ...passOrKey?.type == "key" && { passKeys: { $elemMatch: { keyId: new import_mongodb46.ObjectId(passOrKey.keyId) } } }
16275
16277
  };
16276
16278
  const finalSort = Object.keys(sort).length > 0 ? sort : { latestDate: -1 };
16279
+ const searchSiteIds = query2.site instanceof import_mongodb46.ObjectId ? [query2.site] : query2.site?.$in ?? null;
16277
16280
  try {
16278
16281
  const basePipeline = [
16279
16282
  { $match: query2 },
16280
- ...buildSearchStages(search),
16283
+ ...await buildSearchStages(search, searchSiteIds),
16281
16284
  {
16282
16285
  $addFields: {
16283
16286
  latestDate: { $max: ["$createdAt", "$updatedAt"] }
@@ -27766,8 +27769,9 @@ function requireNoPlatformGrant(role, next) {
27766
27769
  const added = platformPermissionsAdded(next, role?.permissions);
27767
27770
  if (added.length === 0)
27768
27771
  return;
27769
- throw new import_node_server_utils68.UnauthorizedError(
27770
- "These are Seven365 console permissions and cannot be granted on a client role: " + added.join(", ")
27772
+ throw new import_node_server_utils68.AppError(
27773
+ "These are Seven365 console permissions and cannot be granted on a client role: " + added.join(", "),
27774
+ 403
27771
27775
  );
27772
27776
  }
27773
27777
  function permissionsMeanEverything(permissions) {
@@ -27780,15 +27784,17 @@ function refuseSharedClientTemplate(role, next) {
27780
27784
  return true;
27781
27785
  if (Array.isArray(next) && restorableFromHistory(role, next))
27782
27786
  return true;
27783
- throw new import_node_server_utils68.UnauthorizedError(
27784
- "This role is shared by every client that was invited with it and cannot be changed here."
27787
+ throw new import_node_server_utils68.AppError(
27788
+ "This role is shared by every client that was invited with it and cannot be changed here.",
27789
+ 403
27785
27790
  );
27786
27791
  }
27787
27792
  function refuseNewSharedClientTemplate(role) {
27788
27793
  if (roleScope(role) !== "client-template")
27789
27794
  return;
27790
- throw new import_node_server_utils68.UnauthorizedError(
27791
- "A role with no organisation would be shared by every client and cannot be created. Choose the organisation this role belongs to."
27795
+ throw new import_node_server_utils68.AppError(
27796
+ "A role with no organisation would be shared by every client and cannot be created. Choose the organisation this role belongs to.",
27797
+ 403
27792
27798
  );
27793
27799
  }
27794
27800
  function samePermissionSet(a, b) {
@@ -27983,8 +27989,9 @@ async function boundRoleToOwnerGrant(req, role, next, previous) {
27983
27989
  return list;
27984
27990
  const { permissions, refused } = boundToOwnerGrant(ceiling, list, previous);
27985
27991
  if (refused.length) {
27986
- throw new import_node_server_utils70.UnauthorizedError(
27987
- "Seven365 has not given this organisation " + refused.join(", ") + "."
27992
+ throw new import_node_server_utils70.AppError(
27993
+ "Seven365 has not given this organisation " + refused.join(", ") + ".",
27994
+ 403
27988
27995
  );
27989
27996
  }
27990
27997
  return permissions;