@7365admin1/core 3.5.0 → 3.7.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
@@ -536,13 +536,13 @@ var require_logger = __commonJS({
536
536
  "use strict";
537
537
  exports.__esModule = true;
538
538
  var _utils = require_utils();
539
- var logger198 = {
539
+ var logger197 = {
540
540
  methodMap: ["debug", "info", "warn", "error"],
541
541
  level: "info",
542
542
  // Maps a given level value to the `methodMap` indexes above.
543
543
  lookupLevel: function lookupLevel(level) {
544
544
  if (typeof level === "string") {
545
- var levelMap = _utils.indexOf(logger198.methodMap, level.toLowerCase());
545
+ var levelMap = _utils.indexOf(logger197.methodMap, level.toLowerCase());
546
546
  if (levelMap >= 0) {
547
547
  level = levelMap;
548
548
  } else {
@@ -553,9 +553,9 @@ var require_logger = __commonJS({
553
553
  },
554
554
  // Can be overridden in the host environment
555
555
  log: function log(level) {
556
- level = logger198.lookupLevel(level);
557
- if (typeof console !== "undefined" && logger198.lookupLevel(logger198.level) <= level) {
558
- var method = logger198.methodMap[level];
556
+ level = logger197.lookupLevel(level);
557
+ if (typeof console !== "undefined" && logger197.lookupLevel(logger197.level) <= level) {
558
+ var method = logger197.methodMap[level];
559
559
  if (!console[method]) {
560
560
  method = "log";
561
561
  }
@@ -566,7 +566,7 @@ var require_logger = __commonJS({
566
566
  }
567
567
  }
568
568
  };
569
- exports["default"] = logger198;
569
+ exports["default"] = logger197;
570
570
  module2.exports = exports["default"];
571
571
  }
572
572
  });
@@ -5993,7 +5993,6 @@ __export(src_exports, {
5993
5993
  OvernightParkingRequestSort: () => OvernightParkingRequestSort,
5994
5994
  OvernightParkingRequestStatus: () => OvernightParkingRequestStatus,
5995
5995
  PERSON_TYPES: () => PERSON_TYPES,
5996
- PMDashboardCollection: () => PMDashboardCollection,
5997
5996
  PStatus: () => PStatus,
5998
5997
  Period: () => Period,
5999
5998
  PersonStatus: () => PersonStatus,
@@ -6046,8 +6045,6 @@ __export(src_exports, {
6046
6045
  guests_namespace_collection: () => guests_namespace_collection,
6047
6046
  incidentReportLog: () => incidentReportLog,
6048
6047
  incidents_namespace_collection: () => incidents_namespace_collection,
6049
- landscapeDashboardCollection: () => landscapeDashboardCollection,
6050
- mAndEDashboardCollection: () => mAndEDashboardCollection,
6051
6048
  manpowerDesignationsSchema: () => manpowerDesignationsSchema,
6052
6049
  manpowerEvents: () => manpowerEvents,
6053
6050
  manpowerMonitoringSchema: () => manpowerMonitoringSchema,
@@ -6060,8 +6057,6 @@ __export(src_exports, {
6060
6057
  orgSchema: () => orgSchema,
6061
6058
  overnight_parking_requests_namespace_collection: () => overnight_parking_requests_namespace_collection,
6062
6059
  parseDahuaFind: () => parseDahuaFind,
6063
- pestDashboardCollection: () => pestDashboardCollection,
6064
- poolDashboardCollection: () => poolDashboardCollection,
6065
6060
  promoCodeSchema: () => promoCodeSchema,
6066
6061
  remarksSchema: () => remarksSchema,
6067
6062
  residentFormEntry: () => residentFormEntry,
@@ -6152,7 +6147,6 @@ __export(src_exports, {
6152
6147
  schemaVisitorTransaction: () => schemaVisitorTransaction,
6153
6148
  schemeCamera: () => schemeCamera,
6154
6149
  schemeLogCamera: () => schemeLogCamera,
6155
- securityDashboardCollection: () => securityDashboardCollection,
6156
6150
  shiftSchema: () => shiftSchema,
6157
6151
  siteSchema: () => siteSchema,
6158
6152
  site_people_namespace_collection: () => site_people_namespace_collection,
@@ -18819,7 +18813,7 @@ function useServiceProviderRepo() {
18819
18813
  }) {
18820
18814
  page = page > 0 ? page - 1 : 0;
18821
18815
  const query = { status };
18822
- const cacheOptions = { status };
18816
+ const cacheOptions = { status, page, limit };
18823
18817
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
18824
18818
  cacheOptions.sort = JSON.stringify(sort);
18825
18819
  if (search) {
@@ -21343,11 +21337,22 @@ function useVisitorTransactionRepo() {
21343
21337
  return res.insertedId;
21344
21338
  }
21345
21339
  } catch (error) {
21346
- console.log("Error in add visitor transaction:", error);
21347
21340
  const isDuplicated = error.message.includes("duplicate");
21348
21341
  if (isDuplicated) {
21342
+ import_node_server_utils69.logger.warn({
21343
+ operation: "addVisitorTransaction",
21344
+ reason: "Duplicate entry",
21345
+ site: value.site,
21346
+ error: error.message
21347
+ });
21349
21348
  throw new import_node_server_utils69.BadRequestError("Visitor already exists.");
21350
21349
  }
21350
+ import_node_server_utils69.logger.error({
21351
+ operation: "addVisitorTransaction",
21352
+ site: value.site,
21353
+ error: error.message,
21354
+ stack: error.stack
21355
+ });
21351
21356
  throw error;
21352
21357
  }
21353
21358
  }
@@ -21609,6 +21614,10 @@ function useVisitorTransactionRepo() {
21609
21614
  const data = (0, import_node_server_utils69.paginate)(items, page, limit, totalCount);
21610
21615
  return data;
21611
21616
  } catch (error) {
21617
+ import_node_server_utils69.logger.error("Error in getAll visitor transaction repo", {
21618
+ message: error.message,
21619
+ stack: error.stack
21620
+ });
21612
21621
  throw error;
21613
21622
  }
21614
21623
  }
@@ -21681,6 +21690,22 @@ function useVisitorTransactionRepo() {
21681
21690
  ]).toArray();
21682
21691
  return result;
21683
21692
  } catch (error) {
21693
+ if (error instanceof Error) {
21694
+ import_node_server_utils69.logger.error(
21695
+ "Error in getVisitorTransactionById visitor transaction repo",
21696
+ {
21697
+ message: error.message,
21698
+ stack: error.stack
21699
+ }
21700
+ );
21701
+ } else {
21702
+ import_node_server_utils69.logger.error(
21703
+ "Unknown error in getVisitorTransactionById visitor transaction repo",
21704
+ {
21705
+ error
21706
+ }
21707
+ );
21708
+ }
21684
21709
  throw error;
21685
21710
  }
21686
21711
  }
@@ -21695,9 +21720,19 @@ function useVisitorTransactionRepo() {
21695
21720
  const data = await collection.findOne(query);
21696
21721
  return data;
21697
21722
  } catch (error) {
21698
- throw new import_node_server_utils69.InternalServerError(
21699
- "Failed to fetch visitor transaction by plate number."
21700
- );
21723
+ if (error instanceof Error) {
21724
+ import_node_server_utils69.logger.error("Error in getOpenByPlateNumber visitor transaction repo", {
21725
+ message: error.message,
21726
+ stack: error.stack
21727
+ });
21728
+ } else {
21729
+ import_node_server_utils69.logger.error(
21730
+ "Unknown error in getOpenByPlateNumber visitor transaction repo",
21731
+ {
21732
+ error
21733
+ }
21734
+ );
21735
+ }
21701
21736
  }
21702
21737
  }
21703
21738
  async function updateById(_id, value, session, isManualCheckOut = true) {
@@ -25953,7 +25988,6 @@ function useBuildingUnitRepo() {
25953
25988
  const buildingCollection = await db?.collection("buildings").findOne({ _id: (0, import_node_server_utils76.toObjectId)(block) });
25954
25989
  const blockNumber = buildingCollection?.block;
25955
25990
  query.block = blockNumber !== void 0 ? blockNumber : block;
25956
- console.log("Query for getBuildingUnits:", query);
25957
25991
  try {
25958
25992
  const data = await collection.aggregate([{ $match: query }, { $project: { name: 1 } }]).toArray();
25959
25993
  setCache(cacheKey, data, 15 * 60).then(() => {
@@ -26001,30 +26035,44 @@ function useBuildingUnitRepo() {
26001
26035
  }
26002
26036
  const query = {
26003
26037
  site,
26004
- owner: { $nin: [null, ""] }
26038
+ owner: { $nin: [null, ""] },
26039
+ status: "active"
26005
26040
  };
26006
26041
  if (unitIds && unitIds.length > 0) {
26007
26042
  query._id = { $in: unitIds };
26008
26043
  }
26009
- const cacheOptions = {
26010
- site: site.toString()
26011
- };
26012
- const cacheKey = (0, import_node_server_utils76.makeCacheKey)(
26013
- building_units_namespace_collection,
26014
- cacheOptions
26015
- );
26016
- const cachedData = await getCache(cacheKey);
26017
- if (cachedData) {
26018
- import_node_server_utils76.logger.info(`Cache hit for key: ${cacheKey}`);
26019
- return cachedData;
26020
- }
26021
26044
  try {
26022
- const data = await collection.aggregate([{ $match: query }]).toArray();
26023
- setCache(cacheKey, data, 15 * 60).then(() => {
26024
- import_node_server_utils76.logger.info(`Cache set for key: ${cacheKey}`);
26025
- }).catch((err) => {
26026
- import_node_server_utils76.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
26027
- });
26045
+ const data = await collection.aggregate([
26046
+ { $match: query },
26047
+ {
26048
+ $lookup: {
26049
+ from: "buildings",
26050
+ localField: "building",
26051
+ foreignField: "_id",
26052
+ pipeline: [{ $project: { _id: 0, name: 1 } }],
26053
+ as: "_blockData"
26054
+ }
26055
+ },
26056
+ {
26057
+ $unwind: { path: "$_blockData", preserveNullAndEmptyArrays: true }
26058
+ },
26059
+ { $addFields: { blockName: { $ifNull: ["$_blockData.name", ""] } } },
26060
+ { $unset: "_blockData" },
26061
+ {
26062
+ $lookup: {
26063
+ from: "building-levels",
26064
+ localField: "level",
26065
+ foreignField: "_id",
26066
+ pipeline: [{ $project: { _id: 0, name: 1 } }],
26067
+ as: "_levelData"
26068
+ }
26069
+ },
26070
+ {
26071
+ $unwind: { path: "$_levelData", preserveNullAndEmptyArrays: true }
26072
+ },
26073
+ { $addFields: { levelName: { $ifNull: ["$_levelData.name", ""] } } },
26074
+ { $unset: "_levelData" }
26075
+ ]).toArray();
26028
26076
  return data;
26029
26077
  } catch (error) {
26030
26078
  if (error instanceof import_node_server_utils76.AppError) {
@@ -26127,7 +26175,6 @@ function useBuildingUnitRepo() {
26127
26175
  level,
26128
26176
  status: "active"
26129
26177
  };
26130
- console.log(query);
26131
26178
  const result = await collection.findOne(query);
26132
26179
  setCache(cacheKey, result, 300).then(() => {
26133
26180
  import_node_server_utils76.logger.log({
@@ -40965,7 +41012,7 @@ var NotificationService = class {
40965
41012
  await send(
40966
41013
  toStringArray(payload.to),
40967
41014
  "Preloved Marketplace",
40968
- `There is new .`,
41015
+ `New preloved marketplace post added.`,
40969
41016
  {
40970
41017
  prelovedId: payload.prelovedId.toString(),
40971
41018
  status: payload.status,
@@ -43989,14 +44036,14 @@ function useSiteUnitBillingService() {
43989
44036
  billing_item.units,
43990
44037
  billing_item.site?.toString() || ""
43991
44038
  );
43992
- if (unitsWithOwner?.length) {
44039
+ if (unitsWithOwner?.length > 0) {
43993
44040
  const buildUnitBilling = (unit) => ({
43994
- site: billing_item.site,
43995
- org: billing_item.org,
44041
+ site: billing_item.site.toString(),
44042
+ org: billing_item.org.toString(),
43996
44043
  billItem: billing_item._id,
43997
44044
  billName: billing_item.name,
43998
- unitId: unit._id,
43999
- unit: unit.block + " / " + unit.level + " / " + unit.name,
44045
+ unitId: unit._id.toString(),
44046
+ unit: unit.blockName + " / " + unit.levelName + " / " + unit.name,
44000
44047
  unitOwner: unit.ownerName,
44001
44048
  email: unit.email,
44002
44049
  contactNumber: unit.contact,
@@ -44022,6 +44069,7 @@ function useSiteUnitBillingService() {
44022
44069
  );
44023
44070
  await session.commitTransaction();
44024
44071
  } catch (error) {
44072
+ console.log("BILLING ERROR:", error.message, error);
44025
44073
  import_node_server_utils155.logger.log({
44026
44074
  level: "error",
44027
44075
  message: `Failed to proccess cron billing: ${error.message}`
@@ -56325,18 +56373,14 @@ function useNfcPatrolLogController() {
56325
56373
 
56326
56374
  // src/repositories/new-dashboard.repo.ts
56327
56375
  var import_node_server_utils199 = require("@7365admin1/node-server-utils");
56376
+ var import_mongodb121 = require("mongodb");
56377
+ var import_moment = __toESM(require("moment"));
56328
56378
  var Period = /* @__PURE__ */ ((Period2) => {
56329
56379
  Period2["TODAY"] = "today";
56330
56380
  Period2["THIS_WEEK"] = "thisWeek";
56331
56381
  Period2["THIS_MONTH"] = "thisMonth";
56332
56382
  return Period2;
56333
56383
  })(Period || {});
56334
- var securityDashboardCollection = "security-dashboard";
56335
- var PMDashboardCollection = "PM-dashboard";
56336
- var pestDashboardCollection = "pest-dashboard";
56337
- var poolDashboardCollection = "pool-dashboard";
56338
- var mAndEDashboardCollection = "M&E-dashboard";
56339
- var landscapeDashboardCollection = "landscape-dashboard";
56340
56384
  function getPeriodRangeWithPrevious(period) {
56341
56385
  const now = /* @__PURE__ */ new Date();
56342
56386
  let currentStart = /* @__PURE__ */ new Date();
@@ -56409,356 +56453,1275 @@ function useNewDashboardRepo() {
56409
56453
  if (!db) {
56410
56454
  throw new import_node_server_utils199.InternalServerError("Unable to connect to server.");
56411
56455
  }
56412
- const { delNamespace, getCache, setCache } = (0, import_node_server_utils199.useCache)(
56413
- securityDashboardCollection
56456
+ const cleaning_schedule_namespace_collection = "site.cleaning.schedules";
56457
+ const area_checklist_namespace_collection = "site.cleaning.schedule.areas";
56458
+ const supply_namespace_collection = "site.supplies";
56459
+ const work_order_namespace_collection = "work-orders2";
56460
+ const facility_bookings_namespace_collection2 = "facilities-booking";
56461
+ const areaChecklistCollection = db.collection(
56462
+ area_checklist_namespace_collection
56414
56463
  );
56415
- async function getMetric(collectionString, siteId, period) {
56416
- const site = (0, import_node_server_utils199.toObjectId)(siteId);
56417
- const range = getPeriodRangeWithPrevious(period);
56418
- const collection = db.collection(collectionString);
56419
- const current = await collection.countDocuments({
56420
- site,
56421
- createdAt: {
56422
- $gte: range.current.start,
56423
- $lte: range.current.end
56424
- }
56425
- });
56426
- const previous = await collection.countDocuments({
56427
- site,
56428
- createdAt: {
56429
- $gte: range.previous.start,
56430
- $lte: range.previous.end
56431
- }
56464
+ const supplyCollection = db.collection(supply_namespace_collection);
56465
+ const workOrderCollection = db.collection(work_order_namespace_collection);
56466
+ const attendanceCollection = db.collection("site.attendances");
56467
+ const feedbackCollection = db.collection("feedbacks2");
56468
+ const workOrderServiceMap = {
56469
+ security_agency: "Security",
56470
+ cleaning_services: "Cleaning",
56471
+ mechanical_electrical_services: "M&E",
56472
+ landscaping_services: "Landscape",
56473
+ pest_control_services: "Pest Control",
56474
+ pool_maintenance_services: "Pool Maintenance"
56475
+ };
56476
+ function formatEndDate(date) {
56477
+ if (typeof date === "string") {
56478
+ const dateWithoutTimezone = date.replace(/\s*\+\d{2}:\d{2}$/, "");
56479
+ date = new Date(dateWithoutTimezone);
56480
+ }
56481
+ const singaporeMoment = import_moment.default.tz(date, "Asia/Singapore");
56482
+ singaporeMoment.set({
56483
+ hour: 23,
56484
+ minute: 59,
56485
+ second: 59,
56486
+ millisecond: 999
56432
56487
  });
56433
- return {
56434
- count: current,
56435
- percentage: calculatePercentage(current, previous)
56436
- };
56488
+ return singaporeMoment.toDate();
56489
+ }
56490
+ function getDateRange(p) {
56491
+ const start = /* @__PURE__ */ new Date();
56492
+ start.setHours(0, 0, 0, 0);
56493
+ if (p === "today") {
56494
+ return { $gte: start, $lte: formatEndDate(start) };
56495
+ }
56496
+ const days = p === "thisWeek" ? 7 : 30;
56497
+ const rangeStart = /* @__PURE__ */ new Date();
56498
+ rangeStart.setDate(start.getDate() - days);
56499
+ rangeStart.setHours(0, 0, 0, 0);
56500
+ return { $gte: rangeStart, $lte: formatEndDate(/* @__PURE__ */ new Date()) };
56437
56501
  }
56502
+ const calculatePercentageChange = (currentCount, previousCount) => {
56503
+ if (previousCount === 0) {
56504
+ return currentCount > 0 ? 100 : 0;
56505
+ }
56506
+ return Math.round((currentCount - previousCount) / previousCount * 100 * 100) / 100;
56507
+ };
56438
56508
  async function getSecurityDashboard({
56439
56509
  siteId = "",
56440
- feedback = "today" /* TODAY */,
56441
- workOrder = "today" /* TODAY */,
56442
- vehicle = "today" /* TODAY */,
56443
- building = "today" /* TODAY */,
56444
- visitor = "today" /* TODAY */,
56445
- incident = "today" /* TODAY */,
56446
- guest = "today" /* TODAY */
56510
+ period = "today" /* TODAY */,
56511
+ type
56447
56512
  }) {
56448
- const cacheOptions = {
56449
- siteId,
56450
- feedback,
56451
- workOrder,
56452
- vehicle,
56453
- building,
56454
- visitor,
56455
- incident
56513
+ const siteIdObj = (0, import_node_server_utils199.toObjectId)(siteId);
56514
+ const visitorMatchObj = {};
56515
+ if (type) {
56516
+ visitorMatchObj.type = type;
56517
+ }
56518
+ const today = /* @__PURE__ */ new Date();
56519
+ today.setHours(0, 0, 0, 0);
56520
+ const yesterday = /* @__PURE__ */ new Date();
56521
+ yesterday.setDate(today.getDate() - 1);
56522
+ yesterday.setHours(0, 0, 0, 0);
56523
+ const yesterdayEnd = new Date(yesterday);
56524
+ yesterdayEnd.setHours(23, 59, 59, 999);
56525
+ const todayEnd = formatEndDate(/* @__PURE__ */ new Date());
56526
+ const periodRange = getDateRange(period);
56527
+ const incidentCollection = db.collection(incidents_namespace_collection);
56528
+ const visitorCollection = db.collection(visitors_namespace_collection);
56529
+ const nfcPatrolLogCollection = db.collection("nfc-patrol-logs");
56530
+ const [
56531
+ workOrderReport,
56532
+ yesterdayWorkOrderReport,
56533
+ todayWorkOrderReport,
56534
+ incidentReport,
56535
+ yesterdayIncidentReport,
56536
+ todayIncidentReport,
56537
+ visitorReport,
56538
+ yesterdayVisitorReport,
56539
+ todayVisitorReport,
56540
+ currentlyOnSiteCount,
56541
+ patrolReport,
56542
+ yesterdayPatrolReport,
56543
+ todayPatrolReport
56544
+ ] = await Promise.all([
56545
+ workOrderCollection.aggregate([
56546
+ {
56547
+ $match: {
56548
+ site: { $in: [siteIdObj, siteId] },
56549
+ service: "Security",
56550
+ createdAt: periodRange,
56551
+ status: { $nin: ["completed"] }
56552
+ }
56553
+ },
56554
+ {
56555
+ $facet: {
56556
+ total: [{ $count: "count" }],
56557
+ inProgress: [
56558
+ { $match: { status: "in-progress" } },
56559
+ { $count: "count" }
56560
+ ]
56561
+ }
56562
+ }
56563
+ ]).toArray(),
56564
+ workOrderCollection.aggregate([
56565
+ {
56566
+ $match: {
56567
+ site: { $in: [siteIdObj, siteId] },
56568
+ service: "Security",
56569
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd },
56570
+ status: { $nin: ["completed"] }
56571
+ }
56572
+ },
56573
+ { $count: "count" }
56574
+ ]).toArray(),
56575
+ workOrderCollection.aggregate([
56576
+ {
56577
+ $match: {
56578
+ site: { $in: [siteIdObj, siteId] },
56579
+ service: "Security",
56580
+ createdAt: { $gte: today, $lte: todayEnd },
56581
+ status: { $nin: ["completed"] }
56582
+ }
56583
+ },
56584
+ { $count: "count" }
56585
+ ]).toArray(),
56586
+ incidentCollection.aggregate([
56587
+ {
56588
+ $match: {
56589
+ site: { $in: [siteIdObj, siteId] },
56590
+ status: { $in: ["pending", "Pending"] },
56591
+ createdAt: periodRange
56592
+ }
56593
+ },
56594
+ { $count: "count" }
56595
+ ]).toArray(),
56596
+ incidentCollection.aggregate([
56597
+ {
56598
+ $match: {
56599
+ site: { $in: [siteIdObj, siteId] },
56600
+ status: { $in: ["pending", "Pending"] },
56601
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd }
56602
+ }
56603
+ },
56604
+ { $count: "count" }
56605
+ ]).toArray(),
56606
+ incidentCollection.aggregate([
56607
+ {
56608
+ $match: {
56609
+ site: { $in: [siteIdObj, siteId] },
56610
+ status: { $in: ["pending", "Pending"] },
56611
+ createdAt: { $gte: today, $lte: todayEnd }
56612
+ }
56613
+ },
56614
+ { $count: "count" }
56615
+ ]).toArray(),
56616
+ visitorCollection.aggregate([
56617
+ {
56618
+ $match: {
56619
+ site: { $in: [siteIdObj, siteId] },
56620
+ ...visitorMatchObj,
56621
+ createdAt: periodRange,
56622
+ status: { $ne: "deleted" }
56623
+ }
56624
+ },
56625
+ { $count: "count" }
56626
+ ]).toArray(),
56627
+ visitorCollection.aggregate([
56628
+ {
56629
+ $match: {
56630
+ site: { $in: [siteIdObj, siteId] },
56631
+ ...visitorMatchObj,
56632
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd },
56633
+ status: { $ne: "deleted" }
56634
+ }
56635
+ },
56636
+ { $count: "count" }
56637
+ ]).toArray(),
56638
+ visitorCollection.aggregate([
56639
+ {
56640
+ $match: {
56641
+ site: { $in: [siteIdObj, siteId] },
56642
+ ...visitorMatchObj,
56643
+ createdAt: { $gte: today, $lte: todayEnd },
56644
+ status: { $ne: "deleted" }
56645
+ }
56646
+ },
56647
+ { $count: "count" }
56648
+ ]).toArray(),
56649
+ visitorCollection.countDocuments({
56650
+ site: { $in: [siteIdObj, siteId] },
56651
+ ...visitorMatchObj,
56652
+ checkIn: { $ne: null },
56653
+ checkOut: null,
56654
+ status: { $ne: "deleted" }
56655
+ }),
56656
+ nfcPatrolLogCollection.aggregate([
56657
+ {
56658
+ $match: {
56659
+ site: { $in: [siteIdObj, siteId] },
56660
+ createdAt: periodRange
56661
+ }
56662
+ },
56663
+ {
56664
+ $unwind: "$checkPoints"
56665
+ },
56666
+ {
56667
+ $facet: {
56668
+ total: [{ $count: "count" }],
56669
+ completed: [
56670
+ { $match: { "checkPoints.status": "Completed" } },
56671
+ { $count: "count" }
56672
+ ],
56673
+ skipped: [
56674
+ { $match: { "checkPoints.status": "Skipped" } },
56675
+ { $count: "count" }
56676
+ ]
56677
+ }
56678
+ }
56679
+ ]).toArray(),
56680
+ nfcPatrolLogCollection.aggregate([
56681
+ {
56682
+ $match: {
56683
+ site: { $in: [siteIdObj, siteId] },
56684
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd }
56685
+ }
56686
+ },
56687
+ {
56688
+ $unwind: "$checkPoints"
56689
+ },
56690
+ {
56691
+ $facet: {
56692
+ total: [{ $count: "count" }],
56693
+ completed: [
56694
+ { $match: { "checkPoints.status": "Completed" } },
56695
+ { $count: "count" }
56696
+ ],
56697
+ skipped: [
56698
+ { $match: { "checkPoints.status": "Skipped" } },
56699
+ { $count: "count" }
56700
+ ]
56701
+ }
56702
+ }
56703
+ ]).toArray(),
56704
+ nfcPatrolLogCollection.aggregate([
56705
+ {
56706
+ $match: {
56707
+ site: { $in: [siteIdObj, siteId] },
56708
+ createdAt: { $gte: today, $lte: todayEnd }
56709
+ }
56710
+ },
56711
+ {
56712
+ $unwind: "$checkPoints"
56713
+ },
56714
+ {
56715
+ $facet: {
56716
+ total: [{ $count: "count" }],
56717
+ completed: [
56718
+ { $match: { "checkPoints.status": "Completed" } },
56719
+ { $count: "count" }
56720
+ ],
56721
+ skipped: [
56722
+ { $match: { "checkPoints.status": "Skipped" } },
56723
+ { $count: "count" }
56724
+ ]
56725
+ }
56726
+ }
56727
+ ]).toArray()
56728
+ ]);
56729
+ const wFacet = workOrderReport[0] ?? { total: [], inProgress: [] };
56730
+ const pFacet = patrolReport[0] ?? {
56731
+ total: [],
56732
+ completed: [],
56733
+ skipped: []
56456
56734
  };
56457
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(securityDashboardCollection, cacheOptions);
56458
- const cachedData = await getCache(cacheKey);
56459
- if (cachedData) {
56460
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56461
- return cachedData;
56735
+ const totalCheckpoints = pFacet.total[0]?.count ?? 0;
56736
+ const completedCheckpoints = pFacet.completed[0]?.count ?? 0;
56737
+ const skippedCheckpoints = pFacet.skipped[0]?.count ?? 0;
56738
+ const complianceRate = totalCheckpoints > 0 ? Math.round(completedCheckpoints / totalCheckpoints * 100 * 100) / 100 : 100;
56739
+ const yPatrolFacet = yesterdayPatrolReport[0] ?? {
56740
+ total: [],
56741
+ completed: []
56742
+ };
56743
+ const yTotal = yPatrolFacet.total[0]?.count ?? 0;
56744
+ const yCompleted = yPatrolFacet.completed[0]?.count ?? 0;
56745
+ const yesterdayCompliance = yTotal > 0 ? yCompleted / yTotal * 100 : 0;
56746
+ const tPatrolFacet = todayPatrolReport[0] ?? {
56747
+ total: [],
56748
+ completed: []
56749
+ };
56750
+ const tTotal = tPatrolFacet.total[0]?.count ?? 0;
56751
+ const tCompleted = tPatrolFacet.completed[0]?.count ?? 0;
56752
+ const todayCompliance = tTotal > 0 ? tCompleted / tTotal * 100 : 0;
56753
+ const todayString = import_moment.default.tz("Asia/Singapore").format("YYYY-MM-DD");
56754
+ const dayIndex = import_moment.default.tz("Asia/Singapore").day();
56755
+ const routes = await db.collection("nfc-patrol-routes").find({
56756
+ site: { $in: [siteIdObj, siteId] },
56757
+ days: { $in: [dayIndex] },
56758
+ status: { $ne: "Inactive" }
56759
+ }).toArray();
56760
+ const expandedRoutes = [];
56761
+ for (const route of routes) {
56762
+ if (route.startTimes && Array.isArray(route.startTimes)) {
56763
+ for (const startTime of route.startTimes) {
56764
+ expandedRoutes.push({
56765
+ route,
56766
+ startTime,
56767
+ itemIndex: 0
56768
+ });
56769
+ }
56770
+ }
56462
56771
  }
56463
- const feedbacks = await getMetric(
56464
- feedbacks_namespace_collection,
56465
- siteId,
56466
- feedback
56467
- );
56468
- const workOrders = await getMetric(
56469
- work_orders_namespace_collection,
56470
- siteId,
56471
- workOrder
56472
- );
56473
- const vehicles = await getMetric(
56474
- vehicles_namespace_collection,
56475
- siteId,
56476
- vehicle
56477
- );
56478
- const buildings = await getMetric(
56479
- buildings_namespace_collection,
56480
- siteId,
56481
- building
56482
- );
56483
- const visitors = await getMetric(
56484
- visitors_namespace_collection,
56485
- siteId,
56486
- visitor
56487
- );
56488
- const incidents = await getMetric(
56489
- incidents_namespace_collection,
56490
- siteId,
56491
- incident
56772
+ expandedRoutes.sort((a, b) => a.startTime.localeCompare(b.startTime));
56773
+ const limitedRoutes = expandedRoutes.slice(0, 4);
56774
+ limitedRoutes.forEach((item, idx) => {
56775
+ item.itemIndex = idx + 1;
56776
+ });
56777
+ const activePatrolItems = await Promise.all(
56778
+ limitedRoutes.map(async ({ route, startTime, itemIndex }) => {
56779
+ const log = await db.collection("nfc-patrol-logs").findOne({
56780
+ site: { $in: [siteIdObj, siteId] },
56781
+ date: todayString,
56782
+ "route._id": { $in: [route._id, route._id.toString()] },
56783
+ "route.startTime": startTime
56784
+ });
56785
+ let person = "Unassigned";
56786
+ if (log && log.createdBy) {
56787
+ const userDoc = await db.collection("users").findOne({
56788
+ _id: (0, import_node_server_utils199.toObjectId)(log.createdBy)
56789
+ });
56790
+ if (userDoc && userDoc.name) {
56791
+ person = userDoc.name;
56792
+ }
56793
+ }
56794
+ let status = "pending";
56795
+ if (log) {
56796
+ status = "completed";
56797
+ } else {
56798
+ const routeTime = import_moment.default.tz(
56799
+ `${todayString} ${startTime}`,
56800
+ "YYYY-MM-DD HH:mm",
56801
+ "Asia/Singapore"
56802
+ );
56803
+ const nowSg = import_moment.default.tz("Asia/Singapore");
56804
+ const diffMinutes = nowSg.diff(routeTime, "minutes");
56805
+ if (diffMinutes >= 0) {
56806
+ if (diffMinutes <= 120) {
56807
+ status = "on paused";
56808
+ } else {
56809
+ status = "incomplete";
56810
+ }
56811
+ } else {
56812
+ status = "pending";
56813
+ }
56814
+ }
56815
+ return {
56816
+ id: `${route._id.toString()}_${startTime}`,
56817
+ title: route.name,
56818
+ subtitle: `ID${String(itemIndex).padStart(3, "0")}`,
56819
+ person,
56820
+ status,
56821
+ time: startTime
56822
+ };
56823
+ })
56492
56824
  );
56493
- const guests = await getMetric(guests_namespace_collection, siteId, guest);
56494
56825
  const data = {
56495
- feedbacks,
56496
- workOrders,
56497
- vehicles,
56498
- buildings,
56499
- visitors,
56500
- incidents,
56501
- guests
56826
+ openWorkOrder: {
56827
+ count: wFacet.total[0]?.count ?? 0,
56828
+ inProgress: wFacet.inProgress[0]?.count ?? 0,
56829
+ percentage: calculatePercentageChange(
56830
+ todayWorkOrderReport[0]?.count ?? 0,
56831
+ yesterdayWorkOrderReport[0]?.count ?? 0
56832
+ )
56833
+ },
56834
+ openIncidents: {
56835
+ count: incidentReport[0]?.count ?? 0,
56836
+ highSeverity: 0,
56837
+ percentage: calculatePercentageChange(
56838
+ todayIncidentReport[0]?.count ?? 0,
56839
+ yesterdayIncidentReport[0]?.count ?? 0
56840
+ )
56841
+ },
56842
+ visitors: {
56843
+ count: visitorReport[0]?.count ?? 0,
56844
+ currentlyOnSite: currentlyOnSiteCount,
56845
+ percentage: calculatePercentageChange(
56846
+ todayVisitorReport[0]?.count ?? 0,
56847
+ yesterdayVisitorReport[0]?.count ?? 0
56848
+ )
56849
+ },
56850
+ patrolCompliance: {
56851
+ count: complianceRate,
56852
+ missedCheckpoints: skippedCheckpoints,
56853
+ missed: skippedCheckpoints,
56854
+ percentage: calculatePercentageChange(
56855
+ todayCompliance,
56856
+ yesterdayCompliance
56857
+ )
56858
+ },
56859
+ activePatrolItems
56502
56860
  };
56503
- setCache(cacheKey, data, 15 * 60).then(() => {
56504
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56505
- }).catch((err) => {
56506
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56507
- });
56508
56861
  return data;
56509
56862
  }
56510
- async function getPropertyManagementDashboard({
56511
- siteId = "",
56512
- feedback = "today" /* TODAY */,
56513
- workOrder = "today" /* TODAY */,
56514
- sitePeople = "today" /* TODAY */,
56515
- facilityBooking = "today" /* TODAY */,
56516
- bulletinBoard = "today" /* TODAY */,
56517
- event = "today" /* TODAY */,
56518
- vehicle = "today" /* TODAY */,
56519
- building = "today" /* TODAY */,
56520
- visitor = "today" /* TODAY */,
56521
- incident = "today" /* TODAY */
56522
- }) {
56523
- const cacheOptions = {
56524
- siteId,
56525
- feedback,
56526
- workOrder,
56527
- sitePeople,
56528
- facilityBooking,
56529
- bulletinBoard,
56530
- event,
56531
- vehicle,
56532
- building,
56533
- visitor,
56534
- incident
56535
- };
56536
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(PMDashboardCollection, cacheOptions);
56537
- const cachedData = await getCache(cacheKey);
56538
- if (cachedData) {
56539
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56540
- return cachedData;
56541
- }
56542
- const feedbacks = await getMetric(
56543
- feedbacks_namespace_collection,
56544
- siteId,
56545
- feedback
56546
- );
56547
- const workOrders = await getMetric(
56548
- work_orders_namespace_collection,
56549
- siteId,
56550
- workOrder
56551
- );
56552
- const vehicles = await getMetric(
56553
- vehicles_namespace_collection,
56554
- siteId,
56555
- vehicle
56556
- );
56557
- const buildings = await getMetric(
56558
- buildings_namespace_collection,
56559
- siteId,
56560
- building
56561
- );
56562
- const visitors = await getMetric(
56563
- visitors_namespace_collection,
56564
- siteId,
56565
- visitor
56566
- );
56567
- const incidents = await getMetric(
56568
- incidents_namespace_collection,
56569
- siteId,
56570
- incident
56571
- );
56572
- const _sitePeople = await getMetric(
56573
- site_people_namespace_collection,
56574
- siteId,
56575
- sitePeople
56863
+ async function getPropertyManagementDashboard(siteId, period = "today" /* TODAY */, type, facility) {
56864
+ const siteIdObj = (0, import_node_server_utils199.toObjectId)(siteId);
56865
+ const startOfToday = import_moment.default.tz("Asia/Singapore").startOf("day").toDate();
56866
+ const endOfToday = import_moment.default.tz("Asia/Singapore").endOf("day").toDate();
56867
+ const upcomingEvents = await db.collection(events_namespace_collection).find({
56868
+ site: { $in: [siteIdObj, siteId] },
56869
+ status: { $nin: ["deleted", "Deleted"] },
56870
+ $or: [
56871
+ { dateTime: { $gte: startOfToday } },
56872
+ { dateTime: { $gte: startOfToday.toISOString() } }
56873
+ ]
56874
+ }).sort({ dateTime: 1 }).limit(4).toArray();
56875
+ const todayReminders = await db.collection(events_namespace_collection).find({
56876
+ site: { $in: [siteIdObj, siteId] },
56877
+ status: { $nin: ["deleted", "Deleted"] },
56878
+ $or: [
56879
+ { dateTime: { $gte: startOfToday, $lte: endOfToday } },
56880
+ {
56881
+ dateTime: {
56882
+ $gte: startOfToday.toISOString(),
56883
+ $lte: endOfToday.toISOString()
56884
+ }
56885
+ }
56886
+ ]
56887
+ }).sort({ dateTime: 1 }).limit(4).toArray();
56888
+ const [pendingIncidentDocs, pendingFacilityBookingDocs] = await Promise.all(
56889
+ [
56890
+ db.collection(incidents_namespace_collection).find({
56891
+ site: { $in: [siteIdObj, siteId] },
56892
+ status: { $in: ["pending", "Pending"] }
56893
+ }).sort({ createdAt: -1 }).toArray(),
56894
+ db.collection(facility_bookings_namespace_collection2).find({
56895
+ site: { $in: [siteIdObj, siteId] },
56896
+ status: { $in: ["Pending", "pending", "For Review", "for review"] }
56897
+ }).sort({ createdAt: -1 }).toArray()
56898
+ ]
56576
56899
  );
56577
- const bulletinBoards = await getMetric(
56578
- bulletin_boards_namespace_collection,
56579
- siteId,
56580
- bulletinBoard
56900
+ const pendingIncidentCount = pendingIncidentDocs.length;
56901
+ const pendingFacilityBookingCount = pendingFacilityBookingDocs.length;
56902
+ const todayAttentions = [];
56903
+ if (pendingIncidentCount > 0) {
56904
+ todayAttentions.push({
56905
+ id: "incidents-pending",
56906
+ title: `${pendingIncidentCount} incident${pendingIncidentCount === 1 ? "" : "s"} pending acknowledge`,
56907
+ createdAt: pendingIncidentDocs[0].updatedAt || pendingIncidentDocs[0].createdAt || /* @__PURE__ */ new Date()
56908
+ });
56909
+ }
56910
+ if (pendingFacilityBookingCount > 0) {
56911
+ todayAttentions.push({
56912
+ id: "facility-booking-pending",
56913
+ title: `${pendingFacilityBookingCount} facility booking${pendingFacilityBookingCount === 1 ? "" : "s"} need approval`,
56914
+ createdAt: pendingFacilityBookingDocs[0].createdAt || /* @__PURE__ */ new Date()
56915
+ });
56916
+ }
56917
+ todayAttentions.sort(
56918
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
56581
56919
  );
56582
- const events = await getMetric(events_namespace_collection, siteId, event);
56583
- const facilityBookings = await getMetric(
56584
- facility_bookings_namespace_collection,
56585
- siteId,
56586
- facilityBooking
56920
+ const visitorMatchObj = {};
56921
+ if (type) {
56922
+ visitorMatchObj.type = type;
56923
+ }
56924
+ const facilityMatchObj = {};
56925
+ if (facility) {
56926
+ try {
56927
+ facilityMatchObj.facility = { $in: [facility, new import_mongodb121.ObjectId(facility)] };
56928
+ } catch (e) {
56929
+ facilityMatchObj.facility = facility;
56930
+ }
56931
+ }
56932
+ const today = /* @__PURE__ */ new Date();
56933
+ today.setHours(0, 0, 0, 0);
56934
+ const yesterday = /* @__PURE__ */ new Date();
56935
+ yesterday.setDate(today.getDate() - 1);
56936
+ yesterday.setHours(0, 0, 0, 0);
56937
+ const yesterdayEnd = new Date(yesterday);
56938
+ yesterdayEnd.setHours(23, 59, 59, 999);
56939
+ const todayEnd = formatEndDate(/* @__PURE__ */ new Date());
56940
+ const periodRange = getDateRange(period);
56941
+ const incidentCollection = db.collection(incidents_namespace_collection);
56942
+ const visitorCollection = db.collection(visitors_namespace_collection);
56943
+ const facilityCollection = db.collection(
56944
+ facility_bookings_namespace_collection2
56587
56945
  );
56946
+ const [
56947
+ workOrderReport,
56948
+ yesterdayWorkOrderReport,
56949
+ todayWorkOrderReport,
56950
+ incidentReport,
56951
+ yesterdayIncidentReport,
56952
+ todayIncidentReport,
56953
+ visitorReport,
56954
+ yesterdayVisitorReport,
56955
+ todayVisitorReport,
56956
+ currentlyOnSiteCount,
56957
+ facilityReport,
56958
+ yesterdayFacilityReport,
56959
+ todayFacilityReport
56960
+ ] = await Promise.all([
56961
+ workOrderCollection.aggregate([
56962
+ {
56963
+ $match: {
56964
+ site: { $in: [siteIdObj, siteId] },
56965
+ createdAt: periodRange,
56966
+ status: { $nin: ["completed"] }
56967
+ }
56968
+ },
56969
+ {
56970
+ $facet: {
56971
+ total: [{ $count: "count" }],
56972
+ inProgress: [
56973
+ { $match: { status: "in-progress" } },
56974
+ { $count: "count" }
56975
+ ]
56976
+ }
56977
+ }
56978
+ ]).toArray(),
56979
+ workOrderCollection.aggregate([
56980
+ {
56981
+ $match: {
56982
+ site: { $in: [siteIdObj, siteId] },
56983
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd },
56984
+ status: { $nin: ["completed"] }
56985
+ }
56986
+ },
56987
+ { $count: "count" }
56988
+ ]).toArray(),
56989
+ workOrderCollection.aggregate([
56990
+ {
56991
+ $match: {
56992
+ site: { $in: [siteIdObj, siteId] },
56993
+ createdAt: { $gte: today, $lte: todayEnd },
56994
+ status: { $nin: ["completed"] }
56995
+ }
56996
+ },
56997
+ { $count: "count" }
56998
+ ]).toArray(),
56999
+ incidentCollection.aggregate([
57000
+ {
57001
+ $match: {
57002
+ site: { $in: [siteIdObj, siteId] },
57003
+ status: { $in: ["pending", "Pending"] },
57004
+ createdAt: periodRange
57005
+ }
57006
+ },
57007
+ { $count: "count" }
57008
+ ]).toArray(),
57009
+ incidentCollection.aggregate([
57010
+ {
57011
+ $match: {
57012
+ site: { $in: [siteIdObj, siteId] },
57013
+ status: { $in: ["pending", "Pending"] },
57014
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd }
57015
+ }
57016
+ },
57017
+ { $count: "count" }
57018
+ ]).toArray(),
57019
+ incidentCollection.aggregate([
57020
+ {
57021
+ $match: {
57022
+ site: { $in: [siteIdObj, siteId] },
57023
+ status: { $in: ["pending", "Pending"] },
57024
+ createdAt: { $gte: today, $lte: todayEnd }
57025
+ }
57026
+ },
57027
+ { $count: "count" }
57028
+ ]).toArray(),
57029
+ visitorCollection.aggregate([
57030
+ {
57031
+ $match: {
57032
+ site: { $in: [siteIdObj, siteId] },
57033
+ ...visitorMatchObj,
57034
+ createdAt: periodRange,
57035
+ status: { $ne: "deleted" }
57036
+ }
57037
+ },
57038
+ { $count: "count" }
57039
+ ]).toArray(),
57040
+ visitorCollection.aggregate([
57041
+ {
57042
+ $match: {
57043
+ site: { $in: [siteIdObj, siteId] },
57044
+ ...visitorMatchObj,
57045
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd },
57046
+ status: { $ne: "deleted" }
57047
+ }
57048
+ },
57049
+ { $count: "count" }
57050
+ ]).toArray(),
57051
+ visitorCollection.aggregate([
57052
+ {
57053
+ $match: {
57054
+ site: { $in: [siteIdObj, siteId] },
57055
+ ...visitorMatchObj,
57056
+ createdAt: { $gte: today, $lte: todayEnd },
57057
+ status: { $ne: "deleted" }
57058
+ }
57059
+ },
57060
+ { $count: "count" }
57061
+ ]).toArray(),
57062
+ visitorCollection.countDocuments({
57063
+ site: { $in: [siteIdObj, siteId] },
57064
+ ...visitorMatchObj,
57065
+ checkIn: { $ne: null },
57066
+ checkOut: null,
57067
+ status: { $ne: "deleted" }
57068
+ }),
57069
+ facilityCollection.aggregate([
57070
+ {
57071
+ $match: {
57072
+ site: { $in: [siteIdObj, siteId] },
57073
+ ...facilityMatchObj,
57074
+ $or: [
57075
+ { createdAt: periodRange },
57076
+ {
57077
+ createdAt: {
57078
+ $gte: periodRange.$gte.toISOString(),
57079
+ $lte: periodRange.$lte.toISOString()
57080
+ }
57081
+ }
57082
+ ],
57083
+ status: { $nin: ["deleted", "Deleted"] }
57084
+ }
57085
+ },
57086
+ {
57087
+ $facet: {
57088
+ total: [{ $count: "count" }],
57089
+ ongoing: [
57090
+ {
57091
+ $match: {
57092
+ status: {
57093
+ $in: ["Approved", "Ongoing"]
57094
+ }
57095
+ }
57096
+ },
57097
+ { $count: "count" }
57098
+ ],
57099
+ waitingApproval: [
57100
+ {
57101
+ $match: {
57102
+ status: {
57103
+ $in: ["Pending", "pending", "For Review", "for review"]
57104
+ }
57105
+ }
57106
+ },
57107
+ { $count: "count" }
57108
+ ]
57109
+ }
57110
+ }
57111
+ ]).toArray(),
57112
+ facilityCollection.aggregate([
57113
+ {
57114
+ $match: {
57115
+ site: { $in: [siteIdObj, siteId] },
57116
+ ...facilityMatchObj,
57117
+ $or: [
57118
+ { createdAt: { $gte: yesterday, $lte: yesterdayEnd } },
57119
+ {
57120
+ createdAt: {
57121
+ $gte: yesterday.toISOString(),
57122
+ $lte: yesterdayEnd.toISOString()
57123
+ }
57124
+ }
57125
+ ],
57126
+ status: { $nin: ["deleted", "Deleted"] }
57127
+ }
57128
+ },
57129
+ { $count: "count" }
57130
+ ]).toArray(),
57131
+ facilityCollection.aggregate([
57132
+ {
57133
+ $match: {
57134
+ site: { $in: [siteIdObj, siteId] },
57135
+ ...facilityMatchObj,
57136
+ $or: [
57137
+ { createdAt: { $gte: today, $lte: todayEnd } },
57138
+ {
57139
+ createdAt: {
57140
+ $gte: today.toISOString(),
57141
+ $lte: todayEnd.toISOString()
57142
+ }
57143
+ }
57144
+ ],
57145
+ status: { $nin: ["deleted", "Deleted"] }
57146
+ }
57147
+ },
57148
+ { $count: "count" }
57149
+ ]).toArray()
57150
+ ]);
57151
+ const wFacet = workOrderReport[0] ?? { total: [], inProgress: [] };
57152
+ const fFacet = facilityReport[0] ?? {
57153
+ total: [],
57154
+ ongoing: [],
57155
+ waitingApproval: []
57156
+ };
56588
57157
  const data = {
56589
- feedbacks,
56590
- workOrders,
56591
- vehicles,
56592
- buildings,
56593
- visitors,
56594
- incidents,
56595
- sitePeople: _sitePeople,
56596
- bulletinBoards,
56597
- events,
56598
- facilityBookings
57158
+ openWorkOrder: {
57159
+ count: wFacet.total[0]?.count ?? 0,
57160
+ inProgress: wFacet.inProgress[0]?.count ?? 0,
57161
+ percentage: calculatePercentageChange(
57162
+ todayWorkOrderReport[0]?.count ?? 0,
57163
+ yesterdayWorkOrderReport[0]?.count ?? 0
57164
+ )
57165
+ },
57166
+ openIncidents: {
57167
+ count: incidentReport[0]?.count ?? 0,
57168
+ highSeverity: 0,
57169
+ percentage: calculatePercentageChange(
57170
+ todayIncidentReport[0]?.count ?? 0,
57171
+ yesterdayIncidentReport[0]?.count ?? 0
57172
+ )
57173
+ },
57174
+ visitors: {
57175
+ count: visitorReport[0]?.count ?? 0,
57176
+ currentlyOnSite: currentlyOnSiteCount,
57177
+ percentage: calculatePercentageChange(
57178
+ todayVisitorReport[0]?.count ?? 0,
57179
+ yesterdayVisitorReport[0]?.count ?? 0
57180
+ )
57181
+ },
57182
+ facilityBooking: {
57183
+ count: fFacet.total[0]?.count ?? 0,
57184
+ ongoing: fFacet.ongoing[0]?.count ?? 0,
57185
+ waitingApproval: fFacet.waitingApproval[0]?.count ?? 0,
57186
+ percentage: calculatePercentageChange(
57187
+ todayFacilityReport[0]?.count ?? 0,
57188
+ yesterdayFacilityReport[0]?.count ?? 0
57189
+ )
57190
+ },
57191
+ upcomingEvents,
57192
+ todayReminders,
57193
+ todayAttentions
56599
57194
  };
56600
- setCache(cacheKey, data, 15 * 60).then(() => {
56601
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56602
- }).catch((err) => {
56603
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56604
- });
56605
57195
  return data;
56606
57196
  }
56607
- async function getPestManagementDashboard({
56608
- siteId = "",
56609
- feedback = "today" /* TODAY */,
56610
- workOrder = "today" /* TODAY */
57197
+ function areaChecklistScheduleLookup(site, serviceType, createdAtRange) {
57198
+ return [
57199
+ { $match: { serviceType } },
57200
+ {
57201
+ $lookup: {
57202
+ from: cleaning_schedule_namespace_collection,
57203
+ localField: "schedule",
57204
+ foreignField: "_id",
57205
+ as: "scheduleDoc",
57206
+ pipeline: [
57207
+ {
57208
+ $match: {
57209
+ site,
57210
+ serviceType,
57211
+ createdAt: createdAtRange
57212
+ }
57213
+ }
57214
+ ]
57215
+ }
57216
+ },
57217
+ { $unwind: { path: "$scheduleDoc", preserveNullAndEmptyArrays: false } }
57218
+ ];
57219
+ }
57220
+ async function getServiceDashboard({
57221
+ site,
57222
+ serviceType,
57223
+ period = "today" /* TODAY */
56611
57224
  }) {
56612
- const cacheOptions = {
56613
- siteId,
56614
- feedback,
56615
- workOrder
56616
- };
56617
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(pestDashboardCollection, cacheOptions);
56618
- const cachedData = await getCache(cacheKey);
56619
- if (cachedData) {
56620
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56621
- return cachedData;
57225
+ try {
57226
+ site = new import_mongodb121.ObjectId(site);
57227
+ } catch (error) {
57228
+ throw new import_node_server_utils199.BadRequestError("Invalid site ID format.");
57229
+ }
57230
+ const today = /* @__PURE__ */ new Date();
57231
+ today.setHours(0, 0, 0, 0);
57232
+ const yesterday = /* @__PURE__ */ new Date();
57233
+ yesterday.setDate(today.getDate() - 1);
57234
+ yesterday.setHours(0, 0, 0, 0);
57235
+ const yesterdayEnd = new Date(yesterday);
57236
+ yesterdayEnd.setHours(23, 59, 59, 999);
57237
+ const todayEnd = formatEndDate(/* @__PURE__ */ new Date());
57238
+ const periodRange = getDateRange(period);
57239
+ try {
57240
+ const workOrderService = workOrderServiceMap[serviceType] ?? serviceType;
57241
+ const [
57242
+ workOrderReport,
57243
+ supplyAlertReport,
57244
+ taskCompletedReport,
57245
+ yesterdayWorkOrderReport,
57246
+ todayWorkOrderReport,
57247
+ yesterdayTaskCompletedReport,
57248
+ todayTaskCompletedReport
57249
+ ] = await Promise.all([
57250
+ workOrderCollection.aggregate([
57251
+ {
57252
+ $match: {
57253
+ site,
57254
+ service: workOrderService,
57255
+ createdAt: periodRange,
57256
+ status: { $nin: ["completed"] }
57257
+ }
57258
+ },
57259
+ {
57260
+ $facet: {
57261
+ total: [{ $count: "count" }],
57262
+ inProgress: [
57263
+ { $match: { status: "in-progress" } },
57264
+ { $count: "count" }
57265
+ ]
57266
+ }
57267
+ }
57268
+ ]).toArray(),
57269
+ supplyCollection.aggregate([
57270
+ { $match: { site, serviceType, status: "active" } },
57271
+ { $sort: { qty: 1 } },
57272
+ { $limit: 3 },
57273
+ { $project: { _id: 1, name: 1, qty: 1 } }
57274
+ ]).toArray(),
57275
+ areaChecklistCollection.aggregate([
57276
+ ...areaChecklistScheduleLookup(site, serviceType, periodRange),
57277
+ {
57278
+ $facet: {
57279
+ total: [{ $count: "count" }],
57280
+ completed: [
57281
+ { $match: { status: "completed" } },
57282
+ { $count: "count" }
57283
+ ],
57284
+ inProgress: [
57285
+ { $match: { status: { $in: ["open", "ongoing"] } } },
57286
+ { $count: "count" }
57287
+ ]
57288
+ }
57289
+ }
57290
+ ]).toArray(),
57291
+ workOrderCollection.aggregate([
57292
+ {
57293
+ $match: {
57294
+ site,
57295
+ service: workOrderService,
57296
+ createdAt: { $gte: yesterday, $lte: yesterdayEnd },
57297
+ status: { $nin: ["completed"] }
57298
+ }
57299
+ },
57300
+ { $count: "count" }
57301
+ ]).toArray(),
57302
+ workOrderCollection.aggregate([
57303
+ {
57304
+ $match: {
57305
+ site,
57306
+ service: workOrderService,
57307
+ createdAt: { $gte: today, $lte: todayEnd },
57308
+ status: { $nin: ["completed"] }
57309
+ }
57310
+ },
57311
+ { $count: "count" }
57312
+ ]).toArray(),
57313
+ areaChecklistCollection.aggregate([
57314
+ ...areaChecklistScheduleLookup(site, serviceType, {
57315
+ $gte: yesterday,
57316
+ $lte: yesterdayEnd
57317
+ }),
57318
+ { $match: { status: "completed" } },
57319
+ { $count: "count" }
57320
+ ]).toArray(),
57321
+ areaChecklistCollection.aggregate([
57322
+ ...areaChecklistScheduleLookup(site, serviceType, {
57323
+ $gte: today,
57324
+ $lte: todayEnd
57325
+ }),
57326
+ { $match: { status: "completed" } },
57327
+ { $count: "count" }
57328
+ ]).toArray()
57329
+ ]);
57330
+ const wFacet = workOrderReport[0] ?? { total: [], inProgress: [] };
57331
+ const tFacet = taskCompletedReport[0] ?? {
57332
+ total: [],
57333
+ completed: [],
57334
+ inProgress: []
57335
+ };
57336
+ const result = {
57337
+ openWorkOrder: {
57338
+ count: wFacet.total[0]?.count ?? 0,
57339
+ inProgress: wFacet.inProgress[0]?.count ?? 0,
57340
+ percentage: calculatePercentageChange(
57341
+ todayWorkOrderReport[0]?.count ?? 0,
57342
+ yesterdayWorkOrderReport[0]?.count ?? 0
57343
+ )
57344
+ },
57345
+ supplyAlert: {
57346
+ items: supplyAlertReport.map((item) => ({
57347
+ name: item.name,
57348
+ qty: item.qty
57349
+ }))
57350
+ },
57351
+ taskCompleted: {
57352
+ completed: tFacet.completed[0]?.count ?? 0,
57353
+ total: tFacet.total[0]?.count ?? 0,
57354
+ inProgress: tFacet.inProgress[0]?.count ?? 0,
57355
+ percentage: calculatePercentageChange(
57356
+ todayTaskCompletedReport[0]?.count ?? 0,
57357
+ yesterdayTaskCompletedReport[0]?.count ?? 0
57358
+ )
57359
+ }
57360
+ };
57361
+ return result;
57362
+ } catch (error) {
57363
+ throw error;
56622
57364
  }
56623
- const feedbacks = await getMetric(
56624
- feedbacks_namespace_collection,
56625
- siteId,
56626
- feedback
56627
- );
56628
- const workOrders = await getMetric(
56629
- work_orders_namespace_collection,
56630
- siteId,
56631
- workOrder
56632
- );
56633
- const data = {
56634
- feedbacks,
56635
- workOrders
56636
- };
56637
- setCache(cacheKey, data, 15 * 60).then(() => {
56638
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56639
- }).catch((err) => {
56640
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56641
- });
56642
- return data;
56643
57365
  }
56644
- async function getPoolManagementDashboard({
56645
- siteId = "",
56646
- feedback = "today" /* TODAY */,
56647
- workOrder = "today" /* TODAY */
57366
+ async function getServiceWeeklyActivity({
57367
+ site,
57368
+ serviceType,
57369
+ period = "today" /* TODAY */
56648
57370
  }) {
56649
- const cacheOptions = {
56650
- siteId,
56651
- feedback,
56652
- workOrder
56653
- };
56654
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(poolDashboardCollection, cacheOptions);
56655
- const cachedData = await getCache(cacheKey);
56656
- if (cachedData) {
56657
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56658
- return cachedData;
57371
+ const cacheOptions = { serviceType, period };
57372
+ try {
57373
+ site = new import_mongodb121.ObjectId(site);
57374
+ cacheOptions.site = site.toString();
57375
+ } catch {
57376
+ throw new import_node_server_utils199.BadRequestError("Invalid site ID format.");
57377
+ }
57378
+ const workOrderService = workOrderServiceMap[serviceType] ?? serviceType;
57379
+ let rangeStart;
57380
+ let rangeEnd;
57381
+ let labels = [];
57382
+ let getIntervalIndex;
57383
+ if (period === "today" /* TODAY */) {
57384
+ rangeStart = import_moment.default.tz("Asia/Singapore").startOf("day").toDate();
57385
+ rangeEnd = import_moment.default.tz("Asia/Singapore").endOf("day").toDate();
57386
+ labels = ["12 AM", "4 AM", "8 AM", "12 PM", "4 PM", "8 PM"];
57387
+ getIntervalIndex = (date) => {
57388
+ const hour = (0, import_moment.default)(date).tz("Asia/Singapore").hour();
57389
+ return Math.floor(hour / 4);
57390
+ };
57391
+ } else if (period === "thisWeek" /* THIS_WEEK */) {
57392
+ rangeStart = import_moment.default.tz("Asia/Singapore").startOf("isoWeek").toDate();
57393
+ rangeEnd = import_moment.default.tz("Asia/Singapore").endOf("isoWeek").toDate();
57394
+ labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
57395
+ getIntervalIndex = (date) => {
57396
+ const day = (0, import_moment.default)(date).tz("Asia/Singapore").isoWeekday();
57397
+ return day - 1;
57398
+ };
57399
+ } else if (period === "thisMonth" /* THIS_MONTH */) {
57400
+ rangeStart = import_moment.default.tz("Asia/Singapore").startOf("month").toDate();
57401
+ rangeEnd = import_moment.default.tz("Asia/Singapore").endOf("month").toDate();
57402
+ const daysInMonth = import_moment.default.tz("Asia/Singapore").daysInMonth();
57403
+ labels = Array.from({ length: daysInMonth }, (_, i) => String(i + 1));
57404
+ getIntervalIndex = (date) => {
57405
+ return (0, import_moment.default)(date).tz("Asia/Singapore").date() - 1;
57406
+ };
57407
+ } else {
57408
+ throw new import_node_server_utils199.BadRequestError("Invalid period.");
57409
+ }
57410
+ try {
57411
+ const workOrders = await workOrderCollection.find({
57412
+ site,
57413
+ service: workOrderService,
57414
+ status: { $nin: ["deleted", "Deleted"] },
57415
+ $or: [
57416
+ { createdAt: { $gte: rangeStart, $lte: rangeEnd } },
57417
+ {
57418
+ createdAt: {
57419
+ $gte: rangeStart.toISOString(),
57420
+ $lte: rangeEnd.toISOString()
57421
+ }
57422
+ }
57423
+ ]
57424
+ }).project({ status: 1, createdAt: 1 }).toArray();
57425
+ const chartData = labels.map((label) => ({
57426
+ day: label,
57427
+ label,
57428
+ openWorkOrder: 0,
57429
+ closedWorkOrder: 0,
57430
+ workOrder: 0,
57431
+ taskCompleted: 0
57432
+ }));
57433
+ for (const wo of workOrders) {
57434
+ const dateVal = wo.createdAt instanceof Date ? wo.createdAt : new Date(wo.createdAt);
57435
+ const index = getIntervalIndex(dateVal);
57436
+ if (index >= 0 && index < chartData.length) {
57437
+ const isCompleted = wo.status === "completed" || wo.status === "Completed";
57438
+ if (isCompleted) {
57439
+ chartData[index].closedWorkOrder++;
57440
+ chartData[index].taskCompleted++;
57441
+ } else {
57442
+ chartData[index].openWorkOrder++;
57443
+ chartData[index].workOrder++;
57444
+ }
57445
+ }
57446
+ }
57447
+ return chartData;
57448
+ } catch (error) {
57449
+ throw error;
56659
57450
  }
56660
- const feedbacks = await getMetric(
56661
- feedbacks_namespace_collection,
56662
- siteId,
56663
- feedback
56664
- );
56665
- const workOrders = await getMetric(
56666
- work_orders_namespace_collection,
56667
- siteId,
56668
- workOrder
56669
- );
56670
- const data = {
56671
- feedbacks,
56672
- workOrders
56673
- };
56674
- setCache(cacheKey, data, 15 * 60).then(() => {
56675
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56676
- }).catch((err) => {
56677
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56678
- });
56679
- return data;
56680
57451
  }
56681
- async function getMAndEManagementDashboard({
56682
- siteId = "",
56683
- feedback = "today" /* TODAY */,
56684
- workOrder = "today" /* TODAY */
57452
+ async function getServiceTodayTaskSchedule({
57453
+ site,
57454
+ serviceType,
57455
+ page = 1,
57456
+ limit = 10
56685
57457
  }) {
56686
- const cacheOptions = {
56687
- siteId,
56688
- feedback,
56689
- workOrder
56690
- };
56691
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(mAndEDashboardCollection, cacheOptions);
56692
- const cachedData = await getCache(cacheKey);
56693
- if (cachedData) {
56694
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56695
- return cachedData;
57458
+ page = page > 0 ? page - 1 : 0;
57459
+ const cacheOptions = { serviceType, page, limit };
57460
+ try {
57461
+ site = new import_mongodb121.ObjectId(site);
57462
+ cacheOptions.site = site.toString();
57463
+ } catch {
57464
+ throw new import_node_server_utils199.BadRequestError("Invalid site ID format.");
57465
+ }
57466
+ const todayStart = import_moment.default.tz("Asia/Singapore").startOf("day").toDate();
57467
+ const todayEnd = import_moment.default.tz("Asia/Singapore").endOf("day").toDate();
57468
+ const todayRange = { $gte: todayStart, $lte: todayEnd };
57469
+ try {
57470
+ const [items, countResult] = await Promise.all([
57471
+ areaChecklistCollection.aggregate([
57472
+ ...areaChecklistScheduleLookup(site, serviceType, todayRange),
57473
+ {
57474
+ $addFields: {
57475
+ _assigneeId: {
57476
+ $reduce: {
57477
+ input: { $ifNull: ["$checklist", []] },
57478
+ initialValue: null,
57479
+ in: {
57480
+ $cond: {
57481
+ if: { $ne: ["$$value", null] },
57482
+ then: "$$value",
57483
+ else: {
57484
+ $reduce: {
57485
+ input: { $ifNull: ["$$this.units", []] },
57486
+ initialValue: null,
57487
+ in: {
57488
+ $cond: {
57489
+ if: { $ne: ["$$value", null] },
57490
+ then: "$$value",
57491
+ else: {
57492
+ $cond: {
57493
+ if: { $gt: ["$$this.completedBy", null] },
57494
+ then: "$$this.completedBy",
57495
+ else: null
57496
+ }
57497
+ }
57498
+ }
57499
+ }
57500
+ }
57501
+ }
57502
+ }
57503
+ }
57504
+ }
57505
+ }
57506
+ }
57507
+ },
57508
+ {
57509
+ $lookup: {
57510
+ from: "users",
57511
+ localField: "_assigneeId",
57512
+ foreignField: "_id",
57513
+ as: "_assigneeDoc"
57514
+ }
57515
+ },
57516
+ { $sort: { createdAt: -1, _id: -1 } },
57517
+ {
57518
+ $project: {
57519
+ name: 1,
57520
+ type: 1,
57521
+ status: 1,
57522
+ assigneeName: { $arrayElemAt: ["$_assigneeDoc.name", 0] }
57523
+ }
57524
+ },
57525
+ { $skip: page * limit },
57526
+ { $limit: limit }
57527
+ ]).toArray(),
57528
+ areaChecklistCollection.aggregate([
57529
+ ...areaChecklistScheduleLookup(site, serviceType, todayRange),
57530
+ { $count: "count" }
57531
+ ]).toArray()
57532
+ ]);
57533
+ const length = countResult[0]?.count ?? 0;
57534
+ const data = (0, import_node_server_utils199.paginate)(items, page, limit, length);
57535
+ return data;
57536
+ } catch (error) {
57537
+ throw error;
56696
57538
  }
56697
- const feedbacks = await getMetric(
56698
- feedbacks_namespace_collection,
56699
- siteId,
56700
- feedback
56701
- );
56702
- const workOrders = await getMetric(
56703
- work_orders_namespace_collection,
56704
- siteId,
56705
- workOrder
56706
- );
56707
- const data = {
56708
- feedbacks,
56709
- workOrders
56710
- };
56711
- setCache(cacheKey, data, 15 * 60).then(() => {
56712
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56713
- }).catch((err) => {
56714
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56715
- });
56716
- return data;
56717
57539
  }
56718
- async function getLandscapeDashboard({
56719
- siteId = "",
56720
- feedback = "today" /* TODAY */,
56721
- workOrder = "today" /* TODAY */
57540
+ async function getServiceStaffAttendance({
57541
+ site,
57542
+ serviceType,
57543
+ page = 1,
57544
+ limit = 10
56722
57545
  }) {
56723
- const cacheOptions = {
56724
- siteId,
56725
- feedback,
56726
- workOrder
56727
- };
56728
- const cacheKey = (0, import_node_server_utils199.makeCacheKey)(landscapeDashboardCollection, cacheOptions);
56729
- const cachedData = await getCache(cacheKey);
56730
- if (cachedData) {
56731
- import_node_server_utils199.logger.info(`Cache hit for key: ${cacheKey}`);
56732
- return cachedData;
57546
+ page = page > 0 ? page - 1 : 0;
57547
+ const cacheOptions = { serviceType, page, limit };
57548
+ try {
57549
+ site = new import_mongodb121.ObjectId(site);
57550
+ cacheOptions.site = site.toString();
57551
+ } catch {
57552
+ throw new import_node_server_utils199.BadRequestError("Invalid site ID format.");
57553
+ }
57554
+ const todayStart = import_moment.default.tz("Asia/Singapore").startOf("day").toDate();
57555
+ const todayEnd = import_moment.default.tz("Asia/Singapore").endOf("day").toDate();
57556
+ const todayStartStr = todayStart.toISOString();
57557
+ const todayEndStr = todayEnd.toISOString();
57558
+ try {
57559
+ const [items, length] = await Promise.all([
57560
+ attendanceCollection.aggregate([
57561
+ {
57562
+ $match: {
57563
+ site,
57564
+ serviceType,
57565
+ $or: [
57566
+ { createdAt: { $gte: todayStart, $lte: todayEnd } },
57567
+ { createdAt: { $gte: todayStartStr, $lte: todayEndStr } }
57568
+ ]
57569
+ }
57570
+ },
57571
+ {
57572
+ $lookup: {
57573
+ from: "users",
57574
+ localField: "user",
57575
+ foreignField: "_id",
57576
+ as: "_userDoc"
57577
+ }
57578
+ },
57579
+ {
57580
+ $lookup: {
57581
+ from: "members",
57582
+ let: { userId: "$user", siteId: "$site", type: "$serviceType" },
57583
+ pipeline: [
57584
+ {
57585
+ $match: {
57586
+ $expr: {
57587
+ $and: [
57588
+ { $eq: ["$user", "$$userId"] },
57589
+ { $eq: ["$siteId", "$$siteId"] },
57590
+ { $eq: ["$type", "$$type"] },
57591
+ { $ne: ["$status", "deleted"] }
57592
+ ]
57593
+ }
57594
+ }
57595
+ }
57596
+ ],
57597
+ as: "_memberDoc"
57598
+ }
57599
+ },
57600
+ {
57601
+ $unwind: {
57602
+ path: "$_memberDoc",
57603
+ preserveNullAndEmptyArrays: true
57604
+ }
57605
+ },
57606
+ {
57607
+ $lookup: {
57608
+ from: "roles",
57609
+ localField: "_memberDoc.role",
57610
+ foreignField: "_id",
57611
+ as: "_roleDoc"
57612
+ }
57613
+ },
57614
+ {
57615
+ $unwind: {
57616
+ path: "$_roleDoc",
57617
+ preserveNullAndEmptyArrays: true
57618
+ }
57619
+ },
57620
+ { $sort: { createdAt: -1, _id: -1 } },
57621
+ {
57622
+ $project: {
57623
+ checkIn: 1,
57624
+ checkOut: 1,
57625
+ createdAt: 1,
57626
+ userName: { $arrayElemAt: ["$_userDoc.name", 0] },
57627
+ userRole: { $ifNull: ["$_roleDoc.name", ""] },
57628
+ totalHours: {
57629
+ $round: [
57630
+ {
57631
+ $divide: [
57632
+ {
57633
+ $subtract: [
57634
+ {
57635
+ $toDate: {
57636
+ $ifNull: ["$checkOut.timestamp", "$$NOW"]
57637
+ }
57638
+ },
57639
+ { $toDate: "$checkIn.timestamp" }
57640
+ ]
57641
+ },
57642
+ 36e5
57643
+ ]
57644
+ },
57645
+ 2
57646
+ ]
57647
+ }
57648
+ }
57649
+ },
57650
+ { $skip: page * limit },
57651
+ { $limit: limit }
57652
+ ]).toArray(),
57653
+ attendanceCollection.countDocuments({
57654
+ site,
57655
+ serviceType,
57656
+ $or: [
57657
+ { createdAt: { $gte: todayStart, $lte: todayEnd } },
57658
+ { createdAt: { $gte: todayStartStr, $lte: todayEndStr } }
57659
+ ]
57660
+ })
57661
+ ]);
57662
+ const data = (0, import_node_server_utils199.paginate)(items, page, limit, length);
57663
+ return data;
57664
+ } catch (error) {
57665
+ throw error;
57666
+ }
57667
+ }
57668
+ async function getServiceRecentFeedbacks({
57669
+ site,
57670
+ serviceType,
57671
+ page = 1,
57672
+ limit = 10
57673
+ }) {
57674
+ page = page > 0 ? page - 1 : 0;
57675
+ const cacheOptions = { serviceType, page, limit };
57676
+ try {
57677
+ site = new import_mongodb121.ObjectId(site);
57678
+ cacheOptions.site = site.toString();
57679
+ } catch {
57680
+ throw new import_node_server_utils199.BadRequestError("Invalid site ID format.");
57681
+ }
57682
+ const workOrderService = workOrderServiceMap[serviceType] ?? serviceType;
57683
+ try {
57684
+ const [items, length] = await Promise.all([
57685
+ feedbackCollection.aggregate([
57686
+ { $match: { site, service: workOrderService } },
57687
+ { $sort: { createdAt: -1, _id: -1 } },
57688
+ {
57689
+ $lookup: {
57690
+ from: "users",
57691
+ localField: "createdBy",
57692
+ foreignField: "_id",
57693
+ as: "_createdByDoc"
57694
+ }
57695
+ },
57696
+ {
57697
+ $project: {
57698
+ description: 1,
57699
+ subject: 1,
57700
+ app: 1,
57701
+ status: 1,
57702
+ createdAt: 1,
57703
+ createdByName: { $arrayElemAt: ["$_createdByDoc.name", 0] }
57704
+ }
57705
+ },
57706
+ { $skip: page * limit },
57707
+ { $limit: limit }
57708
+ ]).toArray(),
57709
+ feedbackCollection.countDocuments({ site, service: workOrderService })
57710
+ ]);
57711
+ const data = (0, import_node_server_utils199.paginate)(items, page, limit, length);
57712
+ return data;
57713
+ } catch (error) {
57714
+ throw error;
56733
57715
  }
56734
- const feedbacks = await getMetric(
56735
- feedbacks_namespace_collection,
56736
- siteId,
56737
- feedback
56738
- );
56739
- const workOrders = await getMetric(
56740
- work_orders_namespace_collection,
56741
- siteId,
56742
- workOrder
56743
- );
56744
- const data = {
56745
- feedbacks,
56746
- workOrders
56747
- };
56748
- setCache(cacheKey, data, 15 * 60).then(() => {
56749
- import_node_server_utils199.logger.info(`Cache set for key: ${cacheKey}`);
56750
- }).catch((err) => {
56751
- import_node_server_utils199.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
56752
- });
56753
- return data;
56754
57716
  }
56755
57717
  return {
56756
57718
  getSecurityDashboard,
56757
57719
  getPropertyManagementDashboard,
56758
- getPestManagementDashboard,
56759
- getPoolManagementDashboard,
56760
- getMAndEManagementDashboard,
56761
- getLandscapeDashboard
57720
+ getServiceDashboard,
57721
+ getServiceWeeklyActivity,
57722
+ getServiceTodayTaskSchedule,
57723
+ getServiceStaffAttendance,
57724
+ getServiceRecentFeedbacks
56762
57725
  };
56763
57726
  }
56764
57727
 
@@ -56769,23 +57732,19 @@ function useNewDashboardController() {
56769
57732
  const {
56770
57733
  getSecurityDashboard: _getSecurityDashboard,
56771
57734
  getPropertyManagementDashboard: _getPropertyManagementDashboard,
56772
- getPestManagementDashboard: _getPestManagementDashboard,
56773
- getPoolManagementDashboard: _getPoolManagementDashboard,
56774
- getMAndEManagementDashboard: _getMAndEManagementDashboard,
56775
- getLandscapeDashboard: _getLandscapeDashboard
57735
+ getServiceDashboard: _getServiceDashboard,
57736
+ getServiceWeeklyActivity: _getServiceWeeklyActivity,
57737
+ getServiceTodayTaskSchedule: _getServiceTodayTaskSchedule,
57738
+ getServiceStaffAttendance: _getServiceStaffAttendance,
57739
+ getServiceRecentFeedbacks: _getServiceRecentFeedbacks
56776
57740
  } = useNewDashboardRepo();
56777
57741
  const periodField = import_joi112.default.string().valid(...Object.values(Period)).default("today" /* TODAY */);
56778
57742
  async function getSecurityDashboard(req, res, next) {
56779
57743
  try {
56780
57744
  const schema2 = import_joi112.default.object({
56781
57745
  site: import_joi112.default.string().hex().length(24).required(),
56782
- feedbackPeriod: periodField,
56783
- workOrderPeriod: periodField,
56784
- vehiclePeriod: periodField,
56785
- buildingPeriod: periodField,
56786
- visitorPeriod: periodField,
56787
- incidentPeriod: periodField,
56788
- guestPeriod: periodField
57746
+ period: periodField,
57747
+ type: import_joi112.default.string().optional().allow("", null)
56789
57748
  });
56790
57749
  const { error, value } = schema2.validate({
56791
57750
  site: req.params.site,
@@ -56797,25 +57756,11 @@ function useNewDashboardController() {
56797
57756
  next(new import_node_server_utils200.BadRequestError(messages));
56798
57757
  return;
56799
57758
  }
56800
- const {
56801
- site,
56802
- feedbackPeriod,
56803
- workOrderPeriod,
56804
- vehiclePeriod,
56805
- buildingPeriod,
56806
- visitorPeriod,
56807
- incidentPeriod,
56808
- guestPeriod
56809
- } = value;
57759
+ const { site, period, type } = value;
56810
57760
  const data = await _getSecurityDashboard({
56811
57761
  siteId: site,
56812
- feedback: feedbackPeriod,
56813
- workOrder: workOrderPeriod,
56814
- vehicle: vehiclePeriod,
56815
- building: buildingPeriod,
56816
- visitor: visitorPeriod,
56817
- incident: incidentPeriod,
56818
- guest: guestPeriod
57762
+ period,
57763
+ type
56819
57764
  });
56820
57765
  res.status(200).json(data);
56821
57766
  return;
@@ -56829,16 +57774,9 @@ function useNewDashboardController() {
56829
57774
  try {
56830
57775
  const schema2 = import_joi112.default.object({
56831
57776
  site: import_joi112.default.string().hex().length(24).required(),
56832
- feedbackPeriod: periodField,
56833
- workOrderPeriod: periodField,
56834
- vehiclePeriod: periodField,
56835
- buildingPeriod: periodField,
56836
- visitorPeriod: periodField,
56837
- incidentPeriod: periodField,
56838
- sitePeoplePeriod: periodField,
56839
- bulletinBoardPeriod: periodField,
56840
- eventPeriod: periodField,
56841
- facilityBookingPeriod: periodField
57777
+ period: periodField,
57778
+ type: import_joi112.default.string().optional().allow("", null),
57779
+ facility: import_joi112.default.string().hex().optional().allow("", null)
56842
57780
  });
56843
57781
  const { error, value } = schema2.validate({
56844
57782
  site: req.params.site,
@@ -56850,32 +57788,13 @@ function useNewDashboardController() {
56850
57788
  next(new import_node_server_utils200.BadRequestError(messages));
56851
57789
  return;
56852
57790
  }
56853
- const {
57791
+ const { site, period, type, facility } = value;
57792
+ const data = await _getPropertyManagementDashboard(
56854
57793
  site,
56855
- feedbackPeriod,
56856
- workOrderPeriod,
56857
- vehiclePeriod,
56858
- buildingPeriod,
56859
- visitorPeriod,
56860
- incidentPeriod,
56861
- sitePeoplePeriod,
56862
- bulletinBoardPeriod,
56863
- eventPeriod,
56864
- facilityBookingPeriod
56865
- } = value;
56866
- const data = await _getPropertyManagementDashboard({
56867
- siteId: site,
56868
- feedback: feedbackPeriod,
56869
- workOrder: workOrderPeriod,
56870
- vehicle: vehiclePeriod,
56871
- building: buildingPeriod,
56872
- visitor: visitorPeriod,
56873
- incident: incidentPeriod,
56874
- sitePeople: sitePeoplePeriod,
56875
- bulletinBoard: bulletinBoardPeriod,
56876
- event: eventPeriod,
56877
- facilityBooking: facilityBookingPeriod
56878
- });
57794
+ period,
57795
+ type,
57796
+ facility
57797
+ );
56879
57798
  res.status(200).json(data);
56880
57799
  return;
56881
57800
  } catch (error) {
@@ -56884,143 +57803,177 @@ function useNewDashboardController() {
56884
57803
  return;
56885
57804
  }
56886
57805
  }
56887
- async function getPestManagementDashboard(req, res, next) {
57806
+ async function getServiceDashboard(req, res, next) {
57807
+ const query = { ...req.query, ...req.params };
57808
+ const validation = import_joi112.default.object({
57809
+ site: import_joi112.default.string().hex().required(),
57810
+ serviceType: import_joi112.default.string().valid(...Object.values(AppServiceType)).required(),
57811
+ period: import_joi112.default.string().valid(...Object.values(Period)).default("today" /* TODAY */)
57812
+ });
57813
+ const { error } = validation.validate(query);
57814
+ if (error) {
57815
+ import_node_server_utils200.logger.log({ level: "error", message: error.message });
57816
+ next(new import_node_server_utils200.BadRequestError(error.message));
57817
+ return;
57818
+ }
57819
+ const site = req.params.site ?? "";
57820
+ const serviceType = req.params.serviceType;
57821
+ const period = req.query.period;
56888
57822
  try {
56889
- const schema2 = import_joi112.default.object({
56890
- site: import_joi112.default.string().hex().length(24).required(),
56891
- feedbackPeriod: periodField,
56892
- workOrderPeriod: periodField
56893
- });
56894
- const { error, value } = schema2.validate({
56895
- site: req.params.site,
56896
- ...req.query
56897
- });
56898
- if (error) {
56899
- const messages = error.details.map((d) => d.message).join(", ");
56900
- import_node_server_utils200.logger.log({ level: "error", message: messages });
56901
- next(new import_node_server_utils200.BadRequestError(messages));
56902
- return;
56903
- }
56904
- const { site, feedbackPeriod, workOrderPeriod } = value;
56905
- const data = await _getPestManagementDashboard({
56906
- siteId: site,
56907
- feedback: feedbackPeriod,
56908
- workOrder: workOrderPeriod
57823
+ const data = await _getServiceDashboard({
57824
+ site,
57825
+ period,
57826
+ serviceType
56909
57827
  });
56910
- res.status(200).json(data);
57828
+ res.json(data);
56911
57829
  return;
56912
- } catch (error) {
56913
- import_node_server_utils200.logger.log({ level: "error", message: error.message });
56914
- next(error);
57830
+ } catch (error2) {
57831
+ import_node_server_utils200.logger.log({ level: "error", message: error2.message });
57832
+ next(error2);
56915
57833
  return;
56916
57834
  }
56917
57835
  }
56918
- async function getPoolManagementDashboard(req, res, next) {
57836
+ async function getServiceWeeklyActivity(req, res, next) {
57837
+ const query = { ...req.params, ...req.query };
57838
+ const validation = import_joi112.default.object({
57839
+ site: import_joi112.default.string().hex().required(),
57840
+ serviceType: import_joi112.default.string().valid(...Object.values(AppServiceType)).required(),
57841
+ period: import_joi112.default.string().valid(...Object.values(Period)).default("today" /* TODAY */)
57842
+ });
57843
+ const { error, value } = validation.validate(query);
57844
+ if (error) {
57845
+ import_node_server_utils200.logger.log({ level: "error", message: error.message });
57846
+ next(new import_node_server_utils200.BadRequestError(error.message));
57847
+ return;
57848
+ }
57849
+ const { site, serviceType, period } = value;
56919
57850
  try {
56920
- const schema2 = import_joi112.default.object({
56921
- site: import_joi112.default.string().hex().length(24).required(),
56922
- feedbackPeriod: periodField,
56923
- workOrderPeriod: periodField
56924
- });
56925
- const { error, value } = schema2.validate({
56926
- site: req.params.site,
56927
- ...req.query
56928
- });
56929
- if (error) {
56930
- const messages = error.details.map((d) => d.message).join(", ");
56931
- import_node_server_utils200.logger.log({ level: "error", message: messages });
56932
- next(new import_node_server_utils200.BadRequestError(messages));
56933
- return;
56934
- }
56935
- const { site, feedbackPeriod, workOrderPeriod } = value;
56936
- const data = await _getPestManagementDashboard({
56937
- siteId: site,
56938
- feedback: feedbackPeriod,
56939
- workOrder: workOrderPeriod
57851
+ const data = await _getServiceWeeklyActivity({
57852
+ site,
57853
+ serviceType,
57854
+ period
56940
57855
  });
56941
- res.status(200).json(data);
57856
+ res.json(data);
56942
57857
  return;
56943
- } catch (error) {
56944
- import_node_server_utils200.logger.log({ level: "error", message: error.message });
56945
- next(error);
57858
+ } catch (error2) {
57859
+ import_node_server_utils200.logger.log({ level: "error", message: error2.message });
57860
+ next(error2);
56946
57861
  return;
56947
57862
  }
56948
57863
  }
56949
- async function getMAndEManagementDashboard(req, res, next) {
57864
+ async function getServiceTodayTaskSchedule(req, res, next) {
57865
+ const query = { ...req.query, ...req.params };
57866
+ const validation = import_joi112.default.object({
57867
+ site: import_joi112.default.string().hex().required(),
57868
+ serviceType: import_joi112.default.string().valid(...Object.values(AppServiceType)).required(),
57869
+ page: import_joi112.default.number().min(1).optional().allow("", null),
57870
+ limit: import_joi112.default.number().min(1).optional().allow("", null)
57871
+ });
57872
+ const { error } = validation.validate(query);
57873
+ if (error) {
57874
+ import_node_server_utils200.logger.log({ level: "error", message: error.message });
57875
+ next(new import_node_server_utils200.BadRequestError(error.message));
57876
+ return;
57877
+ }
57878
+ const site = req.params.site;
57879
+ const serviceType = req.params.serviceType;
57880
+ const page = parseInt(req.query.page) ?? 1;
57881
+ const limit = parseInt(req.query.limit) ?? 10;
56950
57882
  try {
56951
- const schema2 = import_joi112.default.object({
56952
- site: import_joi112.default.string().hex().length(24).required(),
56953
- feedbackPeriod: periodField,
56954
- workOrderPeriod: periodField
56955
- });
56956
- const { error, value } = schema2.validate({
56957
- site: req.params.site,
56958
- ...req.query
56959
- });
56960
- if (error) {
56961
- const messages = error.details.map((d) => d.message).join(", ");
56962
- import_node_server_utils200.logger.log({ level: "error", message: messages });
56963
- next(new import_node_server_utils200.BadRequestError(messages));
56964
- return;
56965
- }
56966
- const { site, feedbackPeriod, workOrderPeriod } = value;
56967
- const data = await _getMAndEManagementDashboard({
56968
- siteId: site,
56969
- feedback: feedbackPeriod,
56970
- workOrder: workOrderPeriod
57883
+ const data = await _getServiceTodayTaskSchedule({
57884
+ site,
57885
+ serviceType,
57886
+ page,
57887
+ limit
56971
57888
  });
56972
- res.status(200).json(data);
57889
+ res.json(data);
56973
57890
  return;
56974
- } catch (error) {
56975
- import_node_server_utils200.logger.log({ level: "error", message: error.message });
56976
- next(error);
57891
+ } catch (error2) {
57892
+ import_node_server_utils200.logger.log({ level: "error", message: error2.message });
57893
+ next(error2);
56977
57894
  return;
56978
57895
  }
56979
57896
  }
56980
- async function getLandscapeDashboard(req, res, next) {
57897
+ async function getServiceStaffAttendance(req, res, next) {
57898
+ const query = { ...req.query, ...req.params };
57899
+ const validation = import_joi112.default.object({
57900
+ site: import_joi112.default.string().hex().required(),
57901
+ serviceType: import_joi112.default.string().valid(...Object.values(AppServiceType)).required(),
57902
+ page: import_joi112.default.number().min(1).optional().allow("", null),
57903
+ limit: import_joi112.default.number().min(1).optional().allow("", null)
57904
+ });
57905
+ const { error } = validation.validate(query);
57906
+ if (error) {
57907
+ import_node_server_utils200.logger.log({ level: "error", message: error.message });
57908
+ next(new import_node_server_utils200.BadRequestError(error.message));
57909
+ return;
57910
+ }
57911
+ const site = req.params.site;
57912
+ const serviceType = req.params.serviceType;
57913
+ const page = parseInt(req.query.page) ?? 1;
57914
+ const limit = parseInt(req.query.limit) ?? 10;
56981
57915
  try {
56982
- const schema2 = import_joi112.default.object({
56983
- site: import_joi112.default.string().hex().length(24).required(),
56984
- feedbackPeriod: periodField,
56985
- workOrderPeriod: periodField
56986
- });
56987
- const { error, value } = schema2.validate({
56988
- site: req.params.site,
56989
- ...req.query
56990
- });
56991
- if (error) {
56992
- const messages = error.details.map((d) => d.message).join(", ");
56993
- import_node_server_utils200.logger.log({ level: "error", message: messages });
56994
- next(new import_node_server_utils200.BadRequestError(messages));
56995
- return;
56996
- }
56997
- const { site, feedbackPeriod, workOrderPeriod } = value;
56998
- const data = await _getLandscapeDashboard({
56999
- siteId: site,
57000
- feedback: feedbackPeriod,
57001
- workOrder: workOrderPeriod
57916
+ const data = await _getServiceStaffAttendance({
57917
+ site,
57918
+ serviceType,
57919
+ page,
57920
+ limit
57002
57921
  });
57003
- res.status(200).json(data);
57922
+ res.json(data);
57004
57923
  return;
57005
- } catch (error) {
57924
+ } catch (error2) {
57925
+ import_node_server_utils200.logger.log({ level: "error", message: error2.message });
57926
+ next(error2);
57927
+ return;
57928
+ }
57929
+ }
57930
+ async function getServiceRecentFeedbacks(req, res, next) {
57931
+ const query = { ...req.query, ...req.params };
57932
+ const validation = import_joi112.default.object({
57933
+ site: import_joi112.default.string().hex().required(),
57934
+ serviceType: import_joi112.default.string().valid(...Object.values(AppServiceType)).required(),
57935
+ page: import_joi112.default.number().min(1).optional().allow("", null),
57936
+ limit: import_joi112.default.number().min(1).optional().allow("", null)
57937
+ });
57938
+ const { error } = validation.validate(query);
57939
+ if (error) {
57006
57940
  import_node_server_utils200.logger.log({ level: "error", message: error.message });
57007
- next(error);
57941
+ next(new import_node_server_utils200.BadRequestError(error.message));
57942
+ return;
57943
+ }
57944
+ const site = req.params.site;
57945
+ const serviceType = req.params.serviceType;
57946
+ const page = parseInt(req.query.page) ?? 1;
57947
+ const limit = parseInt(req.query.limit) ?? 10;
57948
+ try {
57949
+ const data = await _getServiceRecentFeedbacks({
57950
+ site,
57951
+ serviceType,
57952
+ page,
57953
+ limit
57954
+ });
57955
+ res.json(data);
57956
+ return;
57957
+ } catch (error2) {
57958
+ import_node_server_utils200.logger.log({ level: "error", message: error2.message });
57959
+ next(error2);
57008
57960
  return;
57009
57961
  }
57010
57962
  }
57011
57963
  return {
57012
57964
  getSecurityDashboard,
57013
57965
  getPropertyManagementDashboard,
57014
- getPestManagementDashboard,
57015
- getPoolManagementDashboard,
57016
- getMAndEManagementDashboard,
57017
- getLandscapeDashboard
57966
+ getServiceDashboard,
57967
+ getServiceWeeklyActivity,
57968
+ getServiceTodayTaskSchedule,
57969
+ getServiceStaffAttendance,
57970
+ getServiceRecentFeedbacks
57018
57971
  };
57019
57972
  }
57020
57973
 
57021
57974
  // src/models/manpower-monitoring.model.ts
57022
57975
  var import_joi113 = __toESM(require("joi"));
57023
- var import_mongodb121 = require("mongodb");
57976
+ var import_mongodb122 = require("mongodb");
57024
57977
  var shiftSchema = import_joi113.default.object({
57025
57978
  name: import_joi113.default.string().required(),
57026
57979
  checkIn: import_joi113.default.string().optional().allow("", null),
@@ -57045,7 +57998,7 @@ var manpowerMonitoringSchema = import_joi113.default.object({
57045
57998
  });
57046
57999
  var MManpowerMonitoring = class {
57047
58000
  constructor(data) {
57048
- this._id = new import_mongodb121.ObjectId();
58001
+ this._id = new import_mongodb122.ObjectId();
57049
58002
  this.serviceProviderId = data.serviceProviderId || "";
57050
58003
  this.siteId = data.siteId || "";
57051
58004
  this.siteName = data.siteName;
@@ -57154,7 +58107,7 @@ function filterByShiftTime(attendance, shiftData, timezone, format2) {
57154
58107
  return checkInLocal.isBetween(shiftStart, shiftEnd, null, "[]");
57155
58108
  });
57156
58109
  }
57157
- function paginate51(data, page, limit) {
58110
+ function paginate52(data, page, limit) {
57158
58111
  const length = data.length;
57159
58112
  const startIndex = (page - 1) * limit;
57160
58113
  const endIndex = startIndex + limit;
@@ -57502,7 +58455,7 @@ var hrmlabs_attendance_util_default = {
57502
58455
  hrmLabsAuthentication,
57503
58456
  fetchAttendanceData,
57504
58457
  filterByShiftTime,
57505
- paginate: paginate51,
58458
+ paginate: paginate52,
57506
58459
  designationCount,
57507
58460
  totalCountPerShift,
57508
58461
  filterByStatus,
@@ -57512,7 +58465,7 @@ var hrmlabs_attendance_util_default = {
57512
58465
  };
57513
58466
 
57514
58467
  // src/repositories/manpower-monitoring.repo.ts
57515
- var import_mongodb122 = require("mongodb");
58468
+ var import_mongodb123 = require("mongodb");
57516
58469
  var { hrmLabsAuthentication: hrmLabsAuthentication2, fetchSites: fetchSites2 } = hrmlabs_attendance_util_default;
57517
58470
  function useManpowerMonitoringRepo() {
57518
58471
  const db = import_node_server_utils201.useAtlas.getDb();
@@ -57547,11 +58500,11 @@ function useManpowerMonitoringRepo() {
57547
58500
  try {
57548
58501
  value = new MManpowerMonitoring(value);
57549
58502
  if (value.createdBy)
57550
- value.createdBy = new import_mongodb122.ObjectId(value.createdBy);
58503
+ value.createdBy = new import_mongodb123.ObjectId(value.createdBy);
57551
58504
  if (value.siteId)
57552
- value.siteId = new import_mongodb122.ObjectId(value.siteId);
58505
+ value.siteId = new import_mongodb123.ObjectId(value.siteId);
57553
58506
  if (value.serviceProviderId)
57554
- value.serviceProviderId = new import_mongodb122.ObjectId(value.serviceProviderId);
58507
+ value.serviceProviderId = new import_mongodb123.ObjectId(value.serviceProviderId);
57555
58508
  const result = await collection.insertOne(value, { session });
57556
58509
  return result;
57557
58510
  } catch (error) {
@@ -57592,8 +58545,8 @@ function useManpowerMonitoringRepo() {
57592
58545
  }
57593
58546
  async function getManpowerSettingsBySiteId(_id, serviceProviderId) {
57594
58547
  try {
57595
- _id = new import_mongodb122.ObjectId(_id);
57596
- serviceProviderId = new import_mongodb122.ObjectId(serviceProviderId);
58548
+ _id = new import_mongodb123.ObjectId(_id);
58549
+ serviceProviderId = new import_mongodb123.ObjectId(serviceProviderId);
57597
58550
  } catch (error) {
57598
58551
  throw new Error("Invalid Site ID format.");
57599
58552
  }
@@ -57609,7 +58562,7 @@ function useManpowerMonitoringRepo() {
57609
58562
  }
57610
58563
  async function updateManpowerMonitoringSettings(_id, value) {
57611
58564
  try {
57612
- _id = new import_mongodb122.ObjectId(_id);
58565
+ _id = new import_mongodb123.ObjectId(_id);
57613
58566
  } catch (error) {
57614
58567
  throw new import_node_server_utils201.BadRequestError("Invalid ID format.");
57615
58568
  }
@@ -57636,7 +58589,7 @@ function useManpowerMonitoringRepo() {
57636
58589
  for (let item of value) {
57637
58590
  item = new MManpowerMonitoring(item);
57638
58591
  const data = await collection.findOne({
57639
- siteId: new import_mongodb122.ObjectId(item.siteId)
58592
+ siteId: new import_mongodb123.ObjectId(item.siteId)
57640
58593
  });
57641
58594
  if (data) {
57642
58595
  let updateValue;
@@ -57661,11 +58614,11 @@ function useManpowerMonitoringRepo() {
57661
58614
  }
57662
58615
  } else {
57663
58616
  if (item.createdBy)
57664
- item.createdBy = new import_mongodb122.ObjectId(item.createdBy);
58617
+ item.createdBy = new import_mongodb123.ObjectId(item.createdBy);
57665
58618
  if (item.siteId)
57666
- item.siteId = new import_mongodb122.ObjectId(item.siteId);
58619
+ item.siteId = new import_mongodb123.ObjectId(item.siteId);
57667
58620
  if (item.serviceProviderId)
57668
- item.serviceProviderId = new import_mongodb122.ObjectId(item.serviceProviderId);
58621
+ item.serviceProviderId = new import_mongodb123.ObjectId(item.serviceProviderId);
57669
58622
  const result = await collection.insertOne(item);
57670
58623
  if (result.insertedId) {
57671
58624
  results.inserted++;
@@ -57689,7 +58642,7 @@ function useManpowerMonitoringRepo() {
57689
58642
  const siteUrl = process.env.HRMLABS_SITE_URL;
57690
58643
  try {
57691
58644
  const serviceProvider = await serviceProviderCollection.findOne({
57692
- _id: new import_mongodb122.ObjectId(serviceProviderId)
58645
+ _id: new import_mongodb123.ObjectId(serviceProviderId)
57693
58646
  });
57694
58647
  if (!serviceProvider) {
57695
58648
  throw new Error("Service Provider not found.");
@@ -57732,7 +58685,7 @@ var import_node_server_utils202 = require("@7365admin1/node-server-utils");
57732
58685
 
57733
58686
  // src/models/manpower-remarks.model.ts
57734
58687
  var import_joi114 = __toESM(require("joi"));
57735
- var import_mongodb123 = require("mongodb");
58688
+ var import_mongodb124 = require("mongodb");
57736
58689
  var remarksSchema = import_joi114.default.object({
57737
58690
  name: import_joi114.default.string().required(),
57738
58691
  remark: import_joi114.default.object({
@@ -57756,7 +58709,7 @@ var manpowerRemarksSchema = import_joi114.default.object({
57756
58709
  });
57757
58710
  var MManpowerRemarks = class {
57758
58711
  constructor(data) {
57759
- this._id = new import_mongodb123.ObjectId();
58712
+ this._id = new import_mongodb124.ObjectId();
57760
58713
  this.serviceProviderId = data.serviceProviderId || "";
57761
58714
  this.siteId = data.siteId || "";
57762
58715
  this.siteName = data.siteName || "";
@@ -57774,7 +58727,7 @@ var MManpowerRemarks = class {
57774
58727
  };
57775
58728
 
57776
58729
  // src/repositories/manpower-remarks.repo.ts
57777
- var import_mongodb124 = require("mongodb");
58730
+ var import_mongodb125 = require("mongodb");
57778
58731
  var import_moment_timezone3 = __toESM(require("moment-timezone"));
57779
58732
  function useManpowerRemarksRepo() {
57780
58733
  const db = import_node_server_utils202.useAtlas.getDb();
@@ -57808,9 +58761,9 @@ function useManpowerRemarksRepo() {
57808
58761
  try {
57809
58762
  value = new MManpowerRemarks(value);
57810
58763
  if (value.siteId)
57811
- value.siteId = new import_mongodb124.ObjectId(value.siteId);
58764
+ value.siteId = new import_mongodb125.ObjectId(value.siteId);
57812
58765
  if (value.serviceProviderId)
57813
- value.serviceProviderId = new import_mongodb124.ObjectId(value.serviceProviderId);
58766
+ value.serviceProviderId = new import_mongodb125.ObjectId(value.serviceProviderId);
57814
58767
  const result = await collection.insertOne(value, { session });
57815
58768
  return result;
57816
58769
  } catch (error) {
@@ -57830,7 +58783,7 @@ function useManpowerRemarksRepo() {
57830
58783
  limit = limit || 10;
57831
58784
  const searchQuery = {};
57832
58785
  const nowSGT = (0, import_moment_timezone3.default)().tz("Asia/Singapore");
57833
- searchQuery.serviceProviderId = new import_mongodb124.ObjectId(serviceProviderId);
58786
+ searchQuery.serviceProviderId = new import_mongodb125.ObjectId(serviceProviderId);
57834
58787
  if (search != "") {
57835
58788
  searchQuery.siteName = { $regex: search, $options: "i" };
57836
58789
  }
@@ -57862,8 +58815,8 @@ function useManpowerRemarksRepo() {
57862
58815
  }
57863
58816
  async function getManpowerRemarksBySiteId(_id, date, serviceProviderId) {
57864
58817
  try {
57865
- _id = new import_mongodb124.ObjectId(_id);
57866
- serviceProviderId = new import_mongodb124.ObjectId(serviceProviderId);
58818
+ _id = new import_mongodb125.ObjectId(_id);
58819
+ serviceProviderId = new import_mongodb125.ObjectId(serviceProviderId);
57867
58820
  } catch (error) {
57868
58821
  throw new Error("Invalid Site ID format.");
57869
58822
  }
@@ -57880,13 +58833,13 @@ function useManpowerRemarksRepo() {
57880
58833
  }
57881
58834
  async function updateManpowerRemarks(_id, value) {
57882
58835
  try {
57883
- _id = new import_mongodb124.ObjectId(_id);
58836
+ _id = new import_mongodb125.ObjectId(_id);
57884
58837
  } catch (error) {
57885
58838
  throw new import_node_server_utils202.BadRequestError("Invalid ID format.");
57886
58839
  }
57887
58840
  try {
57888
58841
  if (value.createdBy) {
57889
- value.createdBy = new import_mongodb124.ObjectId(value.createdBy);
58842
+ value.createdBy = new import_mongodb125.ObjectId(value.createdBy);
57890
58843
  }
57891
58844
  const updateValue = {
57892
58845
  ...value,
@@ -57903,7 +58856,7 @@ function useManpowerRemarksRepo() {
57903
58856
  }
57904
58857
  async function updateRemarksStatus(_id, value) {
57905
58858
  try {
57906
- _id = new import_mongodb124.ObjectId(_id);
58859
+ _id = new import_mongodb125.ObjectId(_id);
57907
58860
  } catch (error) {
57908
58861
  throw new import_node_server_utils202.BadRequestError("Invalid ID format.");
57909
58862
  }
@@ -58173,7 +59126,7 @@ function useManpowerMonitoringCtrl() {
58173
59126
 
58174
59127
  // src/models/manpower-designations.model.ts
58175
59128
  var import_joi116 = __toESM(require("joi"));
58176
- var import_mongodb125 = require("mongodb");
59129
+ var import_mongodb126 = require("mongodb");
58177
59130
  var designationsSchema = import_joi116.default.object({
58178
59131
  title: import_joi116.default.string().required(),
58179
59132
  shifts: import_joi116.default.object({
@@ -58192,7 +59145,7 @@ var manpowerDesignationsSchema = import_joi116.default.object({
58192
59145
  });
58193
59146
  var MManpowerDesignations = class {
58194
59147
  constructor(data) {
58195
- this._id = new import_mongodb125.ObjectId();
59148
+ this._id = new import_mongodb126.ObjectId();
58196
59149
  this.siteId = data.siteId || "";
58197
59150
  this.siteName = data.siteName || "";
58198
59151
  this.serviceProviderId = data.serviceProviderId || "";
@@ -58206,7 +59159,7 @@ var MManpowerDesignations = class {
58206
59159
 
58207
59160
  // src/repositories/manpower-designations.repo.ts
58208
59161
  var import_node_server_utils205 = require("@7365admin1/node-server-utils");
58209
- var import_mongodb126 = require("mongodb");
59162
+ var import_mongodb127 = require("mongodb");
58210
59163
  function useManpowerDesignationRepo() {
58211
59164
  const db = import_node_server_utils205.useAtlas.getDb();
58212
59165
  if (!db) {
@@ -58238,11 +59191,11 @@ function useManpowerDesignationRepo() {
58238
59191
  try {
58239
59192
  value = new MManpowerDesignations(value);
58240
59193
  if (value.createdBy)
58241
- value.createdBy = new import_mongodb126.ObjectId(value.createdBy);
59194
+ value.createdBy = new import_mongodb127.ObjectId(value.createdBy);
58242
59195
  if (value.siteId)
58243
- value.siteId = new import_mongodb126.ObjectId(value.siteId);
59196
+ value.siteId = new import_mongodb127.ObjectId(value.siteId);
58244
59197
  if (value.serviceProviderId)
58245
- value.serviceProviderId = new import_mongodb126.ObjectId(value.serviceProviderId);
59198
+ value.serviceProviderId = new import_mongodb127.ObjectId(value.serviceProviderId);
58246
59199
  const result = await collection.insertOne(value);
58247
59200
  return result;
58248
59201
  } catch (error) {
@@ -58251,8 +59204,8 @@ function useManpowerDesignationRepo() {
58251
59204
  }
58252
59205
  async function getManpowerDesignationsBySiteId(_id, serviceProviderId) {
58253
59206
  try {
58254
- _id = new import_mongodb126.ObjectId(_id);
58255
- serviceProviderId = new import_mongodb126.ObjectId(serviceProviderId);
59207
+ _id = new import_mongodb127.ObjectId(_id);
59208
+ serviceProviderId = new import_mongodb127.ObjectId(serviceProviderId);
58256
59209
  } catch (error) {
58257
59210
  throw new Error("Invalid Site ID format.");
58258
59211
  }
@@ -58268,7 +59221,7 @@ function useManpowerDesignationRepo() {
58268
59221
  }
58269
59222
  async function updateManpowerDesignations(_id, value) {
58270
59223
  try {
58271
- _id = new import_mongodb126.ObjectId(_id);
59224
+ _id = new import_mongodb127.ObjectId(_id);
58272
59225
  } catch (error) {
58273
59226
  throw new Error("Invalid ID format.");
58274
59227
  }
@@ -58372,7 +59325,7 @@ function useManpowerDesignationCtrl() {
58372
59325
 
58373
59326
  // src/models/overnight-parking.model.ts
58374
59327
  var import_joi118 = __toESM(require("joi"));
58375
- var import_mongodb127 = require("mongodb");
59328
+ var import_mongodb128 = require("mongodb");
58376
59329
  var dayScheduleSchema = import_joi118.default.object({
58377
59330
  isEnabled: import_joi118.default.boolean().required(),
58378
59331
  startTime: import_joi118.default.string().pattern(/^([01]\d|2[0-3]):([0-5]\d)$/).optional().allow(null, "").messages({
@@ -58414,7 +59367,7 @@ function MOvernightParkingApprovalHours(value) {
58414
59367
  }
58415
59368
  if (value.site && typeof value.site === "string") {
58416
59369
  try {
58417
- value.site = new import_mongodb127.ObjectId(value.site);
59370
+ value.site = new import_mongodb128.ObjectId(value.site);
58418
59371
  } catch {
58419
59372
  throw new Error("Invalid site ID.");
58420
59373
  }
@@ -59177,7 +60130,7 @@ var {
59177
60130
  hrmLabsAuthentication: hrmLabsAuthentication3,
59178
60131
  fetchAttendanceData: fetchAttendanceData2,
59179
60132
  filterByShiftTime: filterByShiftTime2,
59180
- paginate: paginate57,
60133
+ paginate: paginate58,
59181
60134
  designationCount: designationCount2,
59182
60135
  totalCountPerShift: totalCountPerShift2,
59183
60136
  filterByStatus: filterByStatus2,
@@ -59278,7 +60231,7 @@ function useHrmLabsAttendanceSrvc() {
59278
60231
  status
59279
60232
  );
59280
60233
  }
59281
- const paginatedItems = paginate57(filteredAttendance, page, limit);
60234
+ const paginatedItems = paginate58(filteredAttendance, page, limit);
59282
60235
  return {
59283
60236
  items: paginatedItems.items,
59284
60237
  pages: paginatedItems.pages,
@@ -60019,7 +60972,7 @@ function useManpowerRemarkCtrl() {
60019
60972
 
60020
60973
  // src/models/manpower-sites.model.ts
60021
60974
  var import_joi124 = __toESM(require("joi"));
60022
- var import_mongodb128 = require("mongodb");
60975
+ var import_mongodb129 = require("mongodb");
60023
60976
  var manpowerSitesSchema = import_joi124.default.object({
60024
60977
  id: import_joi124.default.string().hex().required(),
60025
60978
  text: import_joi124.default.string().hex().optional().allow("", null),
@@ -60030,7 +60983,7 @@ var manpowerSitesSchema = import_joi124.default.object({
60030
60983
  });
60031
60984
  var MManpowerSites = class {
60032
60985
  constructor(data) {
60033
- this._id = new import_mongodb128.ObjectId();
60986
+ this._id = new import_mongodb129.ObjectId();
60034
60987
  this.id = data.id || "";
60035
60988
  this.text = data.text || "";
60036
60989
  this.contractID = data.contractID || "";
@@ -60240,7 +61193,7 @@ function useManpowerSitesCtrl() {
60240
61193
 
60241
61194
  // src/utils/cron.util.ts
60242
61195
  var import_node_server_utils219 = require("@7365admin1/node-server-utils");
60243
- var import_mongodb129 = require("mongodb");
61196
+ var import_mongodb130 = require("mongodb");
60244
61197
  var import_moment_timezone5 = __toESM(require("moment-timezone"));
60245
61198
  var createManpowerRemarksDaily = async () => {
60246
61199
  const db = import_node_server_utils219.useAtlas.getDb();
@@ -60400,7 +61353,7 @@ var updateRemarksisAcknowledged = async () => {
60400
61353
  for (const id of updatedIds) {
60401
61354
  const doc = await remarks.findOne({ _id: id });
60402
61355
  const setting = await settings.findOne(
60403
- { siteId: new import_mongodb129.ObjectId(doc?.siteId) },
61356
+ { siteId: new import_mongodb130.ObjectId(doc?.siteId) },
60404
61357
  { projection: { emails: 1 } }
60405
61358
  );
60406
61359
  const payload = {
@@ -60486,7 +61439,7 @@ var updateRemarksStatusEod = async () => {
60486
61439
  for (const doc of docs) {
60487
61440
  let shiftsToCheck = [];
60488
61441
  const endShiftTime = await settings.findOne(
60489
- { siteId: new import_mongodb129.ObjectId(doc.siteId) },
61442
+ { siteId: new import_mongodb130.ObjectId(doc.siteId) },
60490
61443
  { projection: { shifts: 1, shiftType: 1 } }
60491
61444
  );
60492
61445
  if (doc.createdAtSGT === nowSGT) {
@@ -60592,7 +61545,7 @@ var isWithinHour = (alertTime, timeNow) => {
60592
61545
 
60593
61546
  // src/events/manpower.event.ts
60594
61547
  var import_node_server_utils220 = require("@7365admin1/node-server-utils");
60595
- var import_mongodb130 = require("mongodb");
61548
+ var import_mongodb131 = require("mongodb");
60596
61549
  var import_moment_timezone6 = __toESM(require("moment-timezone"));
60597
61550
  async function manpowerEvents(io) {
60598
61551
  let intervalId = null;
@@ -60618,7 +61571,7 @@ async function manpowerEvents(io) {
60618
61571
  }).toArray();
60619
61572
  for (const doc of docs) {
60620
61573
  const siteSettings = await settings.findOne(
60621
- { siteId: new import_mongodb130.ObjectId(doc.siteId), enabled: true },
61574
+ { siteId: new import_mongodb131.ObjectId(doc.siteId), enabled: true },
60622
61575
  { projection: { shifts: 1, shiftType: 1 } }
60623
61576
  );
60624
61577
  const shiftType = siteSettings?.shiftType || "2-shifts";
@@ -60737,11 +61690,11 @@ function genericSignature(params, secretKey) {
60737
61690
  }
60738
61691
 
60739
61692
  // src/repositories/reddot-payment.repository.ts
60740
- var import_mongodb132 = require("mongodb");
61693
+ var import_mongodb133 = require("mongodb");
60741
61694
 
60742
61695
  // src/models/billing-payments.model.ts
60743
61696
  var import_node_server_utils221 = require("@7365admin1/node-server-utils");
60744
- var import_mongodb131 = require("mongodb");
61697
+ var import_mongodb132 = require("mongodb");
60745
61698
  var import_joi126 = __toESM(require("joi"));
60746
61699
  var schemaBillingItems = import_joi126.default.object({
60747
61700
  _id: import_joi126.default.string().hex().optional(),
@@ -60775,21 +61728,21 @@ function MBillingItems(value) {
60775
61728
  }
60776
61729
  if (value._id && typeof value._id === "string") {
60777
61730
  try {
60778
- value._id = new import_mongodb131.ObjectId(value._id);
61731
+ value._id = new import_mongodb132.ObjectId(value._id);
60779
61732
  } catch {
60780
61733
  throw new import_node_server_utils221.BadRequestError("Invalid _id format");
60781
61734
  }
60782
61735
  }
60783
61736
  if (value.unitId && typeof value.unitId === "string") {
60784
61737
  try {
60785
- value.unitId = new import_mongodb131.ObjectId(value.unitId);
61738
+ value.unitId = new import_mongodb132.ObjectId(value.unitId);
60786
61739
  } catch {
60787
61740
  throw new import_node_server_utils221.BadRequestError("Invalid unitId id format");
60788
61741
  }
60789
61742
  }
60790
61743
  if (value.paidBy && typeof value.paidBy === "string") {
60791
61744
  try {
60792
- value.paidBy = new import_mongodb131.ObjectId(value.paidBy);
61745
+ value.paidBy = new import_mongodb132.ObjectId(value.paidBy);
60793
61746
  } catch {
60794
61747
  throw new import_node_server_utils221.BadRequestError("Invalid paidBy id format");
60795
61748
  }
@@ -60799,7 +61752,7 @@ function MBillingItems(value) {
60799
61752
  value.unitBillingItems = value.unitBillingItems.map((unitBillingItem) => {
60800
61753
  if (typeof unitBillingItem._id === "string") {
60801
61754
  try {
60802
- unitBillingItem._id = new import_mongodb131.ObjectId(unitBillingItem._id);
61755
+ unitBillingItem._id = new import_mongodb132.ObjectId(unitBillingItem._id);
60803
61756
  } catch {
60804
61757
  throw new import_node_server_utils221.BadRequestError("Invalid unit billing id format");
60805
61758
  }
@@ -60811,7 +61764,7 @@ function MBillingItems(value) {
60811
61764
  }
60812
61765
  }
60813
61766
  return {
60814
- _id: value._id ?? new import_mongodb131.ObjectId(),
61767
+ _id: value._id ?? new import_mongodb132.ObjectId(),
60815
61768
  unitBillingItems: value.unitBillingItems ?? [],
60816
61769
  unitId: value.unitId ?? "",
60817
61770
  unitOwner: value.unitOwner ?? "",
@@ -60879,7 +61832,7 @@ var useRedDotPaymentRepo = () => {
60879
61832
  const res = await paymentCollection().insertOne(payload, { session });
60880
61833
  const unit = payload.unitId?.toString().slice(-4);
60881
61834
  const dateFormatted = formatDateString(/* @__PURE__ */ new Date());
60882
- const newId = new import_mongodb132.ObjectId(res.insertedId).toString().slice(-6);
61835
+ const newId = new import_mongodb133.ObjectId(res.insertedId).toString().slice(-6);
60883
61836
  const referenceNumber = `${unit}${newId}${dateFormatted}`;
60884
61837
  await paymentCollection().updateOne(
60885
61838
  { _id: res.insertedId },
@@ -61979,7 +62932,7 @@ var import_node_server_utils228 = require("@7365admin1/node-server-utils");
61979
62932
  var import_uuid2 = require("uuid");
61980
62933
 
61981
62934
  // src/repositories/user-v2.repo.ts
61982
- var import_mongodb133 = require("mongodb");
62935
+ var import_mongodb134 = require("mongodb");
61983
62936
  var import_node_server_utils227 = require("@7365admin1/node-server-utils");
61984
62937
  function useUserRepoV2() {
61985
62938
  const { updateFeedbackCreatedByName } = useFeedbackRepo();
@@ -62180,7 +63133,7 @@ function useUserRepoV2() {
62180
63133
  }
62181
63134
  if (organization) {
62182
63135
  try {
62183
- query.defaultOrg = new import_mongodb133.ObjectId(organization);
63136
+ query.defaultOrg = new import_mongodb134.ObjectId(organization);
62184
63137
  cacheOptions.organization = organization.toString();
62185
63138
  } catch (error) {
62186
63139
  throw new import_node_server_utils227.BadRequestError("Invalid organization ID format.");
@@ -62319,13 +63272,13 @@ function useUserRepoV2() {
62319
63272
  );
62320
63273
  }
62321
63274
  try {
62322
- _id = new import_mongodb133.ObjectId(_id);
63275
+ _id = new import_mongodb134.ObjectId(_id);
62323
63276
  } catch (error) {
62324
63277
  throw new import_node_server_utils227.BadRequestError("Invalid ID.");
62325
63278
  }
62326
63279
  if (field === "defaultOrg") {
62327
63280
  try {
62328
- value = new import_mongodb133.ObjectId(value);
63281
+ value = new import_mongodb134.ObjectId(value);
62329
63282
  } catch (error) {
62330
63283
  throw new import_node_server_utils227.BadRequestError("Invalid organization ID.");
62331
63284
  }
@@ -62366,7 +63319,7 @@ function useUserRepoV2() {
62366
63319
  year
62367
63320
  }, session) {
62368
63321
  try {
62369
- _id = new import_mongodb133.ObjectId(_id);
63322
+ _id = new import_mongodb134.ObjectId(_id);
62370
63323
  } catch (error) {
62371
63324
  throw new import_node_server_utils227.BadRequestError("Invalid user ID format.");
62372
63325
  }
@@ -62396,7 +63349,7 @@ function useUserRepoV2() {
62396
63349
  }
62397
63350
  async function updatePassword({ _id, password }, session) {
62398
63351
  try {
62399
- _id = new import_mongodb133.ObjectId(_id);
63352
+ _id = new import_mongodb134.ObjectId(_id);
62400
63353
  } catch (error) {
62401
63354
  throw new import_node_server_utils227.BadRequestError("Invalid user ID format.");
62402
63355
  }
@@ -63151,38 +64104,38 @@ function useUserControllerV2() {
63151
64104
 
63152
64105
  // src/models/role-v2.model.ts
63153
64106
  var import_node_server_utils232 = require("@7365admin1/node-server-utils");
63154
- var import_mongodb134 = require("mongodb");
64107
+ var import_mongodb135 = require("mongodb");
63155
64108
  var MRoleV2 = class {
63156
64109
  constructor(value) {
63157
64110
  if (typeof value._id === "string") {
63158
64111
  try {
63159
- value._id = new import_mongodb134.ObjectId(value._id);
64112
+ value._id = new import_mongodb135.ObjectId(value._id);
63160
64113
  } catch (error) {
63161
64114
  throw new import_node_server_utils232.BadRequestError("Invalid role-v2 ID format.");
63162
64115
  }
63163
64116
  }
63164
64117
  if (typeof value.site === "string" && value.site.length === 24) {
63165
64118
  try {
63166
- value.site = new import_mongodb134.ObjectId(value.site);
64119
+ value.site = new import_mongodb135.ObjectId(value.site);
63167
64120
  } catch (error) {
63168
64121
  throw new import_node_server_utils232.BadRequestError("Invalid site ID format.");
63169
64122
  }
63170
64123
  }
63171
64124
  if (typeof value.org === "string" && value.org.length === 24) {
63172
64125
  try {
63173
- value.org = new import_mongodb134.ObjectId(value.org);
64126
+ value.org = new import_mongodb135.ObjectId(value.org);
63174
64127
  } catch (error) {
63175
64128
  throw new import_node_server_utils232.BadRequestError("Invalid org ID format.");
63176
64129
  }
63177
64130
  }
63178
64131
  if (value.createdBy) {
63179
64132
  try {
63180
- value.createdBy = new import_mongodb134.ObjectId(value.createdBy);
64133
+ value.createdBy = new import_mongodb135.ObjectId(value.createdBy);
63181
64134
  } catch (error) {
63182
64135
  throw new import_node_server_utils232.BadRequestError("Invalid created by ID format.");
63183
64136
  }
63184
64137
  }
63185
- this._id = value._id ?? new import_mongodb134.ObjectId();
64138
+ this._id = value._id ?? new import_mongodb135.ObjectId();
63186
64139
  this.name = value.name ?? "";
63187
64140
  this.permissions = value.permissions ?? [];
63188
64141
  this.site = value.site ?? "";
@@ -63317,7 +64270,7 @@ function useRoleControllerV2() {
63317
64270
 
63318
64271
  // src/models/post-preloved.model.ts
63319
64272
  var import_joi133 = __toESM(require("joi"));
63320
- var import_mongodb135 = require("mongodb");
64273
+ var import_mongodb136 = require("mongodb");
63321
64274
  var PostStatus = /* @__PURE__ */ ((PostStatus2) => {
63322
64275
  PostStatus2["PUBLISHED"] = "published";
63323
64276
  PostStatus2["RESERVED"] = "reserved";
@@ -63373,28 +64326,28 @@ function MPost(value) {
63373
64326
  }
63374
64327
  if (value._id && typeof value._id === "string") {
63375
64328
  try {
63376
- value._id = new import_mongodb135.ObjectId(value._id);
64329
+ value._id = new import_mongodb136.ObjectId(value._id);
63377
64330
  } catch {
63378
64331
  throw new Error("Invalid ID.");
63379
64332
  }
63380
64333
  }
63381
64334
  if (value.site && typeof value.site === "string") {
63382
64335
  try {
63383
- value.site = new import_mongodb135.ObjectId(value.site);
64336
+ value.site = new import_mongodb136.ObjectId(value.site);
63384
64337
  } catch {
63385
64338
  throw new Error("Invalid site ID.");
63386
64339
  }
63387
64340
  }
63388
64341
  if (value.createdBy && typeof value.createdBy === "string") {
63389
64342
  try {
63390
- value.createdBy = new import_mongodb135.ObjectId(value.createdBy);
64343
+ value.createdBy = new import_mongodb136.ObjectId(value.createdBy);
63391
64344
  } catch {
63392
64345
  throw new Error("Invalid createdBy ID.");
63393
64346
  }
63394
64347
  }
63395
64348
  if (value.reserverId && typeof value.reserverId === "string") {
63396
64349
  try {
63397
- value.reserverId = new import_mongodb135.ObjectId(value.reserverId);
64350
+ value.reserverId = new import_mongodb136.ObjectId(value.reserverId);
63398
64351
  } catch {
63399
64352
  throw new Error("Invalid reserver ID.");
63400
64353
  }
@@ -63403,7 +64356,7 @@ function MPost(value) {
63403
64356
  value.attachments = value.attachments.map((id) => {
63404
64357
  if (typeof id === "string") {
63405
64358
  try {
63406
- return new import_mongodb135.ObjectId(id);
64359
+ return new import_mongodb136.ObjectId(id);
63407
64360
  } catch {
63408
64361
  throw new Error("Invalid attachment ID.");
63409
64362
  }
@@ -63413,20 +64366,20 @@ function MPost(value) {
63413
64366
  }
63414
64367
  if (value.category && typeof value.category === "string") {
63415
64368
  try {
63416
- value.category = new import_mongodb135.ObjectId(value.category);
64369
+ value.category = new import_mongodb136.ObjectId(value.category);
63417
64370
  } catch {
63418
64371
  throw new Error("Invalid category ID.");
63419
64372
  }
63420
64373
  }
63421
64374
  if (value.subcategory && typeof value.subcategory === "string") {
63422
64375
  try {
63423
- value.subcategory = new import_mongodb135.ObjectId(value.subcategory);
64376
+ value.subcategory = new import_mongodb136.ObjectId(value.subcategory);
63424
64377
  } catch {
63425
64378
  throw new Error("Invalid subcategory ID.");
63426
64379
  }
63427
64380
  }
63428
64381
  return {
63429
- _id: value._id ?? new import_mongodb135.ObjectId(),
64382
+ _id: value._id ?? new import_mongodb136.ObjectId(),
63430
64383
  title: value.title ?? "",
63431
64384
  description: value.description ?? "",
63432
64385
  attachments: value.attachments ?? [],
@@ -63446,7 +64399,7 @@ function MPost(value) {
63446
64399
 
63447
64400
  // src/repositories/post-preloved.repo.ts
63448
64401
  var import_node_server_utils235 = require("@7365admin1/node-server-utils");
63449
- var import_mongodb136 = require("mongodb");
64402
+ var import_mongodb137 = require("mongodb");
63450
64403
  function usePostPrelovedRepo() {
63451
64404
  const db = import_node_server_utils235.useAtlas.getDb();
63452
64405
  if (!db) {
@@ -63510,14 +64463,14 @@ function usePostPrelovedRepo() {
63510
64463
  }
63511
64464
  async function getById(_id, userId) {
63512
64465
  try {
63513
- _id = new import_mongodb136.ObjectId(_id);
64466
+ _id = new import_mongodb137.ObjectId(_id);
63514
64467
  } catch {
63515
64468
  throw new import_node_server_utils235.BadRequestError("Invalid post ID format.");
63516
64469
  }
63517
64470
  let userObjectId = null;
63518
64471
  if (userId) {
63519
64472
  try {
63520
- userObjectId = new import_mongodb136.ObjectId(userId);
64473
+ userObjectId = new import_mongodb137.ObjectId(userId);
63521
64474
  } catch {
63522
64475
  throw new import_node_server_utils235.BadRequestError("Invalid user ID format.");
63523
64476
  }
@@ -63587,7 +64540,7 @@ function usePostPrelovedRepo() {
63587
64540
  page = page > 0 ? page - 1 : 0;
63588
64541
  if (site) {
63589
64542
  try {
63590
- site = new import_mongodb136.ObjectId(site);
64543
+ site = new import_mongodb137.ObjectId(site);
63591
64544
  } catch {
63592
64545
  throw new import_node_server_utils235.BadRequestError("Invalid site ID format.");
63593
64546
  }
@@ -63596,14 +64549,14 @@ function usePostPrelovedRepo() {
63596
64549
  let subcategoryIds = null;
63597
64550
  if (category && subcategory) {
63598
64551
  try {
63599
- categoryId = new import_mongodb136.ObjectId(category);
64552
+ categoryId = new import_mongodb137.ObjectId(category);
63600
64553
  } catch {
63601
64554
  throw new import_node_server_utils235.BadRequestError("Invalid category ID format.");
63602
64555
  }
63603
64556
  if (subcategory.length > 0) {
63604
64557
  subcategoryIds = subcategory.map((id) => {
63605
64558
  try {
63606
- return new import_mongodb136.ObjectId(id);
64559
+ return new import_mongodb137.ObjectId(id);
63607
64560
  } catch {
63608
64561
  throw new import_node_server_utils235.BadRequestError("Invalid subcategory ID format.");
63609
64562
  }
@@ -63628,7 +64581,7 @@ function usePostPrelovedRepo() {
63628
64581
  let userObjectId = null;
63629
64582
  if (userId) {
63630
64583
  try {
63631
- userObjectId = new import_mongodb136.ObjectId(userId);
64584
+ userObjectId = new import_mongodb137.ObjectId(userId);
63632
64585
  } catch {
63633
64586
  throw new import_node_server_utils235.BadRequestError("Invalid user ID format.");
63634
64587
  }
@@ -63677,7 +64630,7 @@ function usePostPrelovedRepo() {
63677
64630
  }
63678
64631
  async function updateById(_id, value, session) {
63679
64632
  try {
63680
- _id = new import_mongodb136.ObjectId(_id);
64633
+ _id = new import_mongodb137.ObjectId(_id);
63681
64634
  } catch {
63682
64635
  throw new import_node_server_utils235.BadRequestError("Invalid post ID format.");
63683
64636
  }
@@ -63698,7 +64651,7 @@ function usePostPrelovedRepo() {
63698
64651
  }
63699
64652
  async function deleteById(_id, session) {
63700
64653
  try {
63701
- _id = new import_mongodb136.ObjectId(_id);
64654
+ _id = new import_mongodb137.ObjectId(_id);
63702
64655
  } catch {
63703
64656
  throw new import_node_server_utils235.BadRequestError("Invalid post ID format.");
63704
64657
  }
@@ -63724,7 +64677,7 @@ function usePostPrelovedRepo() {
63724
64677
  }
63725
64678
  async function updateStatus(_id, status, session) {
63726
64679
  try {
63727
- _id = new import_mongodb136.ObjectId(_id);
64680
+ _id = new import_mongodb137.ObjectId(_id);
63728
64681
  } catch {
63729
64682
  throw new import_node_server_utils235.BadRequestError("Invalid post ID format.");
63730
64683
  }
@@ -63760,11 +64713,11 @@ var import_node_server_utils237 = require("@7365admin1/node-server-utils");
63760
64713
 
63761
64714
  // src/repositories/post-favorite.repo.ts
63762
64715
  var import_node_server_utils236 = require("@7365admin1/node-server-utils");
63763
- var import_mongodb138 = require("mongodb");
64716
+ var import_mongodb139 = require("mongodb");
63764
64717
 
63765
64718
  // src/models/post-favorite.model.ts
63766
64719
  var import_joi134 = __toESM(require("joi"));
63767
- var import_mongodb137 = require("mongodb");
64720
+ var import_mongodb138 = require("mongodb");
63768
64721
  var schemaUpdatePostFavorite = import_joi134.default.object({
63769
64722
  userId: import_joi134.default.string().hex().length(24).required()
63770
64723
  });
@@ -63782,14 +64735,14 @@ function MPostFavorite(value) {
63782
64735
  }
63783
64736
  if (value._id && typeof value._id === "string") {
63784
64737
  try {
63785
- value._id = new import_mongodb137.ObjectId(value._id);
64738
+ value._id = new import_mongodb138.ObjectId(value._id);
63786
64739
  } catch {
63787
64740
  throw new Error("Invalid ID.");
63788
64741
  }
63789
64742
  }
63790
64743
  if (value.postId && typeof value.postId === "string") {
63791
64744
  try {
63792
- value.postId = new import_mongodb137.ObjectId(value.postId);
64745
+ value.postId = new import_mongodb138.ObjectId(value.postId);
63793
64746
  } catch {
63794
64747
  throw new Error("Invalid post ID.");
63795
64748
  }
@@ -63798,7 +64751,7 @@ function MPostFavorite(value) {
63798
64751
  value.userIds = value.userIds.map((id) => {
63799
64752
  if (typeof id === "string") {
63800
64753
  try {
63801
- return new import_mongodb137.ObjectId(id);
64754
+ return new import_mongodb138.ObjectId(id);
63802
64755
  } catch {
63803
64756
  throw new Error("Invalid user ID.");
63804
64757
  }
@@ -63807,7 +64760,7 @@ function MPostFavorite(value) {
63807
64760
  });
63808
64761
  }
63809
64762
  return {
63810
- _id: value._id ?? new import_mongodb137.ObjectId(),
64763
+ _id: value._id ?? new import_mongodb138.ObjectId(),
63811
64764
  postId: value.postId ?? "",
63812
64765
  userIds: value.userIds ?? [],
63813
64766
  createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -63837,7 +64790,7 @@ function usePostFavoriteRepo() {
63837
64790
  }
63838
64791
  async function getById(_id) {
63839
64792
  try {
63840
- _id = new import_mongodb138.ObjectId(_id);
64793
+ _id = new import_mongodb139.ObjectId(_id);
63841
64794
  } catch {
63842
64795
  throw new import_node_server_utils236.BadRequestError("Invalid favorite ID format.");
63843
64796
  }
@@ -63848,7 +64801,7 @@ function usePostFavoriteRepo() {
63848
64801
  }
63849
64802
  async function getByPostId(postId) {
63850
64803
  try {
63851
- postId = new import_mongodb138.ObjectId(postId);
64804
+ postId = new import_mongodb139.ObjectId(postId);
63852
64805
  } catch {
63853
64806
  throw new import_node_server_utils236.BadRequestError("Invalid post ID format.");
63854
64807
  }
@@ -63859,13 +64812,13 @@ function usePostFavoriteRepo() {
63859
64812
  }
63860
64813
  async function updateById(_id, userId, session) {
63861
64814
  try {
63862
- _id = new import_mongodb138.ObjectId(_id);
64815
+ _id = new import_mongodb139.ObjectId(_id);
63863
64816
  } catch {
63864
64817
  throw new import_node_server_utils236.BadRequestError("Invalid favorite ID format.");
63865
64818
  }
63866
64819
  let userObjectId;
63867
64820
  try {
63868
- userObjectId = new import_mongodb138.ObjectId(userId);
64821
+ userObjectId = new import_mongodb139.ObjectId(userId);
63869
64822
  } catch {
63870
64823
  throw new import_node_server_utils236.BadRequestError("Invalid user ID format.");
63871
64824
  }
@@ -63896,7 +64849,7 @@ function usePostFavoriteRepo() {
63896
64849
  }
63897
64850
 
63898
64851
  // src/services/post-preloved.service.ts
63899
- var import_mongodb139 = require("mongodb");
64852
+ var import_mongodb140 = require("mongodb");
63900
64853
  function usePostFavoriteService() {
63901
64854
  const { add: _addPost } = usePostPrelovedRepo();
63902
64855
  const { addFavorite: _addFavorite } = usePostFavoriteRepo();
@@ -63914,7 +64867,7 @@ function usePostFavoriteService() {
63914
64867
  let siteId = value.site;
63915
64868
  let postId = post.toString();
63916
64869
  if (value.site) {
63917
- siteId = new import_mongodb139.ObjectId(value.site);
64870
+ siteId = new import_mongodb140.ObjectId(value.site);
63918
64871
  }
63919
64872
  if (post) {
63920
64873
  postId = post.toString();
@@ -64273,7 +65226,7 @@ function usePostFavoriteController() {
64273
65226
 
64274
65227
  // src/models/category-preloved.model.ts
64275
65228
  var import_joi137 = __toESM(require("joi"));
64276
- var import_mongodb140 = require("mongodb");
65229
+ var import_mongodb141 = require("mongodb");
64277
65230
  var schemaCategoryPreloved = import_joi137.default.object({
64278
65231
  name: import_joi137.default.string().required(),
64279
65232
  createdBy: import_joi137.default.string().hex().optional().allow("", null),
@@ -64290,14 +65243,14 @@ function MCategoryPreloved(value) {
64290
65243
  }
64291
65244
  if (value.createdBy && typeof value.createdBy === "string") {
64292
65245
  try {
64293
- value.createdBy = new import_mongodb140.ObjectId(value.createdBy);
65246
+ value.createdBy = new import_mongodb141.ObjectId(value.createdBy);
64294
65247
  } catch {
64295
65248
  throw new Error("Invalid createdBy ID.");
64296
65249
  }
64297
65250
  }
64298
65251
  if (value.site && typeof value.site === "string") {
64299
65252
  try {
64300
- value.site = new import_mongodb140.ObjectId(value.site);
65253
+ value.site = new import_mongodb141.ObjectId(value.site);
64301
65254
  } catch {
64302
65255
  throw new Error("Invalid site ID.");
64303
65256
  }
@@ -64313,7 +65266,7 @@ function MCategoryPreloved(value) {
64313
65266
 
64314
65267
  // src/repositories/category-preloved.repo.ts
64315
65268
  var import_node_server_utils241 = require("@7365admin1/node-server-utils");
64316
- var import_mongodb141 = require("mongodb");
65269
+ var import_mongodb142 = require("mongodb");
64317
65270
  function useCategoryPrelovedRepo() {
64318
65271
  const db = import_node_server_utils241.useAtlas.getDb();
64319
65272
  if (!db) {
@@ -64327,7 +65280,7 @@ function useCategoryPrelovedRepo() {
64327
65280
  } = {}) {
64328
65281
  if (site) {
64329
65282
  try {
64330
- site = new import_mongodb141.ObjectId(site);
65283
+ site = new import_mongodb142.ObjectId(site);
64331
65284
  } catch {
64332
65285
  throw new import_node_server_utils241.BadRequestError("Invalid site ID format.");
64333
65286
  }
@@ -64346,7 +65299,7 @@ function useCategoryPrelovedRepo() {
64346
65299
  async function getById(_id) {
64347
65300
  let objectId2;
64348
65301
  try {
64349
- objectId2 = new import_mongodb141.ObjectId(_id);
65302
+ objectId2 = new import_mongodb142.ObjectId(_id);
64350
65303
  } catch {
64351
65304
  throw new import_node_server_utils241.BadRequestError("Invalid category-preloved ID format.");
64352
65305
  }
@@ -64376,7 +65329,7 @@ function useCategoryPrelovedRepo() {
64376
65329
  async function updateById(_id, value) {
64377
65330
  let objectId2;
64378
65331
  try {
64379
- objectId2 = new import_mongodb141.ObjectId(_id);
65332
+ objectId2 = new import_mongodb142.ObjectId(_id);
64380
65333
  } catch {
64381
65334
  throw new import_node_server_utils241.BadRequestError("Invalid category ID format.");
64382
65335
  }
@@ -64394,7 +65347,7 @@ function useCategoryPrelovedRepo() {
64394
65347
  async function deleteById(_id) {
64395
65348
  let objectId2;
64396
65349
  try {
64397
- objectId2 = new import_mongodb141.ObjectId(_id);
65350
+ objectId2 = new import_mongodb142.ObjectId(_id);
64398
65351
  } catch {
64399
65352
  throw new import_node_server_utils241.BadRequestError("Invalid category ID format.");
64400
65353
  }
@@ -64515,7 +65468,7 @@ function useCategoryPrelovedController() {
64515
65468
 
64516
65469
  // src/models/subcategory-preloved.model.ts
64517
65470
  var import_joi139 = __toESM(require("joi"));
64518
- var import_mongodb142 = require("mongodb");
65471
+ var import_mongodb143 = require("mongodb");
64519
65472
  var schemaSubcategoryPreloved = import_joi139.default.object({
64520
65473
  name: import_joi139.default.string().required(),
64521
65474
  createdBy: import_joi139.default.string().hex().optional().allow("", null),
@@ -64534,21 +65487,21 @@ function MSubcategoryPreloved(value) {
64534
65487
  }
64535
65488
  if (value.createdBy && typeof value.createdBy === "string") {
64536
65489
  try {
64537
- value.createdBy = new import_mongodb142.ObjectId(value.createdBy);
65490
+ value.createdBy = new import_mongodb143.ObjectId(value.createdBy);
64538
65491
  } catch {
64539
65492
  throw new Error("Invalid createdBy ID.");
64540
65493
  }
64541
65494
  }
64542
65495
  if (value.site && typeof value.site === "string") {
64543
65496
  try {
64544
- value.site = new import_mongodb142.ObjectId(value.site);
65497
+ value.site = new import_mongodb143.ObjectId(value.site);
64545
65498
  } catch {
64546
65499
  throw new Error("Invalid site ID.");
64547
65500
  }
64548
65501
  }
64549
65502
  if (value.category_id && typeof value.category_id === "string") {
64550
65503
  try {
64551
- value.category_id = new import_mongodb142.ObjectId(value.category_id);
65504
+ value.category_id = new import_mongodb143.ObjectId(value.category_id);
64552
65505
  } catch {
64553
65506
  throw new Error("Invalid category ID.");
64554
65507
  }
@@ -64565,7 +65518,7 @@ function MSubcategoryPreloved(value) {
64565
65518
 
64566
65519
  // src/repositories/subcategory-preloved.repo.ts
64567
65520
  var import_node_server_utils243 = require("@7365admin1/node-server-utils");
64568
- var import_mongodb143 = require("mongodb");
65521
+ var import_mongodb144 = require("mongodb");
64569
65522
  function useSubcategoryPrelovedRepo() {
64570
65523
  const db = import_node_server_utils243.useAtlas.getDb();
64571
65524
  if (!db) {
@@ -64580,14 +65533,14 @@ function useSubcategoryPrelovedRepo() {
64580
65533
  } = {}) {
64581
65534
  if (site) {
64582
65535
  try {
64583
- site = new import_mongodb143.ObjectId(site);
65536
+ site = new import_mongodb144.ObjectId(site);
64584
65537
  } catch {
64585
65538
  throw new import_node_server_utils243.BadRequestError("Invalid site ID format.");
64586
65539
  }
64587
65540
  }
64588
65541
  if (category_id) {
64589
65542
  try {
64590
- category_id = new import_mongodb143.ObjectId(category_id);
65543
+ category_id = new import_mongodb144.ObjectId(category_id);
64591
65544
  } catch {
64592
65545
  throw new import_node_server_utils243.BadRequestError("Invalid category ID format.");
64593
65546
  }
@@ -64606,7 +65559,7 @@ function useSubcategoryPrelovedRepo() {
64606
65559
  async function getById(_id) {
64607
65560
  let objectId2;
64608
65561
  try {
64609
- objectId2 = new import_mongodb143.ObjectId(_id);
65562
+ objectId2 = new import_mongodb144.ObjectId(_id);
64610
65563
  } catch {
64611
65564
  throw new import_node_server_utils243.BadRequestError("Invalid subcategory-preloved ID format.");
64612
65565
  }
@@ -64635,20 +65588,20 @@ function useSubcategoryPrelovedRepo() {
64635
65588
  async function updateById(_id, value, session) {
64636
65589
  let objectId2;
64637
65590
  try {
64638
- objectId2 = new import_mongodb143.ObjectId(_id);
65591
+ objectId2 = new import_mongodb144.ObjectId(_id);
64639
65592
  } catch {
64640
65593
  throw new import_node_server_utils243.BadRequestError("Invalid subcategory ID format.");
64641
65594
  }
64642
65595
  if (value.category_id && typeof value.category_id === "string") {
64643
65596
  try {
64644
- value.category_id = new import_mongodb143.ObjectId(value.category_id);
65597
+ value.category_id = new import_mongodb144.ObjectId(value.category_id);
64645
65598
  } catch {
64646
65599
  throw new import_node_server_utils243.BadRequestError("Invalid category ID format.");
64647
65600
  }
64648
65601
  }
64649
65602
  if (value.site && typeof value.site === "string") {
64650
65603
  try {
64651
- value.site = new import_mongodb143.ObjectId(value.site);
65604
+ value.site = new import_mongodb144.ObjectId(value.site);
64652
65605
  } catch {
64653
65606
  throw new import_node_server_utils243.BadRequestError("Invalid site ID format.");
64654
65607
  }
@@ -64666,7 +65619,7 @@ function useSubcategoryPrelovedRepo() {
64666
65619
  async function deleteById(_id, session) {
64667
65620
  let objectId2;
64668
65621
  try {
64669
- objectId2 = new import_mongodb143.ObjectId(_id);
65622
+ objectId2 = new import_mongodb144.ObjectId(_id);
64670
65623
  } catch {
64671
65624
  throw new import_node_server_utils243.BadRequestError("Invalid subcategory ID format.");
64672
65625
  }
@@ -64798,7 +65751,7 @@ function useSubcategoryPrelovedController() {
64798
65751
 
64799
65752
  // src/models/chat-preloved.model.ts
64800
65753
  var import_joi141 = __toESM(require("joi"));
64801
- var import_mongodb144 = require("mongodb");
65754
+ var import_mongodb145 = require("mongodb");
64802
65755
  var schemaMessage = import_joi141.default.object({
64803
65756
  text: import_joi141.default.string().required(),
64804
65757
  date: import_joi141.default.date().optional().allow(null),
@@ -64829,7 +65782,7 @@ var schemaChatPreloved = import_joi141.default.object({
64829
65782
  function toObjectId21(value, label) {
64830
65783
  if (typeof value === "string") {
64831
65784
  try {
64832
- return new import_mongodb144.ObjectId(value);
65785
+ return new import_mongodb145.ObjectId(value);
64833
65786
  } catch {
64834
65787
  throw new Error(`Invalid ${label}.`);
64835
65788
  }
@@ -64861,7 +65814,7 @@ function MChatPreloved(value) {
64861
65814
  value.attachments = value.attachments.map((id) => toObjectId21(id, "attachment ID"));
64862
65815
  }
64863
65816
  return {
64864
- _id: new import_mongodb144.ObjectId(),
65817
+ _id: new import_mongodb145.ObjectId(),
64865
65818
  channelId: value.channelId ?? "",
64866
65819
  senderId: value.senderId ?? "",
64867
65820
  postId: value.postId ?? null,
@@ -64885,7 +65838,7 @@ function MChatPreloved(value) {
64885
65838
 
64886
65839
  // src/repositories/chat-preloved.repo.ts
64887
65840
  var import_node_server_utils245 = require("@7365admin1/node-server-utils");
64888
- var import_mongodb145 = require("mongodb");
65841
+ var import_mongodb146 = require("mongodb");
64889
65842
  function useChatPrelovedRepo() {
64890
65843
  const db = import_node_server_utils245.useAtlas.getDb();
64891
65844
  if (!db)
@@ -64904,7 +65857,7 @@ function useChatPrelovedRepo() {
64904
65857
  async function updateById(_id, value) {
64905
65858
  let objectId2;
64906
65859
  try {
64907
- objectId2 = new import_mongodb145.ObjectId(_id);
65860
+ objectId2 = new import_mongodb146.ObjectId(_id);
64908
65861
  } catch {
64909
65862
  throw new import_node_server_utils245.BadRequestError("Invalid chat ID format.");
64910
65863
  }
@@ -64921,7 +65874,7 @@ function useChatPrelovedRepo() {
64921
65874
  async function deleteById(_id) {
64922
65875
  let objectId2;
64923
65876
  try {
64924
- objectId2 = new import_mongodb145.ObjectId(_id);
65877
+ objectId2 = new import_mongodb146.ObjectId(_id);
64925
65878
  } catch {
64926
65879
  throw new import_node_server_utils245.BadRequestError("Invalid chat ID format.");
64927
65880
  }
@@ -64940,79 +65893,28 @@ function useChatPrelovedRepo() {
64940
65893
  }
64941
65894
 
64942
65895
  // src/controllers/chat-preloved.controller.ts
65896
+ var import_node_server_utils248 = require("@7365admin1/node-server-utils");
65897
+ var import_joi143 = __toESM(require("joi"));
65898
+
65899
+ // src/services/chat-preloved.service.ts
65900
+ var import_node_server_utils247 = require("@7365admin1/node-server-utils");
65901
+
65902
+ // src/repositories/channel-preloved.repo.ts
64943
65903
  var import_node_server_utils246 = require("@7365admin1/node-server-utils");
64944
- var import_joi142 = __toESM(require("joi"));
64945
- function useChatPrelovedController() {
64946
- const { add: _add, updateById: _updateById, deleteById: _deleteById } = useChatPrelovedRepo();
64947
- async function add(req, res, next) {
64948
- const { error, value } = schemaChatPreloved.validate(req.body, {
64949
- abortEarly: false
64950
- });
64951
- if (error) {
64952
- const messages = error.details.map((d) => d.message).join(", ");
64953
- import_node_server_utils246.logger.log({ level: "error", message: messages });
64954
- next(new import_node_server_utils246.BadRequestError(messages));
64955
- return;
64956
- }
64957
- try {
64958
- const data = await _add(value);
64959
- res.status(201).json(data);
64960
- } catch (error2) {
64961
- import_node_server_utils246.logger.log({ level: "error", message: error2.message });
64962
- next(error2);
64963
- }
64964
- }
64965
- async function updateById(req, res, next) {
64966
- const { error, value } = schemaUpdateChatPreloved.validate(req.body, {
64967
- abortEarly: false
64968
- });
64969
- if (error) {
64970
- const messages = error.details.map((d) => d.message).join(", ");
64971
- import_node_server_utils246.logger.log({ level: "error", message: messages });
64972
- next(new import_node_server_utils246.BadRequestError(messages));
64973
- return;
64974
- }
64975
- try {
64976
- const data = await _updateById(req.params.id, value);
64977
- res.status(200).json(data);
64978
- } catch (error2) {
64979
- import_node_server_utils246.logger.log({ level: "error", message: error2.message });
64980
- next(error2);
64981
- }
64982
- }
64983
- async function deleteById(req, res, next) {
64984
- const schema2 = import_joi142.default.object({
64985
- _id: import_joi142.default.string().hex().length(24).required()
64986
- });
64987
- const { error, value } = schema2.validate({ _id: req.params.id });
64988
- if (error) {
64989
- import_node_server_utils246.logger.log({ level: "error", message: error.message });
64990
- next(new import_node_server_utils246.BadRequestError(error.message));
64991
- return;
64992
- }
64993
- try {
64994
- const data = await _deleteById(value._id);
64995
- res.status(200).json(data);
64996
- } catch (error2) {
64997
- import_node_server_utils246.logger.log({ level: "error", message: error2.message });
64998
- next(error2);
64999
- }
65000
- }
65001
- return { add, updateById, deleteById };
65002
- }
65904
+ var import_mongodb148 = require("mongodb");
65003
65905
 
65004
65906
  // src/models/channel-preloved.model.ts
65005
- var import_joi143 = __toESM(require("joi"));
65006
- var import_mongodb146 = require("mongodb");
65007
- var schemaChannelPreloved = import_joi143.default.object({
65008
- receiverId: import_joi143.default.string().hex().length(24).required(),
65009
- senderId: import_joi143.default.string().hex().length(24).required(),
65010
- postId: import_joi143.default.string().hex().length(24).required()
65907
+ var import_joi142 = __toESM(require("joi"));
65908
+ var import_mongodb147 = require("mongodb");
65909
+ var schemaChannelPreloved = import_joi142.default.object({
65910
+ receiverId: import_joi142.default.string().hex().length(24).required(),
65911
+ senderId: import_joi142.default.string().hex().length(24).required(),
65912
+ postId: import_joi142.default.string().hex().length(24).required()
65011
65913
  });
65012
65914
  function toObjectId22(value, label) {
65013
65915
  if (typeof value === "string") {
65014
65916
  try {
65015
- return new import_mongodb146.ObjectId(value);
65917
+ return new import_mongodb147.ObjectId(value);
65016
65918
  } catch {
65017
65919
  throw new Error(`Invalid ${label}.`);
65018
65920
  }
@@ -65030,7 +65932,7 @@ function MChannelPreloved(value) {
65030
65932
  if (value.postId)
65031
65933
  value.postId = toObjectId22(value.postId, "post ID");
65032
65934
  return {
65033
- _id: new import_mongodb146.ObjectId(),
65935
+ _id: new import_mongodb147.ObjectId(),
65034
65936
  name: `seven365-${(/* @__PURE__ */ new Date()).getTime()}`,
65035
65937
  receiverId: value.receiverId,
65036
65938
  senderId: value.senderId,
@@ -65041,12 +65943,12 @@ function MChannelPreloved(value) {
65041
65943
  }
65042
65944
 
65043
65945
  // src/repositories/channel-preloved.repo.ts
65044
- var import_node_server_utils247 = require("@7365admin1/node-server-utils");
65045
65946
  function useChannelPrelovedRepo() {
65046
- const db = import_node_server_utils247.useAtlas.getDb();
65947
+ const db = import_node_server_utils246.useAtlas.getDb();
65047
65948
  if (!db)
65048
- throw new import_node_server_utils247.InternalServerError("Unable to connect to server.");
65949
+ throw new import_node_server_utils246.InternalServerError("Unable to connect to server.");
65049
65950
  const CHANNEL_COLLECTION = "channel-preloved";
65951
+ const CHAT_COLLECTION = "chat-preloved";
65050
65952
  const collection = db.collection(CHANNEL_COLLECTION);
65051
65953
  async function add(value, session) {
65052
65954
  try {
@@ -65057,15 +65959,151 @@ function useChannelPrelovedRepo() {
65057
65959
  throw error;
65058
65960
  }
65059
65961
  }
65962
+ async function getByParticipants(senderId, receiverId, postId, session) {
65963
+ const query = {
65964
+ senderId: new import_mongodb148.ObjectId(senderId),
65965
+ receiverId: new import_mongodb148.ObjectId(receiverId),
65966
+ postId: new import_mongodb148.ObjectId(postId)
65967
+ };
65968
+ return collection.findOne(query, { session });
65969
+ }
65970
+ async function getChannelMessages(channelId, page = 1, limit = 10, isLoadMore = false, lastMessageId = null) {
65971
+ const chatCollection = db.collection(CHAT_COLLECTION);
65972
+ const normalizedPage = page > 0 ? page - 1 : 0;
65973
+ const normalizedLimit = limit || 10;
65974
+ const matchCriteria = {
65975
+ channelId: new import_mongodb148.ObjectId(channelId),
65976
+ deletedAt: null
65977
+ };
65978
+ if (isLoadMore && lastMessageId) {
65979
+ matchCriteria._id = { $lt: new import_mongodb148.ObjectId(lastMessageId) };
65980
+ }
65981
+ try {
65982
+ const result = await chatCollection.aggregate([
65983
+ { $match: matchCriteria },
65984
+ {
65985
+ $lookup: {
65986
+ from: "users",
65987
+ localField: "senderId",
65988
+ foreignField: "_id",
65989
+ pipeline: [
65990
+ {
65991
+ $project: {
65992
+ name: 1,
65993
+ profile: 1,
65994
+ type: 1
65995
+ }
65996
+ }
65997
+ ],
65998
+ as: "senderId"
65999
+ }
66000
+ },
66001
+ { $unwind: { path: "$senderId", preserveNullAndEmptyArrays: true } },
66002
+ {
66003
+ $lookup: {
66004
+ from: "bid-preloved",
66005
+ localField: "bidId",
66006
+ foreignField: "_id",
66007
+ pipeline: [
66008
+ { $project: { price: 1, message: 1, status: 1, type: 1 } }
66009
+ ],
66010
+ as: "bidId"
66011
+ }
66012
+ },
66013
+ { $unwind: { path: "$bidId", preserveNullAndEmptyArrays: true } },
66014
+ {
66015
+ $lookup: {
66016
+ from: "post-preloved",
66017
+ localField: "postId",
66018
+ foreignField: "_id",
66019
+ pipeline: [{ $project: { title: 1, status: 1, reserverId: 1 } }],
66020
+ as: "postDetails"
66021
+ }
66022
+ },
66023
+ {
66024
+ $unwind: {
66025
+ path: "$postDetails",
66026
+ preserveNullAndEmptyArrays: true
66027
+ }
66028
+ },
66029
+ { $sort: { createdAt: -1 } },
66030
+ {
66031
+ $facet: {
66032
+ totalCount: [{ $count: "count" }],
66033
+ items: [
66034
+ { $skip: normalizedPage * normalizedLimit },
66035
+ { $limit: normalizedLimit }
66036
+ ]
66037
+ }
66038
+ }
66039
+ ]).toArray();
66040
+ const totalCount = result[0].totalCount[0]?.count ?? 0;
66041
+ const items = result[0].items;
66042
+ items.reverse();
66043
+ return (0, import_node_server_utils246.paginate)(items, normalizedPage, normalizedLimit, totalCount);
66044
+ } catch (error) {
66045
+ throw error;
66046
+ }
66047
+ }
66048
+ return { add, getByParticipants, getChannelMessages };
66049
+ }
66050
+
66051
+ // src/services/chat-preloved.service.ts
66052
+ function useChatPrelovedService() {
66053
+ const { add: _addChat } = useChatPrelovedRepo();
66054
+ const { add: _addChannel, getByParticipants: _getByParticipants } = useChannelPrelovedRepo();
66055
+ async function add(value) {
66056
+ const client = import_node_server_utils247.useAtlas.getClient();
66057
+ if (!client)
66058
+ throw new import_node_server_utils247.InternalServerError("Unable to connect to server.");
66059
+ const session = client.startSession();
66060
+ session.startTransaction();
66061
+ try {
66062
+ let channelId = value.channelId;
66063
+ if (!channelId) {
66064
+ if (!value.postId) {
66065
+ throw new import_node_server_utils247.BadRequestError("postId is required when creating a new channel.");
66066
+ }
66067
+ const existing = await _getByParticipants(
66068
+ value.senderId,
66069
+ value.receiverId,
66070
+ value.postId,
66071
+ session
66072
+ );
66073
+ if (existing) {
66074
+ channelId = existing._id.toString();
66075
+ } else {
66076
+ const newChannelId = await _addChannel(
66077
+ {
66078
+ receiverId: value.receiverId,
66079
+ senderId: value.senderId,
66080
+ postId: value.postId
66081
+ },
66082
+ session
66083
+ );
66084
+ channelId = newChannelId.toString();
66085
+ }
66086
+ }
66087
+ const { receiverId, ...chatPayload } = value;
66088
+ const insertedId = await _addChat({ ...chatPayload, channelId }, session);
66089
+ await session.commitTransaction();
66090
+ return { insertedId, channelId };
66091
+ } catch (error) {
66092
+ await session.abortTransaction();
66093
+ throw error;
66094
+ } finally {
66095
+ session.endSession();
66096
+ }
66097
+ }
65060
66098
  return { add };
65061
66099
  }
65062
66100
 
65063
- // src/controllers/channel-preloved.controller.ts
65064
- var import_node_server_utils248 = require("@7365admin1/node-server-utils");
65065
- function useChannelPrelovedController() {
65066
- const { add: _add } = useChannelPrelovedRepo();
66101
+ // src/controllers/chat-preloved.controller.ts
66102
+ function useChatPrelovedController() {
66103
+ const { add: _add } = useChatPrelovedService();
66104
+ const { updateById: _updateById, deleteById: _deleteById } = useChatPrelovedRepo();
65067
66105
  async function add(req, res, next) {
65068
- const { error, value } = schemaChannelPreloved.validate(req.body, {
66106
+ const { error, value } = schemaChatPreloved.validate(req.body, {
65069
66107
  abortEarly: false
65070
66108
  });
65071
66109
  if (error) {
@@ -65082,61 +66120,163 @@ function useChannelPrelovedController() {
65082
66120
  next(error2);
65083
66121
  }
65084
66122
  }
65085
- return { add };
66123
+ async function updateById(req, res, next) {
66124
+ const { error, value } = schemaUpdateChatPreloved.validate(req.body, {
66125
+ abortEarly: false
66126
+ });
66127
+ if (error) {
66128
+ const messages = error.details.map((d) => d.message).join(", ");
66129
+ import_node_server_utils248.logger.log({ level: "error", message: messages });
66130
+ next(new import_node_server_utils248.BadRequestError(messages));
66131
+ return;
66132
+ }
66133
+ try {
66134
+ const data = await _updateById(req.params.id, value);
66135
+ res.status(200).json(data);
66136
+ } catch (error2) {
66137
+ import_node_server_utils248.logger.log({ level: "error", message: error2.message });
66138
+ next(error2);
66139
+ }
66140
+ }
66141
+ async function deleteById(req, res, next) {
66142
+ const schema2 = import_joi143.default.object({
66143
+ _id: import_joi143.default.string().hex().length(24).required()
66144
+ });
66145
+ const { error, value } = schema2.validate({ _id: req.params.id });
66146
+ if (error) {
66147
+ import_node_server_utils248.logger.log({ level: "error", message: error.message });
66148
+ next(new import_node_server_utils248.BadRequestError(error.message));
66149
+ return;
66150
+ }
66151
+ try {
66152
+ const data = await _deleteById(value._id);
66153
+ res.status(200).json(data);
66154
+ } catch (error2) {
66155
+ import_node_server_utils248.logger.log({ level: "error", message: error2.message });
66156
+ next(error2);
66157
+ }
66158
+ }
66159
+ return { add, updateById, deleteById };
65086
66160
  }
65087
66161
 
65088
- // src/models/online-forms-v2.model.ts
66162
+ // src/controllers/channel-preloved.controller.ts
66163
+ var import_node_server_utils249 = require("@7365admin1/node-server-utils");
65089
66164
  var import_joi144 = __toESM(require("joi"));
65090
- var import_mongodb147 = require("mongodb");
66165
+ function useChannelPrelovedController() {
66166
+ const { add: _add, getChannelMessages: _getChannelMessages } = useChannelPrelovedRepo();
66167
+ async function add(req, res, next) {
66168
+ const { error, value } = schemaChannelPreloved.validate(req.body, {
66169
+ abortEarly: false
66170
+ });
66171
+ if (error) {
66172
+ const messages = error.details.map((d) => d.message).join(", ");
66173
+ import_node_server_utils249.logger.log({ level: "error", message: messages });
66174
+ next(new import_node_server_utils249.BadRequestError(messages));
66175
+ return;
66176
+ }
66177
+ try {
66178
+ const data = await _add(value);
66179
+ res.status(201).json(data);
66180
+ } catch (error2) {
66181
+ import_node_server_utils249.logger.log({ level: "error", message: error2.message });
66182
+ next(error2);
66183
+ }
66184
+ }
66185
+ async function getChannelMessages(req, res, next) {
66186
+ const paramsSchema = import_joi144.default.object({
66187
+ id: import_joi144.default.string().hex().length(24).required()
66188
+ });
66189
+ const querySchema = import_joi144.default.object({
66190
+ page: import_joi144.default.number().integer().min(1).default(1),
66191
+ limit: import_joi144.default.number().integer().min(1).max(100).default(10),
66192
+ isLoadMore: import_joi144.default.boolean().default(false),
66193
+ lastMessageId: import_joi144.default.string().hex().length(24).optional().allow("", null)
66194
+ });
66195
+ const { error: paramError, value: params } = paramsSchema.validate(
66196
+ req.params
66197
+ );
66198
+ if (paramError) {
66199
+ import_node_server_utils249.logger.log({ level: "error", message: paramError.message });
66200
+ next(new import_node_server_utils249.BadRequestError(paramError.message));
66201
+ return;
66202
+ }
66203
+ const { error: queryError, value: query } = querySchema.validate(
66204
+ req.query
66205
+ );
66206
+ if (queryError) {
66207
+ import_node_server_utils249.logger.log({ level: "error", message: queryError.message });
66208
+ next(new import_node_server_utils249.BadRequestError(queryError.message));
66209
+ return;
66210
+ }
66211
+ try {
66212
+ const data = await _getChannelMessages(
66213
+ params.id,
66214
+ query.page,
66215
+ query.limit,
66216
+ query.isLoadMore,
66217
+ query.lastMessageId || null
66218
+ );
66219
+ res.status(200).json(data);
66220
+ } catch (error) {
66221
+ import_node_server_utils249.logger.log({ level: "error", message: error.message });
66222
+ next(error);
66223
+ }
66224
+ }
66225
+ return { add, getChannelMessages };
66226
+ }
66227
+
66228
+ // src/models/online-forms-v2.model.ts
66229
+ var import_joi145 = __toESM(require("joi"));
66230
+ var import_mongodb149 = require("mongodb");
65091
66231
  var FormEntryStatus = /* @__PURE__ */ ((FormEntryStatus2) => {
65092
66232
  FormEntryStatus2["ACTIVE"] = "active";
65093
66233
  FormEntryStatus2["INACTIVE"] = "inactive";
65094
66234
  FormEntryStatus2["DELETED"] = "deleted";
65095
66235
  return FormEntryStatus2;
65096
66236
  })(FormEntryStatus || {});
65097
- var schemaFormEntry = import_joi144.default.object({
65098
- _id: import_joi144.default.string().hex().optional().allow("", null),
65099
- formType: import_joi144.default.string().required(),
65100
- block: import_joi144.default.string().optional().allow(null, ""),
65101
- level: import_joi144.default.string().optional().allow(null, ""),
65102
- unit: import_joi144.default.string().optional().allow(null, ""),
65103
- name: import_joi144.default.string().optional().allow(null, ""),
65104
- phoneNumber: import_joi144.default.string().optional().allow(null, ""),
65105
- createdBy: import_joi144.default.string().required(),
65106
- fields: import_joi144.default.object().pattern(
65107
- import_joi144.default.string(),
65108
- import_joi144.default.alternatives().try(
65109
- import_joi144.default.string(),
65110
- import_joi144.default.number(),
65111
- import_joi144.default.boolean(),
65112
- import_joi144.default.valid(null)
66237
+ var schemaFormEntry = import_joi145.default.object({
66238
+ _id: import_joi145.default.string().hex().optional().allow("", null),
66239
+ formType: import_joi145.default.string().required(),
66240
+ block: import_joi145.default.string().optional().allow(null, ""),
66241
+ level: import_joi145.default.string().optional().allow(null, ""),
66242
+ unit: import_joi145.default.string().optional().allow(null, ""),
66243
+ name: import_joi145.default.string().optional().allow(null, ""),
66244
+ phoneNumber: import_joi145.default.string().optional().allow(null, ""),
66245
+ createdBy: import_joi145.default.string().required(),
66246
+ fields: import_joi145.default.object().pattern(
66247
+ import_joi145.default.string(),
66248
+ import_joi145.default.alternatives().try(
66249
+ import_joi145.default.string(),
66250
+ import_joi145.default.number(),
66251
+ import_joi145.default.boolean(),
66252
+ import_joi145.default.valid(null)
65113
66253
  )
65114
66254
  ).required(),
65115
- status: import_joi144.default.string().optional().allow("", null),
65116
- org: import_joi144.default.string().hex().optional().allow("", null),
65117
- site: import_joi144.default.string().hex().optional().allow("", null),
65118
- createdAt: import_joi144.default.date().optional().allow("", null),
65119
- updatedAt: import_joi144.default.date().optional().allow("", null),
65120
- deletedAt: import_joi144.default.date().optional().allow("", null)
66255
+ status: import_joi145.default.string().optional().allow("", null),
66256
+ org: import_joi145.default.string().hex().optional().allow("", null),
66257
+ site: import_joi145.default.string().hex().optional().allow("", null),
66258
+ createdAt: import_joi145.default.date().optional().allow("", null),
66259
+ updatedAt: import_joi145.default.date().optional().allow("", null),
66260
+ deletedAt: import_joi145.default.date().optional().allow("", null)
65121
66261
  });
65122
- var schemaUpdateFormEntry = import_joi144.default.object({
65123
- _id: import_joi144.default.string().hex().required(),
65124
- formType: import_joi144.default.string().optional().allow("", null),
65125
- block: import_joi144.default.string().optional().allow(null, ""),
65126
- level: import_joi144.default.string().optional().allow(null, ""),
65127
- unit: import_joi144.default.string().optional().allow(null, ""),
65128
- fields: import_joi144.default.object().pattern(
65129
- import_joi144.default.string(),
65130
- import_joi144.default.alternatives().try(
65131
- import_joi144.default.string(),
65132
- import_joi144.default.number(),
65133
- import_joi144.default.boolean(),
65134
- import_joi144.default.valid(null)
66262
+ var schemaUpdateFormEntry = import_joi145.default.object({
66263
+ _id: import_joi145.default.string().hex().required(),
66264
+ formType: import_joi145.default.string().optional().allow("", null),
66265
+ block: import_joi145.default.string().optional().allow(null, ""),
66266
+ level: import_joi145.default.string().optional().allow(null, ""),
66267
+ unit: import_joi145.default.string().optional().allow(null, ""),
66268
+ fields: import_joi145.default.object().pattern(
66269
+ import_joi145.default.string(),
66270
+ import_joi145.default.alternatives().try(
66271
+ import_joi145.default.string(),
66272
+ import_joi145.default.number(),
66273
+ import_joi145.default.boolean(),
66274
+ import_joi145.default.valid(null)
65135
66275
  )
65136
66276
  ).optional(),
65137
- status: import_joi144.default.string().optional().allow("", null),
65138
- updatedAt: import_joi144.default.date().optional().allow("", null),
65139
- deletedAt: import_joi144.default.date().optional().allow("", null)
66277
+ status: import_joi145.default.string().optional().allow("", null),
66278
+ updatedAt: import_joi145.default.date().optional().allow("", null),
66279
+ deletedAt: import_joi145.default.date().optional().allow("", null)
65140
66280
  });
65141
66281
  function MFormEntry(value) {
65142
66282
  const { error } = schemaFormEntry.validate(value);
@@ -65145,21 +66285,21 @@ function MFormEntry(value) {
65145
66285
  }
65146
66286
  if (value._id && typeof value._id === "string") {
65147
66287
  try {
65148
- value._id = new import_mongodb147.ObjectId(value._id);
66288
+ value._id = new import_mongodb149.ObjectId(value._id);
65149
66289
  } catch {
65150
66290
  throw new Error("Invalid ID.");
65151
66291
  }
65152
66292
  }
65153
66293
  if (value.org && typeof value.org === "string") {
65154
66294
  try {
65155
- value.org = new import_mongodb147.ObjectId(value.org);
66295
+ value.org = new import_mongodb149.ObjectId(value.org);
65156
66296
  } catch {
65157
66297
  throw new Error("Invalid org ID.");
65158
66298
  }
65159
66299
  }
65160
66300
  if (value.site && typeof value.site === "string") {
65161
66301
  try {
65162
- value.site = new import_mongodb147.ObjectId(value.site);
66302
+ value.site = new import_mongodb149.ObjectId(value.site);
65163
66303
  } catch {
65164
66304
  throw new Error("Invalid site ID.");
65165
66305
  }
@@ -65181,39 +66321,49 @@ function MFormEntry(value) {
65181
66321
  deletedAt: value.deletedAt ?? null
65182
66322
  };
65183
66323
  }
65184
- var residentFormEntry = import_joi144.default.object({
65185
- _id: import_joi144.default.string().hex().optional().allow("", null),
65186
- typeOfForm: import_joi144.default.string().optional().allow("", null),
65187
- unitNumber: import_joi144.default.string().optional().allow(null, ""),
65188
- fields: import_joi144.default.object().pattern(
65189
- import_joi144.default.string(),
65190
- import_joi144.default.alternatives().try(
65191
- import_joi144.default.string(),
65192
- import_joi144.default.number(),
65193
- import_joi144.default.boolean(),
65194
- import_joi144.default.valid(null)
66324
+ var residentFormEntry = import_joi145.default.object({
66325
+ _id: import_joi145.default.string().hex().optional().allow("", null),
66326
+ typeOfForm: import_joi145.default.string().optional().allow("", null),
66327
+ unitNumber: import_joi145.default.string().optional().allow(null, ""),
66328
+ fields: import_joi145.default.object().pattern(
66329
+ import_joi145.default.string(),
66330
+ import_joi145.default.alternatives().try(
66331
+ import_joi145.default.string(),
66332
+ import_joi145.default.number(),
66333
+ import_joi145.default.boolean(),
66334
+ import_joi145.default.valid(null)
65195
66335
  )
65196
66336
  ).optional().allow(null, ""),
65197
- status: import_joi144.default.string().optional().allow("", null),
65198
- org: import_joi144.default.string().hex().optional().allow("", null),
65199
- site: import_joi144.default.string().hex().optional().allow("", null),
65200
- userId: import_joi144.default.string().hex().optional().allow("", null),
65201
- createdAt: import_joi144.default.date().optional().allow("", null),
65202
- updatedAt: import_joi144.default.date().optional().allow("", null),
65203
- deletedAt: import_joi144.default.date().optional().allow("", null)
66337
+ status: import_joi145.default.string().optional().allow("", null),
66338
+ org: import_joi145.default.string().hex().optional().allow("", null),
66339
+ site: import_joi145.default.string().hex().optional().allow("", null),
66340
+ userId: import_joi145.default.string().hex().optional().allow("", null),
66341
+ createdAt: import_joi145.default.date().optional().allow("", null),
66342
+ updatedAt: import_joi145.default.date().optional().allow("", null),
66343
+ deletedAt: import_joi145.default.date().optional().allow("", null),
66344
+ remarks: import_joi145.default.string().optional().allow("", null),
66345
+ managementValues: import_joi145.default.object().pattern(
66346
+ import_joi145.default.string(),
66347
+ import_joi145.default.alternatives().try(
66348
+ import_joi145.default.string(),
66349
+ import_joi145.default.number(),
66350
+ import_joi145.default.boolean(),
66351
+ import_joi145.default.valid(null)
66352
+ )
66353
+ ).optional().allow(null, "")
65204
66354
  });
65205
66355
 
65206
66356
  // src/repositories/online-forms-v2.repository.ts
65207
- var import_node_server_utils249 = require("@7365admin1/node-server-utils");
65208
- var import_mongodb148 = require("mongodb");
66357
+ var import_node_server_utils250 = require("@7365admin1/node-server-utils");
66358
+ var import_mongodb150 = require("mongodb");
65209
66359
  var online_forms_namespace_collection = "online-forms";
65210
66360
  function useFormEntryRepo() {
65211
- const db = import_node_server_utils249.useAtlas.getDb();
66361
+ const db = import_node_server_utils250.useAtlas.getDb();
65212
66362
  if (!db) {
65213
- throw new import_node_server_utils249.InternalServerError("Unable to connect to server.");
66363
+ throw new import_node_server_utils250.InternalServerError("Unable to connect to server.");
65214
66364
  }
65215
66365
  const collection = db.collection(online_forms_namespace_collection);
65216
- const { delNamespace, getCache, setCache } = (0, import_node_server_utils249.useCache)(
66366
+ const { delNamespace, getCache, setCache } = (0, import_node_server_utils250.useCache)(
65217
66367
  online_forms_namespace_collection
65218
66368
  );
65219
66369
  async function createTextIndex() {
@@ -65222,7 +66372,7 @@ function useFormEntryRepo() {
65222
66372
  name: "text"
65223
66373
  });
65224
66374
  } catch (error) {
65225
- throw new import_node_server_utils249.InternalServerError(
66375
+ throw new import_node_server_utils250.InternalServerError(
65226
66376
  "Failed to create text index on online form."
65227
66377
  );
65228
66378
  }
@@ -65232,11 +66382,11 @@ function useFormEntryRepo() {
65232
66382
  value = MFormEntry(value);
65233
66383
  const res = await collection.insertOne(value, { session });
65234
66384
  delNamespace().then(() => {
65235
- import_node_server_utils249.logger.info(
66385
+ import_node_server_utils250.logger.info(
65236
66386
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
65237
66387
  );
65238
66388
  }).catch((err) => {
65239
- import_node_server_utils249.logger.error(
66389
+ import_node_server_utils250.logger.error(
65240
66390
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
65241
66391
  err
65242
66392
  );
@@ -65245,7 +66395,7 @@ function useFormEntryRepo() {
65245
66395
  } catch (error) {
65246
66396
  const isDuplicated = error.message.includes("duplicate");
65247
66397
  if (isDuplicated) {
65248
- throw new import_node_server_utils249.BadRequestError("Online Form already exists.");
66398
+ throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
65249
66399
  }
65250
66400
  throw error;
65251
66401
  }
@@ -65261,8 +66411,8 @@ function useFormEntryRepo() {
65261
66411
  }) {
65262
66412
  page = page > 0 ? page - 1 : 0;
65263
66413
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
65264
- site = new import_mongodb148.ObjectId(site);
65265
- org = new import_mongodb148.ObjectId(org);
66414
+ site = new import_mongodb150.ObjectId(site);
66415
+ org = new import_mongodb150.ObjectId(org);
65266
66416
  const cacheOptions = {
65267
66417
  page,
65268
66418
  limit,
@@ -65282,13 +66432,13 @@ function useFormEntryRepo() {
65282
66432
  { unitNumber: { $regex: search, $options: "i" } }
65283
66433
  ];
65284
66434
  }
65285
- const cacheKey = (0, import_node_server_utils249.makeCacheKey)(
66435
+ const cacheKey = (0, import_node_server_utils250.makeCacheKey)(
65286
66436
  online_forms_namespace_collection,
65287
66437
  cacheOptions
65288
66438
  );
65289
66439
  const cachedData = await getCache(cacheKey);
65290
66440
  if (cachedData) {
65291
- import_node_server_utils249.logger.info(`Cache hit for key: ${cacheKey}`);
66441
+ import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
65292
66442
  return cachedData;
65293
66443
  }
65294
66444
  try {
@@ -65299,11 +66449,11 @@ function useFormEntryRepo() {
65299
66449
  { $limit: limit }
65300
66450
  ]).toArray();
65301
66451
  const length = await collection.countDocuments(query);
65302
- const data = (0, import_node_server_utils249.paginate)(items, page, limit, length);
66452
+ const data = (0, import_node_server_utils250.paginate)(items, page, limit, length);
65303
66453
  setCache(cacheKey, data, 15 * 60).then(() => {
65304
- import_node_server_utils249.logger.info(`Cache set for key: ${cacheKey}`);
66454
+ import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
65305
66455
  }).catch((err) => {
65306
- import_node_server_utils249.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
66456
+ import_node_server_utils250.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
65307
66457
  });
65308
66458
  return data;
65309
66459
  } catch (error) {
@@ -65311,27 +66461,27 @@ function useFormEntryRepo() {
65311
66461
  }
65312
66462
  }
65313
66463
  async function getFormEntryById(_id) {
65314
- const cacheKey = (0, import_node_server_utils249.makeCacheKey)(online_forms_namespace_collection, { _id });
66464
+ const cacheKey = (0, import_node_server_utils250.makeCacheKey)(online_forms_namespace_collection, { _id });
65315
66465
  const cachedData = await getCache(cacheKey);
65316
66466
  if (cachedData) {
65317
- import_node_server_utils249.logger.info(`Cache hit for key: ${cacheKey}`);
66467
+ import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
65318
66468
  return cachedData;
65319
66469
  }
65320
66470
  try {
65321
- _id = new import_mongodb148.ObjectId(_id);
66471
+ _id = new import_mongodb150.ObjectId(_id);
65322
66472
  } catch (error) {
65323
- throw new import_node_server_utils249.BadRequestError("Invalid online form ID format.");
66473
+ throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
65324
66474
  }
65325
66475
  const query = { _id, status: { $ne: "deleted" } };
65326
66476
  try {
65327
66477
  const [data] = await collection.aggregate([{ $match: query }]).toArray();
65328
66478
  if (!data) {
65329
- throw new import_node_server_utils249.NotFoundError("Document not found.");
66479
+ throw new import_node_server_utils250.NotFoundError("Document not found.");
65330
66480
  }
65331
66481
  setCache(cacheKey, data, 15 * 60).then(() => {
65332
- import_node_server_utils249.logger.info(`Cache set for key: ${cacheKey}`);
66482
+ import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
65333
66483
  }).catch((err) => {
65334
- import_node_server_utils249.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
66484
+ import_node_server_utils250.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
65335
66485
  });
65336
66486
  return data;
65337
66487
  } catch (error) {
@@ -65340,9 +66490,9 @@ function useFormEntryRepo() {
65340
66490
  }
65341
66491
  async function updateFormEntryById(_id, value) {
65342
66492
  try {
65343
- _id = new import_mongodb148.ObjectId(_id);
66493
+ _id = new import_mongodb150.ObjectId(_id);
65344
66494
  } catch (error) {
65345
- throw new import_node_server_utils249.BadRequestError("Invalid online form ID format.");
66495
+ throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
65346
66496
  }
65347
66497
  try {
65348
66498
  const updateValue = {
@@ -65351,14 +66501,14 @@ function useFormEntryRepo() {
65351
66501
  };
65352
66502
  const res = await collection.updateOne({ _id }, { $set: updateValue });
65353
66503
  if (res.modifiedCount === 0) {
65354
- throw new import_node_server_utils249.InternalServerError("Unable to update online form.");
66504
+ throw new import_node_server_utils250.InternalServerError("Unable to update online form.");
65355
66505
  }
65356
66506
  delNamespace().then(() => {
65357
- import_node_server_utils249.logger.info(
66507
+ import_node_server_utils250.logger.info(
65358
66508
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
65359
66509
  );
65360
66510
  }).catch((err) => {
65361
- import_node_server_utils249.logger.error(
66511
+ import_node_server_utils250.logger.error(
65362
66512
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
65363
66513
  err
65364
66514
  );
@@ -65370,9 +66520,9 @@ function useFormEntryRepo() {
65370
66520
  }
65371
66521
  async function deleteOnlineFormById(_id, session) {
65372
66522
  try {
65373
- _id = new import_mongodb148.ObjectId(_id);
66523
+ _id = new import_mongodb150.ObjectId(_id);
65374
66524
  } catch (error) {
65375
- throw new import_node_server_utils249.BadRequestError("Invalid online form ID format.");
66525
+ throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
65376
66526
  }
65377
66527
  try {
65378
66528
  const updateValue = {
@@ -65386,12 +66536,12 @@ function useFormEntryRepo() {
65386
66536
  { session }
65387
66537
  );
65388
66538
  if (res.modifiedCount === 0) {
65389
- throw new import_node_server_utils249.InternalServerError("Unable to delete online form.");
66539
+ throw new import_node_server_utils250.InternalServerError("Unable to delete online form.");
65390
66540
  }
65391
66541
  delNamespace().then(() => {
65392
- import_node_server_utils249.logger.info(`Cache cleared for namespace: ${online_forms_namespace_collection}`);
66542
+ import_node_server_utils250.logger.info(`Cache cleared for namespace: ${online_forms_namespace_collection}`);
65393
66543
  }).catch((err) => {
65394
- import_node_server_utils249.logger.error(
66544
+ import_node_server_utils250.logger.error(
65395
66545
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
65396
66546
  err
65397
66547
  );
@@ -65403,16 +66553,16 @@ function useFormEntryRepo() {
65403
66553
  }
65404
66554
  async function addResidentForm(value, session) {
65405
66555
  try {
65406
- value.site = new import_mongodb148.ObjectId(value.site);
65407
- value.org = new import_mongodb148.ObjectId(value.org);
65408
- value.userId = new import_mongodb148.ObjectId(value.userId);
66556
+ value.site = new import_mongodb150.ObjectId(value.site);
66557
+ value.org = new import_mongodb150.ObjectId(value.org);
66558
+ value.userId = new import_mongodb150.ObjectId(value.userId);
65409
66559
  const res = await collection.insertOne(value, { session });
65410
66560
  delNamespace().then(() => {
65411
- import_node_server_utils249.logger.info(
66561
+ import_node_server_utils250.logger.info(
65412
66562
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
65413
66563
  );
65414
66564
  }).catch((err) => {
65415
- import_node_server_utils249.logger.error(
66565
+ import_node_server_utils250.logger.error(
65416
66566
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
65417
66567
  err
65418
66568
  );
@@ -65421,16 +66571,16 @@ function useFormEntryRepo() {
65421
66571
  } catch (error) {
65422
66572
  const isDuplicated = error.message.includes("duplicate");
65423
66573
  if (isDuplicated) {
65424
- throw new import_node_server_utils249.BadRequestError("Online Form already exists.");
66574
+ throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
65425
66575
  }
65426
66576
  throw error;
65427
66577
  }
65428
66578
  }
65429
66579
  async function residentForm({ userId, site, org }) {
65430
66580
  try {
65431
- const user = new import_mongodb148.ObjectId(userId);
65432
- const siteId = new import_mongodb148.ObjectId(site);
65433
- const orgId = new import_mongodb148.ObjectId(org);
66581
+ const user = new import_mongodb150.ObjectId(userId);
66582
+ const siteId = new import_mongodb150.ObjectId(site);
66583
+ const orgId = new import_mongodb150.ObjectId(org);
65434
66584
  const res = await collection.aggregate([
65435
66585
  {
65436
66586
  $match: {
@@ -65458,8 +66608,8 @@ function useFormEntryRepo() {
65458
66608
  }
65459
66609
 
65460
66610
  // src/controllers/online-forms-v2.controller.ts
65461
- var import_node_server_utils250 = require("@7365admin1/node-server-utils");
65462
- var import_joi145 = __toESM(require("joi"));
66611
+ var import_node_server_utils251 = require("@7365admin1/node-server-utils");
66612
+ var import_joi146 = __toESM(require("joi"));
65463
66613
  var import_exceljs3 = __toESM(require("exceljs"));
65464
66614
  var import_fs7 = __toESM(require("fs"));
65465
66615
  function useFormEntryController() {
@@ -65485,14 +66635,14 @@ function useFormEntryController() {
65485
66635
  async function uploadFormEntrys(req, res, next) {
65486
66636
  try {
65487
66637
  if (!req.file) {
65488
- next(new import_node_server_utils250.BadRequestError("Excel file is required."));
66638
+ next(new import_node_server_utils251.BadRequestError("Excel file is required."));
65489
66639
  return;
65490
66640
  }
65491
66641
  const workbook = new import_exceljs3.default.Workbook();
65492
66642
  await workbook.xlsx.readFile(req.file.path);
65493
66643
  const worksheet = workbook.worksheets[0];
65494
66644
  if (!worksheet) {
65495
- next(new import_node_server_utils250.BadRequestError("No worksheet found in uploaded Excel file."));
66645
+ next(new import_node_server_utils251.BadRequestError("No worksheet found in uploaded Excel file."));
65496
66646
  return;
65497
66647
  }
65498
66648
  const headerRow = worksheet.getRow(1);
@@ -65520,8 +66670,8 @@ function useFormEntryController() {
65520
66670
  });
65521
66671
  if (error) {
65522
66672
  const messages = error.details.map((d) => d.message).join(", ");
65523
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65524
- next(new import_node_server_utils250.BadRequestError(messages));
66673
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66674
+ next(new import_node_server_utils251.BadRequestError(messages));
65525
66675
  return;
65526
66676
  }
65527
66677
  const result = await _add(value);
@@ -65529,25 +66679,25 @@ function useFormEntryController() {
65529
66679
  import_fs7.default.unlink(req.file.path, () => {
65530
66680
  });
65531
66681
  } catch (error) {
65532
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66682
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65533
66683
  next(error);
65534
66684
  }
65535
66685
  }
65536
66686
  async function getAll(req, res, next) {
65537
66687
  try {
65538
- const schema2 = import_joi145.default.object({
65539
- search: import_joi145.default.string().optional().allow("", null),
65540
- page: import_joi145.default.number().integer().min(1).allow("", null).default(1),
65541
- limit: import_joi145.default.number().integer().min(1).max(100).allow("", null).default(10),
65542
- status: import_joi145.default.string().optional().allow(null, ""),
65543
- org: import_joi145.default.string().hex().optional().allow("", null),
65544
- site: import_joi145.default.string().hex().optional().allow("", null)
66688
+ const schema2 = import_joi146.default.object({
66689
+ search: import_joi146.default.string().optional().allow("", null),
66690
+ page: import_joi146.default.number().integer().min(1).allow("", null).default(1),
66691
+ limit: import_joi146.default.number().integer().min(1).max(100).allow("", null).default(10),
66692
+ status: import_joi146.default.string().optional().allow(null, ""),
66693
+ org: import_joi146.default.string().hex().optional().allow("", null),
66694
+ site: import_joi146.default.string().hex().optional().allow("", null)
65545
66695
  });
65546
66696
  const { error, value } = schema2.validate(req.query);
65547
66697
  if (error) {
65548
66698
  const messages = error.details.map((d) => d.message).join(", ");
65549
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65550
- next(new import_node_server_utils250.BadRequestError(messages));
66699
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66700
+ next(new import_node_server_utils251.BadRequestError(messages));
65551
66701
  return;
65552
66702
  }
65553
66703
  const { search, page, limit, status, org, site } = value;
@@ -65555,21 +66705,21 @@ function useFormEntryController() {
65555
66705
  res.json(data);
65556
66706
  return;
65557
66707
  } catch (error) {
65558
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66708
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65559
66709
  next(error);
65560
66710
  return;
65561
66711
  }
65562
66712
  }
65563
66713
  async function getFormEntryById(req, res, next) {
65564
66714
  try {
65565
- const schema2 = import_joi145.default.object({
65566
- _id: import_joi145.default.string().hex().length(24).required()
66715
+ const schema2 = import_joi146.default.object({
66716
+ _id: import_joi146.default.string().hex().length(24).required()
65567
66717
  });
65568
66718
  const { error, value } = schema2.validate({ _id: req.params.id });
65569
66719
  if (error) {
65570
66720
  const messages = error.details.map((d) => d.message).join(", ");
65571
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65572
- next(new import_node_server_utils250.BadRequestError(messages));
66721
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66722
+ next(new import_node_server_utils251.BadRequestError(messages));
65573
66723
  return;
65574
66724
  }
65575
66725
  const { _id } = value;
@@ -65577,7 +66727,7 @@ function useFormEntryController() {
65577
66727
  res.json(data);
65578
66728
  return;
65579
66729
  } catch (error) {
65580
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66730
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65581
66731
  next(error);
65582
66732
  return;
65583
66733
  }
@@ -65590,8 +66740,8 @@ function useFormEntryController() {
65590
66740
  });
65591
66741
  if (error) {
65592
66742
  const messages = error.details.map((d) => d.message).join(", ");
65593
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65594
- next(new import_node_server_utils250.BadRequestError(messages));
66743
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66744
+ next(new import_node_server_utils251.BadRequestError(messages));
65595
66745
  return;
65596
66746
  }
65597
66747
  const { _id, ...rest } = value;
@@ -65599,26 +66749,26 @@ function useFormEntryController() {
65599
66749
  res.json({ message: "Successfully updated online form." });
65600
66750
  return;
65601
66751
  } catch (error) {
65602
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66752
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65603
66753
  next(error);
65604
66754
  return;
65605
66755
  }
65606
66756
  }
65607
66757
  async function deleteFormEntryById(req, res, next) {
65608
66758
  try {
65609
- const validation = import_joi145.default.string().hex().required();
66759
+ const validation = import_joi146.default.string().hex().required();
65610
66760
  const _id = req.params.id;
65611
66761
  const { error } = validation.validate(_id);
65612
66762
  if (error) {
65613
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
65614
- next(new import_node_server_utils250.BadRequestError(error.message));
66763
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
66764
+ next(new import_node_server_utils251.BadRequestError(error.message));
65615
66765
  return;
65616
66766
  }
65617
66767
  await _deleteOnlineFormById(_id);
65618
66768
  res.json({ message: "Successfully deleted online form." });
65619
66769
  return;
65620
66770
  } catch (error) {
65621
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66771
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65622
66772
  next(error);
65623
66773
  return;
65624
66774
  }
@@ -65635,8 +66785,8 @@ function useFormEntryController() {
65635
66785
  });
65636
66786
  if (error) {
65637
66787
  const messages = error.details.map((d) => d.message).join(", ");
65638
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65639
- next(new import_node_server_utils250.BadRequestError(messages));
66788
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66789
+ next(new import_node_server_utils251.BadRequestError(messages));
65640
66790
  return;
65641
66791
  }
65642
66792
  try {
@@ -65644,7 +66794,7 @@ function useFormEntryController() {
65644
66794
  res.status(201).json({ message: data });
65645
66795
  return;
65646
66796
  } catch (error2) {
65647
- import_node_server_utils250.logger.log({ level: "error", message: error2.message });
66797
+ import_node_server_utils251.logger.log({ level: "error", message: error2.message });
65648
66798
  next(error2);
65649
66799
  return;
65650
66800
  }
@@ -65656,8 +66806,8 @@ function useFormEntryController() {
65656
66806
  });
65657
66807
  if (error) {
65658
66808
  const messages = error.details.map((d) => d.message).join(", ");
65659
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65660
- next(new import_node_server_utils250.BadRequestError(messages));
66809
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66810
+ next(new import_node_server_utils251.BadRequestError(messages));
65661
66811
  return;
65662
66812
  }
65663
66813
  try {
@@ -65665,7 +66815,7 @@ function useFormEntryController() {
65665
66815
  res.status(201).json({ message: data });
65666
66816
  return;
65667
66817
  } catch (error2) {
65668
- import_node_server_utils250.logger.log({ level: "error", message: error2.message });
66818
+ import_node_server_utils251.logger.log({ level: "error", message: error2.message });
65669
66819
  next(error2);
65670
66820
  return;
65671
66821
  }
@@ -65673,22 +66823,22 @@ function useFormEntryController() {
65673
66823
  async function residentForm(req, res, next) {
65674
66824
  try {
65675
66825
  const { site, userId, org } = req.query;
65676
- const residentFormPayload = import_joi145.default.object({
65677
- org: import_joi145.default.string().hex().required(),
65678
- site: import_joi145.default.string().hex().required(),
65679
- userId: import_joi145.default.string().hex().required()
66826
+ const residentFormPayload = import_joi146.default.object({
66827
+ org: import_joi146.default.string().hex().required(),
66828
+ site: import_joi146.default.string().hex().required(),
66829
+ userId: import_joi146.default.string().hex().required()
65680
66830
  });
65681
66831
  const { error } = residentFormPayload.validate({ site, userId, org }, { abortEarly: true });
65682
66832
  if (error) {
65683
66833
  const messages = error.details.map((d) => d.message).join(", ");
65684
- import_node_server_utils250.logger.log({ level: "error", message: messages });
65685
- next(new import_node_server_utils250.BadRequestError(messages));
66834
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66835
+ next(new import_node_server_utils251.BadRequestError(messages));
65686
66836
  return;
65687
66837
  }
65688
66838
  const result = await _residentForm({ userId, site, org });
65689
66839
  res.json(result);
65690
66840
  } catch (error) {
65691
- import_node_server_utils250.logger.log({ level: "error", message: error.message });
66841
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
65692
66842
  next(error);
65693
66843
  return;
65694
66844
  }
@@ -65706,11 +66856,11 @@ function useFormEntryController() {
65706
66856
  }
65707
66857
 
65708
66858
  // src/services/building-level.service.ts
65709
- var import_node_server_utils251 = require("@7365admin1/node-server-utils");
66859
+ var import_node_server_utils252 = require("@7365admin1/node-server-utils");
65710
66860
  function useBuildingLevelService() {
65711
66861
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelRepo();
65712
66862
  async function add(value) {
65713
- const session = import_node_server_utils251.useAtlas.getClient()?.startSession();
66863
+ const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
65714
66864
  try {
65715
66865
  session?.startTransaction();
65716
66866
  await _add(value, session);
@@ -65724,7 +66874,7 @@ function useBuildingLevelService() {
65724
66874
  }
65725
66875
  }
65726
66876
  async function updateLevelById(_id, value) {
65727
- const session = import_node_server_utils251.useAtlas.getClient()?.startSession();
66877
+ const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
65728
66878
  try {
65729
66879
  session?.startTransaction();
65730
66880
  await _updateLevelById(_id, value, session);
@@ -65744,8 +66894,8 @@ function useBuildingLevelService() {
65744
66894
  }
65745
66895
 
65746
66896
  // src/controllers/building-level.controller.ts
65747
- var import_node_server_utils252 = require("@7365admin1/node-server-utils");
65748
- var import_joi146 = __toESM(require("joi"));
66897
+ var import_node_server_utils253 = require("@7365admin1/node-server-utils");
66898
+ var import_joi147 = __toESM(require("joi"));
65749
66899
  function useBuildingLevelController() {
65750
66900
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelService();
65751
66901
  const {
@@ -65762,8 +66912,8 @@ function useBuildingLevelController() {
65762
66912
  });
65763
66913
  if (error) {
65764
66914
  const messages = error.details.map((d) => d.message).join(", ");
65765
- import_node_server_utils252.logger.log({ level: "error", message: messages });
65766
- next(new import_node_server_utils252.BadRequestError(messages));
66915
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
66916
+ next(new import_node_server_utils253.BadRequestError(messages));
65767
66917
  return;
65768
66918
  }
65769
66919
  const result = await _add(value);
@@ -65774,20 +66924,20 @@ function useBuildingLevelController() {
65774
66924
  }
65775
66925
  async function getAll(req, res, next) {
65776
66926
  try {
65777
- const validation = import_joi146.default.object({
65778
- page: import_joi146.default.number().min(1).optional().default(1),
65779
- limit: import_joi146.default.number().min(1).optional().default(20),
65780
- search: import_joi146.default.string().optional().allow("", null),
65781
- site: import_joi146.default.string().hex().length(24).optional().allow("", null),
65782
- status: import_joi146.default.string().valid(...Object.values(BuildingLevelStatus)).default("active" /* ACTIVE */)
66927
+ const validation = import_joi147.default.object({
66928
+ page: import_joi147.default.number().min(1).optional().default(1),
66929
+ limit: import_joi147.default.number().min(1).optional().default(20),
66930
+ search: import_joi147.default.string().optional().allow("", null),
66931
+ site: import_joi147.default.string().hex().length(24).optional().allow("", null),
66932
+ status: import_joi147.default.string().valid(...Object.values(BuildingLevelStatus)).default("active" /* ACTIVE */)
65783
66933
  });
65784
66934
  const { error, value } = validation.validate(req.query, {
65785
66935
  abortEarly: false
65786
66936
  });
65787
66937
  if (error) {
65788
66938
  const messages = error.details.map((d) => d.message);
65789
- import_node_server_utils252.logger.log({ level: "error", message: messages.join(", ") });
65790
- next(new import_node_server_utils252.BadRequestError(messages.join(", ")));
66939
+ import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
66940
+ next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
65791
66941
  return;
65792
66942
  }
65793
66943
  const { page, limit, status, site, search } = value;
@@ -65806,14 +66956,14 @@ function useBuildingLevelController() {
65806
66956
  }
65807
66957
  async function getById(req, res, next) {
65808
66958
  try {
65809
- const schema2 = import_joi146.default.object({
65810
- id: import_joi146.default.string().hex().length(24).required()
66959
+ const schema2 = import_joi147.default.object({
66960
+ id: import_joi147.default.string().hex().length(24).required()
65811
66961
  });
65812
66962
  const { error, value } = schema2.validate({ id: req.params.id });
65813
66963
  if (error) {
65814
66964
  const messages = error.details.map((d) => d.message);
65815
- import_node_server_utils252.logger.log({ level: "error", message: messages.join(", ") });
65816
- next(new import_node_server_utils252.BadRequestError(messages.join(", ")));
66965
+ import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
66966
+ next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
65817
66967
  return;
65818
66968
  }
65819
66969
  const { id } = value;
@@ -65832,8 +66982,8 @@ function useBuildingLevelController() {
65832
66982
  });
65833
66983
  if (error) {
65834
66984
  const messages = error.details.map((d) => d.message);
65835
- import_node_server_utils252.logger.log({ level: "error", message: messages.join(", ") });
65836
- next(new import_node_server_utils252.BadRequestError(messages.join(", ")));
66985
+ import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
66986
+ next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
65837
66987
  return;
65838
66988
  }
65839
66989
  const { _id, ...rest } = value;
@@ -65845,14 +66995,14 @@ function useBuildingLevelController() {
65845
66995
  }
65846
66996
  async function deleteById(req, res, next) {
65847
66997
  try {
65848
- const schema2 = import_joi146.default.object({
65849
- id: import_joi146.default.string().hex().required()
66998
+ const schema2 = import_joi147.default.object({
66999
+ id: import_joi147.default.string().hex().required()
65850
67000
  });
65851
67001
  const { error, value } = schema2.validate({ id: req.params.id });
65852
67002
  if (error) {
65853
67003
  const messages = error.details.map((d) => d.message);
65854
- import_node_server_utils252.logger.log({ level: "error", message: messages.join(", ") });
65855
- next(new import_node_server_utils252.BadRequestError(messages.join(", ")));
67004
+ import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67005
+ next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
65856
67006
  return;
65857
67007
  }
65858
67008
  const { id } = value;
@@ -65865,19 +67015,19 @@ function useBuildingLevelController() {
65865
67015
  }
65866
67016
  async function batchUpdateByIds(req, res, next) {
65867
67017
  try {
65868
- const schema2 = import_joi146.default.array().items(
65869
- import_joi146.default.object({
65870
- _id: import_joi146.default.string().hex().length(24).required(),
65871
- value: import_joi146.default.object({
65872
- name: import_joi146.default.string().optional().allow("", null)
67018
+ const schema2 = import_joi147.default.array().items(
67019
+ import_joi147.default.object({
67020
+ _id: import_joi147.default.string().hex().length(24).required(),
67021
+ value: import_joi147.default.object({
67022
+ name: import_joi147.default.string().optional().allow("", null)
65873
67023
  }).required()
65874
67024
  })
65875
67025
  );
65876
67026
  const { error, value } = schema2.validate(req.body);
65877
67027
  if (error) {
65878
67028
  const messages = error.details.map((d) => d.message);
65879
- import_node_server_utils252.logger.log({ level: "error", message: messages.join(", ") });
65880
- next(new import_node_server_utils252.BadRequestError(messages.join(", ")));
67029
+ import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67030
+ next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
65881
67031
  return;
65882
67032
  }
65883
67033
  const updates = value.map((item) => ({
@@ -65892,9 +67042,9 @@ function useBuildingLevelController() {
65892
67042
  }
65893
67043
  async function getBuildingLevelList(req, res, next) {
65894
67044
  try {
65895
- const schema2 = import_joi146.default.object({
65896
- site: import_joi146.default.string().hex().length(24).required(),
65897
- block: import_joi146.default.string().hex().length(24).required()
67045
+ const schema2 = import_joi147.default.object({
67046
+ site: import_joi147.default.string().hex().length(24).required(),
67047
+ block: import_joi147.default.string().hex().length(24).required()
65898
67048
  });
65899
67049
  const { error, value } = schema2.validate({
65900
67050
  site: req.params.siteId,
@@ -65902,8 +67052,8 @@ function useBuildingLevelController() {
65902
67052
  });
65903
67053
  if (error) {
65904
67054
  const messages = error.details.map((d) => d.message).join(", ");
65905
- import_node_server_utils252.logger.log({ level: "error", message: messages });
65906
- next(new import_node_server_utils252.BadRequestError(messages));
67055
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67056
+ next(new import_node_server_utils253.BadRequestError(messages));
65907
67057
  return;
65908
67058
  }
65909
67059
  const { site, block } = value;
@@ -66030,7 +67180,6 @@ function useBuildingLevelController() {
66030
67180
  OvernightParkingRequestSort,
66031
67181
  OvernightParkingRequestStatus,
66032
67182
  PERSON_TYPES,
66033
- PMDashboardCollection,
66034
67183
  PStatus,
66035
67184
  Period,
66036
67185
  PersonStatus,
@@ -66083,8 +67232,6 @@ function useBuildingLevelController() {
66083
67232
  guests_namespace_collection,
66084
67233
  incidentReportLog,
66085
67234
  incidents_namespace_collection,
66086
- landscapeDashboardCollection,
66087
- mAndEDashboardCollection,
66088
67235
  manpowerDesignationsSchema,
66089
67236
  manpowerEvents,
66090
67237
  manpowerMonitoringSchema,
@@ -66097,8 +67244,6 @@ function useBuildingLevelController() {
66097
67244
  orgSchema,
66098
67245
  overnight_parking_requests_namespace_collection,
66099
67246
  parseDahuaFind,
66100
- pestDashboardCollection,
66101
- poolDashboardCollection,
66102
67247
  promoCodeSchema,
66103
67248
  remarksSchema,
66104
67249
  residentFormEntry,
@@ -66189,7 +67334,6 @@ function useBuildingLevelController() {
66189
67334
  schemaVisitorTransaction,
66190
67335
  schemeCamera,
66191
67336
  schemeLogCamera,
66192
- securityDashboardCollection,
66193
67337
  shiftSchema,
66194
67338
  siteSchema,
66195
67339
  site_people_namespace_collection,