@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.js CHANGED
@@ -332,8 +332,11 @@ __export(src_exports, {
332
332
  SERVICE_PROVIDER_SIGN_IN_TYPE: () => SERVICE_PROVIDER_SIGN_IN_TYPE,
333
333
  SERVICE_PROVIDER_SIGN_UP_SUBJECT: () => SERVICE_PROVIDER_SIGN_UP_SUBJECT,
334
334
  SERVICE_PROVIDER_SIGN_UP_TYPE: () => SERVICE_PROVIDER_SIGN_UP_TYPE,
335
+ SERVICE_TYPE_LABELS: () => SERVICE_TYPE_LABELS,
335
336
  SITE_STATES_MAX: () => SITE_STATES_MAX,
336
337
  SOFTWARE_VERSION_ENDPOINT: () => SOFTWARE_VERSION_ENDPOINT,
338
+ SUBCONTRACT_ADMIN_REFUSAL: () => SUBCONTRACT_ADMIN_REFUSAL,
339
+ SUBCONTRACT_SITE_REFUSAL: () => SUBCONTRACT_SITE_REFUSAL,
337
340
  SiteCategories: () => SiteCategories,
338
341
  SiteStatus: () => SiteStatus,
339
342
  SortFields: () => SortFields,
@@ -380,6 +383,7 @@ __export(src_exports, {
380
383
  applyTrackingFrame: () => applyTrackingFrame,
381
384
  areaColourToHex: () => areaColourToHex,
382
385
  asList: () => asList,
386
+ assertServiceProviderInviteScope: () => assertServiceProviderInviteScope,
383
387
  attendanceSchema: () => attendanceSchema,
384
388
  attendanceSettingsSchema: () => attendanceSettingsSchema,
385
389
  buildSelfServiceEmailContext: () => buildSelfServiceEmailContext,
@@ -493,6 +497,7 @@ __export(src_exports, {
493
497
  ffmpegFrameArgs: () => ffmpegFrameArgs,
494
498
  ffmpegPath: () => ffmpegPath,
495
499
  filterByAccess: () => filterByAccess,
500
+ filterSiteProviderMembers: () => filterSiteProviderMembers,
496
501
  fleetStateItem: () => fleetStateItem,
497
502
  floorNoOf: () => floorNoOf,
498
503
  floorPlanBodySchema: () => floorPlanBodySchema,
@@ -882,7 +887,10 @@ __export(src_exports, {
882
887
  sendNotificationEmails: () => sendNotificationEmails,
883
888
  servesFloor: () => servesFloor,
884
889
  serviceProviderInviteLabel: () => serviceProviderInviteLabel,
890
+ serviceProviderInviteScope: () => serviceProviderInviteScope,
885
891
  serviceProviderInviteViewStatus: () => serviceProviderInviteViewStatus,
892
+ serviceProviderInviterKind: () => serviceProviderInviterKind,
893
+ serviceTypeLabel: () => serviceTypeLabel,
886
894
  sessionSchema: () => sessionSchema,
887
895
  setIO: () => setIO,
888
896
  sha256Hex: () => sha256Hex,
@@ -9467,7 +9475,9 @@ function decideServiceProviderInvite(facts) {
9467
9475
  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."
9468
9476
  };
9469
9477
  }
9470
- const requiresApproval = Boolean(facts.inviterIsPropertyManagement);
9478
+ const requiresApproval = Boolean(
9479
+ facts.inviterIsPropertyManagement || facts.inviterIsServiceProvider
9480
+ );
9471
9481
  if (facts.hasProviderOrg) {
9472
9482
  return {
9473
9483
  ok: true,
@@ -9491,6 +9501,31 @@ function decideServiceProviderInvite(facts) {
9491
9501
  requiresApproval
9492
9502
  };
9493
9503
  }
9504
+ var SUBCONTRACT_SITE_REFUSAL = "You can only invite service providers for sites your company works on.";
9505
+ var SUBCONTRACT_ADMIN_REFUSAL = "Only your company's owner or an administrator can invite other service providers.";
9506
+ function serviceProviderInviteScope(facts) {
9507
+ if (facts.isStaff)
9508
+ return { ok: true, sender: "staff" };
9509
+ if (!facts.callerInInviterOrg) {
9510
+ return {
9511
+ ok: false,
9512
+ reason: "You can only invite service providers to your own organisation's sites."
9513
+ };
9514
+ }
9515
+ if (facts.siteOwnerOrg && facts.siteOwnerOrg === facts.inviterOrg) {
9516
+ return { ok: true, sender: "client" };
9517
+ }
9518
+ if (!facts.inviterEngagedOnSite) {
9519
+ return { ok: false, reason: SUBCONTRACT_SITE_REFUSAL };
9520
+ }
9521
+ if (!facts.callerRunsInviterOrg) {
9522
+ return { ok: false, reason: SUBCONTRACT_ADMIN_REFUSAL };
9523
+ }
9524
+ return { ok: true, sender: "subcontract" };
9525
+ }
9526
+ function serviceProviderInviterKind(inviterOrg, siteOwnerOrg) {
9527
+ return inviterOrg && siteOwnerOrg && inviterOrg !== siteOwnerOrg ? "service-provider" : "property-management";
9528
+ }
9494
9529
  var SERVICE_PROVIDER_INVITE_TRANSITIONS = {
9495
9530
  approve: { from: ["awaiting-approval"], to: "pending" },
9496
9531
  reject: { from: ["awaiting-approval"], to: "rejected" },
@@ -9570,6 +9605,27 @@ var RECEIVED_INVITE_LABELS = {
9570
9605
  expired: "Expired",
9571
9606
  cancelled: "Withdrawn by the client"
9572
9607
  };
9608
+ var SERVICE_TYPE_LABELS = {
9609
+ security_agency: "Security",
9610
+ cleaning_services: "Cleaning",
9611
+ mechanical_electrical_services: "Mechanical & Electrical",
9612
+ landscaping_services: "Landscaping",
9613
+ pest_control_services: "Pest Control",
9614
+ pool_maintenance_services: "Pool Maintenance",
9615
+ property_management_agency: "Property Management"
9616
+ };
9617
+ function serviceTypeLabel(code) {
9618
+ const key = String(code ?? "").trim();
9619
+ if (!key)
9620
+ return "Other";
9621
+ return SERVICE_TYPE_LABELS[key] ?? key.replace(/_/g, " ");
9622
+ }
9623
+ function filterSiteProviderMembers(items, { type = "", company = "", search = "" }) {
9624
+ const needle = search.trim().toLowerCase();
9625
+ return items.filter(
9626
+ (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)))
9627
+ );
9628
+ }
9573
9629
 
9574
9630
  // src/utils/invite-actor.util.ts
9575
9631
  var import_node_server_utils28 = require("@7365admin1/node-server-utils");
@@ -12506,6 +12562,30 @@ var NotificationService = class {
12506
12562
  "platform"
12507
12563
  );
12508
12564
  }
12565
+ /**
12566
+ * A service-provider invitation is waiting in SP Approvals. Seven365 staff
12567
+ * only - the provider is still told nothing. Names who sent it (a property
12568
+ * manager, or a provider bringing in a subcontractor) and for which site.
12569
+ */
12570
+ static async serviceProviderInviteAwaitingApproval(payload) {
12571
+ const staff = await staffRecipients();
12572
+ if (!staff.length)
12573
+ return;
12574
+ await send(
12575
+ staff,
12576
+ "Service provider invitation to approve",
12577
+ 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}.`,
12578
+ {
12579
+ module: "platform",
12580
+ kind: "spApproval",
12581
+ screen: "",
12582
+ params: { id: payload.invitationId.toString() }
12583
+ },
12584
+ false,
12585
+ void 0,
12586
+ "platform"
12587
+ );
12588
+ }
12509
12589
  static async clientInvitationAccepted(payload) {
12510
12590
  const staff = await staffRecipients();
12511
12591
  if (!staff.length)
@@ -13874,6 +13954,13 @@ function useCustomerSiteService() {
13874
13954
  getServiceProviderInviteById: _getInviteFresh,
13875
13955
  transitionServiceProviderInvite: _transitionInvite
13876
13956
  } = useVerificationRepoV2();
13957
+ async function siteOwnerOf(site, senderOrg, senderName) {
13958
+ const owner = String(site?.orgId ?? site?.org ?? "") || senderOrg;
13959
+ if (owner === senderOrg)
13960
+ return { siteOrg: senderOrg, siteOrgName: senderName };
13961
+ const ownerOrg = await _getByOrgId(owner).catch(() => null);
13962
+ return { siteOrg: owner, siteOrgName: ownerOrg?.name ?? "" };
13963
+ }
13877
13964
  async function addViaInvite(invite, actor, forOrgId) {
13878
13965
  const session = import_node_server_utils42.useAtlas.getClient()?.startSession();
13879
13966
  session?.startTransaction();
@@ -13882,6 +13969,9 @@ function useCustomerSiteService() {
13882
13969
  if (!verification) {
13883
13970
  throw new import_node_server_utils42.NotFoundError("Invite not found.");
13884
13971
  }
13972
+ if (!(verification.history?.length > 0)) {
13973
+ throw new import_node_server_utils42.NotFoundError("Invite not found.");
13974
+ }
13885
13975
  const siteId = verification.metadata?.siteId?.toString() ?? "";
13886
13976
  if (!siteId) {
13887
13977
  throw new import_node_server_utils42.BadRequestError("Invalid invite, missing site ID.");
@@ -13945,6 +14035,12 @@ function useCustomerSiteService() {
13945
14035
  verification.status === "complete" ? "This invitation has already been used." : "This invitation is no longer valid. Ask for a new one."
13946
14036
  );
13947
14037
  }
14038
+ const owner = String(site?.orgId ?? site?.org ?? "");
14039
+ if (owner && owner !== orgId && await _countActiveByOrgAndSite(orgId, siteId) < 1) {
14040
+ throw new import_node_server_utils42.BadRequestError(
14041
+ "This invitation is no longer valid. Ask for a new one."
14042
+ );
14043
+ }
13948
14044
  if (!serviceProvider.defaultSite) {
13949
14045
  const updateOrgField = await _updateFieldById(
13950
14046
  {
@@ -13980,8 +14076,10 @@ function useCustomerSiteService() {
13980
14076
  {
13981
14077
  name: site.name,
13982
14078
  site: siteId,
13983
- siteOrg: orgId,
13984
- siteOrgName: org.name,
14079
+ // The site's OWNER, not the sender: a provider that brought in a
14080
+ // subcontractor sent this invitation, but the site is still its
14081
+ // client's, and every reader of `siteOrg` means the owner.
14082
+ ...await siteOwnerOf(site, orgId, org.name),
13985
14083
  org: providerOrgId
13986
14084
  },
13987
14085
  session
@@ -14078,8 +14176,7 @@ function useCustomerSiteService() {
14078
14176
  {
14079
14177
  name: site.name,
14080
14178
  site: siteId,
14081
- siteOrg: orgId,
14082
- siteOrgName: org.name,
14179
+ ...await siteOwnerOf(site, orgId, org.name),
14083
14180
  org: forOrgId
14084
14181
  },
14085
14182
  session
@@ -15239,6 +15336,50 @@ function isPreCheckInStatusOnly(status) {
15239
15336
  return requested.length > 0 && requested.every((s) => PRE_CHECK_IN_STATUSES.includes(s));
15240
15337
  }
15241
15338
 
15339
+ // src/utils/visitor-search.util.ts
15340
+ var VISITOR_SEARCH_MAX_LENGTH = 100;
15341
+ var MIN_PHONE_DIGITS = 3;
15342
+ var MIN_PLATE_CHARS = 2;
15343
+ function escapeRegex2(value) {
15344
+ return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15345
+ }
15346
+ function normaliseVisitorSearch(raw) {
15347
+ if (typeof raw !== "string")
15348
+ return "";
15349
+ return raw.replace(/\s+/g, " ").trim().slice(0, VISITOR_SEARCH_MAX_LENGTH);
15350
+ }
15351
+ function looseSequence(chars, gap) {
15352
+ return chars.map(escapeRegex2).join(gap);
15353
+ }
15354
+ function visitorRowSearchOr(raw) {
15355
+ const q = normaliseVisitorSearch(raw);
15356
+ if (!q)
15357
+ return [];
15358
+ const contains = { $regex: escapeRegex2(q), $options: "i" };
15359
+ const or = [
15360
+ { name: contains },
15361
+ { company: contains },
15362
+ { purpose: contains },
15363
+ { nric: contains },
15364
+ { contractorType: contains },
15365
+ { deliveryType: contains },
15366
+ { unitName: contains },
15367
+ { "members.name": contains },
15368
+ { "members.nric": contains }
15369
+ ];
15370
+ const plateChars = q.replace(/[^A-Za-z0-9]/g, "").split("");
15371
+ if (plateChars.length >= MIN_PLATE_CHARS) {
15372
+ const plate = { $regex: looseSequence(plateChars, "[\\s-]*"), $options: "i" };
15373
+ or.push({ plateNumber: plate }, { "members.plateNumber": plate });
15374
+ }
15375
+ const digits = q.replace(/\D/g, "").split("");
15376
+ if (/^[+\d\s()-]+$/.test(q) && digits.length >= MIN_PHONE_DIGITS) {
15377
+ const phone = { $regex: looseSequence(digits, "\\D*") };
15378
+ or.push({ contact: phone }, { "members.contact": phone });
15379
+ }
15380
+ return or;
15381
+ }
15382
+
15242
15383
  // src/repositories/visitor-transaction.repo.ts
15243
15384
  var visitors_namespace_collection = "visitor.transactions";
15244
15385
  function useVisitorTransactionRepo() {
@@ -15247,6 +15388,113 @@ function useVisitorTransactionRepo() {
15247
15388
  throw new import_node_server_utils46.InternalServerError("Unable to connect to server.");
15248
15389
  }
15249
15390
  const collection = db2.collection(visitors_namespace_collection);
15391
+ function buildSearchStages(search) {
15392
+ const text2 = normaliseVisitorSearch(search);
15393
+ if (!text2)
15394
+ return [];
15395
+ const escape = escapeRegex2;
15396
+ const like = (value) => ({ $regex: escape(value), $options: "i" });
15397
+ const exact = (value) => ({
15398
+ $regex: `^${escape(value)}$`,
15399
+ $options: "i"
15400
+ });
15401
+ const blockName = (value) => ({
15402
+ $regex: `(^|\\s)${escape(value)}$`,
15403
+ $options: "i"
15404
+ });
15405
+ const nameLookup = (from, localField, as) => ({
15406
+ $lookup: {
15407
+ from,
15408
+ localField,
15409
+ foreignField: "_id",
15410
+ pipeline: [{ $project: { _id: 0, name: 1 } }],
15411
+ as
15412
+ }
15413
+ });
15414
+ const keyNameLookup = (localField, as) => ({
15415
+ $lookup: {
15416
+ from: "keys",
15417
+ localField,
15418
+ foreignField: "_id",
15419
+ pipeline: [
15420
+ {
15421
+ $lookup: {
15422
+ from: "qr-code-templates",
15423
+ localField: "template",
15424
+ foreignField: "_id",
15425
+ pipeline: [{ $project: { prefixPass: 1 } }],
15426
+ as: "template"
15427
+ }
15428
+ },
15429
+ {
15430
+ $project: {
15431
+ _id: 0,
15432
+ prefixAndName: {
15433
+ $concat: [
15434
+ { $ifNull: [{ $arrayElemAt: ["$template.prefixPass", 0] }, ""] },
15435
+ { $ifNull: ["$name", ""] }
15436
+ ]
15437
+ }
15438
+ }
15439
+ }
15440
+ ],
15441
+ as
15442
+ }
15443
+ });
15444
+ const locationLookups = [
15445
+ nameLookup("buildings", "block", "_searchBlock"),
15446
+ nameLookup("building-levels", "level", "_searchLevel"),
15447
+ nameLookup("building-units", "unit", "_searchUnit")
15448
+ ];
15449
+ const cleanup = {
15450
+ $project: {
15451
+ _searchBlock: 0,
15452
+ _searchLevel: 0,
15453
+ _searchUnit: 0,
15454
+ _searchPass: 0,
15455
+ _searchKeys: 0
15456
+ }
15457
+ };
15458
+ const unitMatch = (value, match = like) => ({
15459
+ $or: [{ "_searchUnit.name": match(value) }, { unitName: match(value) }]
15460
+ });
15461
+ const parts = text2.split("/").map((part) => part.trim());
15462
+ if (parts.length >= 2 && parts.length <= 3 && parts.every(Boolean)) {
15463
+ const [block, level2, unit] = parts;
15464
+ return [
15465
+ ...locationLookups,
15466
+ {
15467
+ $match: {
15468
+ "_searchBlock.name": blockName(block),
15469
+ "_searchLevel.name": exact(level2),
15470
+ ...unit && unitMatch(unit, exact)
15471
+ }
15472
+ },
15473
+ cleanup
15474
+ ];
15475
+ }
15476
+ const compact = text2.replace(/\s+/g, "");
15477
+ return [
15478
+ ...locationLookups,
15479
+ keyNameLookup("visitorPass.keyId", "_searchPass"),
15480
+ keyNameLookup("passKeys.keyId", "_searchKeys"),
15481
+ {
15482
+ $match: {
15483
+ $or: [
15484
+ // name, company, purpose, NRIC, types, members; plates ignoring
15485
+ // spaces/hyphens/case; phones by digits - visitor-search.util.
15486
+ ...visitorRowSearchOr(text2),
15487
+ { "_searchBlock.name": like(text2) },
15488
+ { "_searchLevel.name": like(text2) },
15489
+ unitMatch(text2),
15490
+ { "_searchPass.prefixAndName": like(compact) },
15491
+ { "_searchKeys.prefixAndName": like(compact) }
15492
+ ]
15493
+ }
15494
+ },
15495
+ cleanup
15496
+ ];
15497
+ }
15250
15498
  async function createTextIndex() {
15251
15499
  try {
15252
15500
  await collection.createIndex({
@@ -15342,9 +15590,6 @@ function useVisitorTransactionRepo() {
15342
15590
  },
15343
15591
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
15344
15592
  ...checkedOut == false && { checkOut: { $eq: null } },
15345
- ...search && {
15346
- $or: [{ name: { $regex: search, $options: "i" } }]
15347
- },
15348
15593
  ...plateNumber && { plateNumber },
15349
15594
  ...Array.isArray(status) ? { status: { $in: status } } : status ? { status } : {},
15350
15595
  ...tab == "Overnight Parking" && { isOvernightParking: true },
@@ -15355,6 +15600,7 @@ function useVisitorTransactionRepo() {
15355
15600
  try {
15356
15601
  const basePipeline = [
15357
15602
  { $match: query2 },
15603
+ ...buildSearchStages(search),
15358
15604
  {
15359
15605
  $addFields: {
15360
15606
  latestDate: { $max: ["$createdAt", "$updatedAt"] }
@@ -16695,7 +16941,7 @@ function useVehicleRepo() {
16695
16941
  let query2 = { ...baseQuery };
16696
16942
  if (search)
16697
16943
  query2.$text = { $search: search };
16698
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16944
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16699
16945
  const buildGroupedPipeline = (matchQuery) => [
16700
16946
  { $match: matchQuery },
16701
16947
  {
@@ -16879,7 +17125,7 @@ function useVehicleRepo() {
16879
17125
  const countResult = await collection.aggregate(buildGroupedCountPipeline(query2)).toArray();
16880
17126
  length = countResult[0]?.total || 0;
16881
17127
  if ((!items || items.length === 0) && search) {
16882
- const escaped = escapeRegex3(search);
17128
+ const escaped = escapeRegex4(search);
16883
17129
  const regexQuery = {
16884
17130
  ...baseQuery,
16885
17131
  $or: [
@@ -17668,7 +17914,7 @@ function useVehicleRepo() {
17668
17914
  ...baseQuery,
17669
17915
  ...search && { $text: { $search: search } }
17670
17916
  };
17671
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17917
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17672
17918
  const buildPipeline = (matchQuery) => [
17673
17919
  { $match: matchQuery },
17674
17920
  {
@@ -17696,7 +17942,7 @@ function useVehicleRepo() {
17696
17942
  const countResult = await collection.aggregate(buildCountPipeline(query2)).toArray();
17697
17943
  length = countResult[0]?.total || 0;
17698
17944
  if ((!items || items.length === 0) && search) {
17699
- const escaped = escapeRegex3(search);
17945
+ const escaped = escapeRegex4(search);
17700
17946
  const regexQuery = {
17701
17947
  ...baseQuery,
17702
17948
  $or: [
@@ -23142,6 +23388,28 @@ async function requireRoleAssigner(req, orgId) {
23142
23388
 
23143
23389
  // src/services/service-provider-invite.service.ts
23144
23390
  var INVITE_VALID_HOURS = 72;
23391
+ async function assertServiceProviderInviteScope(actor, orgId, siteId) {
23392
+ const site = await useSiteRepo().getSiteById(siteId);
23393
+ const siteOwnerOrg = String(site?.orgId ?? site?.org ?? "");
23394
+ const isStaff = staffMayBypass(actor);
23395
+ const callerInInviterOrg = actor.orgIds.includes(orgId);
23396
+ const owns = siteOwnerOrg !== "" && siteOwnerOrg === orgId;
23397
+ const inviterEngagedOnSite = !isStaff && callerInInviterOrg && !owns ? await useCustomerSiteRepo().countActiveByOrgAndSite(orgId, siteId).catch(() => 0) > 0 : false;
23398
+ const scope = serviceProviderInviteScope({
23399
+ isStaff,
23400
+ siteOwnerOrg,
23401
+ inviterOrg: orgId,
23402
+ callerInInviterOrg,
23403
+ inviterEngagedOnSite,
23404
+ // The same "runs this company" test Accept uses (`memberOrg`).
23405
+ callerRunsInviterOrg: actor.memberships.some(
23406
+ (m) => m.org === orgId && (m.companyWideRole === true || !m.siteId && m.orgLevelRole === true)
23407
+ )
23408
+ });
23409
+ if (!scope.ok)
23410
+ throw new import_node_server_utils57.UnauthorizedError(scope.reason);
23411
+ return { sender: scope.sender, siteOwnerOrg };
23412
+ }
23145
23413
  function useServiceProviderInviteService() {
23146
23414
  const mailer2 = new import_node_server_utils57.useMailer({
23147
23415
  host: MAILER_TRANSPORT_HOST,
@@ -23278,9 +23546,55 @@ function useServiceProviderInviteService() {
23278
23546
  });
23279
23547
  return {
23280
23548
  ...data,
23549
+ items: await withSender(data?.items ?? []),
23281
23550
  awaitingApprovalCount: await _countAwaiting()
23282
23551
  };
23283
23552
  }
23553
+ async function withSender(items) {
23554
+ const orgNames = /* @__PURE__ */ new Map();
23555
+ const owners = /* @__PURE__ */ new Map();
23556
+ const orgName = (id) => {
23557
+ if (!id)
23558
+ return Promise.resolve("");
23559
+ if (!orgNames.has(id)) {
23560
+ orgNames.set(
23561
+ id,
23562
+ getOrgById(id).then((o) => String(o?.name ?? "")).catch(() => "")
23563
+ );
23564
+ }
23565
+ return orgNames.get(id);
23566
+ };
23567
+ const ownerOf = (siteId) => {
23568
+ if (!siteId)
23569
+ return Promise.resolve("");
23570
+ if (!owners.has(siteId)) {
23571
+ owners.set(
23572
+ siteId,
23573
+ useSiteRepo().getSiteById(siteId).then((s) => String(s?.orgId ?? s?.org ?? "")).catch(() => "")
23574
+ );
23575
+ }
23576
+ return owners.get(siteId);
23577
+ };
23578
+ return Promise.all(
23579
+ items.map(async (invite) => {
23580
+ const inviterOrg = inviteOrgId(invite);
23581
+ const siteOwnerOrg = await ownerOf(
23582
+ invite.metadata?.siteId?.toString?.() ?? ""
23583
+ );
23584
+ const [inviterOrgName, siteOwnerName] = await Promise.all([
23585
+ orgName(inviterOrg),
23586
+ siteOwnerOrg === inviterOrg ? orgName(inviterOrg) : orgName(siteOwnerOrg)
23587
+ ]);
23588
+ return {
23589
+ ...invite,
23590
+ inviterOrgName,
23591
+ inviterKind: serviceProviderInviterKind(inviterOrg, siteOwnerOrg),
23592
+ siteOwnerName,
23593
+ service: String(invite.metadata?.app ?? "")
23594
+ };
23595
+ })
23596
+ );
23597
+ }
23284
23598
  async function listForCaller({
23285
23599
  userId,
23286
23600
  orgId,
@@ -23433,7 +23747,7 @@ function useServiceProviderInviteService() {
23433
23747
  const trimmed = String(reason ?? "").trim();
23434
23748
  if (!trimmed) {
23435
23749
  throw new import_node_server_utils57.BadRequestError(
23436
- "Give a reason for not approving this invitation. The property manager will see it."
23750
+ "Give a reason for not approving this invitation. Whoever sent it will see it."
23437
23751
  );
23438
23752
  }
23439
23753
  const invite = await load(id);
@@ -23451,7 +23765,7 @@ function useServiceProviderInviteService() {
23451
23765
  if (!updated) {
23452
23766
  return { message: "This invitation has already been rejected." };
23453
23767
  }
23454
- return { message: "Invitation rejected. The property manager can see your reason." };
23768
+ return { message: "Invitation rejected. Whoever sent it can see your reason." };
23455
23769
  }
23456
23770
  async function cancel({ id, userId }) {
23457
23771
  const actor = await actorFor(userId);
@@ -24068,11 +24382,11 @@ function useVerificationService() {
24068
24382
  if (!actor.id) {
24069
24383
  throw new import_node_server_utils58.UnauthorizedError("Sign in to continue.");
24070
24384
  }
24071
- if (!staffMayBypass(actor) && !actor.orgIds.includes(orgId)) {
24072
- throw new import_node_server_utils58.UnauthorizedError(
24073
- "You can only invite service providers to your own organisation's sites."
24074
- );
24075
- }
24385
+ const { sender } = await assertServiceProviderInviteScope(
24386
+ actor,
24387
+ orgId,
24388
+ siteId
24389
+ );
24076
24390
  const invitedEmail = email.trim().toLowerCase();
24077
24391
  const [providerOrg, existingUser, pendingInvite] = await Promise.all([
24078
24392
  getOrgByEmail(invitedEmail),
@@ -24085,7 +24399,10 @@ function useVerificationService() {
24085
24399
  hasProviderOrg: Boolean(providerOrgId),
24086
24400
  engagedOnSite: providerOrgId ? await _countActiveEngagement(providerOrgId, siteId) > 0 : false,
24087
24401
  invitePending: Boolean(pendingInvite),
24088
- inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId)
24402
+ inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId),
24403
+ // A provider bringing in a subcontractor is held for Seven365
24404
+ // exactly like a property manager (owner request 2026-09-28).
24405
+ inviterIsServiceProvider: sender === "subcontract"
24089
24406
  });
24090
24407
  if (!decision.ok) {
24091
24408
  throw new import_node_server_utils58.BadRequestError(decision.reason);
@@ -24097,7 +24414,7 @@ function useVerificationService() {
24097
24414
  ...value.metadata,
24098
24415
  invitedBy: actor.id,
24099
24416
  invitedByName: actor.name,
24100
- invitedByPropertyManagement: decision.requiresApproval
24417
+ invitedByPropertyManagement: decision.requiresApproval && actor.propertyManagementOrgIds.includes(orgId)
24101
24418
  };
24102
24419
  value.history = [
24103
24420
  {
@@ -24109,6 +24426,12 @@ function useVerificationService() {
24109
24426
  ];
24110
24427
  const res = await _add(value);
24111
24428
  if (decision.requiresApproval) {
24429
+ NotificationService.serviceProviderInviteAwaitingApproval({
24430
+ invitationId: String(res),
24431
+ inviterOrgName: org?.name ?? "",
24432
+ siteName,
24433
+ subcontract: sender === "subcontract"
24434
+ }).catch(() => void 0);
24112
24435
  return res;
24113
24436
  }
24114
24437
  await useServiceProviderInviteService().notifyProvider({
@@ -34325,6 +34648,7 @@ function useServiceProviderRepo() {
34325
34648
  _id: "$org",
34326
34649
  engagementId: { $first: "$_id" },
34327
34650
  siteName: { $first: "$name" },
34651
+ siteOrg: { $first: "$siteOrg" },
34328
34652
  since: { $first: "$createdAt" }
34329
34653
  }
34330
34654
  },
@@ -34371,6 +34695,7 @@ function useServiceProviderRepo() {
34371
34695
  status: "active",
34372
34696
  category: "external",
34373
34697
  since: 1,
34698
+ siteOrg: 1,
34374
34699
  source: "engagement",
34375
34700
  members: {
34376
34701
  $ifNull: [{ $arrayElemAt: ["$_memberCount.c", 0] }, 0]
@@ -34400,7 +34725,70 @@ function useServiceProviderRepo() {
34400
34725
  )
34401
34726
  };
34402
34727
  }
34728
+ async function getProviderMembersBySite(site, orgIds) {
34729
+ try {
34730
+ site = new import_mongodb75.ObjectId(site);
34731
+ } catch {
34732
+ throw new import_node_server_utils99.BadRequestError("Invalid site ID format.");
34733
+ }
34734
+ const orgs = [];
34735
+ for (const o of orgIds) {
34736
+ if (!import_mongodb75.ObjectId.isValid(o))
34737
+ continue;
34738
+ orgs.push(new import_mongodb75.ObjectId(o), o);
34739
+ }
34740
+ if (!orgs.length)
34741
+ return [];
34742
+ return await db2.collection("members").aggregate([
34743
+ {
34744
+ $match: {
34745
+ org: { $in: orgs },
34746
+ siteId: { $in: [site, site.toString()] },
34747
+ status: { $nin: ["deleted"] },
34748
+ deletedAt: { $in: [null, ""] }
34749
+ }
34750
+ },
34751
+ { $sort: { _id: 1 } },
34752
+ { $limit: 1e3 },
34753
+ {
34754
+ $lookup: {
34755
+ from: "users",
34756
+ localField: "user",
34757
+ foreignField: "_id",
34758
+ as: "_user",
34759
+ pipeline: [{ $project: { email: 1, name: 1 } }]
34760
+ }
34761
+ },
34762
+ {
34763
+ $lookup: {
34764
+ from: "roles",
34765
+ localField: "role",
34766
+ foreignField: "_id",
34767
+ as: "_role",
34768
+ pipeline: [{ $project: { name: 1 } }]
34769
+ }
34770
+ },
34771
+ {
34772
+ $project: {
34773
+ _id: 1,
34774
+ user: 1,
34775
+ org: 1,
34776
+ type: 1,
34777
+ status: 1,
34778
+ createdAt: 1,
34779
+ name: {
34780
+ $ifNull: ["$name", { $arrayElemAt: ["$_user.name", 0] }]
34781
+ },
34782
+ email: {
34783
+ $ifNull: [{ $arrayElemAt: ["$_user.email", 0] }, "$email"]
34784
+ },
34785
+ roleName: { $ifNull: [{ $arrayElemAt: ["$_role.name", 0] }, ""] }
34786
+ }
34787
+ }
34788
+ ]).toArray();
34789
+ }
34403
34790
  return {
34791
+ getProviderMembersBySite,
34404
34792
  createTextIndex,
34405
34793
  createUniqueIndex,
34406
34794
  createServiceProvider,
@@ -35134,8 +35522,10 @@ function useServiceProviderService() {
35134
35522
  createServiceProvider: _createServiceProvider,
35135
35523
  getServiceProviders: _getServiceProviders,
35136
35524
  getEngagedProvidersBySite: _getEngaged,
35137
- getSiteProviderKeys: _getSiteProviderKeys
35525
+ getSiteProviderKeys: _getSiteProviderKeys,
35526
+ getProviderMembersBySite: _getProviderMembers
35138
35527
  } = useServiceProviderRepo();
35528
+ const { getServiceProviderInvites: _listInvites } = useVerificationRepoV2();
35139
35529
  const { getById: getOrgById, getByEmail: getOrgByEmail } = useOrgRepo();
35140
35530
  const { getSiteById } = useSiteRepo();
35141
35531
  const { getById: getVerificationById, updateStatusById } = useVerificationRepo();
@@ -35218,17 +35608,27 @@ function useServiceProviderService() {
35218
35608
  search = "",
35219
35609
  page: page2 = 1,
35220
35610
  limit = 10,
35221
- siteId
35611
+ siteId,
35612
+ invitedBy,
35613
+ storedOrgId = ""
35222
35614
  }) {
35223
- const [engaged, keys] = await Promise.all([
35615
+ const [engaged, keys, via] = await Promise.all([
35224
35616
  _getEngaged(siteId),
35225
- _getSiteProviderKeys(siteId)
35617
+ _getSiteProviderKeys(siteId),
35618
+ subcontractorsOf(siteId)
35226
35619
  ]);
35227
35620
  const needle = search.trim().toLowerCase();
35228
- const derived = engaged.filter(
35229
- (row) => !keys.orgIds.has(row.serviceProviderOrgId?.toString?.() ?? "") && !(row.email && keys.emails.has(String(row.email).trim().toLowerCase())) && (!needle || String(row.name ?? "").toLowerCase().includes(needle))
35621
+ const derived = engaged.map((row) => withVia(row, via)).filter(
35622
+ (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 ?? ""))
35230
35623
  );
35231
- const stored = (p, l) => _getServiceProviders({ search, page: p, limit: l, siteId, status: "active" });
35624
+ const stored = (p, l) => _getServiceProviders({
35625
+ search,
35626
+ page: p,
35627
+ limit: l,
35628
+ siteId,
35629
+ status: "active",
35630
+ ...storedOrgId ? { orgId: storedOrgId } : {}
35631
+ });
35232
35632
  if (!derived.length)
35233
35633
  return await stored(page2, limit);
35234
35634
  const start = (Math.max(page2, 1) - 1) * limit;
@@ -35240,6 +35640,103 @@ function useServiceProviderService() {
35240
35640
  const fromStored = need > 0 ? (first?.items ?? []).slice(storedStart, storedStart + need) : [];
35241
35641
  return (0, import_node_server_utils104.paginate)([...fromDerived, ...fromStored], Math.max(page2, 1) - 1, limit, total);
35242
35642
  }
35643
+ async function subcontractorsOf(siteId) {
35644
+ const via = /* @__PURE__ */ new Map();
35645
+ const data = await _listInvites({
35646
+ statuses: ["complete"],
35647
+ siteId,
35648
+ page: 1,
35649
+ limit: 200
35650
+ }).catch(() => null);
35651
+ const names = /* @__PURE__ */ new Map();
35652
+ for (const invite of data?.items ?? []) {
35653
+ const provider = invite.metadata?.providerOrg?.toString?.() ?? "";
35654
+ const sender = invite.metadata?.org?.toString?.() ?? "";
35655
+ if (!provider || !sender || via.has(provider))
35656
+ continue;
35657
+ if (!names.has(sender)) {
35658
+ names.set(
35659
+ sender,
35660
+ getOrgById(sender).then((o) => String(o?.name ?? "")).catch(() => "")
35661
+ );
35662
+ }
35663
+ via.set(provider, { orgId: sender, name: await names.get(sender) });
35664
+ }
35665
+ return via;
35666
+ }
35667
+ function withVia(row, via) {
35668
+ const provider = row.serviceProviderOrgId?.toString?.() ?? "";
35669
+ const owner = row.siteOrg?.toString?.() ?? "";
35670
+ const sender = via.get(provider);
35671
+ const { siteOrg: _siteOrg, ...rest } = row;
35672
+ if (!sender || !owner || sender.orgId === owner)
35673
+ return rest;
35674
+ return { ...rest, invitedViaOrgId: sender.orgId, invitedVia: sender.name };
35675
+ }
35676
+ async function getSiteProviderMembers({ siteId }) {
35677
+ const [engaged, storedRows, via] = await Promise.all([
35678
+ _getEngaged(siteId),
35679
+ _getServiceProviders({ siteId, status: "active", page: 1, limit: 200 }),
35680
+ subcontractorsOf(siteId)
35681
+ ]);
35682
+ const companies = /* @__PURE__ */ new Map();
35683
+ for (const row of engaged) {
35684
+ const id = row.serviceProviderOrgId?.toString?.() ?? "";
35685
+ if (!id)
35686
+ continue;
35687
+ const r = withVia(row, via);
35688
+ companies.set(id, {
35689
+ orgId: id,
35690
+ name: r.name ?? "",
35691
+ type: r.type ?? "",
35692
+ email: r.email ?? "",
35693
+ since: r.since ?? null,
35694
+ invitedVia: r.invitedVia ?? ""
35695
+ });
35696
+ }
35697
+ for (const row of storedRows?.items ?? []) {
35698
+ const id = row.serviceProviderOrgId?.toString?.() ?? "";
35699
+ if (!id || companies.has(id))
35700
+ continue;
35701
+ companies.set(id, {
35702
+ orgId: id,
35703
+ name: row.name ?? "",
35704
+ type: row.type ?? "",
35705
+ email: row.email ?? "",
35706
+ since: row.createdAt ?? null,
35707
+ invitedVia: ""
35708
+ });
35709
+ }
35710
+ const people = await _getProviderMembers(siteId, [...companies.keys()]);
35711
+ const counts = /* @__PURE__ */ new Map();
35712
+ const items = people.map((m) => {
35713
+ const orgId = m.org?.toString?.() ?? "";
35714
+ const company = companies.get(orgId) ?? {};
35715
+ counts.set(orgId, (counts.get(orgId) ?? 0) + 1);
35716
+ return {
35717
+ _id: m._id,
35718
+ name: m.name ?? "",
35719
+ email: m.email ?? "",
35720
+ companyId: orgId,
35721
+ company: company.name ?? "",
35722
+ // the company's line of business; the membership type as a fallback
35723
+ type: company.type || m.type || "",
35724
+ typeLabel: serviceTypeLabel(company.type || m.type),
35725
+ role: m.roleName ?? "",
35726
+ status: m.status ?? "active",
35727
+ addedAt: m.createdAt ?? null,
35728
+ invitedVia: company.invitedVia ?? ""
35729
+ };
35730
+ });
35731
+ return {
35732
+ items,
35733
+ companies: [...companies.values()].map((c) => ({
35734
+ ...c,
35735
+ typeLabel: serviceTypeLabel(c.type),
35736
+ people: counts.get(c.orgId) ?? 0
35737
+ })).sort((a, b) => String(a.name).localeCompare(String(b.name)))
35738
+ };
35739
+ }
35243
35740
  function totalOf(data) {
35244
35741
  const match = /of\s+(\d+)/.exec(String(data?.pageRange ?? ""));
35245
35742
  return match ? Number(match[1]) : (data?.items ?? []).length;
@@ -35247,11 +35744,13 @@ function useServiceProviderService() {
35247
35744
  return {
35248
35745
  createServiceProvider,
35249
35746
  getServiceProviders,
35250
- getServiceProvidersForSite
35747
+ getServiceProvidersForSite,
35748
+ getSiteProviderMembers
35251
35749
  };
35252
35750
  }
35253
35751
 
35254
35752
  // src/controllers/service-provider.controller.ts
35753
+ var import_exceljs = __toESM(require("exceljs"));
35255
35754
  function useServiceProviderController() {
35256
35755
  const {
35257
35756
  getServiceProviderNames: _getServiceProviderNames,
@@ -35264,7 +35763,8 @@ function useServiceProviderController() {
35264
35763
  } = useServiceProviderRepo();
35265
35764
  const {
35266
35765
  createServiceProvider: _createServiceProvider,
35267
- getServiceProvidersForSite: _getServiceProvidersForSite
35766
+ getServiceProvidersForSite: _getServiceProvidersForSite,
35767
+ getSiteProviderMembers: _getSiteProviderMembers
35268
35768
  } = useServiceProviderService();
35269
35769
  async function isSiteClient(req, siteId) {
35270
35770
  const actor = await resolveInviteActor(callerId(req));
@@ -35274,6 +35774,78 @@ function useServiceProviderController() {
35274
35774
  const owner = (site?.orgId ?? site?.org)?.toString?.() ?? "";
35275
35775
  return Boolean(owner) && actor.orgIds.includes(owner);
35276
35776
  }
35777
+ async function providerView(req, q) {
35778
+ const actor = await resolveInviteActor(callerId(req));
35779
+ const preferred2 = membershipPreferenceOf(req).org ?? "";
35780
+ return _getServiceProvidersForSite({
35781
+ ...q,
35782
+ invitedBy: actor.orgIds,
35783
+ storedOrgId: actor.orgIds.includes(preferred2) ? preferred2 : ""
35784
+ });
35785
+ }
35786
+ async function getSiteProviderMembers(req, res, next) {
35787
+ try {
35788
+ const { error, value } = import_joi46.default.object({
35789
+ siteId: import_joi46.default.string().hex().length(24).required(),
35790
+ type: import_joi46.default.string().max(60).optional().allow("", null),
35791
+ company: import_joi46.default.string().hex().length(24).optional().allow("", null),
35792
+ search: import_joi46.default.string().max(200).optional().allow("", null),
35793
+ format: import_joi46.default.string().valid("json", "xlsx").optional().allow("", null)
35794
+ }).validate(req.query);
35795
+ if (error)
35796
+ throw new import_node_server_utils105.BadRequestError(`Invalid input: ${error.message}`);
35797
+ await requireSiteReach(req, value.siteId);
35798
+ if (!await isSiteClient(req, value.siteId)) {
35799
+ throw new import_node_server_utils105.UnauthorizedError(
35800
+ "Only the site's own organisation can see its service providers' people."
35801
+ );
35802
+ }
35803
+ const data = await _getSiteProviderMembers({ siteId: value.siteId });
35804
+ if (value.format !== "xlsx") {
35805
+ res.json(data);
35806
+ return;
35807
+ }
35808
+ const rows = filterSiteProviderMembers(data.items, {
35809
+ type: value.type || "",
35810
+ company: value.company || "",
35811
+ search: value.search || ""
35812
+ });
35813
+ const workbook = new import_exceljs.default.Workbook();
35814
+ const sheet = workbook.addWorksheet("Service provider people");
35815
+ sheet.columns = [
35816
+ { header: "Name", key: "name", width: 28 },
35817
+ { header: "Email", key: "email", width: 32 },
35818
+ { header: "Company", key: "company", width: 28 },
35819
+ { header: "Service", key: "typeLabel", width: 22 },
35820
+ { header: "Role at this site", key: "role", width: 24 },
35821
+ { header: "Invited by", key: "invitedVia", width: 26 },
35822
+ { header: "Added", key: "added", width: 14 },
35823
+ { header: "Status", key: "status", width: 12 }
35824
+ ];
35825
+ sheet.getRow(1).font = { bold: true };
35826
+ for (const r of rows) {
35827
+ sheet.addRow({
35828
+ ...r,
35829
+ invitedVia: r.invitedVia || "The client",
35830
+ added: r.addedAt ? String(r.addedAt).slice(0, 10) : "",
35831
+ status: r.status === "active" ? "Active" : String(r.status ?? "")
35832
+ });
35833
+ }
35834
+ const buffer = await workbook.xlsx.writeBuffer();
35835
+ res.setHeader(
35836
+ "Content-Type",
35837
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
35838
+ );
35839
+ res.setHeader(
35840
+ "Content-Disposition",
35841
+ 'attachment; filename="service-provider-people.xlsx"'
35842
+ );
35843
+ res.send(Buffer.from(buffer));
35844
+ } catch (error) {
35845
+ import_node_server_utils105.logger.log({ level: "error", message: error.message });
35846
+ next(error);
35847
+ }
35848
+ }
35277
35849
  const { createServiceProvider: _add } = useServiceProviderRepo();
35278
35850
  async function createServiceProvider(req, res, next) {
35279
35851
  const validation = import_joi46.default.string().hex().required();
@@ -35326,7 +35898,14 @@ function useServiceProviderController() {
35326
35898
  try {
35327
35899
  if (siteId)
35328
35900
  await requireSiteReach(req, siteId);
35329
- const data = req.query.include === "engagements" && siteId && status === "active" && !orgId && !serviceProviderOrgId && await isSiteClient(req, siteId) ? await _getServiceProvidersForSite({ search, page: page2, limit, siteId }) : await _getServiceProviders({
35901
+ const engagements = req.query.include === "engagements" && siteId && status === "active" && !orgId && !serviceProviderOrgId;
35902
+ const client = engagements ? await isSiteClient(req, siteId) : false;
35903
+ const data = client ? await _getServiceProvidersForSite({ search, page: page2, limit, siteId }) : engagements ? (
35904
+ // A provider's own Service Providers page: the subcontractors it
35905
+ // brought onto this site, never the client's other contractors,
35906
+ // plus the stored rows it already saw here.
35907
+ await providerView(req, { search, page: page2, limit, siteId })
35908
+ ) : await _getServiceProviders({
35330
35909
  search,
35331
35910
  page: page2,
35332
35911
  limit,
@@ -35544,6 +36123,7 @@ function useServiceProviderController() {
35544
36123
  }
35545
36124
  return {
35546
36125
  createServiceProvider,
36126
+ getSiteProviderMembers,
35547
36127
  getServiceProviders,
35548
36128
  getByProviderOrg,
35549
36129
  getByEmail,
@@ -41840,7 +42420,7 @@ function useBuildingService() {
41840
42420
  // src/controllers/building.controller.ts
41841
42421
  var import_node_server_utils124 = require("@7365admin1/node-server-utils");
41842
42422
  var import_joi55 = __toESM(require("joi"));
41843
- var import_exceljs = __toESM(require("exceljs"));
42423
+ var import_exceljs2 = __toESM(require("exceljs"));
41844
42424
  var import_csv_parser = __toESM(require("csv-parser"));
41845
42425
  var import_fs3 = __toESM(require("fs"));
41846
42426
  function normalizeSpreadsheetHeader(header) {
@@ -42143,7 +42723,7 @@ function useBuildingController() {
42143
42723
  const { site, org } = queryValue;
42144
42724
  let rows = [];
42145
42725
  if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) {
42146
- const workbook = new import_exceljs.default.Workbook();
42726
+ const workbook = new import_exceljs2.default.Workbook();
42147
42727
  await workbook.xlsx.readFile(path5);
42148
42728
  const worksheet = workbook.worksheets[0];
42149
42729
  if (!worksheet) {
@@ -42858,7 +43438,7 @@ function parseExpiryDate(value) {
42858
43438
  }
42859
43439
 
42860
43440
  // src/controllers/vehicle.controller.ts
42861
- var import_exceljs2 = __toESM(require("exceljs"));
43441
+ var import_exceljs3 = __toESM(require("exceljs"));
42862
43442
  var import_csv_parser2 = __toESM(require("csv-parser"));
42863
43443
  var import_fs4 = __toESM(require("fs"));
42864
43444
  function actingUser(req) {
@@ -43009,7 +43589,7 @@ function useVehicleController() {
43009
43589
  const { site, org } = queryValue;
43010
43590
  let rows = [];
43011
43591
  if (lowerName.endsWith(".xlsx") || lowerName.endsWith(".xls")) {
43012
- const workbook = new import_exceljs2.default.Workbook();
43592
+ const workbook = new import_exceljs3.default.Workbook();
43013
43593
  await workbook.xlsx.readFile(path5);
43014
43594
  const worksheet = workbook.worksheets[0];
43015
43595
  if (!worksheet) {
@@ -46995,7 +47575,7 @@ function usePersonService() {
46995
47575
  let set = {};
46996
47576
  const cleanInput = (str2) => str2.replace(/\s+/g, "");
46997
47577
  const cleanPhone = (str2) => str2.replace(/\D/g, "");
46998
- const escapeRegex3 = (str2) => str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
47578
+ const escapeRegex4 = (str2) => str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46999
47579
  const nric = value.nric ? cleanInput(value.nric) : "";
47000
47580
  const name = value.name?.trim();
47001
47581
  const contact = value.contact?.trim();
@@ -47003,8 +47583,8 @@ function usePersonService() {
47003
47583
  const email = value.email?.trim();
47004
47584
  const type = value.type?.trim();
47005
47585
  const company = value.company?.trim();
47006
- const nricQuery = nric ? { nric: { $regex: `^${escapeRegex3(nric)}$`, $options: "i" } } : null;
47007
- const nameQuery = name ? { name: { $regex: `^${escapeRegex3(name)}$`, $options: "i" } } : null;
47586
+ const nricQuery = nric ? { nric: { $regex: `^${escapeRegex4(nric)}$`, $options: "i" } } : null;
47587
+ const nameQuery = name ? { name: { $regex: `^${escapeRegex4(name)}$`, $options: "i" } } : null;
47008
47588
  let nricCondition = null;
47009
47589
  if (nric) {
47010
47590
  if (nric.length < 9) {
@@ -47017,8 +47597,8 @@ function usePersonService() {
47017
47597
  }
47018
47598
  const orConditions = [
47019
47599
  ...nricCondition ? [nricCondition] : [],
47020
- ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex3(contact))}$`, $options: "i" } }] : [],
47021
- ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex3(plateNumber)}$`, $options: "i" } }] : []
47600
+ ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex4(contact))}$`, $options: "i" } }] : [],
47601
+ ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex4(plateNumber)}$`, $options: "i" } }] : []
47022
47602
  ];
47023
47603
  const existingPerson2 = await findFirstTen(
47024
47604
  {
@@ -48905,7 +49485,7 @@ function useHidAmicoRepo() {
48905
49485
  passwordSet: Boolean(password)
48906
49486
  };
48907
49487
  }
48908
- function escapeRegex3(value) {
49488
+ function escapeRegex4(value) {
48909
49489
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48910
49490
  }
48911
49491
  function buildIdentityKeyQuery(value) {
@@ -49108,7 +49688,7 @@ function useHidAmicoRepo() {
49108
49688
  query2.type = value.type;
49109
49689
  }
49110
49690
  if (value.search) {
49111
- const search = escapeRegex3(value.search);
49691
+ const search = escapeRegex4(value.search);
49112
49692
  query2.$or = [
49113
49693
  { hidUserId: { $regex: search, $options: "i" } },
49114
49694
  { registration: { $regex: search, $options: "i" } },
@@ -49349,7 +49929,7 @@ function useHidAmicoRepo() {
49349
49929
  const text2 = search.trim();
49350
49930
  if (!text2)
49351
49931
  return {};
49352
- const pattern = { $regex: escapeRegex3(text2), $options: "i" };
49932
+ const pattern = { $regex: escapeRegex4(text2), $options: "i" };
49353
49933
  return {
49354
49934
  $or: [
49355
49935
  { name: pattern },
@@ -61727,7 +62307,7 @@ var NETWORK_SORTS = {
61727
62307
  };
61728
62308
  var NETWORK_OFFLINE_CODE = "OFFLINE";
61729
62309
  var ROBOT_FAULTS_COLLECTION = "robot-faults";
61730
- function escapeRegex2(value) {
62310
+ function escapeRegex3(value) {
61731
62311
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
61732
62312
  }
61733
62313
  function matchDefaulted(field, value, fallback) {
@@ -61831,7 +62411,7 @@ function networkListPipeline(q) {
61831
62411
  pipeline.push({ $match: { offline: true } });
61832
62412
  const search = (q.search ?? "").trim();
61833
62413
  if (search) {
61834
- const rx = { $regex: escapeRegex2(search), $options: "i" };
62414
+ const rx = { $regex: escapeRegex3(search), $options: "i" };
61835
62415
  pipeline.push({
61836
62416
  $match: { $or: [{ name: rx }, { robotSn: rx }, { "client.name": rx }, { "site.name": rx }] }
61837
62417
  });
@@ -73622,7 +74202,7 @@ function usePatrolEmailRepo() {
73622
74202
  throw new import_node_server_utils186.BadRequestError(`Invalid ${label2} format.`);
73623
74203
  }
73624
74204
  }
73625
- function escapeRegex3(value) {
74205
+ function escapeRegex4(value) {
73626
74206
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
73627
74207
  }
73628
74208
  async function createIndexes() {
@@ -73759,8 +74339,8 @@ function usePatrolEmailRepo() {
73759
74339
  ...status ? { status } : { status: { $ne: "deleted" } },
73760
74340
  ...search && {
73761
74341
  $or: [
73762
- { subject: { $regex: escapeRegex3(search), $options: "i" } },
73763
- { recipients: { $regex: escapeRegex3(search), $options: "i" } }
74342
+ { subject: { $regex: escapeRegex4(search), $options: "i" } },
74343
+ { recipients: { $regex: escapeRegex4(search), $options: "i" } }
73764
74344
  ]
73765
74345
  }
73766
74346
  };
@@ -97489,11 +98069,11 @@ function useVerificationServiceV2() {
97489
98069
  if (!actor.id) {
97490
98070
  throw new import_node_server_utils289.UnauthorizedError("Sign in to continue.");
97491
98071
  }
97492
- if (!staffMayBypass(actor) && !actor.orgIds.includes(orgId)) {
97493
- throw new import_node_server_utils289.UnauthorizedError(
97494
- "You can only invite service providers to your own organisation's sites."
97495
- );
97496
- }
98072
+ const { sender } = await assertServiceProviderInviteScope(
98073
+ actor,
98074
+ orgId,
98075
+ siteId
98076
+ );
97497
98077
  const invitedEmail = email.trim().toLowerCase();
97498
98078
  const [providerOrg, existingUser, pendingInvite] = await Promise.all([
97499
98079
  _getByEmail(invitedEmail),
@@ -97506,7 +98086,10 @@ function useVerificationServiceV2() {
97506
98086
  hasProviderOrg: Boolean(providerOrgId),
97507
98087
  engagedOnSite: providerOrgId ? await _countActiveEngagement(providerOrgId, siteId) > 0 : false,
97508
98088
  invitePending: Boolean(pendingInvite),
97509
- inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId)
98089
+ inviterIsPropertyManagement: actor.propertyManagementOrgIds.includes(orgId),
98090
+ // A provider bringing in a subcontractor is held for Seven365
98091
+ // exactly like a property manager (owner request 2026-09-28).
98092
+ inviterIsServiceProvider: sender === "subcontract"
97510
98093
  });
97511
98094
  if (!decision.ok) {
97512
98095
  throw new import_node_server_utils289.BadRequestError(decision.reason);
@@ -97518,7 +98101,7 @@ function useVerificationServiceV2() {
97518
98101
  ...value.metadata,
97519
98102
  invitedBy: actor.id,
97520
98103
  invitedByName: actor.name,
97521
- invitedByPropertyManagement: decision.requiresApproval
98104
+ invitedByPropertyManagement: decision.requiresApproval && actor.propertyManagementOrgIds.includes(orgId)
97522
98105
  };
97523
98106
  value.history = [
97524
98107
  {
@@ -97530,6 +98113,12 @@ function useVerificationServiceV2() {
97530
98113
  ];
97531
98114
  const res = await _add(value);
97532
98115
  if (decision.requiresApproval) {
98116
+ NotificationService.serviceProviderInviteAwaitingApproval({
98117
+ invitationId: String(res),
98118
+ inviterOrgName: org?.name ?? "",
98119
+ siteName,
98120
+ subcontract: sender === "subcontract"
98121
+ }).catch(() => void 0);
97533
98122
  return res;
97534
98123
  }
97535
98124
  await useServiceProviderInviteService().notifyProvider({
@@ -98544,7 +99133,7 @@ function useServiceProviderInviteController() {
98544
99133
  }).validate(req.body ?? {});
98545
99134
  if (error) {
98546
99135
  throw new import_node_server_utils291.BadRequestError(
98547
- "Give a reason for not approving this invitation. The property manager will see it."
99136
+ "Give a reason for not approving this invitation. Whoever sent it will see it."
98548
99137
  );
98549
99138
  }
98550
99139
  res.json(
@@ -102697,7 +103286,7 @@ function useFormEntryRepo() {
102697
103286
  // src/controllers/online-forms-v2.controller.ts
102698
103287
  var import_node_server_utils319 = require("@7365admin1/node-server-utils");
102699
103288
  var import_joi169 = __toESM(require("joi"));
102700
- var import_exceljs3 = __toESM(require("exceljs"));
103289
+ var import_exceljs4 = __toESM(require("exceljs"));
102701
103290
  var import_fs7 = __toESM(require("fs"));
102702
103291
  function useFormEntryController() {
102703
103292
  const {
@@ -102735,7 +103324,7 @@ function useFormEntryController() {
102735
103324
  next(new import_node_server_utils319.BadRequestError("Excel file is required."));
102736
103325
  return;
102737
103326
  }
102738
- const workbook = new import_exceljs3.default.Workbook();
103327
+ const workbook = new import_exceljs4.default.Workbook();
102739
103328
  await workbook.xlsx.readFile(req.file.path);
102740
103329
  const worksheet = workbook.worksheets[0];
102741
103330
  if (!worksheet) {
@@ -105435,8 +106024,11 @@ function usePersonalEmergencyChainController() {
105435
106024
  SERVICE_PROVIDER_SIGN_IN_TYPE,
105436
106025
  SERVICE_PROVIDER_SIGN_UP_SUBJECT,
105437
106026
  SERVICE_PROVIDER_SIGN_UP_TYPE,
106027
+ SERVICE_TYPE_LABELS,
105438
106028
  SITE_STATES_MAX,
105439
106029
  SOFTWARE_VERSION_ENDPOINT,
106030
+ SUBCONTRACT_ADMIN_REFUSAL,
106031
+ SUBCONTRACT_SITE_REFUSAL,
105440
106032
  SiteCategories,
105441
106033
  SiteStatus,
105442
106034
  SortFields,
@@ -105483,6 +106075,7 @@ function usePersonalEmergencyChainController() {
105483
106075
  applyTrackingFrame,
105484
106076
  areaColourToHex,
105485
106077
  asList,
106078
+ assertServiceProviderInviteScope,
105486
106079
  attendanceSchema,
105487
106080
  attendanceSettingsSchema,
105488
106081
  buildSelfServiceEmailContext,
@@ -105596,6 +106189,7 @@ function usePersonalEmergencyChainController() {
105596
106189
  ffmpegFrameArgs,
105597
106190
  ffmpegPath,
105598
106191
  filterByAccess,
106192
+ filterSiteProviderMembers,
105599
106193
  fleetStateItem,
105600
106194
  floorNoOf,
105601
106195
  floorPlanBodySchema,
@@ -105985,7 +106579,10 @@ function usePersonalEmergencyChainController() {
105985
106579
  sendNotificationEmails,
105986
106580
  servesFloor,
105987
106581
  serviceProviderInviteLabel,
106582
+ serviceProviderInviteScope,
105988
106583
  serviceProviderInviteViewStatus,
106584
+ serviceProviderInviterKind,
106585
+ serviceTypeLabel,
105989
106586
  sessionSchema,
105990
106587
  setIO,
105991
106588
  sha256Hex,