@7365admin1/core 3.101.0 → 3.102.1

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
@@ -8346,6 +8346,7 @@ function useVerificationRepoV2() {
8346
8346
  statuses = [],
8347
8347
  orgIds,
8348
8348
  email = "",
8349
+ siteId = "",
8349
8350
  search = "",
8350
8351
  includeDeleted = false,
8351
8352
  page = 1,
@@ -8364,6 +8365,12 @@ function useVerificationRepoV2() {
8364
8365
  query2.status = { $in: statuses };
8365
8366
  if (email)
8366
8367
  query2.email = email.trim().toLowerCase();
8368
+ if (siteId) {
8369
+ const ids2 = [siteId];
8370
+ if (import_mongodb22.ObjectId.isValid(siteId))
8371
+ ids2.push(new import_mongodb22.ObjectId(siteId));
8372
+ query2["metadata.siteId"] = { $in: ids2 };
8373
+ }
8367
8374
  if (!includeDeleted)
8368
8375
  query2.deletedAt = null;
8369
8376
  if (search.trim()) {
@@ -8534,6 +8541,91 @@ function MCustomerSite(value) {
8534
8541
  // src/repositories/customer-site.repo.ts
8535
8542
  var import_mongodb24 = require("mongodb");
8536
8543
  var import_joi13 = __toESM(require("joi"));
8544
+
8545
+ // src/utils/customer-site-list.util.ts
8546
+ var SITE_RELATIONSHIPS = ["own", "served"];
8547
+ var SP_INVITE_TYPES = [
8548
+ "service-provider-invite",
8549
+ "service-provider-create-org"
8550
+ ];
8551
+ function escapeRegex(value) {
8552
+ return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8553
+ }
8554
+ function relationshipMatch(org, relationship, client) {
8555
+ const self = [org, String(org)];
8556
+ const match = {};
8557
+ const and = [];
8558
+ if (relationship === "own") {
8559
+ and.push({ siteOrg: { $in: [...self, null, ""] } });
8560
+ } else if (relationship === "served") {
8561
+ and.push({ siteOrg: { $nin: [...self, null, ""] } });
8562
+ }
8563
+ if (client) {
8564
+ and.push(
8565
+ { siteOrg: { $in: [client, String(client)] } },
8566
+ { siteOrg: { $nin: self } }
8567
+ );
8568
+ }
8569
+ if (and.length)
8570
+ match.$and = and;
8571
+ return match;
8572
+ }
8573
+ function relationshipField(orgId) {
8574
+ return {
8575
+ relationship: {
8576
+ $cond: [
8577
+ {
8578
+ $or: [
8579
+ { $in: [{ $ifNull: ["$siteOrg", ""] }, ["", null]] },
8580
+ { $eq: [{ $toString: "$siteOrg" }, orgId] }
8581
+ ]
8582
+ },
8583
+ "own",
8584
+ "served"
8585
+ ]
8586
+ }
8587
+ };
8588
+ }
8589
+ function searchMatch(search) {
8590
+ const term = String(search ?? "").trim();
8591
+ if (!term)
8592
+ return null;
8593
+ const re = { $regex: escapeRegex(term), $options: "i" };
8594
+ return {
8595
+ $or: [
8596
+ { name: re },
8597
+ { siteOrgName: re },
8598
+ { "siteAddress.line1": re },
8599
+ { "siteAddress.line2": re },
8600
+ { "siteAddress.city": re },
8601
+ { "siteAddress.postalCode": re },
8602
+ { "siteAddress.country": re }
8603
+ ]
8604
+ };
8605
+ }
8606
+ var iso = (value) => {
8607
+ if (!value)
8608
+ return null;
8609
+ const d = new Date(value);
8610
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
8611
+ };
8612
+ function invitationFor(siteId, invites) {
8613
+ const mine = invites.filter((v2) => String(v2?.metadata?.siteId ?? "") === siteId).sort(
8614
+ (a, b) => new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime()
8615
+ );
8616
+ const v = mine[0];
8617
+ if (!v)
8618
+ return null;
8619
+ const accepted = [...v.history ?? []].reverse().find((h) => h?.action === "accepted" || h?.action === "site-linked");
8620
+ return {
8621
+ id: String(v._id ?? ""),
8622
+ invitedByName: String(v.metadata?.invitedByName ?? ""),
8623
+ invitedAt: iso(v.createdAt),
8624
+ acceptedAt: iso(accepted?.at)
8625
+ };
8626
+ }
8627
+
8628
+ // src/repositories/customer-site.repo.ts
8537
8629
  function useCustomerSiteRepo() {
8538
8630
  const db2 = import_node_server_utils26.useAtlas.getDb();
8539
8631
  if (!db2) {
@@ -8541,6 +8633,7 @@ function useCustomerSiteRepo() {
8541
8633
  }
8542
8634
  const namespace_collection3 = "customer.sites";
8543
8635
  const collection = db2.collection(namespace_collection3);
8636
+ const verifications = db2.collection("verifications");
8544
8637
  const { delNamespace, getCache, setCache } = (0, import_node_server_utils26.useCache)(namespace_collection3);
8545
8638
  async function createIndexes() {
8546
8639
  try {
@@ -8630,7 +8723,10 @@ function useCustomerSiteRepo() {
8630
8723
  sort = {},
8631
8724
  org = "",
8632
8725
  status = "active",
8633
- siteScope = null
8726
+ siteScope = null,
8727
+ relationship = "",
8728
+ client = "",
8729
+ category = ""
8634
8730
  }, session) {
8635
8731
  page = page > 0 ? page - 1 : 0;
8636
8732
  try {
@@ -8642,6 +8738,14 @@ function useCustomerSiteRepo() {
8642
8738
  org,
8643
8739
  status
8644
8740
  };
8741
+ let clientId = null;
8742
+ if (client) {
8743
+ try {
8744
+ clientId = new import_mongodb24.ObjectId(client);
8745
+ } catch (error) {
8746
+ throw new import_node_server_utils26.BadRequestError("Invalid client ID format.");
8747
+ }
8748
+ }
8645
8749
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
8646
8750
  const cacheOptions = {
8647
8751
  org: org.toString(),
@@ -8658,6 +8762,12 @@ function useCustomerSiteRepo() {
8658
8762
  if (search) {
8659
8763
  cacheOptions.search = search;
8660
8764
  }
8765
+ if (relationship)
8766
+ cacheOptions.relationship = relationship;
8767
+ if (client)
8768
+ cacheOptions.client = client;
8769
+ if (category)
8770
+ cacheOptions.category = category;
8661
8771
  const cacheKey = (0, import_node_server_utils26.makeCacheKey)(namespace_collection3, cacheOptions);
8662
8772
  const cachedData = await getCache(cacheKey);
8663
8773
  if (cachedData) {
@@ -8665,8 +8775,14 @@ function useCustomerSiteRepo() {
8665
8775
  return cachedData;
8666
8776
  }
8667
8777
  try {
8778
+ const orgId = org.toString();
8779
+ const search_ = searchMatch(search);
8780
+ const listMatch = {
8781
+ ...query2,
8782
+ ...relationshipMatch(org, relationship, clientId)
8783
+ };
8668
8784
  const distinctPipeline = [
8669
- { $match: query2 },
8785
+ { $match: listMatch },
8670
8786
  { $sort: sort },
8671
8787
  { $group: { _id: "$site", doc: { $first: "$$ROOT" } } },
8672
8788
  { $replaceRoot: { newRoot: "$doc" } },
@@ -8683,8 +8799,22 @@ function useCustomerSiteRepo() {
8683
8799
  // The site's own timezone, so the Edit Site form opens on the zone the
8684
8800
  // site really has. Lives only on the site, never on this row.
8685
8801
  { $set: { timezone: "$_liveSite.timezone" } },
8802
+ /*
8803
+ * The Sites list's columns. Address and category come from the SITE,
8804
+ * like the name: a served site's engagement row was written by the
8805
+ * invitation with neither. The row's own `address` / `category` are
8806
+ * left exactly as they were for every other caller.
8807
+ */
8808
+ {
8809
+ $set: {
8810
+ siteAddress: { $ifNull: ["$_liveSite.address", "$address"] },
8811
+ siteCategory: { $ifNull: ["$_liveSite.category", "$category"] },
8812
+ ...relationshipField(orgId)
8813
+ }
8814
+ },
8686
8815
  { $unset: "_liveSite" },
8687
- ...search ? [{ $match: { name: { $regex: search, $options: "i" } } }] : [],
8816
+ ...search_ ? [{ $match: search_ }] : [],
8817
+ ...category ? [{ $match: { siteCategory: category } }] : [],
8688
8818
  { $sort: sort }
8689
8819
  ];
8690
8820
  const items = await collection.aggregate(
@@ -8697,7 +8827,54 @@ function useCustomerSiteRepo() {
8697
8827
  ).toArray();
8698
8828
  const countResult = await collection.aggregate([...distinctPipeline, { $count: "total" }], { session }).toArray();
8699
8829
  const length = countResult[0]?.total ?? 0;
8700
- const data = (0, import_node_server_utils26.paginate)(items, page, limit, length);
8830
+ const servedSites = items.filter((row) => row.relationship === "served" && row.site).map((row) => row.site);
8831
+ if (servedSites.length) {
8832
+ const invites = await verifications.find(
8833
+ {
8834
+ type: { $in: SP_INVITE_TYPES },
8835
+ status: "complete",
8836
+ "metadata.providerOrg": { $in: [orgId, org] },
8837
+ "metadata.siteId": {
8838
+ $in: [...servedSites, ...servedSites.map(String)]
8839
+ }
8840
+ },
8841
+ {
8842
+ projection: {
8843
+ createdAt: 1,
8844
+ history: 1,
8845
+ "metadata.siteId": 1,
8846
+ "metadata.invitedByName": 1
8847
+ },
8848
+ session
8849
+ }
8850
+ ).toArray().catch((error) => {
8851
+ import_node_server_utils26.logger.error(
8852
+ `Sites list: invitation lookup failed: ${error?.message}`
8853
+ );
8854
+ return [];
8855
+ });
8856
+ for (const row of items) {
8857
+ if (row.relationship === "served") {
8858
+ row.invitation = invitationFor(String(row.site), invites);
8859
+ }
8860
+ }
8861
+ }
8862
+ const clients = await collection.aggregate(
8863
+ [
8864
+ { $match: { ...query2, ...relationshipMatch(org, "served") } },
8865
+ { $sort: { _id: -1 } },
8866
+ { $group: { _id: "$siteOrg", name: { $first: "$siteOrgName" } } },
8867
+ { $sort: { name: 1 } }
8868
+ ],
8869
+ { session }
8870
+ ).toArray();
8871
+ const data = {
8872
+ ...(0, import_node_server_utils26.paginate)(items, page, limit, length),
8873
+ clients: clients.map((c) => ({
8874
+ _id: String(c._id),
8875
+ name: c.name ?? ""
8876
+ }))
8877
+ };
8701
8878
  setCache(cacheKey, data, 15 * 60).then(() => {
8702
8879
  import_node_server_utils26.logger.info(`Cache set for key: ${cacheKey}`);
8703
8880
  }).catch((err) => {
@@ -13461,6 +13638,7 @@ function useServiceProviderInviteService() {
13461
13638
  async function listForCaller({
13462
13639
  userId,
13463
13640
  orgId,
13641
+ siteId,
13464
13642
  statuses,
13465
13643
  search = "",
13466
13644
  page = 1,
@@ -13481,16 +13659,85 @@ function useServiceProviderInviteService() {
13481
13659
  // A super admin asking for everything passes no scope; everyone else is
13482
13660
  // pinned to their own organisations even if they ask for more.
13483
13661
  orgIds: staffMayBypass(actor) && !orgId ? void 0 : scope,
13662
+ siteId: siteId || void 0,
13484
13663
  search,
13485
13664
  page,
13486
13665
  limit
13487
13666
  });
13667
+ const names = /* @__PURE__ */ new Map();
13668
+ const items = await Promise.all(
13669
+ (data.items ?? []).map(
13670
+ (invite) => sentRow(invite, names)
13671
+ )
13672
+ );
13673
+ return { ...data, items };
13674
+ }
13675
+ async function sentRow(invite, names) {
13676
+ const metadata = invite.metadata ?? {};
13677
+ const status = serviceProviderInviteViewStatus(invite);
13678
+ const accepted = status === "complete" /* COMPLETE */ && !invite.deletedAt;
13679
+ const siteId = metadata.siteId?.toString?.() ?? "";
13680
+ const history = invite.history ?? [];
13681
+ const answer = [...history].reverse().find(
13682
+ (h) => ["accepted", "site-linked", "declined", "cancelled", "rejected"].includes(h?.action)
13683
+ );
13684
+ let providerOrgId = metadata.providerOrg?.toString?.() ?? "";
13685
+ let providerOrgName = String(metadata.providerOrgName ?? "");
13686
+ if (accepted && !providerOrgId) {
13687
+ const byEmail = await getOrgByEmail(
13688
+ String(invite.email ?? "").trim().toLowerCase()
13689
+ ).catch(() => null);
13690
+ providerOrgId = byEmail?._id?.toString?.() ?? "";
13691
+ providerOrgName = byEmail?.name ?? "";
13692
+ }
13693
+ let contactEmail = "";
13694
+ let contactPhone = "";
13695
+ let onSite = false;
13696
+ if (accepted && providerOrgId) {
13697
+ const [org, links] = await Promise.all([
13698
+ getOrgById(providerOrgId).catch(() => null),
13699
+ siteId ? useCustomerSiteRepo().countActiveByOrgAndSite(providerOrgId, siteId).catch(() => 0) : Promise.resolve(0)
13700
+ ]);
13701
+ providerOrgName = providerOrgName || org?.name || "";
13702
+ contactEmail = String(org?.email ?? "");
13703
+ contactPhone = String(org?.contact ?? "");
13704
+ onSite = links > 0;
13705
+ }
13706
+ const invitedBy = metadata.invitedBy?.toString?.() ?? "";
13707
+ let invitedByName = String(metadata.invitedByName ?? "");
13708
+ if (!invitedByName && invitedBy) {
13709
+ if (!names.has(invitedBy)) {
13710
+ names.set(
13711
+ invitedBy,
13712
+ getUserById(invitedBy).then((u) => String(u?.name ?? "")).catch(() => "")
13713
+ );
13714
+ }
13715
+ invitedByName = await names.get(invitedBy);
13716
+ }
13717
+ const companyName = providerOrgName || String(metadata.name ?? "");
13488
13718
  return {
13489
- ...data,
13490
- items: (data.items ?? []).map((invite) => ({
13491
- ...invite,
13492
- statusLabel: serviceProviderInviteLabel(invite.status)
13493
- }))
13719
+ ...invite,
13720
+ // Apps still on an older layer-common read the company from
13721
+ // `metadata.name` (set only on sign-up invitations). Filled in the reply
13722
+ // only - nothing is written. ponytail: drop once every app's pin reads
13723
+ // `companyName`.
13724
+ metadata: { ...metadata, name: companyName },
13725
+ // `status` stays the stored value (it decides which actions a row
13726
+ // offers); `viewStatus` reads a lapsed "pending" as "expired".
13727
+ viewStatus: status,
13728
+ statusLabel: serviceProviderInviteLabel(status),
13729
+ // The company the invitation is for: the one that accepted it, else the
13730
+ // new company's name the sender typed (a sign-up invitation).
13731
+ companyName,
13732
+ providerOrgId,
13733
+ service: String(metadata.app ?? ""),
13734
+ siteName: String(metadata.siteName ?? ""),
13735
+ invitedByName,
13736
+ invitedAt: invite.createdAt ?? null,
13737
+ answeredAt: status === "expired" ? invite.expireAt ?? null : status === "pending" || status === "awaiting-approval" /* AWAITING_APPROVAL */ ? null : answer?.at ?? invite.updatedAt ?? null,
13738
+ contactEmail,
13739
+ contactPhone,
13740
+ onSite
13494
13741
  };
13495
13742
  }
13496
13743
  async function approvalCount({ userId }) {
@@ -20239,7 +20486,7 @@ function useVehicleRepo() {
20239
20486
  let query2 = { ...baseQuery };
20240
20487
  if (search)
20241
20488
  query2.$text = { $search: search };
20242
- const escapeRegex2 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20489
+ const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20243
20490
  const buildGroupedPipeline = (matchQuery) => [
20244
20491
  { $match: matchQuery },
20245
20492
  {
@@ -20423,7 +20670,7 @@ function useVehicleRepo() {
20423
20670
  const countResult = await collection.aggregate(buildGroupedCountPipeline(query2)).toArray();
20424
20671
  length = countResult[0]?.total || 0;
20425
20672
  if ((!items || items.length === 0) && search) {
20426
- const escaped = escapeRegex2(search);
20673
+ const escaped = escapeRegex3(search);
20427
20674
  const regexQuery = {
20428
20675
  ...baseQuery,
20429
20676
  $or: [
@@ -21212,7 +21459,7 @@ function useVehicleRepo() {
21212
21459
  ...baseQuery,
21213
21460
  ...search && { $text: { $search: search } }
21214
21461
  };
21215
- const escapeRegex2 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21462
+ const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21216
21463
  const buildPipeline = (matchQuery) => [
21217
21464
  { $match: matchQuery },
21218
21465
  {
@@ -21240,7 +21487,7 @@ function useVehicleRepo() {
21240
21487
  const countResult = await collection.aggregate(buildCountPipeline(query2)).toArray();
21241
21488
  length = countResult[0]?.total || 0;
21242
21489
  if ((!items || items.length === 0) && search) {
21243
- const escaped = escapeRegex2(search);
21490
+ const escaped = escapeRegex3(search);
21244
21491
  const regexQuery = {
21245
21492
  ...baseQuery,
21246
21493
  $or: [
@@ -29401,9 +29648,9 @@ function parsePromoExpiry(value) {
29401
29648
  const us = raw.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
29402
29649
  if (us)
29403
29650
  return endOfDay(us[3], us[1], us[2]);
29404
- const iso = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/);
29405
- if (iso)
29406
- return endOfDay(iso[1], iso[2], iso[3]);
29651
+ const iso2 = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/);
29652
+ if (iso2)
29653
+ return endOfDay(iso2[1], iso2[2], iso2[3]);
29407
29654
  const parsed = new Date(raw);
29408
29655
  return Number.isNaN(parsed.getTime()) ? null : parsed;
29409
29656
  }
@@ -32606,7 +32853,7 @@ function useServiceProviderRepo() {
32606
32853
  throw new import_node_server_utils97.BadRequestError("Invalid site ID format.");
32607
32854
  }
32608
32855
  }
32609
- cacheOptions.membersLookup = "1";
32856
+ cacheOptions.membersLookup = "2";
32610
32857
  const cacheKey = (0, import_node_server_utils97.makeCacheKey)(namespace_collection3, cacheOptions);
32611
32858
  const cachedData = await getCache(cacheKey);
32612
32859
  if (cachedData) {
@@ -32622,7 +32869,7 @@ function useServiceProviderRepo() {
32622
32869
  localField: "serviceProviderOrgId",
32623
32870
  foreignField: "_id",
32624
32871
  as: "organization",
32625
- pipeline: [{ $project: { nature: 1, email: 1 } }]
32872
+ pipeline: [{ $project: { nature: 1, email: 1, contact: 1 } }]
32626
32873
  }
32627
32874
  },
32628
32875
  {
@@ -32634,11 +32881,19 @@ function useServiceProviderRepo() {
32634
32881
  {
32635
32882
  $lookup: {
32636
32883
  from: "members",
32637
- let: { spOrgId: "$serviceProviderOrgId" },
32884
+ // The provider's staff assigned to THIS site, not the provider's
32885
+ // whole headcount - the client has no business knowing how big
32886
+ // its contractor is, only who works on its estate.
32887
+ let: { spOrgId: "$serviceProviderOrgId", spSiteId: "$siteId" },
32638
32888
  pipeline: [
32639
32889
  {
32640
32890
  $match: {
32641
- $expr: { $eq: ["$org", "$$spOrgId"] },
32891
+ $expr: {
32892
+ $and: [
32893
+ { $eq: ["$org", "$$spOrgId"] },
32894
+ { $eq: ["$siteId", "$$spSiteId"] }
32895
+ ]
32896
+ },
32642
32897
  status: "active"
32643
32898
  }
32644
32899
  },
@@ -32661,6 +32916,7 @@ function useServiceProviderRepo() {
32661
32916
  }
32662
32917
  },
32663
32918
  nature: "$organization.nature",
32919
+ contact: { $ifNull: ["$organization.contact", ""] },
32664
32920
  orgId: 1,
32665
32921
  siteId: 1,
32666
32922
  siteName: 1,
@@ -32910,6 +33166,104 @@ function useServiceProviderRepo() {
32910
33166
  throw error;
32911
33167
  }
32912
33168
  }
33169
+ async function getEngagedProvidersBySite(site) {
33170
+ try {
33171
+ site = new import_mongodb72.ObjectId(site);
33172
+ } catch {
33173
+ throw new import_node_server_utils97.BadRequestError("Invalid site ID format.");
33174
+ }
33175
+ return await db2.collection("customer.sites").aggregate([
33176
+ {
33177
+ $match: {
33178
+ site,
33179
+ status: "active",
33180
+ // The client's own row for its own site is not a provider, and a
33181
+ // row that does not say whose site it is proves nothing.
33182
+ siteOrg: { $nin: [null, ""] },
33183
+ $expr: { $ne: ["$org", "$siteOrg"] }
33184
+ }
33185
+ },
33186
+ { $sort: { _id: 1 } },
33187
+ {
33188
+ $group: {
33189
+ _id: "$org",
33190
+ engagementId: { $first: "$_id" },
33191
+ siteName: { $first: "$name" },
33192
+ since: { $first: "$createdAt" }
33193
+ }
33194
+ },
33195
+ {
33196
+ $lookup: {
33197
+ from: "organizations",
33198
+ localField: "_id",
33199
+ foreignField: "_id",
33200
+ as: "organization",
33201
+ pipeline: [
33202
+ { $project: { name: 1, nature: 1, email: 1, contact: 1 } }
33203
+ ]
33204
+ }
33205
+ },
33206
+ { $unwind: { path: "$organization", preserveNullAndEmptyArrays: true } },
33207
+ {
33208
+ $lookup: {
33209
+ from: "members",
33210
+ let: { spOrgId: "$_id" },
33211
+ pipeline: [
33212
+ {
33213
+ $match: {
33214
+ $expr: { $eq: ["$org", "$$spOrgId"] },
33215
+ siteId: site,
33216
+ status: "active"
33217
+ }
33218
+ },
33219
+ { $count: "c" }
33220
+ ],
33221
+ as: "_memberCount"
33222
+ }
33223
+ },
33224
+ {
33225
+ $project: {
33226
+ _id: "$engagementId",
33227
+ name: { $ifNull: ["$organization.name", ""] },
33228
+ type: { $ifNull: ["$organization.nature", ""] },
33229
+ nature: "$organization.nature",
33230
+ email: { $ifNull: ["$organization.email", ""] },
33231
+ contact: { $ifNull: ["$organization.contact", ""] },
33232
+ siteId: site,
33233
+ siteName: 1,
33234
+ serviceProviderOrgId: "$_id",
33235
+ status: "active",
33236
+ category: "external",
33237
+ since: 1,
33238
+ source: "engagement",
33239
+ members: {
33240
+ $ifNull: [{ $arrayElemAt: ["$_memberCount.c", 0] }, 0]
33241
+ }
33242
+ }
33243
+ },
33244
+ { $sort: { name: 1 } },
33245
+ { $limit: 200 }
33246
+ ]).toArray();
33247
+ }
33248
+ async function getSiteProviderKeys(site) {
33249
+ try {
33250
+ site = new import_mongodb72.ObjectId(site);
33251
+ } catch {
33252
+ throw new import_node_server_utils97.BadRequestError("Invalid site ID format.");
33253
+ }
33254
+ const rows = await collection.find(
33255
+ { siteId: site },
33256
+ { projection: { serviceProviderOrgId: 1, email: 1 } }
33257
+ ).toArray();
33258
+ return {
33259
+ orgIds: new Set(
33260
+ rows.map((r) => r.serviceProviderOrgId?.toString?.() ?? "").filter(Boolean)
33261
+ ),
33262
+ emails: new Set(
33263
+ rows.map((r) => String(r.email ?? "").trim().toLowerCase()).filter(Boolean)
33264
+ )
33265
+ };
33266
+ }
32913
33267
  return {
32914
33268
  createTextIndex,
32915
33269
  createUniqueIndex,
@@ -32920,7 +33274,9 @@ function useServiceProviderRepo() {
32920
33274
  getServiceProviderById,
32921
33275
  getByServiceProviderOrgIdType,
32922
33276
  getByEmail,
32923
- updateStatusById
33277
+ updateStatusById,
33278
+ getEngagedProvidersBySite,
33279
+ getSiteProviderKeys
32924
33280
  };
32925
33281
  }
32926
33282
 
@@ -33640,7 +33996,9 @@ var import_node_server_utils102 = require("@7365admin1/node-server-utils");
33640
33996
  function useServiceProviderService() {
33641
33997
  const {
33642
33998
  createServiceProvider: _createServiceProvider,
33643
- getServiceProviders: _getServiceProviders
33999
+ getServiceProviders: _getServiceProviders,
34000
+ getEngagedProvidersBySite: _getEngaged,
34001
+ getSiteProviderKeys: _getSiteProviderKeys
33644
34002
  } = useServiceProviderRepo();
33645
34003
  const { getById: getOrgById, getByEmail: getOrgByEmail } = useOrgRepo();
33646
34004
  const { getSiteById } = useSiteRepo();
@@ -33720,9 +34078,40 @@ function useServiceProviderService() {
33720
34078
  status
33721
34079
  });
33722
34080
  }
34081
+ async function getServiceProvidersForSite({
34082
+ search = "",
34083
+ page = 1,
34084
+ limit = 10,
34085
+ siteId
34086
+ }) {
34087
+ const [engaged, keys] = await Promise.all([
34088
+ _getEngaged(siteId),
34089
+ _getSiteProviderKeys(siteId)
34090
+ ]);
34091
+ const needle = search.trim().toLowerCase();
34092
+ const derived = engaged.filter(
34093
+ (row) => !keys.orgIds.has(row.serviceProviderOrgId?.toString?.() ?? "") && !(row.email && keys.emails.has(String(row.email).trim().toLowerCase())) && (!needle || String(row.name ?? "").toLowerCase().includes(needle))
34094
+ );
34095
+ const stored = (p, l) => _getServiceProviders({ search, page: p, limit: l, siteId, status: "active" });
34096
+ if (!derived.length)
34097
+ return await stored(page, limit);
34098
+ const start = (Math.max(page, 1) - 1) * limit;
34099
+ const fromDerived = derived.slice(start, start + limit);
34100
+ const need = limit - fromDerived.length;
34101
+ const storedStart = Math.max(0, start - derived.length);
34102
+ const first = await stored(1, Math.max(storedStart + need, 1));
34103
+ const total = derived.length + totalOf(first);
34104
+ const fromStored = need > 0 ? (first?.items ?? []).slice(storedStart, storedStart + need) : [];
34105
+ return (0, import_node_server_utils102.paginate)([...fromDerived, ...fromStored], Math.max(page, 1) - 1, limit, total);
34106
+ }
34107
+ function totalOf(data) {
34108
+ const match = /of\s+(\d+)/.exec(String(data?.pageRange ?? ""));
34109
+ return match ? Number(match[1]) : (data?.items ?? []).length;
34110
+ }
33723
34111
  return {
33724
34112
  createServiceProvider,
33725
- getServiceProviders
34113
+ getServiceProviders,
34114
+ getServiceProvidersForSite
33726
34115
  };
33727
34116
  }
33728
34117
 
@@ -33737,7 +34126,18 @@ function useServiceProviderController() {
33737
34126
  getByEmail: _getByEmail,
33738
34127
  updateStatusById: _updateStatusById
33739
34128
  } = useServiceProviderRepo();
33740
- const { createServiceProvider: _createServiceProvider } = useServiceProviderService();
34129
+ const {
34130
+ createServiceProvider: _createServiceProvider,
34131
+ getServiceProvidersForSite: _getServiceProvidersForSite
34132
+ } = useServiceProviderService();
34133
+ async function isSiteClient(req, siteId) {
34134
+ const actor = await resolveInviteActor(callerId(req));
34135
+ if (staffMayBypass(actor))
34136
+ return true;
34137
+ const site = await useSiteRepo().getSiteById(siteId).catch(() => null);
34138
+ const owner = (site?.orgId ?? site?.org)?.toString?.() ?? "";
34139
+ return Boolean(owner) && actor.orgIds.includes(owner);
34140
+ }
33741
34141
  const { createServiceProvider: _add } = useServiceProviderRepo();
33742
34142
  async function createServiceProvider(req, res, next) {
33743
34143
  const validation = import_joi46.default.string().hex().required();
@@ -33766,7 +34166,12 @@ function useServiceProviderController() {
33766
34166
  orgId: import_joi46.default.string().hex().optional().allow("", null),
33767
34167
  siteId: import_joi46.default.string().hex().optional().allow("", null),
33768
34168
  serviceProviderOrgId: import_joi46.default.string().hex().optional().allow("", null),
33769
- status: import_joi46.default.string().optional().allow("", null)
34169
+ status: import_joi46.default.string().optional().allow("", null),
34170
+ // "engagements": also list providers engaged through an accepted
34171
+ // invitation. Opt-in, because those rows carry the engagement's id, not
34172
+ // a service-providers id - a caller that stores the id (the MA app's
34173
+ // feedback provider picker) must keep getting stored rows only.
34174
+ include: import_joi46.default.string().valid("engagements").optional().allow("", null)
33770
34175
  });
33771
34176
  const query2 = { ...req.query };
33772
34177
  const { error } = validation.validate(query2);
@@ -33783,7 +34188,9 @@ function useServiceProviderController() {
33783
34188
  const serviceProviderOrgId = req.query.serviceProviderOrgId ?? "";
33784
34189
  const status = req.query.status ?? "active";
33785
34190
  try {
33786
- const data = await _getServiceProviders({
34191
+ if (siteId)
34192
+ await requireSiteReach(req, siteId);
34193
+ const data = req.query.include === "engagements" && siteId && status === "active" && !orgId && !serviceProviderOrgId && await isSiteClient(req, siteId) ? await _getServiceProvidersForSite({ search, page, limit, siteId }) : await _getServiceProviders({
33787
34194
  search,
33788
34195
  page,
33789
34196
  limit,
@@ -43319,7 +43726,7 @@ function useCustomerSiteController() {
43319
43726
  }
43320
43727
  }
43321
43728
  async function getAll(req, res, next) {
43322
- const allowedFields = ["createdAt", "name"];
43729
+ const allowedFields = ["createdAt", "name", "siteOrgName"];
43323
43730
  const allowedOrder = ["asc", "desc"];
43324
43731
  const validation = import_joi61.default.object({
43325
43732
  search: import_joi61.default.string().optional().allow("", null),
@@ -43328,7 +43735,13 @@ function useCustomerSiteController() {
43328
43735
  sort: import_joi61.default.string().pattern(/^([a-zA-Z0-9_]+)(,[a-zA-Z0-9_]+)*$/).optional().allow("", ...allowedFields),
43329
43736
  order: import_joi61.default.string().pattern(/^(asc|desc)(,(asc|desc))*$/).optional().allow("", ...allowedOrder),
43330
43737
  org: import_joi61.default.string().hex().required(),
43331
- status: import_joi61.default.string().required()
43738
+ status: import_joi61.default.string().required(),
43739
+ // The Organization app's Sites list filters. All optional: every other
43740
+ // caller (site switchers, mobile pickers) sends none of them and gets
43741
+ // exactly the list it got before.
43742
+ relationship: import_joi61.default.string().valid(...SITE_RELATIONSHIPS).optional().allow("", null),
43743
+ client: import_joi61.default.string().hex().length(24).optional().allow("", null),
43744
+ category: import_joi61.default.string().valid(...Object.values(SiteCategories)).optional().allow("", null)
43332
43745
  });
43333
43746
  const query2 = { ...req.query };
43334
43747
  const { error } = validation.validate(query2);
@@ -43342,6 +43755,9 @@ function useCustomerSiteController() {
43342
43755
  const limit = parseInt(req.query.limit ?? "10");
43343
43756
  const org = req.query.org ?? "";
43344
43757
  const status = req.query.status ?? "active";
43758
+ const relationship = req.query.relationship || "";
43759
+ const client = req.query.client || "";
43760
+ const category = req.query.category || "";
43345
43761
  const sortObj = {};
43346
43762
  const sortFields = String(req.query.sort).split(",");
43347
43763
  const sortOrders = String(req.query.order).split(",");
@@ -43361,7 +43777,10 @@ function useCustomerSiteController() {
43361
43777
  sort: sortObj,
43362
43778
  org,
43363
43779
  status,
43364
- siteScope
43780
+ siteScope,
43781
+ relationship,
43782
+ client,
43783
+ category
43365
43784
  });
43366
43785
  res.json(data);
43367
43786
  return;
@@ -45349,7 +45768,7 @@ function usePersonService() {
45349
45768
  let set = {};
45350
45769
  const cleanInput = (str) => str.replace(/\s+/g, "");
45351
45770
  const cleanPhone = (str) => str.replace(/\D/g, "");
45352
- const escapeRegex2 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45771
+ const escapeRegex3 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45353
45772
  const nric = value.nric ? cleanInput(value.nric) : "";
45354
45773
  const name = value.name?.trim();
45355
45774
  const contact = value.contact?.trim();
@@ -45357,8 +45776,8 @@ function usePersonService() {
45357
45776
  const email = value.email?.trim();
45358
45777
  const type = value.type?.trim();
45359
45778
  const company = value.company?.trim();
45360
- const nricQuery = nric ? { nric: { $regex: `^${escapeRegex2(nric)}$`, $options: "i" } } : null;
45361
- const nameQuery = name ? { name: { $regex: `^${escapeRegex2(name)}$`, $options: "i" } } : null;
45779
+ const nricQuery = nric ? { nric: { $regex: `^${escapeRegex3(nric)}$`, $options: "i" } } : null;
45780
+ const nameQuery = name ? { name: { $regex: `^${escapeRegex3(name)}$`, $options: "i" } } : null;
45362
45781
  let nricCondition = null;
45363
45782
  if (nric) {
45364
45783
  if (nric.length < 9) {
@@ -45371,8 +45790,8 @@ function usePersonService() {
45371
45790
  }
45372
45791
  const orConditions = [
45373
45792
  ...nricCondition ? [nricCondition] : [],
45374
- ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex2(contact))}$`, $options: "i" } }] : [],
45375
- ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex2(plateNumber)}$`, $options: "i" } }] : []
45793
+ ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex3(contact))}$`, $options: "i" } }] : [],
45794
+ ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex3(plateNumber)}$`, $options: "i" } }] : []
45376
45795
  ];
45377
45796
  const existingPerson2 = await findFirstTen(
45378
45797
  {
@@ -47259,7 +47678,7 @@ function useHidAmicoRepo() {
47259
47678
  passwordSet: Boolean(password)
47260
47679
  };
47261
47680
  }
47262
- function escapeRegex2(value) {
47681
+ function escapeRegex3(value) {
47263
47682
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
47264
47683
  }
47265
47684
  function buildIdentityKeyQuery(value) {
@@ -47462,7 +47881,7 @@ function useHidAmicoRepo() {
47462
47881
  query2.type = value.type;
47463
47882
  }
47464
47883
  if (value.search) {
47465
- const search = escapeRegex2(value.search);
47884
+ const search = escapeRegex3(value.search);
47466
47885
  query2.$or = [
47467
47886
  { hidUserId: { $regex: search, $options: "i" } },
47468
47887
  { registration: { $regex: search, $options: "i" } },
@@ -47703,7 +48122,7 @@ function useHidAmicoRepo() {
47703
48122
  const text2 = search.trim();
47704
48123
  if (!text2)
47705
48124
  return {};
47706
- const pattern = { $regex: escapeRegex2(text2), $options: "i" };
48125
+ const pattern = { $regex: escapeRegex3(text2), $options: "i" };
47707
48126
  return {
47708
48127
  $or: [
47709
48128
  { name: pattern },
@@ -60081,7 +60500,7 @@ var NETWORK_SORTS = {
60081
60500
  };
60082
60501
  var NETWORK_OFFLINE_CODE = "OFFLINE";
60083
60502
  var ROBOT_FAULTS_COLLECTION = "robot-faults";
60084
- function escapeRegex(value) {
60503
+ function escapeRegex2(value) {
60085
60504
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
60086
60505
  }
60087
60506
  function matchDefaulted(field, value, fallback) {
@@ -60185,7 +60604,7 @@ function networkListPipeline(q) {
60185
60604
  pipeline.push({ $match: { offline: true } });
60186
60605
  const search = (q.search ?? "").trim();
60187
60606
  if (search) {
60188
- const rx = { $regex: escapeRegex(search), $options: "i" };
60607
+ const rx = { $regex: escapeRegex2(search), $options: "i" };
60189
60608
  pipeline.push({
60190
60609
  $match: { $or: [{ name: rx }, { robotSn: rx }, { "client.name": rx }, { "site.name": rx }] }
60191
60610
  });
@@ -67345,7 +67764,7 @@ function usePatrolEmailRepo() {
67345
67764
  throw new import_node_server_utils177.BadRequestError(`Invalid ${label2} format.`);
67346
67765
  }
67347
67766
  }
67348
- function escapeRegex2(value) {
67767
+ function escapeRegex3(value) {
67349
67768
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
67350
67769
  }
67351
67770
  async function createIndexes() {
@@ -67482,8 +67901,8 @@ function usePatrolEmailRepo() {
67482
67901
  ...status ? { status } : { status: { $ne: "deleted" } },
67483
67902
  ...search && {
67484
67903
  $or: [
67485
- { subject: { $regex: escapeRegex2(search), $options: "i" } },
67486
- { recipients: { $regex: escapeRegex2(search), $options: "i" } }
67904
+ { subject: { $regex: escapeRegex3(search), $options: "i" } },
67905
+ { recipients: { $regex: escapeRegex3(search), $options: "i" } }
67487
67906
  ]
67488
67907
  }
67489
67908
  };
@@ -83898,6 +84317,8 @@ var Period = /* @__PURE__ */ ((Period2) => {
83898
84317
  Period2["THIS_MONTH"] = "thisMonth";
83899
84318
  return Period2;
83900
84319
  })(Period || {});
84320
+ var WORK_ORDER_DELETED = ["Deleted", "deleted"];
84321
+ var WORK_ORDER_NOT_OPEN = ["Completed", ...WORK_ORDER_DELETED];
83901
84322
  function useNewDashboardRepo() {
83902
84323
  const db2 = import_node_server_utils252.useAtlas.getDb();
83903
84324
  if (!db2) {
@@ -83999,7 +84420,7 @@ function useNewDashboardRepo() {
83999
84420
  $match: {
84000
84421
  site: { $in: [siteIdObj, siteId] },
84001
84422
  service: "Security",
84002
- status: { $nin: ["Completed", "Deleted"] }
84423
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84003
84424
  }
84004
84425
  },
84005
84426
  {
@@ -84031,7 +84452,7 @@ function useNewDashboardRepo() {
84031
84452
  site: { $in: [siteIdObj, siteId] },
84032
84453
  service: "Security",
84033
84454
  createdAt: priorPeriodRange,
84034
- status: { $nin: ["Completed", "Deleted"] }
84455
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84035
84456
  }
84036
84457
  },
84037
84458
  { $count: "count" }
@@ -84042,7 +84463,7 @@ function useNewDashboardRepo() {
84042
84463
  site: { $in: [siteIdObj, siteId] },
84043
84464
  service: "Security",
84044
84465
  createdAt: periodRange,
84045
- status: { $nin: ["Completed", "Deleted"] }
84466
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84046
84467
  }
84047
84468
  },
84048
84469
  { $count: "count" }
@@ -84402,7 +84823,7 @@ function useNewDashboardRepo() {
84402
84823
  {
84403
84824
  $match: {
84404
84825
  site: { $in: [siteIdObj, siteId] },
84405
- status: { $nin: ["Completed", "Deleted"] }
84826
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84406
84827
  }
84407
84828
  },
84408
84829
  {
@@ -84433,7 +84854,7 @@ function useNewDashboardRepo() {
84433
84854
  $match: {
84434
84855
  site: { $in: [siteIdObj, siteId] },
84435
84856
  createdAt: priorPeriodRange,
84436
- status: { $nin: ["Completed", "Deleted"] }
84857
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84437
84858
  }
84438
84859
  },
84439
84860
  { $count: "count" }
@@ -84443,7 +84864,7 @@ function useNewDashboardRepo() {
84443
84864
  $match: {
84444
84865
  site: { $in: [siteIdObj, siteId] },
84445
84866
  createdAt: periodRange,
84446
- status: { $nin: ["Completed", "Deleted"] }
84867
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84447
84868
  }
84448
84869
  },
84449
84870
  { $count: "count" }
@@ -84627,7 +85048,8 @@ function useNewDashboardRepo() {
84627
85048
  {
84628
85049
  $match: {
84629
85050
  site: { $in: [siteIdObj, siteId] },
84630
- createdAt: periodRange
85051
+ createdAt: periodRange,
85052
+ status: { $nin: WORK_ORDER_DELETED }
84631
85053
  }
84632
85054
  },
84633
85055
  {
@@ -84789,7 +85211,7 @@ function useNewDashboardRepo() {
84789
85211
  const workOrderService = workOrderServiceMap[serviceType] ?? serviceType;
84790
85212
  const workOrderMatchQuery = {
84791
85213
  site,
84792
- status: { $nin: ["Completed", "Deleted"] }
85214
+ status: { $nin: WORK_ORDER_NOT_OPEN }
84793
85215
  };
84794
85216
  if (serviceType !== "property_management_agency") {
84795
85217
  workOrderMatchQuery.service = workOrderService;
@@ -84965,7 +85387,7 @@ function useNewDashboardRepo() {
84965
85387
  try {
84966
85388
  const workOrderQuery = {
84967
85389
  site,
84968
- status: { $nin: ["Deleted"] },
85390
+ status: { $nin: WORK_ORDER_DELETED },
84969
85391
  $or: [
84970
85392
  { createdAt: { $gte: rangeStart, $lte: rangeEnd } },
84971
85393
  {
@@ -85684,7 +86106,7 @@ function filterByShiftTime(attendance, shiftData, timezone, format2) {
85684
86106
  return checkInLocal.isBetween(shiftStart, shiftEnd, null, "[]");
85685
86107
  });
85686
86108
  }
85687
- function paginate58(data, page, limit) {
86109
+ function paginate59(data, page, limit) {
85688
86110
  const length = data.length;
85689
86111
  const startIndex = (page - 1) * limit;
85690
86112
  const endIndex = startIndex + limit;
@@ -86032,7 +86454,7 @@ var hrmlabs_attendance_util_default = {
86032
86454
  hrmLabsAuthentication,
86033
86455
  fetchAttendanceData,
86034
86456
  filterByShiftTime,
86035
- paginate: paginate58,
86457
+ paginate: paginate59,
86036
86458
  designationCount,
86037
86459
  totalCountPerShift,
86038
86460
  filterByStatus,
@@ -87769,7 +88191,7 @@ var {
87769
88191
  hrmLabsAuthentication: hrmLabsAuthentication3,
87770
88192
  fetchAttendanceData: fetchAttendanceData2,
87771
88193
  filterByShiftTime: filterByShiftTime2,
87772
- paginate: paginate64,
88194
+ paginate: paginate65,
87773
88195
  designationCount: designationCount2,
87774
88196
  totalCountPerShift: totalCountPerShift2,
87775
88197
  filterByStatus: filterByStatus2,
@@ -87879,7 +88301,7 @@ function useHrmLabsAttendanceSrvc() {
87879
88301
  status
87880
88302
  );
87881
88303
  }
87882
- const paginatedItems = paginate64(filteredAttendance, page, limit);
88304
+ const paginatedItems = paginate65(filteredAttendance, page, limit);
87883
88305
  return {
87884
88306
  items: paginatedItems.items,
87885
88307
  pages: paginatedItems.pages,
@@ -92179,6 +92601,7 @@ function useServiceProviderInviteController() {
92179
92601
  try {
92180
92602
  const schema2 = import_joi149.default.object({
92181
92603
  org: import_joi149.default.string().hex().length(24).optional().allow("", null),
92604
+ siteId: import_joi149.default.string().hex().length(24).optional().allow("", null),
92182
92605
  status: import_joi149.default.string().optional().allow("", null),
92183
92606
  search: import_joi149.default.string().max(200).optional().allow("", null),
92184
92607
  page: import_joi149.default.number().min(1).default(1),
@@ -92188,10 +92611,13 @@ function useServiceProviderInviteController() {
92188
92611
  if (error)
92189
92612
  throw new import_node_server_utils282.BadRequestError(`Invalid input: ${error.message}`);
92190
92613
  const statuses = String(value.status ?? "").split(",").map((s) => s.trim()).filter(Boolean);
92614
+ if (value.siteId)
92615
+ await requireSiteReach(req, value.siteId);
92191
92616
  res.json(
92192
92617
  await listForCaller({
92193
92618
  userId: callerId5(req),
92194
92619
  orgId: value.org || void 0,
92620
+ siteId: value.siteId || void 0,
92195
92621
  statuses,
92196
92622
  search: value.search || "",
92197
92623
  page: value.page,