@7365admin1/core 3.125.0 → 3.126.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.mjs CHANGED
@@ -8407,7 +8407,9 @@ function decideServiceProviderInvite(facts) {
8407
8407
  reason: "An invitation to this site is already waiting for this email address. Cancel the pending invitation first if you want to send a new one."
8408
8408
  };
8409
8409
  }
8410
- const requiresApproval = Boolean(facts.inviterIsPropertyManagement);
8410
+ const requiresApproval = Boolean(
8411
+ facts.inviterIsPropertyManagement || facts.inviterIsServiceProvider
8412
+ );
8411
8413
  if (facts.hasProviderOrg) {
8412
8414
  return {
8413
8415
  ok: true,
@@ -8431,6 +8433,31 @@ function decideServiceProviderInvite(facts) {
8431
8433
  requiresApproval
8432
8434
  };
8433
8435
  }
8436
+ var SUBCONTRACT_SITE_REFUSAL = "You can only invite service providers for sites your company works on.";
8437
+ var SUBCONTRACT_ADMIN_REFUSAL = "Only your company's owner or an administrator can invite other service providers.";
8438
+ function serviceProviderInviteScope(facts) {
8439
+ if (facts.isStaff)
8440
+ return { ok: true, sender: "staff" };
8441
+ if (!facts.callerInInviterOrg) {
8442
+ return {
8443
+ ok: false,
8444
+ reason: "You can only invite service providers to your own organisation's sites."
8445
+ };
8446
+ }
8447
+ if (facts.siteOwnerOrg && facts.siteOwnerOrg === facts.inviterOrg) {
8448
+ return { ok: true, sender: "client" };
8449
+ }
8450
+ if (!facts.inviterEngagedOnSite) {
8451
+ return { ok: false, reason: SUBCONTRACT_SITE_REFUSAL };
8452
+ }
8453
+ if (!facts.callerRunsInviterOrg) {
8454
+ return { ok: false, reason: SUBCONTRACT_ADMIN_REFUSAL };
8455
+ }
8456
+ return { ok: true, sender: "subcontract" };
8457
+ }
8458
+ function serviceProviderInviterKind(inviterOrg, siteOwnerOrg) {
8459
+ return inviterOrg && siteOwnerOrg && inviterOrg !== siteOwnerOrg ? "service-provider" : "property-management";
8460
+ }
8434
8461
  var SERVICE_PROVIDER_INVITE_TRANSITIONS = {
8435
8462
  approve: { from: ["awaiting-approval"], to: "pending" },
8436
8463
  reject: { from: ["awaiting-approval"], to: "rejected" },
@@ -8510,6 +8537,27 @@ var RECEIVED_INVITE_LABELS = {
8510
8537
  expired: "Expired",
8511
8538
  cancelled: "Withdrawn by the client"
8512
8539
  };
8540
+ var SERVICE_TYPE_LABELS = {
8541
+ security_agency: "Security",
8542
+ cleaning_services: "Cleaning",
8543
+ mechanical_electrical_services: "Mechanical & Electrical",
8544
+ landscaping_services: "Landscaping",
8545
+ pest_control_services: "Pest Control",
8546
+ pool_maintenance_services: "Pool Maintenance",
8547
+ property_management_agency: "Property Management"
8548
+ };
8549
+ function serviceTypeLabel(code) {
8550
+ const key = String(code ?? "").trim();
8551
+ if (!key)
8552
+ return "Other";
8553
+ return SERVICE_TYPE_LABELS[key] ?? key.replace(/_/g, " ");
8554
+ }
8555
+ function filterSiteProviderMembers(items, { type = "", company = "", search = "" }) {
8556
+ const needle = search.trim().toLowerCase();
8557
+ return items.filter(
8558
+ (m) => (!type || m.type === type) && (!company || m.companyId === company) && (!needle || [m.name, m.email, m.company, m.role, m.invitedVia].map((v) => String(v ?? "").toLowerCase()).some((v) => v.includes(needle)))
8559
+ );
8560
+ }
8513
8561
 
8514
8562
  // src/utils/invite-actor.util.ts
8515
8563
  import { useAtlas as useAtlas17 } from "@7365admin1/node-server-utils";
@@ -11473,6 +11521,30 @@ var NotificationService = class {
11473
11521
  "platform"
11474
11522
  );
11475
11523
  }
11524
+ /**
11525
+ * A service-provider invitation is waiting in SP Approvals. Seven365 staff
11526
+ * only - the provider is still told nothing. Names who sent it (a property
11527
+ * manager, or a provider bringing in a subcontractor) and for which site.
11528
+ */
11529
+ static async serviceProviderInviteAwaitingApproval(payload) {
11530
+ const staff = await staffRecipients();
11531
+ if (!staff.length)
11532
+ return;
11533
+ await send(
11534
+ staff,
11535
+ "Service provider invitation to approve",
11536
+ payload.subcontract ? `${payload.inviterOrgName} (a service provider) wants to bring in another service provider at ${payload.siteName}.` : `${payload.inviterOrgName} invited a service provider to ${payload.siteName}.`,
11537
+ {
11538
+ module: "platform",
11539
+ kind: "spApproval",
11540
+ screen: "",
11541
+ params: { id: payload.invitationId.toString() }
11542
+ },
11543
+ false,
11544
+ void 0,
11545
+ "platform"
11546
+ );
11547
+ }
11476
11548
  static async clientInvitationAccepted(payload) {
11477
11549
  const staff = await staffRecipients();
11478
11550
  if (!staff.length)
@@ -12859,6 +12931,13 @@ function useCustomerSiteService() {
12859
12931
  getServiceProviderInviteById: _getInviteFresh,
12860
12932
  transitionServiceProviderInvite: _transitionInvite
12861
12933
  } = useVerificationRepoV2();
12934
+ async function siteOwnerOf(site, senderOrg, senderName) {
12935
+ const owner = String(site?.orgId ?? site?.org ?? "") || senderOrg;
12936
+ if (owner === senderOrg)
12937
+ return { siteOrg: senderOrg, siteOrgName: senderName };
12938
+ const ownerOrg = await _getByOrgId(owner).catch(() => null);
12939
+ return { siteOrg: owner, siteOrgName: ownerOrg?.name ?? "" };
12940
+ }
12862
12941
  async function addViaInvite(invite, actor, forOrgId) {
12863
12942
  const session = useAtlas26.getClient()?.startSession();
12864
12943
  session?.startTransaction();
@@ -12867,6 +12946,9 @@ function useCustomerSiteService() {
12867
12946
  if (!verification) {
12868
12947
  throw new NotFoundError11("Invite not found.");
12869
12948
  }
12949
+ if (!(verification.history?.length > 0)) {
12950
+ throw new NotFoundError11("Invite not found.");
12951
+ }
12870
12952
  const siteId = verification.metadata?.siteId?.toString() ?? "";
12871
12953
  if (!siteId) {
12872
12954
  throw new BadRequestError32("Invalid invite, missing site ID.");
@@ -12930,6 +13012,12 @@ function useCustomerSiteService() {
12930
13012
  verification.status === "complete" ? "This invitation has already been used." : "This invitation is no longer valid. Ask for a new one."
12931
13013
  );
12932
13014
  }
13015
+ const owner = String(site?.orgId ?? site?.org ?? "");
13016
+ if (owner && owner !== orgId && await _countActiveByOrgAndSite(orgId, siteId) < 1) {
13017
+ throw new BadRequestError32(
13018
+ "This invitation is no longer valid. Ask for a new one."
13019
+ );
13020
+ }
12933
13021
  if (!serviceProvider.defaultSite) {
12934
13022
  const updateOrgField = await _updateFieldById(
12935
13023
  {
@@ -12965,8 +13053,10 @@ function useCustomerSiteService() {
12965
13053
  {
12966
13054
  name: site.name,
12967
13055
  site: siteId,
12968
- siteOrg: orgId,
12969
- siteOrgName: org.name,
13056
+ // The site's OWNER, not the sender: a provider that brought in a
13057
+ // subcontractor sent this invitation, but the site is still its
13058
+ // client's, and every reader of `siteOrg` means the owner.
13059
+ ...await siteOwnerOf(site, orgId, org.name),
12970
13060
  org: providerOrgId
12971
13061
  },
12972
13062
  session
@@ -13063,8 +13153,7 @@ function useCustomerSiteService() {
13063
13153
  {
13064
13154
  name: site.name,
13065
13155
  site: siteId,
13066
- siteOrg: orgId,
13067
- siteOrgName: org.name,
13156
+ ...await siteOwnerOf(site, orgId, org.name),
13068
13157
  org: forOrgId
13069
13158
  },
13070
13159
  session
@@ -14252,6 +14341,50 @@ function isPreCheckInStatusOnly(status) {
14252
14341
  return requested.length > 0 && requested.every((s) => PRE_CHECK_IN_STATUSES.includes(s));
14253
14342
  }
14254
14343
 
14344
+ // src/utils/visitor-search.util.ts
14345
+ var VISITOR_SEARCH_MAX_LENGTH = 100;
14346
+ var MIN_PHONE_DIGITS = 3;
14347
+ var MIN_PLATE_CHARS = 2;
14348
+ function escapeRegex2(value) {
14349
+ return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14350
+ }
14351
+ function normaliseVisitorSearch(raw) {
14352
+ if (typeof raw !== "string")
14353
+ return "";
14354
+ return raw.replace(/\s+/g, " ").trim().slice(0, VISITOR_SEARCH_MAX_LENGTH);
14355
+ }
14356
+ function looseSequence(chars, gap) {
14357
+ return chars.map(escapeRegex2).join(gap);
14358
+ }
14359
+ function visitorRowSearchOr(raw) {
14360
+ const q = normaliseVisitorSearch(raw);
14361
+ if (!q)
14362
+ return [];
14363
+ const contains = { $regex: escapeRegex2(q), $options: "i" };
14364
+ const or = [
14365
+ { name: contains },
14366
+ { company: contains },
14367
+ { purpose: contains },
14368
+ { nric: contains },
14369
+ { contractorType: contains },
14370
+ { deliveryType: contains },
14371
+ { unitName: contains },
14372
+ { "members.name": contains },
14373
+ { "members.nric": contains }
14374
+ ];
14375
+ const plateChars = q.replace(/[^A-Za-z0-9]/g, "").split("");
14376
+ if (plateChars.length >= MIN_PLATE_CHARS) {
14377
+ const plate = { $regex: looseSequence(plateChars, "[\\s-]*"), $options: "i" };
14378
+ or.push({ plateNumber: plate }, { "members.plateNumber": plate });
14379
+ }
14380
+ const digits = q.replace(/\D/g, "").split("");
14381
+ if (/^[+\d\s()-]+$/.test(q) && digits.length >= MIN_PHONE_DIGITS) {
14382
+ const phone = { $regex: looseSequence(digits, "\\D*") };
14383
+ or.push({ contact: phone }, { "members.contact": phone });
14384
+ }
14385
+ return or;
14386
+ }
14387
+
14255
14388
  // src/repositories/visitor-transaction.repo.ts
14256
14389
  var visitors_namespace_collection = "visitor.transactions";
14257
14390
  function useVisitorTransactionRepo() {
@@ -14260,6 +14393,113 @@ function useVisitorTransactionRepo() {
14260
14393
  throw new InternalServerError17("Unable to connect to server.");
14261
14394
  }
14262
14395
  const collection = db2.collection(visitors_namespace_collection);
14396
+ function buildSearchStages(search) {
14397
+ const text2 = normaliseVisitorSearch(search);
14398
+ if (!text2)
14399
+ return [];
14400
+ const escape = escapeRegex2;
14401
+ const like = (value) => ({ $regex: escape(value), $options: "i" });
14402
+ const exact = (value) => ({
14403
+ $regex: `^${escape(value)}$`,
14404
+ $options: "i"
14405
+ });
14406
+ const blockName = (value) => ({
14407
+ $regex: `(^|\\s)${escape(value)}$`,
14408
+ $options: "i"
14409
+ });
14410
+ const nameLookup = (from, localField, as) => ({
14411
+ $lookup: {
14412
+ from,
14413
+ localField,
14414
+ foreignField: "_id",
14415
+ pipeline: [{ $project: { _id: 0, name: 1 } }],
14416
+ as
14417
+ }
14418
+ });
14419
+ const keyNameLookup = (localField, as) => ({
14420
+ $lookup: {
14421
+ from: "keys",
14422
+ localField,
14423
+ foreignField: "_id",
14424
+ pipeline: [
14425
+ {
14426
+ $lookup: {
14427
+ from: "qr-code-templates",
14428
+ localField: "template",
14429
+ foreignField: "_id",
14430
+ pipeline: [{ $project: { prefixPass: 1 } }],
14431
+ as: "template"
14432
+ }
14433
+ },
14434
+ {
14435
+ $project: {
14436
+ _id: 0,
14437
+ prefixAndName: {
14438
+ $concat: [
14439
+ { $ifNull: [{ $arrayElemAt: ["$template.prefixPass", 0] }, ""] },
14440
+ { $ifNull: ["$name", ""] }
14441
+ ]
14442
+ }
14443
+ }
14444
+ }
14445
+ ],
14446
+ as
14447
+ }
14448
+ });
14449
+ const locationLookups = [
14450
+ nameLookup("buildings", "block", "_searchBlock"),
14451
+ nameLookup("building-levels", "level", "_searchLevel"),
14452
+ nameLookup("building-units", "unit", "_searchUnit")
14453
+ ];
14454
+ const cleanup = {
14455
+ $project: {
14456
+ _searchBlock: 0,
14457
+ _searchLevel: 0,
14458
+ _searchUnit: 0,
14459
+ _searchPass: 0,
14460
+ _searchKeys: 0
14461
+ }
14462
+ };
14463
+ const unitMatch = (value, match = like) => ({
14464
+ $or: [{ "_searchUnit.name": match(value) }, { unitName: match(value) }]
14465
+ });
14466
+ const parts = text2.split("/").map((part) => part.trim());
14467
+ if (parts.length >= 2 && parts.length <= 3 && parts.every(Boolean)) {
14468
+ const [block, level2, unit] = parts;
14469
+ return [
14470
+ ...locationLookups,
14471
+ {
14472
+ $match: {
14473
+ "_searchBlock.name": blockName(block),
14474
+ "_searchLevel.name": exact(level2),
14475
+ ...unit && unitMatch(unit, exact)
14476
+ }
14477
+ },
14478
+ cleanup
14479
+ ];
14480
+ }
14481
+ const compact = text2.replace(/\s+/g, "");
14482
+ return [
14483
+ ...locationLookups,
14484
+ keyNameLookup("visitorPass.keyId", "_searchPass"),
14485
+ keyNameLookup("passKeys.keyId", "_searchKeys"),
14486
+ {
14487
+ $match: {
14488
+ $or: [
14489
+ // name, company, purpose, NRIC, types, members; plates ignoring
14490
+ // spaces/hyphens/case; phones by digits - visitor-search.util.
14491
+ ...visitorRowSearchOr(text2),
14492
+ { "_searchBlock.name": like(text2) },
14493
+ { "_searchLevel.name": like(text2) },
14494
+ unitMatch(text2),
14495
+ { "_searchPass.prefixAndName": like(compact) },
14496
+ { "_searchKeys.prefixAndName": like(compact) }
14497
+ ]
14498
+ }
14499
+ },
14500
+ cleanup
14501
+ ];
14502
+ }
14263
14503
  async function createTextIndex() {
14264
14504
  try {
14265
14505
  await collection.createIndex({
@@ -14355,9 +14595,6 @@ function useVisitorTransactionRepo() {
14355
14595
  },
14356
14596
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
14357
14597
  ...checkedOut == false && { checkOut: { $eq: null } },
14358
- ...search && {
14359
- $or: [{ name: { $regex: search, $options: "i" } }]
14360
- },
14361
14598
  ...plateNumber && { plateNumber },
14362
14599
  ...Array.isArray(status) ? { status: { $in: status } } : status ? { status } : {},
14363
14600
  ...tab == "Overnight Parking" && { isOvernightParking: true },
@@ -14368,6 +14605,7 @@ function useVisitorTransactionRepo() {
14368
14605
  try {
14369
14606
  const basePipeline = [
14370
14607
  { $match: query2 },
14608
+ ...buildSearchStages(search),
14371
14609
  {
14372
14610
  $addFields: {
14373
14611
  latestDate: { $max: ["$createdAt", "$updatedAt"] }
@@ -15717,7 +15955,7 @@ function useVehicleRepo() {
15717
15955
  let query2 = { ...baseQuery };
15718
15956
  if (search)
15719
15957
  query2.$text = { $search: search };
15720
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15958
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15721
15959
  const buildGroupedPipeline = (matchQuery) => [
15722
15960
  { $match: matchQuery },
15723
15961
  {
@@ -15901,7 +16139,7 @@ function useVehicleRepo() {
15901
16139
  const countResult = await collection.aggregate(buildGroupedCountPipeline(query2)).toArray();
15902
16140
  length = countResult[0]?.total || 0;
15903
16141
  if ((!items || items.length === 0) && search) {
15904
- const escaped = escapeRegex3(search);
16142
+ const escaped = escapeRegex4(search);
15905
16143
  const regexQuery = {
15906
16144
  ...baseQuery,
15907
16145
  $or: [
@@ -16690,7 +16928,7 @@ function useVehicleRepo() {
16690
16928
  ...baseQuery,
16691
16929
  ...search && { $text: { $search: search } }
16692
16930
  };
16693
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16931
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16694
16932
  const buildPipeline = (matchQuery) => [
16695
16933
  { $match: matchQuery },
16696
16934
  {
@@ -16718,7 +16956,7 @@ function useVehicleRepo() {
16718
16956
  const countResult = await collection.aggregate(buildCountPipeline(query2)).toArray();
16719
16957
  length = countResult[0]?.total || 0;
16720
16958
  if ((!items || items.length === 0) && search) {
16721
- const escaped = escapeRegex3(search);
16959
+ const escaped = escapeRegex4(search);
16722
16960
  const regexQuery = {
16723
16961
  ...baseQuery,
16724
16962
  $or: [
@@ -22172,6 +22410,28 @@ async function requireRoleAssigner(req, orgId) {
22172
22410
 
22173
22411
  // src/services/service-provider-invite.service.ts
22174
22412
  var INVITE_VALID_HOURS = 72;
22413
+ async function assertServiceProviderInviteScope(actor, orgId, siteId) {
22414
+ const site = await useSiteRepo().getSiteById(siteId);
22415
+ const siteOwnerOrg = String(site?.orgId ?? site?.org ?? "");
22416
+ const isStaff = staffMayBypass(actor);
22417
+ const callerInInviterOrg = actor.orgIds.includes(orgId);
22418
+ const owns = siteOwnerOrg !== "" && siteOwnerOrg === orgId;
22419
+ const inviterEngagedOnSite = !isStaff && callerInInviterOrg && !owns ? await useCustomerSiteRepo().countActiveByOrgAndSite(orgId, siteId).catch(() => 0) > 0 : false;
22420
+ const scope = serviceProviderInviteScope({
22421
+ isStaff,
22422
+ siteOwnerOrg,
22423
+ inviterOrg: orgId,
22424
+ callerInInviterOrg,
22425
+ inviterEngagedOnSite,
22426
+ // The same "runs this company" test Accept uses (`memberOrg`).
22427
+ callerRunsInviterOrg: actor.memberships.some(
22428
+ (m) => m.org === orgId && (m.companyWideRole === true || !m.siteId && m.orgLevelRole === true)
22429
+ )
22430
+ });
22431
+ if (!scope.ok)
22432
+ throw new UnauthorizedError5(scope.reason);
22433
+ return { sender: scope.sender, siteOwnerOrg };
22434
+ }
22175
22435
  function useServiceProviderInviteService() {
22176
22436
  const mailer2 = new useMailer2({
22177
22437
  host: MAILER_TRANSPORT_HOST,
@@ -22308,9 +22568,55 @@ function useServiceProviderInviteService() {
22308
22568
  });
22309
22569
  return {
22310
22570
  ...data,
22571
+ items: await withSender(data?.items ?? []),
22311
22572
  awaitingApprovalCount: await _countAwaiting()
22312
22573
  };
22313
22574
  }
22575
+ async function withSender(items) {
22576
+ const orgNames = /* @__PURE__ */ new Map();
22577
+ const owners = /* @__PURE__ */ new Map();
22578
+ const orgName = (id) => {
22579
+ if (!id)
22580
+ return Promise.resolve("");
22581
+ if (!orgNames.has(id)) {
22582
+ orgNames.set(
22583
+ id,
22584
+ getOrgById(id).then((o) => String(o?.name ?? "")).catch(() => "")
22585
+ );
22586
+ }
22587
+ return orgNames.get(id);
22588
+ };
22589
+ const ownerOf = (siteId) => {
22590
+ if (!siteId)
22591
+ return Promise.resolve("");
22592
+ if (!owners.has(siteId)) {
22593
+ owners.set(
22594
+ siteId,
22595
+ useSiteRepo().getSiteById(siteId).then((s) => String(s?.orgId ?? s?.org ?? "")).catch(() => "")
22596
+ );
22597
+ }
22598
+ return owners.get(siteId);
22599
+ };
22600
+ return Promise.all(
22601
+ items.map(async (invite) => {
22602
+ const inviterOrg = inviteOrgId(invite);
22603
+ const siteOwnerOrg = await ownerOf(
22604
+ invite.metadata?.siteId?.toString?.() ?? ""
22605
+ );
22606
+ const [inviterOrgName, siteOwnerName] = await Promise.all([
22607
+ orgName(inviterOrg),
22608
+ siteOwnerOrg === inviterOrg ? orgName(inviterOrg) : orgName(siteOwnerOrg)
22609
+ ]);
22610
+ return {
22611
+ ...invite,
22612
+ inviterOrgName,
22613
+ inviterKind: serviceProviderInviterKind(inviterOrg, siteOwnerOrg),
22614
+ siteOwnerName,
22615
+ service: String(invite.metadata?.app ?? "")
22616
+ };
22617
+ })
22618
+ );
22619
+ }
22314
22620
  async function listForCaller({
22315
22621
  userId,
22316
22622
  orgId,
@@ -22463,7 +22769,7 @@ function useServiceProviderInviteService() {
22463
22769
  const trimmed = String(reason ?? "").trim();
22464
22770
  if (!trimmed) {
22465
22771
  throw new BadRequestError44(
22466
- "Give a reason for not approving this invitation. The property manager will see it."
22772
+ "Give a reason for not approving this invitation. Whoever sent it will see it."
22467
22773
  );
22468
22774
  }
22469
22775
  const invite = await load(id);
@@ -22481,7 +22787,7 @@ function useServiceProviderInviteService() {
22481
22787
  if (!updated) {
22482
22788
  return { message: "This invitation has already been rejected." };
22483
22789
  }
22484
- return { message: "Invitation rejected. The property manager can see your reason." };
22790
+ return { message: "Invitation rejected. Whoever sent it can see your reason." };
22485
22791
  }
22486
22792
  async function cancel({ id, userId }) {
22487
22793
  const actor = await actorFor(userId);
@@ -23098,11 +23404,11 @@ function useVerificationService() {
23098
23404
  if (!actor.id) {
23099
23405
  throw new UnauthorizedError6("Sign in to continue.");
23100
23406
  }
23101
- if (!staffMayBypass(actor) && !actor.orgIds.includes(orgId)) {
23102
- throw new UnauthorizedError6(
23103
- "You can only invite service providers to your own organisation's sites."
23104
- );
23105
- }
23407
+ const { sender } = await assertServiceProviderInviteScope(
23408
+ actor,
23409
+ orgId,
23410
+ siteId
23411
+ );
23106
23412
  const invitedEmail = email.trim().toLowerCase();
23107
23413
  const [providerOrg, existingUser, pendingInvite] = await Promise.all([
23108
23414
  getOrgByEmail(invitedEmail),
@@ -23115,7 +23421,10 @@ function useVerificationService() {
23115
23421
  hasProviderOrg: Boolean(providerOrgId),
23116
23422
  engagedOnSite: providerOrgId ? await _countActiveEngagement(providerOrgId, siteId) > 0 : false,
23117
23423
  invitePending: Boolean(pendingInvite),
23118
- inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId)
23424
+ inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId),
23425
+ // A provider bringing in a subcontractor is held for Seven365
23426
+ // exactly like a property manager (owner request 2026-09-28).
23427
+ inviterIsServiceProvider: sender === "subcontract"
23119
23428
  });
23120
23429
  if (!decision.ok) {
23121
23430
  throw new BadRequestError45(decision.reason);
@@ -23127,7 +23436,7 @@ function useVerificationService() {
23127
23436
  ...value.metadata,
23128
23437
  invitedBy: actor.id,
23129
23438
  invitedByName: actor.name,
23130
- invitedByPropertyManagement: decision.requiresApproval
23439
+ invitedByPropertyManagement: decision.requiresApproval && actor.propertyManagementOrgIds.includes(orgId)
23131
23440
  };
23132
23441
  value.history = [
23133
23442
  {
@@ -23139,6 +23448,12 @@ function useVerificationService() {
23139
23448
  ];
23140
23449
  const res = await _add(value);
23141
23450
  if (decision.requiresApproval) {
23451
+ NotificationService.serviceProviderInviteAwaitingApproval({
23452
+ invitationId: String(res),
23453
+ inviterOrgName: org?.name ?? "",
23454
+ siteName,
23455
+ subcontract: sender === "subcontract"
23456
+ }).catch(() => void 0);
23142
23457
  return res;
23143
23458
  }
23144
23459
  await useServiceProviderInviteService().notifyProvider({
@@ -33492,6 +33807,7 @@ function useServiceProviderRepo() {
33492
33807
  _id: "$org",
33493
33808
  engagementId: { $first: "$_id" },
33494
33809
  siteName: { $first: "$name" },
33810
+ siteOrg: { $first: "$siteOrg" },
33495
33811
  since: { $first: "$createdAt" }
33496
33812
  }
33497
33813
  },
@@ -33538,6 +33854,7 @@ function useServiceProviderRepo() {
33538
33854
  status: "active",
33539
33855
  category: "external",
33540
33856
  since: 1,
33857
+ siteOrg: 1,
33541
33858
  source: "engagement",
33542
33859
  members: {
33543
33860
  $ifNull: [{ $arrayElemAt: ["$_memberCount.c", 0] }, 0]
@@ -33567,7 +33884,70 @@ function useServiceProviderRepo() {
33567
33884
  )
33568
33885
  };
33569
33886
  }
33887
+ async function getProviderMembersBySite(site, orgIds) {
33888
+ try {
33889
+ site = new ObjectId75(site);
33890
+ } catch {
33891
+ throw new BadRequestError81("Invalid site ID format.");
33892
+ }
33893
+ const orgs = [];
33894
+ for (const o of orgIds) {
33895
+ if (!ObjectId75.isValid(o))
33896
+ continue;
33897
+ orgs.push(new ObjectId75(o), o);
33898
+ }
33899
+ if (!orgs.length)
33900
+ return [];
33901
+ return await db2.collection("members").aggregate([
33902
+ {
33903
+ $match: {
33904
+ org: { $in: orgs },
33905
+ siteId: { $in: [site, site.toString()] },
33906
+ status: { $nin: ["deleted"] },
33907
+ deletedAt: { $in: [null, ""] }
33908
+ }
33909
+ },
33910
+ { $sort: { _id: 1 } },
33911
+ { $limit: 1e3 },
33912
+ {
33913
+ $lookup: {
33914
+ from: "users",
33915
+ localField: "user",
33916
+ foreignField: "_id",
33917
+ as: "_user",
33918
+ pipeline: [{ $project: { email: 1, name: 1 } }]
33919
+ }
33920
+ },
33921
+ {
33922
+ $lookup: {
33923
+ from: "roles",
33924
+ localField: "role",
33925
+ foreignField: "_id",
33926
+ as: "_role",
33927
+ pipeline: [{ $project: { name: 1 } }]
33928
+ }
33929
+ },
33930
+ {
33931
+ $project: {
33932
+ _id: 1,
33933
+ user: 1,
33934
+ org: 1,
33935
+ type: 1,
33936
+ status: 1,
33937
+ createdAt: 1,
33938
+ name: {
33939
+ $ifNull: ["$name", { $arrayElemAt: ["$_user.name", 0] }]
33940
+ },
33941
+ email: {
33942
+ $ifNull: [{ $arrayElemAt: ["$_user.email", 0] }, "$email"]
33943
+ },
33944
+ roleName: { $ifNull: [{ $arrayElemAt: ["$_role.name", 0] }, ""] }
33945
+ }
33946
+ }
33947
+ ]).toArray();
33948
+ }
33570
33949
  return {
33950
+ getProviderMembersBySite,
33571
33951
  createTextIndex,
33572
33952
  createUniqueIndex,
33573
33953
  createServiceProvider,
@@ -34292,7 +34672,11 @@ function useWorkOrderController() {
34292
34672
 
34293
34673
  // src/controllers/service-provider.controller.ts
34294
34674
  import Joi46 from "joi";
34295
- import { BadRequestError as BadRequestError87, logger as logger64 } from "@7365admin1/node-server-utils";
34675
+ import {
34676
+ BadRequestError as BadRequestError87,
34677
+ UnauthorizedError as UnauthorizedError14,
34678
+ logger as logger64
34679
+ } from "@7365admin1/node-server-utils";
34296
34680
 
34297
34681
  // src/services/service-provider.service.ts
34298
34682
  import {
@@ -34305,8 +34689,10 @@ function useServiceProviderService() {
34305
34689
  createServiceProvider: _createServiceProvider,
34306
34690
  getServiceProviders: _getServiceProviders,
34307
34691
  getEngagedProvidersBySite: _getEngaged,
34308
- getSiteProviderKeys: _getSiteProviderKeys
34692
+ getSiteProviderKeys: _getSiteProviderKeys,
34693
+ getProviderMembersBySite: _getProviderMembers
34309
34694
  } = useServiceProviderRepo();
34695
+ const { getServiceProviderInvites: _listInvites } = useVerificationRepoV2();
34310
34696
  const { getById: getOrgById, getByEmail: getOrgByEmail } = useOrgRepo();
34311
34697
  const { getSiteById } = useSiteRepo();
34312
34698
  const { getById: getVerificationById, updateStatusById } = useVerificationRepo();
@@ -34389,17 +34775,27 @@ function useServiceProviderService() {
34389
34775
  search = "",
34390
34776
  page: page2 = 1,
34391
34777
  limit = 10,
34392
- siteId
34778
+ siteId,
34779
+ invitedBy,
34780
+ storedOrgId = ""
34393
34781
  }) {
34394
- const [engaged, keys] = await Promise.all([
34782
+ const [engaged, keys, via] = await Promise.all([
34395
34783
  _getEngaged(siteId),
34396
- _getSiteProviderKeys(siteId)
34784
+ _getSiteProviderKeys(siteId),
34785
+ subcontractorsOf(siteId)
34397
34786
  ]);
34398
34787
  const needle = search.trim().toLowerCase();
34399
- const derived = engaged.filter(
34400
- (row) => !keys.orgIds.has(row.serviceProviderOrgId?.toString?.() ?? "") && !(row.email && keys.emails.has(String(row.email).trim().toLowerCase())) && (!needle || String(row.name ?? "").toLowerCase().includes(needle))
34788
+ const derived = engaged.map((row) => withVia(row, via)).filter(
34789
+ (row) => !keys.orgIds.has(row.serviceProviderOrgId?.toString?.() ?? "") && !(row.email && keys.emails.has(String(row.email).trim().toLowerCase())) && (!needle || String(row.name ?? "").toLowerCase().includes(needle)) && (!invitedBy || invitedBy.includes(row.invitedViaOrgId ?? ""))
34401
34790
  );
34402
- const stored = (p, l) => _getServiceProviders({ search, page: p, limit: l, siteId, status: "active" });
34791
+ const stored = (p, l) => _getServiceProviders({
34792
+ search,
34793
+ page: p,
34794
+ limit: l,
34795
+ siteId,
34796
+ status: "active",
34797
+ ...storedOrgId ? { orgId: storedOrgId } : {}
34798
+ });
34403
34799
  if (!derived.length)
34404
34800
  return await stored(page2, limit);
34405
34801
  const start = (Math.max(page2, 1) - 1) * limit;
@@ -34411,6 +34807,103 @@ function useServiceProviderService() {
34411
34807
  const fromStored = need > 0 ? (first?.items ?? []).slice(storedStart, storedStart + need) : [];
34412
34808
  return paginate25([...fromDerived, ...fromStored], Math.max(page2, 1) - 1, limit, total);
34413
34809
  }
34810
+ async function subcontractorsOf(siteId) {
34811
+ const via = /* @__PURE__ */ new Map();
34812
+ const data = await _listInvites({
34813
+ statuses: ["complete"],
34814
+ siteId,
34815
+ page: 1,
34816
+ limit: 200
34817
+ }).catch(() => null);
34818
+ const names = /* @__PURE__ */ new Map();
34819
+ for (const invite of data?.items ?? []) {
34820
+ const provider = invite.metadata?.providerOrg?.toString?.() ?? "";
34821
+ const sender = invite.metadata?.org?.toString?.() ?? "";
34822
+ if (!provider || !sender || via.has(provider))
34823
+ continue;
34824
+ if (!names.has(sender)) {
34825
+ names.set(
34826
+ sender,
34827
+ getOrgById(sender).then((o) => String(o?.name ?? "")).catch(() => "")
34828
+ );
34829
+ }
34830
+ via.set(provider, { orgId: sender, name: await names.get(sender) });
34831
+ }
34832
+ return via;
34833
+ }
34834
+ function withVia(row, via) {
34835
+ const provider = row.serviceProviderOrgId?.toString?.() ?? "";
34836
+ const owner = row.siteOrg?.toString?.() ?? "";
34837
+ const sender = via.get(provider);
34838
+ const { siteOrg: _siteOrg, ...rest } = row;
34839
+ if (!sender || !owner || sender.orgId === owner)
34840
+ return rest;
34841
+ return { ...rest, invitedViaOrgId: sender.orgId, invitedVia: sender.name };
34842
+ }
34843
+ async function getSiteProviderMembers({ siteId }) {
34844
+ const [engaged, storedRows, via] = await Promise.all([
34845
+ _getEngaged(siteId),
34846
+ _getServiceProviders({ siteId, status: "active", page: 1, limit: 200 }),
34847
+ subcontractorsOf(siteId)
34848
+ ]);
34849
+ const companies = /* @__PURE__ */ new Map();
34850
+ for (const row of engaged) {
34851
+ const id = row.serviceProviderOrgId?.toString?.() ?? "";
34852
+ if (!id)
34853
+ continue;
34854
+ const r = withVia(row, via);
34855
+ companies.set(id, {
34856
+ orgId: id,
34857
+ name: r.name ?? "",
34858
+ type: r.type ?? "",
34859
+ email: r.email ?? "",
34860
+ since: r.since ?? null,
34861
+ invitedVia: r.invitedVia ?? ""
34862
+ });
34863
+ }
34864
+ for (const row of storedRows?.items ?? []) {
34865
+ const id = row.serviceProviderOrgId?.toString?.() ?? "";
34866
+ if (!id || companies.has(id))
34867
+ continue;
34868
+ companies.set(id, {
34869
+ orgId: id,
34870
+ name: row.name ?? "",
34871
+ type: row.type ?? "",
34872
+ email: row.email ?? "",
34873
+ since: row.createdAt ?? null,
34874
+ invitedVia: ""
34875
+ });
34876
+ }
34877
+ const people = await _getProviderMembers(siteId, [...companies.keys()]);
34878
+ const counts = /* @__PURE__ */ new Map();
34879
+ const items = people.map((m) => {
34880
+ const orgId = m.org?.toString?.() ?? "";
34881
+ const company = companies.get(orgId) ?? {};
34882
+ counts.set(orgId, (counts.get(orgId) ?? 0) + 1);
34883
+ return {
34884
+ _id: m._id,
34885
+ name: m.name ?? "",
34886
+ email: m.email ?? "",
34887
+ companyId: orgId,
34888
+ company: company.name ?? "",
34889
+ // the company's line of business; the membership type as a fallback
34890
+ type: company.type || m.type || "",
34891
+ typeLabel: serviceTypeLabel(company.type || m.type),
34892
+ role: m.roleName ?? "",
34893
+ status: m.status ?? "active",
34894
+ addedAt: m.createdAt ?? null,
34895
+ invitedVia: company.invitedVia ?? ""
34896
+ };
34897
+ });
34898
+ return {
34899
+ items,
34900
+ companies: [...companies.values()].map((c) => ({
34901
+ ...c,
34902
+ typeLabel: serviceTypeLabel(c.type),
34903
+ people: counts.get(c.orgId) ?? 0
34904
+ })).sort((a, b) => String(a.name).localeCompare(String(b.name)))
34905
+ };
34906
+ }
34414
34907
  function totalOf(data) {
34415
34908
  const match = /of\s+(\d+)/.exec(String(data?.pageRange ?? ""));
34416
34909
  return match ? Number(match[1]) : (data?.items ?? []).length;
@@ -34418,11 +34911,13 @@ function useServiceProviderService() {
34418
34911
  return {
34419
34912
  createServiceProvider,
34420
34913
  getServiceProviders,
34421
- getServiceProvidersForSite
34914
+ getServiceProvidersForSite,
34915
+ getSiteProviderMembers
34422
34916
  };
34423
34917
  }
34424
34918
 
34425
34919
  // src/controllers/service-provider.controller.ts
34920
+ import ExcelJS from "exceljs";
34426
34921
  function useServiceProviderController() {
34427
34922
  const {
34428
34923
  getServiceProviderNames: _getServiceProviderNames,
@@ -34435,7 +34930,8 @@ function useServiceProviderController() {
34435
34930
  } = useServiceProviderRepo();
34436
34931
  const {
34437
34932
  createServiceProvider: _createServiceProvider,
34438
- getServiceProvidersForSite: _getServiceProvidersForSite
34933
+ getServiceProvidersForSite: _getServiceProvidersForSite,
34934
+ getSiteProviderMembers: _getSiteProviderMembers
34439
34935
  } = useServiceProviderService();
34440
34936
  async function isSiteClient(req, siteId) {
34441
34937
  const actor = await resolveInviteActor(callerId(req));
@@ -34445,6 +34941,78 @@ function useServiceProviderController() {
34445
34941
  const owner = (site?.orgId ?? site?.org)?.toString?.() ?? "";
34446
34942
  return Boolean(owner) && actor.orgIds.includes(owner);
34447
34943
  }
34944
+ async function providerView(req, q) {
34945
+ const actor = await resolveInviteActor(callerId(req));
34946
+ const preferred2 = membershipPreferenceOf(req).org ?? "";
34947
+ return _getServiceProvidersForSite({
34948
+ ...q,
34949
+ invitedBy: actor.orgIds,
34950
+ storedOrgId: actor.orgIds.includes(preferred2) ? preferred2 : ""
34951
+ });
34952
+ }
34953
+ async function getSiteProviderMembers(req, res, next) {
34954
+ try {
34955
+ const { error, value } = Joi46.object({
34956
+ siteId: Joi46.string().hex().length(24).required(),
34957
+ type: Joi46.string().max(60).optional().allow("", null),
34958
+ company: Joi46.string().hex().length(24).optional().allow("", null),
34959
+ search: Joi46.string().max(200).optional().allow("", null),
34960
+ format: Joi46.string().valid("json", "xlsx").optional().allow("", null)
34961
+ }).validate(req.query);
34962
+ if (error)
34963
+ throw new BadRequestError87(`Invalid input: ${error.message}`);
34964
+ await requireSiteReach(req, value.siteId);
34965
+ if (!await isSiteClient(req, value.siteId)) {
34966
+ throw new UnauthorizedError14(
34967
+ "Only the site's own organisation can see its service providers' people."
34968
+ );
34969
+ }
34970
+ const data = await _getSiteProviderMembers({ siteId: value.siteId });
34971
+ if (value.format !== "xlsx") {
34972
+ res.json(data);
34973
+ return;
34974
+ }
34975
+ const rows = filterSiteProviderMembers(data.items, {
34976
+ type: value.type || "",
34977
+ company: value.company || "",
34978
+ search: value.search || ""
34979
+ });
34980
+ const workbook = new ExcelJS.Workbook();
34981
+ const sheet = workbook.addWorksheet("Service provider people");
34982
+ sheet.columns = [
34983
+ { header: "Name", key: "name", width: 28 },
34984
+ { header: "Email", key: "email", width: 32 },
34985
+ { header: "Company", key: "company", width: 28 },
34986
+ { header: "Service", key: "typeLabel", width: 22 },
34987
+ { header: "Role at this site", key: "role", width: 24 },
34988
+ { header: "Invited by", key: "invitedVia", width: 26 },
34989
+ { header: "Added", key: "added", width: 14 },
34990
+ { header: "Status", key: "status", width: 12 }
34991
+ ];
34992
+ sheet.getRow(1).font = { bold: true };
34993
+ for (const r of rows) {
34994
+ sheet.addRow({
34995
+ ...r,
34996
+ invitedVia: r.invitedVia || "The client",
34997
+ added: r.addedAt ? String(r.addedAt).slice(0, 10) : "",
34998
+ status: r.status === "active" ? "Active" : String(r.status ?? "")
34999
+ });
35000
+ }
35001
+ const buffer = await workbook.xlsx.writeBuffer();
35002
+ res.setHeader(
35003
+ "Content-Type",
35004
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
35005
+ );
35006
+ res.setHeader(
35007
+ "Content-Disposition",
35008
+ 'attachment; filename="service-provider-people.xlsx"'
35009
+ );
35010
+ res.send(Buffer.from(buffer));
35011
+ } catch (error) {
35012
+ logger64.log({ level: "error", message: error.message });
35013
+ next(error);
35014
+ }
35015
+ }
34448
35016
  const { createServiceProvider: _add } = useServiceProviderRepo();
34449
35017
  async function createServiceProvider(req, res, next) {
34450
35018
  const validation = Joi46.string().hex().required();
@@ -34497,7 +35065,14 @@ function useServiceProviderController() {
34497
35065
  try {
34498
35066
  if (siteId)
34499
35067
  await requireSiteReach(req, siteId);
34500
- const data = req.query.include === "engagements" && siteId && status === "active" && !orgId && !serviceProviderOrgId && await isSiteClient(req, siteId) ? await _getServiceProvidersForSite({ search, page: page2, limit, siteId }) : await _getServiceProviders({
35068
+ const engagements = req.query.include === "engagements" && siteId && status === "active" && !orgId && !serviceProviderOrgId;
35069
+ const client = engagements ? await isSiteClient(req, siteId) : false;
35070
+ const data = client ? await _getServiceProvidersForSite({ search, page: page2, limit, siteId }) : engagements ? (
35071
+ // A provider's own Service Providers page: the subcontractors it
35072
+ // brought onto this site, never the client's other contractors,
35073
+ // plus the stored rows it already saw here.
35074
+ await providerView(req, { search, page: page2, limit, siteId })
35075
+ ) : await _getServiceProviders({
34501
35076
  search,
34502
35077
  page: page2,
34503
35078
  limit,
@@ -34715,6 +35290,7 @@ function useServiceProviderController() {
34715
35290
  }
34716
35291
  return {
34717
35292
  createServiceProvider,
35293
+ getSiteProviderMembers,
34718
35294
  getServiceProviders,
34719
35295
  getByProviderOrg,
34720
35296
  getByEmail,
@@ -38602,7 +39178,7 @@ import {
38602
39178
  BadRequestError as BadRequestError96,
38603
39179
  logger as logger72,
38604
39180
  NotFoundError as NotFoundError28,
38605
- UnauthorizedError as UnauthorizedError14,
39181
+ UnauthorizedError as UnauthorizedError15,
38606
39182
  useAtlas as useAtlas62
38607
39183
  } from "@7365admin1/node-server-utils";
38608
39184
  import Joi52 from "joi";
@@ -38748,7 +39324,7 @@ function siteModulesHandlers({
38748
39324
  return;
38749
39325
  }
38750
39326
  if (!await mayManage(actor, site)) {
38751
- throw new UnauthorizedError14("Not authorized.");
39327
+ throw new UnauthorizedError15("Not authorized.");
38752
39328
  }
38753
39329
  const org = site.orgId ? await _getOrgById(site.orgId.toString()) : null;
38754
39330
  const rejected = rejectedSiteModules(
@@ -38810,7 +39386,7 @@ function siteModulesHandlers({
38810
39386
  if (!site)
38811
39387
  throw new NotFoundError28("Site not found.");
38812
39388
  if (!await mayManage(actor, site))
38813
- throw new UnauthorizedError14("Not authorized.");
39389
+ throw new UnauthorizedError15("Not authorized.");
38814
39390
  const org = site?.orgId ? await _getOrgById(site.orgId.toString()) : null;
38815
39391
  res.json(
38816
39392
  await siteModulePreview(site, org, normaliseModules(req.body.modules), gateData)
@@ -41080,7 +41656,7 @@ function useBuildingService() {
41080
41656
  // src/controllers/building.controller.ts
41081
41657
  import { BadRequestError as BadRequestError103, logger as logger80 } from "@7365admin1/node-server-utils";
41082
41658
  import Joi55 from "joi";
41083
- import ExcelJS from "exceljs";
41659
+ import ExcelJS2 from "exceljs";
41084
41660
  import csv from "csv-parser";
41085
41661
  import fs2 from "fs";
41086
41662
  function normalizeSpreadsheetHeader(header) {
@@ -41383,7 +41959,7 @@ function useBuildingController() {
41383
41959
  const { site, org } = queryValue;
41384
41960
  let rows = [];
41385
41961
  if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) {
41386
- const workbook = new ExcelJS.Workbook();
41962
+ const workbook = new ExcelJS2.Workbook();
41387
41963
  await workbook.xlsx.readFile(path5);
41388
41964
  const worksheet = workbook.worksheets[0];
41389
41965
  if (!worksheet) {
@@ -42103,7 +42679,7 @@ function parseExpiryDate(value) {
42103
42679
  }
42104
42680
 
42105
42681
  // src/controllers/vehicle.controller.ts
42106
- import ExcelJS2 from "exceljs";
42682
+ import ExcelJS3 from "exceljs";
42107
42683
  import csv2 from "csv-parser";
42108
42684
  import fs3 from "fs";
42109
42685
  function actingUser(req) {
@@ -42254,7 +42830,7 @@ function useVehicleController() {
42254
42830
  const { site, org } = queryValue;
42255
42831
  let rows = [];
42256
42832
  if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) {
42257
- const workbook = new ExcelJS2.Workbook();
42833
+ const workbook = new ExcelJS3.Workbook();
42258
42834
  await workbook.xlsx.readFile(path5);
42259
42835
  const worksheet = workbook.worksheets[0];
42260
42836
  if (!worksheet) {
@@ -44135,7 +44711,7 @@ function useCameraViewController() {
44135
44711
  import Joi61 from "joi";
44136
44712
  import {
44137
44713
  BadRequestError as BadRequestError110,
44138
- UnauthorizedError as UnauthorizedError15,
44714
+ UnauthorizedError as UnauthorizedError16,
44139
44715
  logger as logger85
44140
44716
  } from "@7365admin1/node-server-utils";
44141
44717
  async function requireEitherOrg(req, ...orgs) {
@@ -44144,7 +44720,7 @@ async function requireEitherOrg(req, ...orgs) {
44144
44720
  if (staffMayBypass(actor))
44145
44721
  return actor;
44146
44722
  if (wanted.length === 0 || !wanted.some((org) => actor.orgIds.includes(org))) {
44147
- throw new UnauthorizedError15("Not authorized.");
44723
+ throw new UnauthorizedError16("Not authorized.");
44148
44724
  }
44149
44725
  return actor;
44150
44726
  }
@@ -46293,7 +46869,7 @@ function usePersonService() {
46293
46869
  let set = {};
46294
46870
  const cleanInput = (str2) => str2.replace(/\s+/g, "");
46295
46871
  const cleanPhone = (str2) => str2.replace(/\D/g, "");
46296
- const escapeRegex3 = (str2) => str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46872
+ const escapeRegex4 = (str2) => str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46297
46873
  const nric = value.nric ? cleanInput(value.nric) : "";
46298
46874
  const name = value.name?.trim();
46299
46875
  const contact = value.contact?.trim();
@@ -46301,8 +46877,8 @@ function usePersonService() {
46301
46877
  const email = value.email?.trim();
46302
46878
  const type = value.type?.trim();
46303
46879
  const company = value.company?.trim();
46304
- const nricQuery = nric ? { nric: { $regex: `^${escapeRegex3(nric)}$`, $options: "i" } } : null;
46305
- const nameQuery = name ? { name: { $regex: `^${escapeRegex3(name)}$`, $options: "i" } } : null;
46880
+ const nricQuery = nric ? { nric: { $regex: `^${escapeRegex4(nric)}$`, $options: "i" } } : null;
46881
+ const nameQuery = name ? { name: { $regex: `^${escapeRegex4(name)}$`, $options: "i" } } : null;
46306
46882
  let nricCondition = null;
46307
46883
  if (nric) {
46308
46884
  if (nric.length < 9) {
@@ -46315,8 +46891,8 @@ function usePersonService() {
46315
46891
  }
46316
46892
  const orConditions = [
46317
46893
  ...nricCondition ? [nricCondition] : [],
46318
- ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex3(contact))}$`, $options: "i" } }] : [],
46319
- ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex3(plateNumber)}$`, $options: "i" } }] : []
46894
+ ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex4(contact))}$`, $options: "i" } }] : [],
46895
+ ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex4(plateNumber)}$`, $options: "i" } }] : []
46320
46896
  ];
46321
46897
  const existingPerson2 = await findFirstTen(
46322
46898
  {
@@ -47373,7 +47949,7 @@ import {
47373
47949
  BadRequestError as BadRequestError124,
47374
47950
  InternalServerError as InternalServerError45,
47375
47951
  NotFoundError as NotFoundError38,
47376
- UnauthorizedError as UnauthorizedError16,
47952
+ UnauthorizedError as UnauthorizedError17,
47377
47953
  logger as logger97
47378
47954
  } from "@7365admin1/node-server-utils";
47379
47955
 
@@ -48215,7 +48791,7 @@ function useHidAmicoRepo() {
48215
48791
  passwordSet: Boolean(password)
48216
48792
  };
48217
48793
  }
48218
- function escapeRegex3(value) {
48794
+ function escapeRegex4(value) {
48219
48795
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48220
48796
  }
48221
48797
  function buildIdentityKeyQuery(value) {
@@ -48418,7 +48994,7 @@ function useHidAmicoRepo() {
48418
48994
  query2.type = value.type;
48419
48995
  }
48420
48996
  if (value.search) {
48421
- const search = escapeRegex3(value.search);
48997
+ const search = escapeRegex4(value.search);
48422
48998
  query2.$or = [
48423
48999
  { hidUserId: { $regex: search, $options: "i" } },
48424
49000
  { registration: { $regex: search, $options: "i" } },
@@ -48659,7 +49235,7 @@ function useHidAmicoRepo() {
48659
49235
  const text2 = search.trim();
48660
49236
  if (!text2)
48661
49237
  return {};
48662
- const pattern = { $regex: escapeRegex3(text2), $options: "i" };
49238
+ const pattern = { $regex: escapeRegex4(text2), $options: "i" };
48663
49239
  return {
48664
49240
  $or: [
48665
49241
  { name: pattern },
@@ -50907,8 +51483,8 @@ function useHidAmicoService() {
50907
51483
  await siteAccess.authorizeSite({ siteId, userId: value.userId, permissions });
50908
51484
  }
50909
51485
  } catch (error) {
50910
- if (error instanceof UnauthorizedError16) {
50911
- throw new UnauthorizedError16("You do not have permission to manage HID access at this site.");
51486
+ if (error instanceof UnauthorizedError17) {
51487
+ throw new UnauthorizedError17("You do not have permission to manage HID access at this site.");
50912
51488
  }
50913
51489
  throw error;
50914
51490
  }
@@ -50932,7 +51508,7 @@ function useHidAmicoService() {
50932
51508
  try {
50933
51509
  await authorizeSiteForCaller(String(reader.site || ""), userId);
50934
51510
  } catch (error) {
50935
- if (error instanceof UnauthorizedError16)
51511
+ if (error instanceof UnauthorizedError17)
50936
51512
  throw error;
50937
51513
  throw new NotFoundError38(HID_READER_NOT_FOUND);
50938
51514
  }
@@ -50984,10 +51560,10 @@ function useHidAmicoService() {
50984
51560
  async function assertUserReaderPermission(reader, userId, options = {}) {
50985
51561
  const permission = await getReaderPermissionForUser(reader, userId);
50986
51562
  if (!permission.granted) {
50987
- throw new UnauthorizedError16("You do not have HID access permission for this reader.");
51563
+ throw new UnauthorizedError17("You do not have HID access permission for this reader.");
50988
51564
  }
50989
51565
  if (options.intercom && !permission.intercom) {
50990
- throw new UnauthorizedError16("You do not have HID intercom permission for this reader.");
51566
+ throw new UnauthorizedError17("You do not have HID intercom permission for this reader.");
50991
51567
  }
50992
51568
  return permission;
50993
51569
  }
@@ -52325,10 +52901,10 @@ function useHidAmicoService() {
52325
52901
  const hasActiveMembership = memberships.some((membership) => membership.status !== "deleted" && membership.status !== "inactive");
52326
52902
  const resolvedIssuer = issuer || (hasResidentMembership ? "resident" : "property_management");
52327
52903
  if (resolvedIssuer === "resident" && !hasResidentMembership) {
52328
- throw new UnauthorizedError16("Only a Resident account can issue a Resident visitor QR code.");
52904
+ throw new UnauthorizedError17("Only a Resident account can issue a Resident visitor QR code.");
52329
52905
  }
52330
52906
  if (resolvedIssuer === "property_management" && !hasActiveMembership) {
52331
- throw new UnauthorizedError16("Only a site Property Management account can issue this visitor QR code.");
52907
+ throw new UnauthorizedError17("Only a site Property Management account can issue this visitor QR code.");
52332
52908
  }
52333
52909
  const configuredGateIds = site?.metadata?.hidQrCodePass?.qrGatePermissions?.[resolvedIssuer === "resident" ? "resident" : "propertyManagement"] || [];
52334
52910
  const gateReaderIds = configuredGateIds.filter((readerId) => typeof readerId === "string" && /^[a-f0-9]{24}$/i.test(readerId)).map(String);
@@ -54921,7 +55497,7 @@ function useVisitorTransactionService() {
54921
55497
  import Joi70 from "joi";
54922
55498
  import moment5 from "moment-timezone";
54923
55499
  import { ObjectId as ObjectId103 } from "mongodb";
54924
- import { BadRequestError as BadRequestError127, NotFoundError as NotFoundError40, InternalServerError as InternalServerError47, UnauthorizedError as UnauthorizedError17, logger as logger101 } from "@7365admin1/node-server-utils";
55500
+ import { BadRequestError as BadRequestError127, NotFoundError as NotFoundError40, InternalServerError as InternalServerError47, UnauthorizedError as UnauthorizedError18, logger as logger101 } from "@7365admin1/node-server-utils";
54925
55501
 
54926
55502
  // src/models/visitor-invite.model.ts
54927
55503
  import Joi68 from "joi";
@@ -59794,7 +60370,7 @@ function useVisitorTransactionController() {
59794
60370
  }
59795
60371
  const inviterUserId = callerId(req);
59796
60372
  if (!inviterUserId) {
59797
- next(new UnauthorizedError17("Not authorized."));
60373
+ next(new UnauthorizedError18("Not authorized."));
59798
60374
  return;
59799
60375
  }
59800
60376
  try {
@@ -60358,7 +60934,7 @@ function useGuestManagementController() {
60358
60934
  // src/controllers/person.controller.ts
60359
60935
  import Joi73 from "joi";
60360
60936
  import { BadRequestError as BadRequestError130, logger as logger104 } from "@7365admin1/node-server-utils";
60361
- import { NotFoundError as NotFoundError41, UnauthorizedError as UnauthorizedError18 } from "@7365admin1/node-server-utils";
60937
+ import { NotFoundError as NotFoundError41, UnauthorizedError as UnauthorizedError19 } from "@7365admin1/node-server-utils";
60362
60938
 
60363
60939
  // src/utils/people-create-gate.util.ts
60364
60940
  var PEOPLE_CREATE_REACH_MODE_DEFAULT = "enforce";
@@ -60425,7 +61001,7 @@ function usePersonController() {
60425
61001
  }
60426
61002
  const org = person.org?.toString() ?? "";
60427
61003
  if (!org || !actor.orgIds.includes(org)) {
60428
- throw new UnauthorizedError18("Not authorized.");
61004
+ throw new UnauthorizedError19("Not authorized.");
60429
61005
  }
60430
61006
  return actor;
60431
61007
  }
@@ -60508,7 +61084,7 @@ function usePersonController() {
60508
61084
  });
60509
61085
  }
60510
61086
  if (verdict.refuse) {
60511
- next(new UnauthorizedError18("Not authorized."));
61087
+ next(new UnauthorizedError19("Not authorized."));
60512
61088
  return;
60513
61089
  }
60514
61090
  }
@@ -60591,7 +61167,7 @@ function usePersonController() {
60591
61167
  });
60592
61168
  } else if (org) {
60593
61169
  if (!actor.orgIds.includes(org)) {
60594
- throw new UnauthorizedError18("Not authorized.");
61170
+ throw new UnauthorizedError19("Not authorized.");
60595
61171
  }
60596
61172
  } else {
60597
61173
  orgs = actor.orgIds;
@@ -61058,7 +61634,7 @@ var NETWORK_SORTS = {
61058
61634
  };
61059
61635
  var NETWORK_OFFLINE_CODE = "OFFLINE";
61060
61636
  var ROBOT_FAULTS_COLLECTION = "robot-faults";
61061
- function escapeRegex2(value) {
61637
+ function escapeRegex3(value) {
61062
61638
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
61063
61639
  }
61064
61640
  function matchDefaulted(field, value, fallback) {
@@ -61162,7 +61738,7 @@ function networkListPipeline(q) {
61162
61738
  pipeline.push({ $match: { offline: true } });
61163
61739
  const search = (q.search ?? "").trim();
61164
61740
  if (search) {
61165
- const rx = { $regex: escapeRegex2(search), $options: "i" };
61741
+ const rx = { $regex: escapeRegex3(search), $options: "i" };
61166
61742
  pipeline.push({
61167
61743
  $match: { $or: [{ name: rx }, { robotSn: rx }, { "client.name": rx }, { "site.name": rx }] }
61168
61744
  });
@@ -73000,7 +73576,7 @@ function usePatrolEmailRepo() {
73000
73576
  throw new BadRequestError155(`Invalid ${label2} format.`);
73001
73577
  }
73002
73578
  }
73003
- function escapeRegex3(value) {
73579
+ function escapeRegex4(value) {
73004
73580
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
73005
73581
  }
73006
73582
  async function createIndexes() {
@@ -73137,8 +73713,8 @@ function usePatrolEmailRepo() {
73137
73713
  ...status ? { status } : { status: { $ne: "deleted" } },
73138
73714
  ...search && {
73139
73715
  $or: [
73140
- { subject: { $regex: escapeRegex3(search), $options: "i" } },
73141
- { recipients: { $regex: escapeRegex3(search), $options: "i" } }
73716
+ { subject: { $regex: escapeRegex4(search), $options: "i" } },
73717
+ { recipients: { $regex: escapeRegex4(search), $options: "i" } }
73142
73718
  ]
73143
73719
  }
73144
73720
  };
@@ -74477,7 +75053,7 @@ function useSiteFacilityService() {
74477
75053
  import {
74478
75054
  BadRequestError as BadRequestError161,
74479
75055
  NotFoundError as NotFoundError52,
74480
- UnauthorizedError as UnauthorizedError19,
75056
+ UnauthorizedError as UnauthorizedError20,
74481
75057
  logger as logger131
74482
75058
  } from "@7365admin1/node-server-utils";
74483
75059
  import Joi90 from "joi";
@@ -74564,7 +75140,7 @@ function useSiteFacilityController() {
74564
75140
  } else {
74565
75141
  const { actor } = await siteReachOf(req);
74566
75142
  if (!actor.isSuperAdmin)
74567
- throw new UnauthorizedError19("Not authorized.");
75143
+ throw new UnauthorizedError20("Not authorized.");
74568
75144
  }
74569
75145
  const data = await _getAll({
74570
75146
  search,
@@ -77599,7 +78175,7 @@ function useBulletinBoardService() {
77599
78175
  import {
77600
78176
  BadRequestError as BadRequestError170,
77601
78177
  NotFoundError as NotFoundError60,
77602
- UnauthorizedError as UnauthorizedError20,
78178
+ UnauthorizedError as UnauthorizedError21,
77603
78179
  logger as logger140
77604
78180
  } from "@7365admin1/node-server-utils";
77605
78181
  import Joi98 from "joi";
@@ -77635,7 +78211,7 @@ function useBulletinBoardController() {
77635
78211
  } else {
77636
78212
  const { canReach } = await siteReachOf(req);
77637
78213
  if (!await canReach(scopeOf(value))) {
77638
- throw new UnauthorizedError20("Not authorized.");
78214
+ throw new UnauthorizedError21("Not authorized.");
77639
78215
  }
77640
78216
  }
77641
78217
  const data = await _add(value);
@@ -78192,7 +78768,7 @@ import { BadRequestError as BadRequestError176, logger as logger146 } from "@736
78192
78768
  import {
78193
78769
  BadRequestError as BadRequestError175,
78194
78770
  logger as logger145,
78195
- UnauthorizedError as UnauthorizedError21,
78771
+ UnauthorizedError as UnauthorizedError22,
78196
78772
  useAtlas as useAtlas100
78197
78773
  } from "@7365admin1/node-server-utils";
78198
78774
 
@@ -78576,7 +79152,7 @@ function useSiteBillingItemService() {
78576
79152
  function assertUnitAtSite(buildingUnit, site) {
78577
79153
  const siteId = site?.toString?.() ?? "";
78578
79154
  if (!siteId || (buildingUnit?.site?.toString() ?? "") !== siteId) {
78579
- throw new UnauthorizedError21("Not authorized.");
79155
+ throw new UnauthorizedError22("Not authorized.");
78580
79156
  }
78581
79157
  }
78582
79158
  async function add(value) {
@@ -78747,7 +79323,7 @@ function useSiteBillingItemService() {
78747
79323
  message: error.message
78748
79324
  });
78749
79325
  await session.abortTransaction();
78750
- if (error instanceof BadRequestError175 || error instanceof UnauthorizedError21) {
79326
+ if (error instanceof BadRequestError175 || error instanceof UnauthorizedError22) {
78751
79327
  throw error;
78752
79328
  }
78753
79329
  throw new BadRequestError175("Failed to update Site Billing Item.");
@@ -80716,7 +81292,7 @@ import Joi106 from "joi";
80716
81292
 
80717
81293
  // src/utils/resident-unit.util.ts
80718
81294
  import { ObjectId as ObjectId141 } from "mongodb";
80719
- import { UnauthorizedError as UnauthorizedError22, useAtlas as useAtlas106 } from "@7365admin1/node-server-utils";
81295
+ import { UnauthorizedError as UnauthorizedError23, useAtlas as useAtlas106 } from "@7365admin1/node-server-utils";
80720
81296
  async function requireOwnUnit(req, site, unitId) {
80721
81297
  const actor = await resolveInviteActor(callerId(req));
80722
81298
  if (staffMayBypass(actor))
@@ -80724,7 +81300,7 @@ async function requireOwnUnit(req, site, unitId) {
80724
81300
  const unit = unitId?.toString?.() ?? "";
80725
81301
  const siteId = site?.toString?.() ?? "";
80726
81302
  if (!ObjectId141.isValid(unit) || !ObjectId141.isValid(siteId) || !actor.id) {
80727
- throw new UnauthorizedError22("Not authorized.");
81303
+ throw new UnauthorizedError23("Not authorized.");
80728
81304
  }
80729
81305
  const db2 = useAtlas106.getDb();
80730
81306
  if (!db2)
@@ -80736,7 +81312,7 @@ async function requireOwnUnit(req, site, unitId) {
80736
81312
  status: { $ne: "deleted" }
80737
81313
  });
80738
81314
  if (!own)
80739
- throw new UnauthorizedError22("Not authorized.");
81315
+ throw new UnauthorizedError23("Not authorized.");
80740
81316
  }
80741
81317
 
80742
81318
  // src/controllers/site-unit-billing.controller.ts
@@ -88826,7 +89402,7 @@ function useOnlineFormRepo() {
88826
89402
  import {
88827
89403
  BadRequestError as BadRequestError215,
88828
89404
  NotFoundError as NotFoundError79,
88829
- UnauthorizedError as UnauthorizedError23,
89405
+ UnauthorizedError as UnauthorizedError24,
88830
89406
  logger as logger183
88831
89407
  } from "@7365admin1/node-server-utils";
88832
89408
  import Joi128 from "joi";
@@ -88898,10 +89474,10 @@ function useOnlineFormController() {
88898
89474
  if (site) {
88899
89475
  await requireSiteReach(req, site);
88900
89476
  } else if (!staffMayBypass(actor)) {
88901
- throw new UnauthorizedError23("Not authorized.");
89477
+ throw new UnauthorizedError24("Not authorized.");
88902
89478
  }
88903
89479
  if (org && !staffMayBypass(actor) && !actor.orgIds.includes(org)) {
88904
- throw new UnauthorizedError23("Not authorized.");
89480
+ throw new UnauthorizedError24("Not authorized.");
88905
89481
  }
88906
89482
  const data = await _getAll({ search, page: page2, limit, status, org, site });
88907
89483
  res.json(data);
@@ -88966,7 +89542,7 @@ function useOnlineFormController() {
88966
89542
  if (payload.org) {
88967
89543
  const { actor } = await siteReachOf(req);
88968
89544
  if (!staffMayBypass(actor) && !actor.orgIds.includes(payload.org)) {
88969
- throw new UnauthorizedError23("Not authorized.");
89545
+ throw new UnauthorizedError24("Not authorized.");
88970
89546
  }
88971
89547
  }
88972
89548
  await _updateOnlineFormById(_id, payload);
@@ -96298,7 +96874,7 @@ import {
96298
96874
  BadRequestError as BadRequestError242,
96299
96875
  NotFoundError as NotFoundError88,
96300
96876
  InternalServerError as InternalServerError87,
96301
- UnauthorizedError as UnauthorizedError24,
96877
+ UnauthorizedError as UnauthorizedError25,
96302
96878
  useAtlas as useAtlas143,
96303
96879
  hashPassword as hashPassword4
96304
96880
  } from "@7365admin1/node-server-utils";
@@ -97221,13 +97797,13 @@ function useVerificationServiceV2() {
97221
97797
  const org = await getOrgById(orgId);
97222
97798
  const actor = await resolveInviteActor(invitedBy);
97223
97799
  if (!actor.id) {
97224
- throw new UnauthorizedError24("Sign in to continue.");
97225
- }
97226
- if (!staffMayBypass(actor) && !actor.orgIds.includes(orgId)) {
97227
- throw new UnauthorizedError24(
97228
- "You can only invite service providers to your own organisation's sites."
97229
- );
97800
+ throw new UnauthorizedError25("Sign in to continue.");
97230
97801
  }
97802
+ const { sender } = await assertServiceProviderInviteScope(
97803
+ actor,
97804
+ orgId,
97805
+ siteId
97806
+ );
97231
97807
  const invitedEmail = email.trim().toLowerCase();
97232
97808
  const [providerOrg, existingUser, pendingInvite] = await Promise.all([
97233
97809
  _getByEmail(invitedEmail),
@@ -97240,7 +97816,10 @@ function useVerificationServiceV2() {
97240
97816
  hasProviderOrg: Boolean(providerOrgId),
97241
97817
  engagedOnSite: providerOrgId ? await _countActiveEngagement(providerOrgId, siteId) > 0 : false,
97242
97818
  invitePending: Boolean(pendingInvite),
97243
- inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId)
97819
+ inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId),
97820
+ // A provider bringing in a subcontractor is held for Seven365
97821
+ // exactly like a property manager (owner request 2026-09-28).
97822
+ inviterIsServiceProvider: sender === "subcontract"
97244
97823
  });
97245
97824
  if (!decision.ok) {
97246
97825
  throw new BadRequestError242(decision.reason);
@@ -97252,7 +97831,7 @@ function useVerificationServiceV2() {
97252
97831
  ...value.metadata,
97253
97832
  invitedBy: actor.id,
97254
97833
  invitedByName: actor.name,
97255
- invitedByPropertyManagement: decision.requiresApproval
97834
+ invitedByPropertyManagement: decision.requiresApproval && actor.propertyManagementOrgIds.includes(orgId)
97256
97835
  };
97257
97836
  value.history = [
97258
97837
  {
@@ -97264,6 +97843,12 @@ function useVerificationServiceV2() {
97264
97843
  ];
97265
97844
  const res = await _add(value);
97266
97845
  if (decision.requiresApproval) {
97846
+ NotificationService.serviceProviderInviteAwaitingApproval({
97847
+ invitationId: String(res),
97848
+ inviterOrgName: org?.name ?? "",
97849
+ siteName,
97850
+ subcontract: sender === "subcontract"
97851
+ }).catch(() => void 0);
97267
97852
  return res;
97268
97853
  }
97269
97854
  await useServiceProviderInviteService().notifyProvider({
@@ -97537,7 +98122,7 @@ function useVerificationServiceV2() {
97537
98122
  const user = await _getUserById(userId).catch(() => null);
97538
98123
  const email = user?.email;
97539
98124
  if (!email) {
97540
- throw new UnauthorizedError24("Not authorized.");
98125
+ throw new UnauthorizedError25("Not authorized.");
97541
98126
  }
97542
98127
  return email;
97543
98128
  }
@@ -97575,7 +98160,7 @@ function useVerificationServiceV2() {
97575
98160
  throw new NotFoundError88("Invitation not found.");
97576
98161
  }
97577
98162
  if (invite.email.toLowerCase() !== email.toLowerCase()) {
97578
- throw new UnauthorizedError24("Not authorized.");
98163
+ throw new UnauthorizedError25("Not authorized.");
97579
98164
  }
97580
98165
  await _setOnboardingById({
97581
98166
  _id: inviteId,
@@ -98278,7 +98863,7 @@ function useServiceProviderInviteController() {
98278
98863
  }).validate(req.body ?? {});
98279
98864
  if (error) {
98280
98865
  throw new BadRequestError244(
98281
- "Give a reason for not approving this invitation. The property manager will see it."
98866
+ "Give a reason for not approving this invitation. Whoever sent it will see it."
98282
98867
  );
98283
98868
  }
98284
98869
  res.json(
@@ -101548,7 +102133,7 @@ import Joi164 from "joi";
101548
102133
  import { ObjectId as ObjectId194 } from "mongodb";
101549
102134
  import {
101550
102135
  InternalServerError as InternalServerError97,
101551
- UnauthorizedError as UnauthorizedError25,
102136
+ UnauthorizedError as UnauthorizedError26,
101552
102137
  useAtlas as useAtlas155
101553
102138
  } from "@7365admin1/node-server-utils";
101554
102139
  function db() {
@@ -101564,7 +102149,7 @@ function asObjectId(value) {
101564
102149
  function requireCaller(req) {
101565
102150
  const id = callerId(req);
101566
102151
  if (!id || !ObjectId194.isValid(id)) {
101567
- throw new UnauthorizedError25("Not authorized.");
102152
+ throw new UnauthorizedError26("Not authorized.");
101568
102153
  }
101569
102154
  return id;
101570
102155
  }
@@ -101572,7 +102157,7 @@ function requireSelfId(req, claimed) {
101572
102157
  const caller = requireCaller(req);
101573
102158
  const asked = claimed?.toString?.() ?? "";
101574
102159
  if (!asked || asked !== caller) {
101575
- throw new UnauthorizedError25("Not authorized.");
102160
+ throw new UnauthorizedError26("Not authorized.");
101576
102161
  }
101577
102162
  return caller;
101578
102163
  }
@@ -101580,11 +102165,11 @@ async function requireOwnChannel(req, channelId) {
101580
102165
  const caller = requireCaller(req);
101581
102166
  const _id = asObjectId(channelId);
101582
102167
  if (!_id)
101583
- throw new UnauthorizedError25("Not authorized.");
102168
+ throw new UnauthorizedError26("Not authorized.");
101584
102169
  const channel = await db().collection("channel-preloved").findOne({ _id }, { projection: { senderId: 1, receiverId: 1, postId: 1 } });
101585
102170
  const participants = [channel?.senderId, channel?.receiverId].map((id) => id?.toString?.() ?? "").filter(Boolean);
101586
102171
  if (!channel || !participants.includes(caller)) {
101587
- throw new UnauthorizedError25("Not authorized.");
102172
+ throw new UnauthorizedError26("Not authorized.");
101588
102173
  }
101589
102174
  return { caller, channel };
101590
102175
  }
@@ -101592,10 +102177,10 @@ async function requireOwnChatMessage(req, chatId) {
101592
102177
  const caller = requireCaller(req);
101593
102178
  const _id = asObjectId(chatId);
101594
102179
  if (!_id)
101595
- throw new UnauthorizedError25("Not authorized.");
102180
+ throw new UnauthorizedError26("Not authorized.");
101596
102181
  const message = await db().collection("chat-preloved").findOne({ _id }, { projection: { senderId: 1 } });
101597
102182
  if (!message || message.senderId?.toString?.() !== caller) {
101598
- throw new UnauthorizedError25("Not authorized.");
102183
+ throw new UnauthorizedError26("Not authorized.");
101599
102184
  }
101600
102185
  return caller;
101601
102186
  }
@@ -102021,7 +102606,7 @@ function useBidPrelovedService() {
102021
102606
  // src/controllers/bid-preloved.controller.ts
102022
102607
  import {
102023
102608
  BadRequestError as BadRequestError263,
102024
- UnauthorizedError as UnauthorizedError26,
102609
+ UnauthorizedError as UnauthorizedError27,
102025
102610
  logger as logger227
102026
102611
  } from "@7365admin1/node-server-utils";
102027
102612
  import Joi167 from "joi";
@@ -102073,7 +102658,7 @@ function useBidPrelovedController() {
102073
102658
  const bid = await _getById(params.id);
102074
102659
  const seller = await sellerOfPost(bid?.postId);
102075
102660
  if (!seller || seller !== caller) {
102076
- throw new UnauthorizedError26("Not authorized.");
102661
+ throw new UnauthorizedError27("Not authorized.");
102077
102662
  }
102078
102663
  const data = await _updateStatus(params.id, body.status);
102079
102664
  res.status(200).json(data);
@@ -102097,7 +102682,7 @@ function useBidPrelovedController() {
102097
102682
  const data = await _getById(params.id);
102098
102683
  const seller = await sellerOfPost(data?.postId);
102099
102684
  if (data?.buyerId?.toString?.() !== caller && seller !== caller) {
102100
- throw new UnauthorizedError26("Not authorized.");
102685
+ throw new UnauthorizedError27("Not authorized.");
102101
102686
  }
102102
102687
  res.status(200).json(data);
102103
102688
  } catch (error2) {
@@ -102495,11 +103080,11 @@ function useFormEntryRepo() {
102495
103080
  import {
102496
103081
  BadRequestError as BadRequestError265,
102497
103082
  NotFoundError as NotFoundError97,
102498
- UnauthorizedError as UnauthorizedError27,
103083
+ UnauthorizedError as UnauthorizedError28,
102499
103084
  logger as logger229
102500
103085
  } from "@7365admin1/node-server-utils";
102501
103086
  import Joi169 from "joi";
102502
- import ExcelJS3 from "exceljs";
103087
+ import ExcelJS4 from "exceljs";
102503
103088
  import fs6 from "fs";
102504
103089
  function useFormEntryController() {
102505
103090
  const {
@@ -102537,7 +103122,7 @@ function useFormEntryController() {
102537
103122
  next(new BadRequestError265("Excel file is required."));
102538
103123
  return;
102539
103124
  }
102540
- const workbook = new ExcelJS3.Workbook();
103125
+ const workbook = new ExcelJS4.Workbook();
102541
103126
  await workbook.xlsx.readFile(req.file.path);
102542
103127
  const worksheet = workbook.worksheets[0];
102543
103128
  if (!worksheet) {
@@ -102605,7 +103190,7 @@ function useFormEntryController() {
102605
103190
  } else {
102606
103191
  const { actor } = await siteReachOf(req);
102607
103192
  if (!actor.isSuperAdmin)
102608
- throw new UnauthorizedError27("Not authorized.");
103193
+ throw new UnauthorizedError28("Not authorized.");
102609
103194
  }
102610
103195
  const data = await _getAll({ search, page: page2, limit, status, org, site });
102611
103196
  res.json(data);
@@ -102656,7 +103241,7 @@ function useFormEntryController() {
102656
103241
  await requireSiteReach(req, rest.site);
102657
103242
  delete rest.userId;
102658
103243
  if (isOwner && rest.status && rest.status !== "pending") {
102659
- throw new UnauthorizedError27("Not authorized.");
103244
+ throw new UnauthorizedError28("Not authorized.");
102660
103245
  }
102661
103246
  await _updateFormEntryById(_id, rest);
102662
103247
  res.json({ message: "Successfully updated online form." });
@@ -102713,7 +103298,7 @@ function useFormEntryController() {
102713
103298
  async function residentFormSubmission(req, res, next) {
102714
103299
  const userId = callerId(req);
102715
103300
  if (!userId) {
102716
- next(new UnauthorizedError27("Not authorized."));
103301
+ next(new UnauthorizedError28("Not authorized."));
102717
103302
  return;
102718
103303
  }
102719
103304
  const payload = { ...req.body, userId };
@@ -103944,7 +104529,7 @@ function useHidAmicoController() {
103944
104529
  import {
103945
104530
  BadRequestError as BadRequestError268,
103946
104531
  logger as logger231,
103947
- UnauthorizedError as UnauthorizedError28
104532
+ UnauthorizedError as UnauthorizedError29
103948
104533
  } from "@7365admin1/node-server-utils";
103949
104534
  import Joi171 from "joi";
103950
104535
  function usePlatformTermsController() {
@@ -103960,7 +104545,7 @@ function usePlatformTermsController() {
103960
104545
  async function requireOwnRecord(req, user, { staffMayRead = false } = {}) {
103961
104546
  const id = callerId(req);
103962
104547
  if (!id) {
103963
- throw new UnauthorizedError28("Not authorized.");
104548
+ throw new UnauthorizedError29("Not authorized.");
103964
104549
  }
103965
104550
  if (id === user) {
103966
104551
  return id;
@@ -103968,7 +104553,7 @@ function usePlatformTermsController() {
103968
104553
  if (staffMayRead) {
103969
104554
  return await requireConsolePermission(req, "platform-terms", "see-platform-terms");
103970
104555
  }
103971
- throw new UnauthorizedError28("Not authorized.");
104556
+ throw new UnauthorizedError29("Not authorized.");
103972
104557
  }
103973
104558
  async function getLatest(_req, res, next) {
103974
104559
  try {
@@ -104177,7 +104762,7 @@ function useConsoleAuditController() {
104177
104762
  // src/controllers/notification.controller.ts
104178
104763
  import {
104179
104764
  BadRequestError as BadRequestError270,
104180
- UnauthorizedError as UnauthorizedError29,
104765
+ UnauthorizedError as UnauthorizedError30,
104181
104766
  logger as logger233
104182
104767
  } from "@7365admin1/node-server-utils";
104183
104768
  function useNotificationController() {
@@ -104195,10 +104780,10 @@ function useNotificationController() {
104195
104780
  function inboxOwner(req, claimed) {
104196
104781
  const caller = callerId5(req);
104197
104782
  if (!caller) {
104198
- throw new UnauthorizedError29("Not authorized.");
104783
+ throw new UnauthorizedError30("Not authorized.");
104199
104784
  }
104200
104785
  if (claimed && claimed !== caller) {
104201
- throw new UnauthorizedError29("Not authorized.");
104786
+ throw new UnauthorizedError30("Not authorized.");
104202
104787
  }
104203
104788
  return caller;
104204
104789
  }
@@ -104210,7 +104795,7 @@ function useNotificationController() {
104210
104795
  }
104211
104796
  try {
104212
104797
  if (!await isSuperAdmin(callerId5(req))) {
104213
- throw new UnauthorizedError29("Not authorized.");
104798
+ throw new UnauthorizedError30("Not authorized.");
104214
104799
  }
104215
104800
  const inserted = await _addMany(value.to, {
104216
104801
  title: value.title,
@@ -105254,8 +105839,11 @@ export {
105254
105839
  SERVICE_PROVIDER_SIGN_IN_TYPE,
105255
105840
  SERVICE_PROVIDER_SIGN_UP_SUBJECT,
105256
105841
  SERVICE_PROVIDER_SIGN_UP_TYPE,
105842
+ SERVICE_TYPE_LABELS,
105257
105843
  SITE_STATES_MAX,
105258
105844
  SOFTWARE_VERSION_ENDPOINT,
105845
+ SUBCONTRACT_ADMIN_REFUSAL,
105846
+ SUBCONTRACT_SITE_REFUSAL,
105259
105847
  SiteCategories,
105260
105848
  SiteStatus,
105261
105849
  SortFields,
@@ -105302,6 +105890,7 @@ export {
105302
105890
  applyTrackingFrame,
105303
105891
  areaColourToHex,
105304
105892
  asList,
105893
+ assertServiceProviderInviteScope,
105305
105894
  attendanceSchema,
105306
105895
  attendanceSettingsSchema,
105307
105896
  buildSelfServiceEmailContext,
@@ -105415,6 +106004,7 @@ export {
105415
106004
  ffmpegFrameArgs,
105416
106005
  ffmpegPath,
105417
106006
  filterByAccess,
106007
+ filterSiteProviderMembers,
105418
106008
  fleetStateItem,
105419
106009
  floorNoOf,
105420
106010
  floorPlanBodySchema,
@@ -105804,7 +106394,10 @@ export {
105804
106394
  sendNotificationEmails,
105805
106395
  servesFloor,
105806
106396
  serviceProviderInviteLabel,
106397
+ serviceProviderInviteScope,
105807
106398
  serviceProviderInviteViewStatus,
106399
+ serviceProviderInviterKind,
106400
+ serviceTypeLabel,
105808
106401
  sessionSchema,
105809
106402
  setIO,
105810
106403
  sha256Hex,