@7365admin1/core 3.99.1-staging.372 → 3.99.1-staging.373

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ ---
2
+ "@7365admin1/core": minor
3
+ ---
4
+
5
+ Sites list (`GET /api/customer-sites`): optional `relationship` (own|served), `client` and `category` filters, search across site name, client name and address (literal, no regex), sort by `siteOrgName`. Each row now also carries `relationship`, `siteAddress`, `siteCategory` and, on a served site, `invitation` (who invited this company and when, only when an accepted invitation records this company). The response adds `clients` for the Client filter. Callers that send none of the new params get the same rows as before.
package/dist/index.d.ts CHANGED
@@ -5953,7 +5953,7 @@ declare function MCustomerSite(value: TCustomerSite): {
5953
5953
  declare function useCustomerSiteRepo(): {
5954
5954
  createIndexes: () => Promise<void>;
5955
5955
  add: (value: TCustomerSite, session?: ClientSession) => Promise<ObjectId>;
5956
- getAll: ({ search, page, limit, sort, org, status, siteScope, }: {
5956
+ getAll: ({ search, page, limit, sort, org, status, siteScope, relationship, client, category, }: {
5957
5957
  search?: string | undefined;
5958
5958
  page?: number | undefined;
5959
5959
  limit?: number | undefined;
@@ -5967,6 +5967,12 @@ declare function useCustomerSiteRepo(): {
5967
5967
  * counts and `pageRange` describe what the caller can actually see.
5968
5968
  */
5969
5969
  siteScope?: string[] | null | undefined;
5970
+ /** "own" | "served" | "" (all). See customer-site-list.util. */
5971
+ relationship?: string | undefined;
5972
+ /** Only the sites this client organisation owns. */
5973
+ client?: string | undefined;
5974
+ /** The site's category (live from the site, the row as a fallback). */
5975
+ category?: string | undefined;
5970
5976
  }, session?: ClientSession) => Promise<{}>;
5971
5977
  getByName: (value: {
5972
5978
  name: string;
package/dist/index.js CHANGED
@@ -8585,6 +8585,91 @@ function MCustomerSite(value) {
8585
8585
  // src/repositories/customer-site.repo.ts
8586
8586
  var import_mongodb24 = require("mongodb");
8587
8587
  var import_joi13 = __toESM(require("joi"));
8588
+
8589
+ // src/utils/customer-site-list.util.ts
8590
+ var SITE_RELATIONSHIPS = ["own", "served"];
8591
+ var SP_INVITE_TYPES = [
8592
+ "service-provider-invite",
8593
+ "service-provider-create-org"
8594
+ ];
8595
+ function escapeRegex2(value) {
8596
+ return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8597
+ }
8598
+ function relationshipMatch(org, relationship, client) {
8599
+ const self = [org, String(org)];
8600
+ const match = {};
8601
+ const and = [];
8602
+ if (relationship === "own") {
8603
+ and.push({ siteOrg: { $in: [...self, null, ""] } });
8604
+ } else if (relationship === "served") {
8605
+ and.push({ siteOrg: { $nin: [...self, null, ""] } });
8606
+ }
8607
+ if (client) {
8608
+ and.push(
8609
+ { siteOrg: { $in: [client, String(client)] } },
8610
+ { siteOrg: { $nin: self } }
8611
+ );
8612
+ }
8613
+ if (and.length)
8614
+ match.$and = and;
8615
+ return match;
8616
+ }
8617
+ function relationshipField(orgId) {
8618
+ return {
8619
+ relationship: {
8620
+ $cond: [
8621
+ {
8622
+ $or: [
8623
+ { $in: [{ $ifNull: ["$siteOrg", ""] }, ["", null]] },
8624
+ { $eq: [{ $toString: "$siteOrg" }, orgId] }
8625
+ ]
8626
+ },
8627
+ "own",
8628
+ "served"
8629
+ ]
8630
+ }
8631
+ };
8632
+ }
8633
+ function searchMatch(search) {
8634
+ const term = String(search ?? "").trim();
8635
+ if (!term)
8636
+ return null;
8637
+ const re = { $regex: escapeRegex2(term), $options: "i" };
8638
+ return {
8639
+ $or: [
8640
+ { name: re },
8641
+ { siteOrgName: re },
8642
+ { "siteAddress.line1": re },
8643
+ { "siteAddress.line2": re },
8644
+ { "siteAddress.city": re },
8645
+ { "siteAddress.postalCode": re },
8646
+ { "siteAddress.country": re }
8647
+ ]
8648
+ };
8649
+ }
8650
+ var iso = (value) => {
8651
+ if (!value)
8652
+ return null;
8653
+ const d = new Date(value);
8654
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
8655
+ };
8656
+ function invitationFor(siteId, invites) {
8657
+ const mine = invites.filter((v2) => String(v2?.metadata?.siteId ?? "") === siteId).sort(
8658
+ (a, b) => new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime()
8659
+ );
8660
+ const v = mine[0];
8661
+ if (!v)
8662
+ return null;
8663
+ const accepted = [...v.history ?? []].reverse().find((h) => h?.action === "accepted" || h?.action === "site-linked");
8664
+ return {
8665
+ id: String(v._id ?? ""),
8666
+ invitedByName: String(v.metadata?.invitedByName ?? ""),
8667
+ invitedAt: iso(v.createdAt),
8668
+ acceptedAt: iso(accepted?.at)
8669
+ };
8670
+ }
8671
+
8672
+ // src/repositories/customer-site.repo.ts
8588
8673
  function useCustomerSiteRepo() {
8589
8674
  const db2 = import_node_server_utils26.useAtlas.getDb();
8590
8675
  if (!db2) {
@@ -8592,6 +8677,7 @@ function useCustomerSiteRepo() {
8592
8677
  }
8593
8678
  const namespace_collection3 = "customer.sites";
8594
8679
  const collection = db2.collection(namespace_collection3);
8680
+ const verifications = db2.collection("verifications");
8595
8681
  const { delNamespace, getCache, setCache } = (0, import_node_server_utils26.useCache)(namespace_collection3);
8596
8682
  async function createIndexes() {
8597
8683
  try {
@@ -8681,7 +8767,10 @@ function useCustomerSiteRepo() {
8681
8767
  sort = {},
8682
8768
  org = "",
8683
8769
  status = "active",
8684
- siteScope = null
8770
+ siteScope = null,
8771
+ relationship = "",
8772
+ client = "",
8773
+ category = ""
8685
8774
  }, session) {
8686
8775
  page = page > 0 ? page - 1 : 0;
8687
8776
  try {
@@ -8693,6 +8782,14 @@ function useCustomerSiteRepo() {
8693
8782
  org,
8694
8783
  status
8695
8784
  };
8785
+ let clientId = null;
8786
+ if (client) {
8787
+ try {
8788
+ clientId = new import_mongodb24.ObjectId(client);
8789
+ } catch (error) {
8790
+ throw new import_node_server_utils26.BadRequestError("Invalid client ID format.");
8791
+ }
8792
+ }
8696
8793
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
8697
8794
  const cacheOptions = {
8698
8795
  org: org.toString(),
@@ -8709,6 +8806,12 @@ function useCustomerSiteRepo() {
8709
8806
  if (search) {
8710
8807
  cacheOptions.search = search;
8711
8808
  }
8809
+ if (relationship)
8810
+ cacheOptions.relationship = relationship;
8811
+ if (client)
8812
+ cacheOptions.client = client;
8813
+ if (category)
8814
+ cacheOptions.category = category;
8712
8815
  const cacheKey = (0, import_node_server_utils26.makeCacheKey)(namespace_collection3, cacheOptions);
8713
8816
  const cachedData = await getCache(cacheKey);
8714
8817
  if (cachedData) {
@@ -8716,8 +8819,14 @@ function useCustomerSiteRepo() {
8716
8819
  return cachedData;
8717
8820
  }
8718
8821
  try {
8822
+ const orgId = org.toString();
8823
+ const search_ = searchMatch(search);
8824
+ const listMatch = {
8825
+ ...query2,
8826
+ ...relationshipMatch(org, relationship, clientId)
8827
+ };
8719
8828
  const distinctPipeline = [
8720
- { $match: query2 },
8829
+ { $match: listMatch },
8721
8830
  { $sort: sort },
8722
8831
  { $group: { _id: "$site", doc: { $first: "$$ROOT" } } },
8723
8832
  { $replaceRoot: { newRoot: "$doc" } },
@@ -8734,8 +8843,22 @@ function useCustomerSiteRepo() {
8734
8843
  // The site's own timezone, so the Edit Site form opens on the zone the
8735
8844
  // site really has. Lives only on the site, never on this row.
8736
8845
  { $set: { timezone: "$_liveSite.timezone" } },
8846
+ /*
8847
+ * The Sites list's columns. Address and category come from the SITE,
8848
+ * like the name: a served site's engagement row was written by the
8849
+ * invitation with neither. The row's own `address` / `category` are
8850
+ * left exactly as they were for every other caller.
8851
+ */
8852
+ {
8853
+ $set: {
8854
+ siteAddress: { $ifNull: ["$_liveSite.address", "$address"] },
8855
+ siteCategory: { $ifNull: ["$_liveSite.category", "$category"] },
8856
+ ...relationshipField(orgId)
8857
+ }
8858
+ },
8737
8859
  { $unset: "_liveSite" },
8738
- ...search ? [{ $match: { name: { $regex: search, $options: "i" } } }] : [],
8860
+ ...search_ ? [{ $match: search_ }] : [],
8861
+ ...category ? [{ $match: { siteCategory: category } }] : [],
8739
8862
  { $sort: sort }
8740
8863
  ];
8741
8864
  const items = await collection.aggregate(
@@ -8748,7 +8871,54 @@ function useCustomerSiteRepo() {
8748
8871
  ).toArray();
8749
8872
  const countResult = await collection.aggregate([...distinctPipeline, { $count: "total" }], { session }).toArray();
8750
8873
  const length = countResult[0]?.total ?? 0;
8751
- const data = (0, import_node_server_utils26.paginate)(items, page, limit, length);
8874
+ const servedSites = items.filter((row) => row.relationship === "served" && row.site).map((row) => row.site);
8875
+ if (servedSites.length) {
8876
+ const invites = await verifications.find(
8877
+ {
8878
+ type: { $in: SP_INVITE_TYPES },
8879
+ status: "complete",
8880
+ "metadata.providerOrg": { $in: [orgId, org] },
8881
+ "metadata.siteId": {
8882
+ $in: [...servedSites, ...servedSites.map(String)]
8883
+ }
8884
+ },
8885
+ {
8886
+ projection: {
8887
+ createdAt: 1,
8888
+ history: 1,
8889
+ "metadata.siteId": 1,
8890
+ "metadata.invitedByName": 1
8891
+ },
8892
+ session
8893
+ }
8894
+ ).toArray().catch((error) => {
8895
+ import_node_server_utils26.logger.error(
8896
+ `Sites list: invitation lookup failed: ${error?.message}`
8897
+ );
8898
+ return [];
8899
+ });
8900
+ for (const row of items) {
8901
+ if (row.relationship === "served") {
8902
+ row.invitation = invitationFor(String(row.site), invites);
8903
+ }
8904
+ }
8905
+ }
8906
+ const clients = await collection.aggregate(
8907
+ [
8908
+ { $match: { ...query2, ...relationshipMatch(org, "served") } },
8909
+ { $sort: { _id: -1 } },
8910
+ { $group: { _id: "$siteOrg", name: { $first: "$siteOrgName" } } },
8911
+ { $sort: { name: 1 } }
8912
+ ],
8913
+ { session }
8914
+ ).toArray();
8915
+ const data = {
8916
+ ...(0, import_node_server_utils26.paginate)(items, page, limit, length),
8917
+ clients: clients.map((c) => ({
8918
+ _id: String(c._id),
8919
+ name: c.name ?? ""
8920
+ }))
8921
+ };
8752
8922
  setCache(cacheKey, data, 15 * 60).then(() => {
8753
8923
  import_node_server_utils26.logger.info(`Cache set for key: ${cacheKey}`);
8754
8924
  }).catch((err) => {
@@ -20569,7 +20739,7 @@ function useVehicleRepo() {
20569
20739
  let query2 = { ...baseQuery };
20570
20740
  if (search)
20571
20741
  query2.$text = { $search: search };
20572
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20742
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20573
20743
  const buildGroupedPipeline = (matchQuery) => [
20574
20744
  { $match: matchQuery },
20575
20745
  {
@@ -20753,7 +20923,7 @@ function useVehicleRepo() {
20753
20923
  const countResult = await collection.aggregate(buildGroupedCountPipeline(query2)).toArray();
20754
20924
  length = countResult[0]?.total || 0;
20755
20925
  if ((!items || items.length === 0) && search) {
20756
- const escaped = escapeRegex3(search);
20926
+ const escaped = escapeRegex4(search);
20757
20927
  const regexQuery = {
20758
20928
  ...baseQuery,
20759
20929
  $or: [
@@ -21542,7 +21712,7 @@ function useVehicleRepo() {
21542
21712
  ...baseQuery,
21543
21713
  ...search && { $text: { $search: search } }
21544
21714
  };
21545
- const escapeRegex3 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21715
+ const escapeRegex4 = (input) => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21546
21716
  const buildPipeline = (matchQuery) => [
21547
21717
  { $match: matchQuery },
21548
21718
  {
@@ -21570,7 +21740,7 @@ function useVehicleRepo() {
21570
21740
  const countResult = await collection.aggregate(buildCountPipeline(query2)).toArray();
21571
21741
  length = countResult[0]?.total || 0;
21572
21742
  if ((!items || items.length === 0) && search) {
21573
- const escaped = escapeRegex3(search);
21743
+ const escaped = escapeRegex4(search);
21574
21744
  const regexQuery = {
21575
21745
  ...baseQuery,
21576
21746
  $or: [
@@ -29737,9 +29907,9 @@ function parsePromoExpiry(value) {
29737
29907
  const us = raw.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
29738
29908
  if (us)
29739
29909
  return endOfDay(us[3], us[1], us[2]);
29740
- const iso = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/);
29741
- if (iso)
29742
- return endOfDay(iso[1], iso[2], iso[3]);
29910
+ const iso2 = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/);
29911
+ if (iso2)
29912
+ return endOfDay(iso2[1], iso2[2], iso2[3]);
29743
29913
  const parsed = new Date(raw);
29744
29914
  return Number.isNaN(parsed.getTime()) ? null : parsed;
29745
29915
  }
@@ -43655,7 +43825,7 @@ function useCustomerSiteController() {
43655
43825
  }
43656
43826
  }
43657
43827
  async function getAll(req, res, next) {
43658
- const allowedFields = ["createdAt", "name"];
43828
+ const allowedFields = ["createdAt", "name", "siteOrgName"];
43659
43829
  const allowedOrder = ["asc", "desc"];
43660
43830
  const validation = import_joi61.default.object({
43661
43831
  search: import_joi61.default.string().optional().allow("", null),
@@ -43664,7 +43834,13 @@ function useCustomerSiteController() {
43664
43834
  sort: import_joi61.default.string().pattern(/^([a-zA-Z0-9_]+)(,[a-zA-Z0-9_]+)*$/).optional().allow("", ...allowedFields),
43665
43835
  order: import_joi61.default.string().pattern(/^(asc|desc)(,(asc|desc))*$/).optional().allow("", ...allowedOrder),
43666
43836
  org: import_joi61.default.string().hex().required(),
43667
- status: import_joi61.default.string().required()
43837
+ status: import_joi61.default.string().required(),
43838
+ // The Organization app's Sites list filters. All optional: every other
43839
+ // caller (site switchers, mobile pickers) sends none of them and gets
43840
+ // exactly the list it got before.
43841
+ relationship: import_joi61.default.string().valid(...SITE_RELATIONSHIPS).optional().allow("", null),
43842
+ client: import_joi61.default.string().hex().length(24).optional().allow("", null),
43843
+ category: import_joi61.default.string().valid(...Object.values(SiteCategories)).optional().allow("", null)
43668
43844
  });
43669
43845
  const query2 = { ...req.query };
43670
43846
  const { error } = validation.validate(query2);
@@ -43678,6 +43854,9 @@ function useCustomerSiteController() {
43678
43854
  const limit = parseInt(req.query.limit ?? "10");
43679
43855
  const org = req.query.org ?? "";
43680
43856
  const status = req.query.status ?? "active";
43857
+ const relationship = req.query.relationship || "";
43858
+ const client = req.query.client || "";
43859
+ const category = req.query.category || "";
43681
43860
  const sortObj = {};
43682
43861
  const sortFields = String(req.query.sort).split(",");
43683
43862
  const sortOrders = String(req.query.order).split(",");
@@ -43697,7 +43876,10 @@ function useCustomerSiteController() {
43697
43876
  sort: sortObj,
43698
43877
  org,
43699
43878
  status,
43700
- siteScope
43879
+ siteScope,
43880
+ relationship,
43881
+ client,
43882
+ category
43701
43883
  });
43702
43884
  res.json(data);
43703
43885
  return;
@@ -45784,7 +45966,7 @@ function usePersonService() {
45784
45966
  let set = {};
45785
45967
  const cleanInput = (str) => str.replace(/\s+/g, "");
45786
45968
  const cleanPhone = (str) => str.replace(/\D/g, "");
45787
- const escapeRegex3 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45969
+ const escapeRegex4 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45788
45970
  const nric = value.nric ? cleanInput(value.nric) : "";
45789
45971
  const name = value.name?.trim();
45790
45972
  const contact = value.contact?.trim();
@@ -45792,8 +45974,8 @@ function usePersonService() {
45792
45974
  const email = value.email?.trim();
45793
45975
  const type = value.type?.trim();
45794
45976
  const company = value.company?.trim();
45795
- const nricQuery = nric ? { nric: { $regex: `^${escapeRegex3(nric)}$`, $options: "i" } } : null;
45796
- const nameQuery = name ? { name: { $regex: `^${escapeRegex3(name)}$`, $options: "i" } } : null;
45977
+ const nricQuery = nric ? { nric: { $regex: `^${escapeRegex4(nric)}$`, $options: "i" } } : null;
45978
+ const nameQuery = name ? { name: { $regex: `^${escapeRegex4(name)}$`, $options: "i" } } : null;
45797
45979
  let nricCondition = null;
45798
45980
  if (nric) {
45799
45981
  if (nric.length < 9) {
@@ -45806,8 +45988,8 @@ function usePersonService() {
45806
45988
  }
45807
45989
  const orConditions = [
45808
45990
  ...nricCondition ? [nricCondition] : [],
45809
- ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex3(contact))}$`, $options: "i" } }] : [],
45810
- ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex3(plateNumber)}$`, $options: "i" } }] : []
45991
+ ...contact ? [{ contacts: { $regex: `^\\+?${cleanPhone(escapeRegex4(contact))}$`, $options: "i" } }] : [],
45992
+ ...plateNumber ? [{ plateNumbers: { $regex: `^${escapeRegex4(plateNumber)}$`, $options: "i" } }] : []
45811
45993
  ];
45812
45994
  const existingPerson2 = await findFirstTen(
45813
45995
  {
@@ -47802,7 +47984,7 @@ function useHidAmicoRepo() {
47802
47984
  passwordSet: Boolean(password)
47803
47985
  };
47804
47986
  }
47805
- function escapeRegex3(value) {
47987
+ function escapeRegex4(value) {
47806
47988
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
47807
47989
  }
47808
47990
  function buildIdentityKeyQuery(value) {
@@ -48031,7 +48213,7 @@ function useHidAmicoRepo() {
48031
48213
  { serviceProvider: { $in: subjectIds } },
48032
48214
  { user: { $in: subjectIds } }
48033
48215
  ] : null;
48034
- const search = value.search ? escapeRegex3(value.search) : "";
48216
+ const search = value.search ? escapeRegex4(value.search) : "";
48035
48217
  const searchOr = search ? [
48036
48218
  { hidUserId: { $regex: search, $options: "i" } },
48037
48219
  { registration: { $regex: search, $options: "i" } },
@@ -48444,7 +48626,7 @@ function useHidAmicoRepo() {
48444
48626
  const text2 = search.trim();
48445
48627
  if (!text2)
48446
48628
  return {};
48447
- const pattern = { $regex: escapeRegex3(text2), $options: "i" };
48629
+ const pattern = { $regex: escapeRegex4(text2), $options: "i" };
48448
48630
  return {
48449
48631
  $or: [
48450
48632
  { name: pattern },
@@ -61715,7 +61897,7 @@ var NETWORK_SORTS = {
61715
61897
  };
61716
61898
  var NETWORK_OFFLINE_CODE = "OFFLINE";
61717
61899
  var ROBOT_FAULTS_COLLECTION = "robot-faults";
61718
- function escapeRegex2(value) {
61900
+ function escapeRegex3(value) {
61719
61901
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
61720
61902
  }
61721
61903
  function matchDefaulted(field, value, fallback) {
@@ -61819,7 +62001,7 @@ function networkListPipeline(q) {
61819
62001
  pipeline.push({ $match: { offline: true } });
61820
62002
  const search = (q.search ?? "").trim();
61821
62003
  if (search) {
61822
- const rx = { $regex: escapeRegex2(search), $options: "i" };
62004
+ const rx = { $regex: escapeRegex3(search), $options: "i" };
61823
62005
  pipeline.push({
61824
62006
  $match: { $or: [{ name: rx }, { robotSn: rx }, { "client.name": rx }, { "site.name": rx }] }
61825
62007
  });
@@ -68979,7 +69161,7 @@ function usePatrolEmailRepo() {
68979
69161
  throw new import_node_server_utils177.BadRequestError(`Invalid ${label2} format.`);
68980
69162
  }
68981
69163
  }
68982
- function escapeRegex3(value) {
69164
+ function escapeRegex4(value) {
68983
69165
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
68984
69166
  }
68985
69167
  async function createIndexes() {
@@ -69116,8 +69298,8 @@ function usePatrolEmailRepo() {
69116
69298
  ...status ? { status } : { status: { $ne: "deleted" } },
69117
69299
  ...search && {
69118
69300
  $or: [
69119
- { subject: { $regex: escapeRegex3(search), $options: "i" } },
69120
- { recipients: { $regex: escapeRegex3(search), $options: "i" } }
69301
+ { subject: { $regex: escapeRegex4(search), $options: "i" } },
69302
+ { recipients: { $regex: escapeRegex4(search), $options: "i" } }
69121
69303
  ]
69122
69304
  }
69123
69305
  };