@7365admin1/core 2.37.0 → 2.38.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
@@ -92,6 +92,7 @@ __export(src_exports, {
92
92
  MPromoCode: () => MPromoCode,
93
93
  MRobot: () => MRobot,
94
94
  MRole: () => MRole,
95
+ MRoleV2: () => MRoleV2,
95
96
  MServiceProvider: () => MServiceProvider,
96
97
  MServiceProviderBilling: () => MServiceProviderBilling,
97
98
  MSession: () => MSession,
@@ -114,6 +115,7 @@ __export(src_exports, {
114
115
  OvernightParkingRequestStatus: () => OvernightParkingRequestStatus,
115
116
  PERSON_TYPES: () => PERSON_TYPES,
116
117
  PMDashboardCollection: () => PMDashboardCollection,
118
+ PStatus: () => PStatus,
117
119
  Period: () => Period,
118
120
  PersonStatus: () => PersonStatus,
119
121
  PersonTypes: () => PersonTypes,
@@ -121,6 +123,7 @@ __export(src_exports, {
121
123
  SiteStatus: () => SiteStatus,
122
124
  SortFields: () => SortFields,
123
125
  SortOrder: () => SortOrder,
126
+ Status: () => Status,
124
127
  SubscriptionType: () => SubscriptionType,
125
128
  UseAccessManagementRepo: () => UseAccessManagementRepo,
126
129
  UserStatus: () => UserStatus,
@@ -375,7 +378,10 @@ __export(src_exports, {
375
378
  useRobotRepo: () => useRobotRepo,
376
379
  useRobotService: () => useRobotService,
377
380
  useRoleController: () => useRoleController,
381
+ useRoleControllerV2: () => useRoleControllerV2,
378
382
  useRoleRepo: () => useRoleRepo,
383
+ useRoleRepoV2: () => useRoleRepoV2,
384
+ useRoleServiceV2: () => useRoleServiceV2,
379
385
  useServiceProviderBillingController: () => useServiceProviderBillingController,
380
386
  useServiceProviderBillingRepo: () => useServiceProviderBillingRepo,
381
387
  useServiceProviderBillingService: () => useServiceProviderBillingService,
@@ -5178,6 +5184,7 @@ function useSiteRepo() {
5178
5184
 
5179
5185
  // src/services/verification.service.ts
5180
5186
  var import_joi11 = __toESM(require("joi"));
5187
+ var import_path = __toESM(require("path"));
5181
5188
  function useVerificationService() {
5182
5189
  const MailerConfig = {
5183
5190
  host: MAILER_TRANSPORT_HOST,
@@ -5208,7 +5215,6 @@ function useVerificationService() {
5208
5215
  expireAt: new Date(
5209
5216
  (/* @__PURE__ */ new Date()).getTime() + 72 * 60 * 60 * 1e3
5210
5217
  ).toISOString(),
5211
- // 72 hours (3 days) from now
5212
5218
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
5213
5219
  };
5214
5220
  if (value.metadata?.org)
@@ -5296,8 +5302,11 @@ function useVerificationService() {
5296
5302
  subject = "Service Provider Organization Invite";
5297
5303
  }
5298
5304
  const res = await add(value);
5299
- const dir = __dirname;
5300
- const filePath = (0, import_node_server_utils20.getDirectory)(dir, `./public/handlebars/${value.type}`);
5305
+ const filePath = import_path.default.resolve(
5306
+ __dirname,
5307
+ "../public/handlebars",
5308
+ value.type
5309
+ );
5301
5310
  const link = org ? `${APP_MAIN}/verify/${value.type}/${res}` : `${APP_ORG}/organizations/create?email=${email}`;
5302
5311
  const emailContent = (0, import_node_server_utils20.compileHandlebar)({
5303
5312
  context: {
@@ -5333,6 +5342,9 @@ function useVerificationService() {
5333
5342
  };
5334
5343
  try {
5335
5344
  const user = await getUserByEmail(email);
5345
+ if (!user) {
5346
+ throw new import_node_server_utils20.NotFoundError("Email not found");
5347
+ }
5336
5348
  const res = await add(value);
5337
5349
  const dir = __dirname;
5338
5350
  const filePath = (0, import_node_server_utils20.getDirectory)(dir, "./public/handlebars/forget-password");
@@ -13399,7 +13411,7 @@ var schemaVisitorTransaction = import_joi36.default.object({
13399
13411
  checkOutRemarks: import_joi36.default.string().optional().allow("", null),
13400
13412
  expectedCheckIn: import_joi36.default.string().isoDate().optional(),
13401
13413
  purpose: import_joi36.default.string().optional().allow(null, ""),
13402
- invitedId: import_joi36.default.any().optional().allow(null, "")
13414
+ inviterId: import_joi36.default.any().optional().allow(null, "")
13403
13415
  });
13404
13416
  var schemaUpdateVisTrans = import_joi36.default.object({
13405
13417
  _id: import_joi36.default.string().hex().length(24).required(),
@@ -13508,11 +13520,11 @@ function MVisitorTransaction(value) {
13508
13520
  return p;
13509
13521
  });
13510
13522
  }
13511
- if (value.invitedId && typeof value.invitedId === "string") {
13523
+ if (value.inviterId && typeof value.inviterId === "string") {
13512
13524
  try {
13513
- value.invitedId = new import_mongodb39.ObjectId(value.invitedId);
13525
+ value.inviterId = new import_mongodb39.ObjectId(value.inviterId);
13514
13526
  } catch (error2) {
13515
- throw new Error("Invalid invited ID.");
13527
+ throw new Error("Invalid inviter ID.");
13516
13528
  }
13517
13529
  }
13518
13530
  const newDate = /* @__PURE__ */ new Date();
@@ -13555,11 +13567,11 @@ function MVisitorTransaction(value) {
13555
13567
  numberOfPassengers: value.numberOfPassengers ?? null,
13556
13568
  email: value.email,
13557
13569
  isOvernightParking: value.isOvernightParking ?? false,
13558
- invitedId: value.invitedId ?? "",
13570
+ inviterId: value.inviterId ?? "",
13559
13571
  overnightParking: value.isOvernightParking == true ? {
13560
13572
  status: "pending approval",
13561
13573
  remarks: "",
13562
- updatedBy: value.invitedId ?? ""
13574
+ updatedBy: value.inviterId ?? ""
13563
13575
  } : null,
13564
13576
  arrivalTime: value.arrivalTime,
13565
13577
  duration: value.duration
@@ -13610,14 +13622,15 @@ function useVisitorTransactionRepo() {
13610
13622
  page = 1,
13611
13623
  limit = 10,
13612
13624
  sort = {},
13613
- status = "registered",
13625
+ status,
13614
13626
  org = "",
13615
13627
  site = "",
13616
13628
  dateTo = "",
13617
13629
  dateFrom = "",
13618
13630
  type = "",
13619
13631
  checkedOut,
13620
- plateNumber = ""
13632
+ plateNumber = "",
13633
+ tab = ""
13621
13634
  }) {
13622
13635
  page = page > 0 ? page - 1 : 0;
13623
13636
  const skip = page * limit;
@@ -13635,7 +13648,6 @@ function useVisitorTransactionRepo() {
13635
13648
  expectedCheckInFilter.$lte = new Date(dateTo);
13636
13649
  }
13637
13650
  const query = {
13638
- status,
13639
13651
  ...import_mongodb40.ObjectId.isValid(org) && { org: new import_mongodb40.ObjectId(org) },
13640
13652
  ...import_mongodb40.ObjectId.isValid(site) && { site: new import_mongodb40.ObjectId(site) },
13641
13653
  ...Object.keys(checkInFilter).length > 0 && { checkIn: checkInFilter },
@@ -13643,7 +13655,9 @@ function useVisitorTransactionRepo() {
13643
13655
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
13644
13656
  ...checkedOut == false && { checkOut: { $eq: null } },
13645
13657
  ...search && { $text: { $search: search } },
13646
- ...plateNumber && { plateNumber }
13658
+ ...plateNumber && { plateNumber },
13659
+ ...status && { status },
13660
+ ...tab == "Overnight Parking" && { isOvernightParking: true }
13647
13661
  };
13648
13662
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
13649
13663
  try {
@@ -13789,7 +13803,31 @@ function useVisitorTransactionRepo() {
13789
13803
  },
13790
13804
  { $sort: sort },
13791
13805
  { $skip: skip },
13792
- { $limit: limit }
13806
+ { $limit: limit },
13807
+ {
13808
+ $lookup: {
13809
+ from: "users",
13810
+ localField: "inviterId",
13811
+ foreignField: "_id",
13812
+ as: "inviterData"
13813
+ }
13814
+ },
13815
+ {
13816
+ $unwind: {
13817
+ path: "$inviterData",
13818
+ preserveNullAndEmptyArrays: true
13819
+ }
13820
+ },
13821
+ {
13822
+ $addFields: {
13823
+ inviterName: "$inviterData.name"
13824
+ }
13825
+ },
13826
+ {
13827
+ $project: {
13828
+ inviterData: 0
13829
+ }
13830
+ }
13793
13831
  ]).toArray(),
13794
13832
  collection.aggregate([...basePipeline, { $count: "total" }]).toArray()
13795
13833
  ]);
@@ -14105,7 +14143,7 @@ function MVehicle(value) {
14105
14143
  block: value.block ?? 0,
14106
14144
  level: value.level ?? "",
14107
14145
  unit: value.unit ?? "",
14108
- nric: value.nric,
14146
+ nric: value.nric ?? "",
14109
14147
  remarks: value.remarks ?? "",
14110
14148
  seasonPassType: value.seasonPassType ?? "",
14111
14149
  start: value.start ?? createdAt,
@@ -14165,7 +14203,7 @@ function MVehicleTransaction(value) {
14165
14203
  var import_node_server_utils73 = require("@7365admin1/node-server-utils");
14166
14204
  var import_fs = require("fs");
14167
14205
  var import_joi39 = __toESM(require("joi"));
14168
- var path = __toESM(require("path"));
14206
+ var path2 = __toESM(require("path"));
14169
14207
  var import_urllib = require("urllib");
14170
14208
 
14171
14209
  // src/repositories/vehicle.repo.ts
@@ -14800,6 +14838,66 @@ function useVehicleRepo() {
14800
14838
  throw error;
14801
14839
  }
14802
14840
  }
14841
+ async function bulkUpsertVehicles(values, session) {
14842
+ try {
14843
+ if (!Array.isArray(values) || values.length === 0) {
14844
+ return {
14845
+ matchedCount: 0,
14846
+ modifiedCount: 0,
14847
+ upsertedCount: 0
14848
+ };
14849
+ }
14850
+ const now = (/* @__PURE__ */ new Date()).toISOString();
14851
+ const operations = values.map((item) => {
14852
+ const vehicle = MVehicle(item);
14853
+ const plateNumber = Array.isArray(vehicle.plateNumber) ? vehicle.plateNumber[0] : vehicle.plateNumber;
14854
+ const { createdAt, ...rest } = vehicle;
14855
+ return {
14856
+ updateOne: {
14857
+ filter: {
14858
+ site: vehicle.site,
14859
+ plateNumber,
14860
+ $or: [
14861
+ { deletedAt: "" },
14862
+ { deletedAt: null },
14863
+ { deletedAt: { $exists: false } }
14864
+ ]
14865
+ },
14866
+ update: {
14867
+ $set: {
14868
+ ...rest,
14869
+ plateNumber,
14870
+ updatedAt: now
14871
+ },
14872
+ $setOnInsert: {
14873
+ createdAt: vehicle.createdAt || now
14874
+ }
14875
+ },
14876
+ upsert: true
14877
+ }
14878
+ };
14879
+ });
14880
+ const res = await collection.bulkWrite(operations, {
14881
+ ordered: false,
14882
+ session
14883
+ });
14884
+ return {
14885
+ matchedCount: res.matchedCount,
14886
+ modifiedCount: res.modifiedCount,
14887
+ upsertedCount: res.upsertedCount,
14888
+ upsertedIds: res.upsertedIds
14889
+ };
14890
+ } catch (error) {
14891
+ import_node_server_utils70.logger.log({
14892
+ level: "error",
14893
+ message: error.message
14894
+ });
14895
+ if (error instanceof import_node_server_utils70.AppError) {
14896
+ throw error;
14897
+ }
14898
+ throw new Error("Failed to bulk upsert vehicles.");
14899
+ }
14900
+ }
14803
14901
  return {
14804
14902
  createIndex,
14805
14903
  createTextIndex,
@@ -14814,7 +14912,8 @@ function useVehicleRepo() {
14814
14912
  getVehiclesByNRIC,
14815
14913
  deleteExpiredVehicles,
14816
14914
  getAllVehiclesByUnitId,
14817
- getAllExpiredVehicles
14915
+ getAllExpiredVehicles,
14916
+ bulkUpsertVehicles
14818
14917
  };
14819
14918
  }
14820
14919
 
@@ -15446,7 +15545,8 @@ function useVehicleService() {
15446
15545
  getVehicleById: _getVehicleById,
15447
15546
  deleteExpiredVehicles: _deleteExpiredVehicles,
15448
15547
  getVehicleByPlateNumber: _getVehicleByPlateNumber,
15449
- getAllExpiredVehicles: _getAllExpiredVehicles
15548
+ getAllExpiredVehicles: _getAllExpiredVehicles,
15549
+ bulkUpsertVehicles: _bulkUpsertVehicles
15450
15550
  } = useVehicleRepo();
15451
15551
  const {
15452
15552
  addPlateNumber: _addPlateNumber,
@@ -16063,13 +16163,38 @@ function useVehicleService() {
16063
16163
  session.endSession();
16064
16164
  }
16065
16165
  }
16166
+ async function bulkUpsertVehicles(values) {
16167
+ const session = import_node_server_utils72.useAtlas.getClient()?.startSession();
16168
+ if (!session) {
16169
+ throw new Error("Unable to start session for vehicle service.");
16170
+ }
16171
+ try {
16172
+ if (!Array.isArray(values) || values.length === 0) {
16173
+ throw new Error("Vehicle list is required.");
16174
+ }
16175
+ const sanitizedValues = values.map((item) => {
16176
+ const plateNumber = Array.isArray(item.plateNumber) ? item.plateNumber[0] : item.plateNumber;
16177
+ return {
16178
+ ...item,
16179
+ plateNumber: typeof plateNumber === "string" ? plateNumber.trim() : plateNumber
16180
+ };
16181
+ }).filter((item) => item.site && item.plateNumber);
16182
+ if (sanitizedValues.length === 0) {
16183
+ throw new Error("No valid vehicle plate numbers found.");
16184
+ }
16185
+ return await _bulkUpsertVehicles(sanitizedValues, session);
16186
+ } catch (error) {
16187
+ throw error;
16188
+ }
16189
+ }
16066
16190
  return {
16067
16191
  add,
16068
16192
  deleteVehicle,
16069
16193
  approveVehicleById,
16070
16194
  processDeletingExpiredVehicles,
16071
16195
  reactivateVehicleById,
16072
- updateVehicleById
16196
+ updateVehicleById,
16197
+ bulkUpsertVehicles
16073
16198
  };
16074
16199
  }
16075
16200
 
@@ -16343,8 +16468,8 @@ function useDahuaService() {
16343
16468
  const utcMs = Number(UTCMs) || Date.now() % 1e3;
16344
16469
  const timeData = createFileNameFromEvent(utcSec, utcMs);
16345
16470
  const filename = plateNumber ? `${gate}-${timeData}-${plateNumber}.jpeg` : `${gate}-${timeData}.jpeg`;
16346
- const snapFolder = path.join(__dirname, `../snap/${site}/${filename}`);
16347
- const dir = path.dirname(snapFolder);
16471
+ const snapFolder = path2.join(__dirname, `../snap/${site}/${filename}`);
16472
+ const dir = path2.dirname(snapFolder);
16348
16473
  try {
16349
16474
  await import_fs.promises.mkdir(dir, { recursive: true });
16350
16475
  await import_fs.promises.writeFile(snapFolder, accumulatedImageBuffer);
@@ -18745,13 +18870,18 @@ function useBuildingUnitController() {
18745
18870
  // src/controllers/vehicle.controller.ts
18746
18871
  var import_node_server_utils86 = require("@7365admin1/node-server-utils");
18747
18872
  var import_joi46 = __toESM(require("joi"));
18873
+ var import_exceljs = __toESM(require("exceljs"));
18874
+ var import_stream = require("stream");
18875
+ var import_csv_parser = __toESM(require("csv-parser"));
18876
+ var import_fs2 = __toESM(require("fs"));
18748
18877
  function useVehicleController() {
18749
18878
  const {
18750
18879
  add: _add,
18751
18880
  deleteVehicle: _deleteVehicle,
18752
18881
  approveVehicleById: _approveVehicleById,
18753
18882
  reactivateVehicleById: _reactivateVehicleById,
18754
- updateVehicleById: _updateVehicleById
18883
+ updateVehicleById: _updateVehicleById,
18884
+ bulkUpsertVehicles: _bulkUpsertVehicles
18755
18885
  } = useVehicleService();
18756
18886
  const {
18757
18887
  getSeasonPassTypes: _getSeasonPassTypes,
@@ -18760,6 +18890,141 @@ function useVehicleController() {
18760
18890
  getVehiclesByNRIC: _getVehiclesByNRIC,
18761
18891
  getAllVehiclesByUnitId: _getAllVehiclesByUnitId
18762
18892
  } = useVehicleRepo();
18893
+ function normalizeRow(row) {
18894
+ return Object.fromEntries(
18895
+ Object.entries(row).map(([key, value]) => [
18896
+ key,
18897
+ typeof value === "string" ? value.trim() : value
18898
+ ])
18899
+ );
18900
+ }
18901
+ function mapRowToVehicle(row) {
18902
+ const cleanRow = normalizeRow(row);
18903
+ return {
18904
+ name: cleanRow.fullName,
18905
+ category: cleanRow.userType,
18906
+ type: cleanRow.recordType,
18907
+ phoneNumber: cleanRow.phoneNumber || "",
18908
+ block: Number(cleanRow.block),
18909
+ level: String(cleanRow.level || ""),
18910
+ unitName: String(cleanRow.unit || ""),
18911
+ plateNumber: String(cleanRow.plateNumber || "").toUpperCase(),
18912
+ remarks: `Model: ${cleanRow.vehicleModel || ""}, Color: ${cleanRow.vehicleColor || ""}`,
18913
+ org: cleanRow.org,
18914
+ site: cleanRow.site,
18915
+ end: parseExpiryDate(cleanRow.subscriptionExpiry)
18916
+ };
18917
+ }
18918
+ function parseExpiryDate(value) {
18919
+ if (!value)
18920
+ return void 0;
18921
+ const [day, monthStr, yearShort] = value.split("-");
18922
+ const months = {
18923
+ Jan: 0,
18924
+ Feb: 1,
18925
+ Mar: 2,
18926
+ Apr: 3,
18927
+ May: 4,
18928
+ Jun: 5,
18929
+ Jul: 6,
18930
+ Aug: 7,
18931
+ Sep: 8,
18932
+ Oct: 9,
18933
+ Nov: 10,
18934
+ Dec: 11
18935
+ };
18936
+ const month = months[monthStr];
18937
+ if (month === void 0)
18938
+ return void 0;
18939
+ const year = 2e3 + Number(yearShort);
18940
+ const date = new Date(year, month, Number(day));
18941
+ return isNaN(date.getTime()) ? void 0 : date.toISOString();
18942
+ }
18943
+ async function uploadCsvVehicles(req, res, next) {
18944
+ try {
18945
+ if (!req.file) {
18946
+ next(new import_node_server_utils86.BadRequestError("CSV file is required."));
18947
+ return;
18948
+ }
18949
+ if (!req.file.originalname.toLowerCase().endsWith(".csv")) {
18950
+ next(new import_node_server_utils86.BadRequestError("Only .csv files are allowed."));
18951
+ return;
18952
+ }
18953
+ const rows = [];
18954
+ const stream = import_stream.Readable.from(req.file.buffer);
18955
+ stream.pipe((0, import_csv_parser.default)()).on("data", (row) => {
18956
+ rows.push(row);
18957
+ }).on("end", async () => {
18958
+ try {
18959
+ const vehicles = rows.map(mapRowToVehicle);
18960
+ const data = await _bulkUpsertVehicles(vehicles);
18961
+ res.status(200).json({
18962
+ message: "CSV import completed.",
18963
+ count: rows.length,
18964
+ data
18965
+ });
18966
+ } catch (error) {
18967
+ import_node_server_utils86.logger.log({ level: "error", message: error.message });
18968
+ next(error);
18969
+ }
18970
+ }).on("error", (error) => {
18971
+ import_node_server_utils86.logger.log({ level: "error", message: error.message });
18972
+ next(error);
18973
+ });
18974
+ } catch (error) {
18975
+ import_node_server_utils86.logger.log({ level: "error", message: error.message });
18976
+ next(error);
18977
+ }
18978
+ }
18979
+ async function uploadExcelVehicles(req, res, next) {
18980
+ try {
18981
+ if (!req.file) {
18982
+ next(new import_node_server_utils86.BadRequestError("Excel file is required."));
18983
+ return;
18984
+ }
18985
+ if (!req.file.originalname.toLowerCase().endsWith(".xlsx")) {
18986
+ next(new import_node_server_utils86.BadRequestError("Only .xlsx files are allowed."));
18987
+ return;
18988
+ }
18989
+ const workbook = new import_exceljs.default.Workbook();
18990
+ await workbook.xlsx.readFile(req.file.path);
18991
+ const worksheet = workbook.worksheets[0];
18992
+ if (!worksheet) {
18993
+ next(new import_node_server_utils86.BadRequestError("No worksheet found in uploaded Excel file."));
18994
+ return;
18995
+ }
18996
+ const rows = [];
18997
+ const headerRow = worksheet.getRow(1);
18998
+ const headers = (headerRow.values || []).slice(1).map((header) => String(header ?? "").trim());
18999
+ worksheet.eachRow((row, rowNumber) => {
19000
+ if (rowNumber === 1)
19001
+ return;
19002
+ const rowData = {};
19003
+ headers.forEach((header, index) => {
19004
+ rowData[header] = row.getCell(index + 1).value ?? "";
19005
+ });
19006
+ const hasValue = Object.values(rowData).some(
19007
+ (value) => value !== null && value !== void 0 && value !== ""
19008
+ );
19009
+ if (hasValue) {
19010
+ rows.push(rowData);
19011
+ }
19012
+ });
19013
+ const vehicles = rows.map(mapRowToVehicle);
19014
+ const data = await _bulkUpsertVehicles(vehicles);
19015
+ res.status(200).json({
19016
+ message: "Excel import completed.",
19017
+ sheetName: worksheet.name,
19018
+ count: rows.length,
19019
+ data
19020
+ });
19021
+ import_fs2.default.unlink(req.file.path, () => {
19022
+ });
19023
+ } catch (error) {
19024
+ import_node_server_utils86.logger.log({ level: "error", message: error.message });
19025
+ next(error);
19026
+ }
19027
+ }
18763
19028
  async function add(req, res, next) {
18764
19029
  const { error, value } = vehicleSchema.validate(req.body, {
18765
19030
  abortEarly: false
@@ -19084,6 +19349,69 @@ function useVehicleController() {
19084
19349
  return;
19085
19350
  }
19086
19351
  }
19352
+ async function bulkUpsertVehicles(req, res, next) {
19353
+ const items = Array.isArray(req.body) ? req.body : req.body?.items;
19354
+ if (!Array.isArray(items) || items.length === 0) {
19355
+ next(new import_node_server_utils86.BadRequestError("A non-empty array of vehicles is required."));
19356
+ return;
19357
+ }
19358
+ const success = [];
19359
+ const failed = [];
19360
+ try {
19361
+ for (let index = 0; index < items.length; index++) {
19362
+ const item = items[index];
19363
+ const schema2 = import_joi46.default.object({
19364
+ fullName: import_joi46.default.string().trim().required(),
19365
+ category: import_joi46.default.string().trim().lowercase().valid(...Object.values(PersonTypes)).required(),
19366
+ type: import_joi46.default.string().trim().lowercase().valid(...Object.values(VehicleType)),
19367
+ phoneNumber: import_joi46.default.string().trim().allow(null, "").optional(),
19368
+ block: import_joi46.default.number().integer().min(1).required(),
19369
+ level: import_joi46.default.string().trim().required(),
19370
+ unit: import_joi46.default.string().trim().required(),
19371
+ plateNumber: import_joi46.default.string().trim().uppercase().required(),
19372
+ vehicleModel: import_joi46.default.string().trim().required(),
19373
+ vehicleColor: import_joi46.default.string().trim().required(),
19374
+ subscriptionExpiry: import_joi46.default.string().trim().allow(null, "").optional()
19375
+ });
19376
+ const { error, value } = schema2.validate(item, {
19377
+ abortEarly: false
19378
+ });
19379
+ if (error) {
19380
+ const message = error.details.map((d) => d.message).join(", ");
19381
+ failed.push({
19382
+ index,
19383
+ item,
19384
+ message
19385
+ });
19386
+ continue;
19387
+ }
19388
+ try {
19389
+ const data = await _bulkUpsertVehicles(value);
19390
+ success.push({
19391
+ index,
19392
+ data
19393
+ });
19394
+ } catch (error2) {
19395
+ failed.push({
19396
+ index,
19397
+ item,
19398
+ message: error2.message
19399
+ });
19400
+ }
19401
+ }
19402
+ res.status(201).json({
19403
+ message: "Bulk vehicle import completed.",
19404
+ successCount: success.length,
19405
+ failedCount: failed.length,
19406
+ success,
19407
+ failed
19408
+ });
19409
+ } catch (error) {
19410
+ import_node_server_utils86.logger.log({ level: "error", message: error.message });
19411
+ next(error);
19412
+ return;
19413
+ }
19414
+ }
19087
19415
  return {
19088
19416
  add,
19089
19417
  getVehicles,
@@ -19094,7 +19422,10 @@ function useVehicleController() {
19094
19422
  approveVehicleById,
19095
19423
  getVehiclesByNRIC,
19096
19424
  reactivateVehicleById,
19097
- getAllVehiclesByUnitId
19425
+ getAllVehiclesByUnitId,
19426
+ bulkUpsertVehicles,
19427
+ uploadCsvVehicles,
19428
+ uploadExcelVehicles
19098
19429
  };
19099
19430
  }
19100
19431
 
@@ -22300,7 +22631,7 @@ function useVisitorTransactionService() {
22300
22631
  org: inviter?.org.toString(),
22301
22632
  site: inviter?.site.toString(),
22302
22633
  status: "approved" /* APPROVED */,
22303
- invitedId: inviter?._id
22634
+ inviterId: userId
22304
22635
  };
22305
22636
  const result = await _add(payload);
22306
22637
  const emailContent = (0, import_node_server_utils101.compileHandlebar)({
@@ -22451,7 +22782,8 @@ function useVisitorTransactionController() {
22451
22782
  }).optional().allow(null, ""),
22452
22783
  checkedOut: import_joi55.default.boolean().allow(null, ""),
22453
22784
  plateNumber: import_joi55.default.string().optional().allow(null, ""),
22454
- order: import_joi55.default.string().valid(...Object.values(SortOrder)).default("asc" /* ASC */)
22785
+ order: import_joi55.default.string().valid(...Object.values(SortOrder)).default("asc" /* ASC */),
22786
+ tab: import_joi55.default.string().optional().allow(null, "")
22455
22787
  });
22456
22788
  const { error, value } = validation.validate(req.query, {
22457
22789
  abortEarly: false
@@ -22475,7 +22807,8 @@ function useVisitorTransactionController() {
22475
22807
  checkedOut,
22476
22808
  sort,
22477
22809
  order,
22478
- plateNumber
22810
+ plateNumber,
22811
+ tab
22479
22812
  } = value;
22480
22813
  const sortObj = {
22481
22814
  [sort ? sort : "_id" /* ID */]: order === "asc" /* ASC */ ? 1 : -1
@@ -22492,7 +22825,8 @@ function useVisitorTransactionController() {
22492
22825
  dateFrom,
22493
22826
  type,
22494
22827
  checkedOut,
22495
- plateNumber
22828
+ plateNumber,
22829
+ tab
22496
22830
  });
22497
22831
  res.status(200).json(data);
22498
22832
  return;
@@ -29705,7 +30039,7 @@ function useSiteBillingItemService() {
29705
30039
  }
29706
30040
  try {
29707
30041
  await session.startTransaction();
29708
- const billing_item = await _getBillingItemById(id, session);
30042
+ const billing_item = await _getBillingItemById(id);
29709
30043
  if (!billing_item) {
29710
30044
  throw new import_node_server_utils141.BadRequestError("Billing item not found.");
29711
30045
  }
@@ -30712,10 +31046,32 @@ function useEventManagementController() {
30712
31046
  var import_node_server_utils148 = require("@7365admin1/node-server-utils");
30713
31047
  var import_mongodb85 = require("mongodb");
30714
31048
  var import_joi83 = __toESM(require("joi"));
31049
+ var Status = /* @__PURE__ */ ((Status3) => {
31050
+ Status3["PENDING"] = "pending";
31051
+ Status3["COMPLETED"] = "completed";
31052
+ Status3["APPROVED"] = "approved";
31053
+ Status3["REJECTED"] = "rejected";
31054
+ Status3["CANCELLED"] = "cancelled";
31055
+ Status3["RECURRING"] = "recurring";
31056
+ Status3["NONRECURRING"] = "non-recurring";
31057
+ Status3["ACTIVE"] = "active";
31058
+ Status3["INACTIVE"] = "inactive";
31059
+ return Status3;
31060
+ })(Status || {});
31061
+ var PStatus = /* @__PURE__ */ ((PStatus2) => {
31062
+ PStatus2["PROCESSING"] = "processing";
31063
+ PStatus2["UNPAID"] = "unpaid";
31064
+ PStatus2["PAID"] = "paid";
31065
+ PStatus2["OVERDUE"] = "overdue";
31066
+ PStatus2["PARTIAL"] = "partial-payment";
31067
+ PStatus2["AWAITING_PAYMENT"] = "awaiting-payment";
31068
+ PStatus2["FAILED"] = "failed";
31069
+ return PStatus2;
31070
+ })(PStatus || {});
30715
31071
  var schemaUnitBilling = import_joi83.default.object({
30716
31072
  _id: import_joi83.default.string().hex().optional(),
30717
- site: import_joi83.default.string().hex().required(),
30718
- org: import_joi83.default.string().hex().required(),
31073
+ site: import_joi83.default.string().hex().optional().allow(null, ""),
31074
+ org: import_joi83.default.string().hex().optional().allow(null, ""),
30719
31075
  billItem: import_joi83.default.string().hex().optional().allow(null, ""),
30720
31076
  billName: import_joi83.default.string().optional().allow(null, ""),
30721
31077
  unitId: import_joi83.default.string().hex().optional().allow(null, ""),
@@ -30735,6 +31091,7 @@ var schemaUnitBilling = import_joi83.default.object({
30735
31091
  paymentStatus: import_joi83.default.string().optional().allow(null, ""),
30736
31092
  status: import_joi83.default.string().optional().allow(null, ""),
30737
31093
  amountPaid: import_joi83.default.number().optional().allow(null, ""),
31094
+ balanceAmount: import_joi83.default.number().optional().allow(null, ""),
30738
31095
  paidBy: import_joi83.default.string().hex().optional().allow(null, ""),
30739
31096
  datePaid: import_joi83.default.date().optional().allow(null, ""),
30740
31097
  transaction_id: import_joi83.default.string().optional().allow(null, ""),
@@ -30758,6 +31115,7 @@ var schemaUpdateSiteUnitBilling = import_joi83.default.object({
30758
31115
  category: import_joi83.default.string().optional().allow(null, ""),
30759
31116
  frequency: import_joi83.default.string().optional().allow(null, ""),
30760
31117
  totalAmount: import_joi83.default.number().optional().allow(null, ""),
31118
+ balanceAmount: import_joi83.default.number().optional().allow(null, ""),
30761
31119
  taxPercentage: import_joi83.default.number().optional().allow(null, ""),
30762
31120
  taxAmount: import_joi83.default.number().optional().allow(null, ""),
30763
31121
  amount: import_joi83.default.number().optional().allow(null, ""),
@@ -30823,8 +31181,8 @@ function MUnitBilling(value) {
30823
31181
  }
30824
31182
  return {
30825
31183
  _id: value._id ?? new import_mongodb85.ObjectId(),
30826
- site: value.site,
30827
- org: value.org,
31184
+ site: value.site ?? "",
31185
+ org: value.org ?? "",
30828
31186
  billItem: value.billItem ?? "",
30829
31187
  billName: value.billName ?? "",
30830
31188
  unitId: value.unitId ?? "",
@@ -30844,6 +31202,7 @@ function MUnitBilling(value) {
30844
31202
  paymentStatus: value.paymentStatus ?? "",
30845
31203
  status: value.status ?? "active",
30846
31204
  amountPaid: value.amountPaid ?? 0,
31205
+ balanceAmount: value.balanceAmount ?? 0,
30847
31206
  paidBy: value.paidBy ?? "",
30848
31207
  datePaid: value.datePaid ?? "",
30849
31208
  transaction_id: value.transaction_id ?? "",
@@ -30887,7 +31246,7 @@ function useSiteUnitBillingRepo() {
30887
31246
  value = MUnitBilling(value);
30888
31247
  const res = await collection.insertOne(value, { session });
30889
31248
  const acronym = createAcronym(value.billName || "NA");
30890
- const dateFormatted = formatDateString2(/* @__PURE__ */ new Date());
31249
+ const dateFormatted = formatDateString(/* @__PURE__ */ new Date());
30891
31250
  const newId = new import_mongodb86.ObjectId(res.insertedId).toString().slice(-6);
30892
31251
  const referenceNumber = `${acronym}${newId}${dateFormatted}`;
30893
31252
  await collection.updateOne(
@@ -31313,7 +31672,7 @@ function useSiteUnitBillingRepo() {
31313
31672
  function createAcronym(billName) {
31314
31673
  return billName.split(" ").map((word) => word.charAt(0).toUpperCase()).join("");
31315
31674
  }
31316
- function formatDateString2(today) {
31675
+ function formatDateString(today) {
31317
31676
  today = typeof today === "string" ? new Date(today) : today;
31318
31677
  let month = today.getMonth() + 1;
31319
31678
  let day = today.getDate();
@@ -31830,8 +32189,8 @@ var import_node_server_utils152 = require("@7365admin1/node-server-utils");
31830
32189
  var import_mongodb89 = require("mongodb");
31831
32190
 
31832
32191
  // src/utils/access-management.ts
31833
- var import_fs2 = __toESM(require("fs"));
31834
- var import_path = __toESM(require("path"));
32192
+ var import_fs3 = __toESM(require("fs"));
32193
+ var import_path2 = __toESM(require("path"));
31835
32194
  var import_axios = __toESM(require("axios"));
31836
32195
  var import_xml2js = require("xml2js");
31837
32196
  var import_crypto = __toESM(require("crypto"));
@@ -31860,8 +32219,8 @@ var minifyXml = (xml) => {
31860
32219
  return xml.replace(/>\s+</g, "><").replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").trim();
31861
32220
  };
31862
32221
  var readTemplate = (name, params) => {
31863
- const template = import_fs2.default.readFileSync(
31864
- import_path.default.join(__dirname, `../src/public/xml-templates/${name}.xml`),
32222
+ const template = import_fs3.default.readFileSync(
32223
+ import_path2.default.join(__dirname, `../src/public/xml-templates/${name}.xml`),
31865
32224
  "utf-8"
31866
32225
  );
31867
32226
  if (!params)
@@ -31970,14 +32329,14 @@ var import_xml2js2 = require("xml2js");
31970
32329
 
31971
32330
  // src/utils/rsa-encryption.ts
31972
32331
  var crypto2 = __toESM(require("crypto"));
31973
- var import_fs3 = __toESM(require("fs"));
31974
- var import_path2 = __toESM(require("path"));
31975
- var pub = import_path2.default.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_pub.pem");
31976
- var priv = import_path2.default.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_priv.pem");
32332
+ var import_fs4 = __toESM(require("fs"));
32333
+ var import_path3 = __toESM(require("path"));
32334
+ var pub = import_path3.default.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_pub.pem");
32335
+ var priv = import_path3.default.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_priv.pem");
31977
32336
  var EncryptionCredentials = class {
31978
32337
  };
31979
- EncryptionCredentials.RAW_PUBLIC_KEY = import_fs3.default.readFileSync(pub, "utf8");
31980
- EncryptionCredentials.RAW_PRIVATE_KEY = import_fs3.default.readFileSync(priv, "utf8");
32338
+ EncryptionCredentials.RAW_PUBLIC_KEY = import_fs4.default.readFileSync(pub, "utf8");
32339
+ EncryptionCredentials.RAW_PRIVATE_KEY = import_fs4.default.readFileSync(priv, "utf8");
31981
32340
  var EntrypassRSAEncryption = class extends EncryptionCredentials {
31982
32341
  static hexToCardNumber(hex) {
31983
32342
  if (!/^[0-9A-Fa-f]{8}$/.test(hex)) {
@@ -33933,7 +34292,7 @@ var import_joi85 = __toESM(require("joi"));
33933
34292
 
33934
34293
  // src/services/access-management.service.ts
33935
34294
  var import_xml2js3 = require("xml2js");
33936
- var import_stream = require("stream");
34295
+ var import_stream2 = require("stream");
33937
34296
  var xlsx = __toESM(require("xlsx"));
33938
34297
  function useAccessManagementSvc() {
33939
34298
  const {
@@ -34138,7 +34497,7 @@ function useAccessManagementSvc() {
34138
34497
  };
34139
34498
  const convertBufferFile = async (bufferFile) => {
34140
34499
  return new Promise((resolve, reject) => {
34141
- const fileStream = import_stream.Readable.from(bufferFile);
34500
+ const fileStream = import_stream2.Readable.from(bufferFile);
34142
34501
  let fileBuffer = Buffer.alloc(0);
34143
34502
  fileStream.on("data", (chunk) => {
34144
34503
  fileBuffer = Buffer.concat([fileBuffer, chunk]);
@@ -46379,118 +46738,8 @@ function genericSignature(params, secretKey) {
46379
46738
  }
46380
46739
 
46381
46740
  // src/repositories/reddot-payment.repository.ts
46382
- var import_mongodb127 = require("mongodb");
46383
-
46384
- // src/utils/date-format.util.ts
46385
- var import_moment_timezone6 = __toESM(require("moment-timezone"));
46386
- function formatDateString(today, format, dateRange) {
46387
- today = typeof today === "string" ? new Date(today) : today;
46388
- let month = today.getMonth() + 1;
46389
- let day = today.getDate();
46390
- let year = today.getFullYear();
46391
- let formattedDate;
46392
- if (format === "mm-dd-yyyy") {
46393
- formattedDate = `${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}-${year}`;
46394
- } else if (format === "dd-mm-yyyy") {
46395
- formattedDate = `${day.toString().padStart(2, "0")}-${month.toString().padStart(2, "0")}-${year}`;
46396
- } else if (format === "for-ref") {
46397
- formattedDate = `${month.toString().padStart(2, "0")}${day.toString().padStart(2, "0")}${year}`;
46398
- } else if (format === "mm/dd/yyyy") {
46399
- formattedDate = `${month.toString().padStart(2, "0")}/${day.toString().padStart(2, "0")}/${year}`;
46400
- } else {
46401
- formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
46402
- }
46403
- return formattedDate;
46404
- }
46405
-
46406
- // src/models/credit-card.model.ts
46407
- var import_mongodb124 = require("mongodb");
46408
- var MCardInfo = class {
46409
- // this is coming from RDP transaction
46410
- constructor({
46411
- _id = new import_mongodb124.ObjectId(),
46412
- userId,
46413
- cardType,
46414
- cardNumber,
46415
- cardId,
46416
- fullName,
46417
- expiryDate,
46418
- cvv,
46419
- site,
46420
- siteName,
46421
- organization,
46422
- createdBy,
46423
- createdAt,
46424
- updatedAt,
46425
- transaction_id
46426
- } = {}) {
46427
- this._id = _id;
46428
- this.userId = userId;
46429
- this.cardType = cardType;
46430
- this.cardNumber = cardNumber;
46431
- this.cardId = cardId;
46432
- this.fullName = fullName;
46433
- this.expiryDate = expiryDate;
46434
- this.cvv = cvv;
46435
- this.site = site;
46436
- this.siteName = siteName;
46437
- this.organization = organization;
46438
- this.createdBy = createdBy;
46439
- this.createdAt = createdAt;
46440
- this.updatedAt = updatedAt;
46441
- this.transaction_id = transaction_id;
46442
- }
46443
- };
46444
-
46445
- // src/models/cart.model.ts
46446
- var import_mongodb125 = require("mongodb");
46447
- var MUnitBillings = class {
46448
- // transaction response messages
46449
- constructor({
46450
- _id = new import_mongodb125.ObjectId(),
46451
- unit,
46452
- unitId,
46453
- unitBill,
46454
- paymentStatus = "Processing" /* processing */,
46455
- referenceNumber,
46456
- amountPaid,
46457
- paidBy,
46458
- datePaid,
46459
- billCategory,
46460
- billFrom,
46461
- billTo,
46462
- site,
46463
- organization,
46464
- createdBy,
46465
- createdAt,
46466
- updatedAt,
46467
- message
46468
- } = {}) {
46469
- this._id = _id;
46470
- this.unit = unit;
46471
- this.unitId = unitId;
46472
- this.referenceNumber = referenceNumber;
46473
- this.unitBill = unitBill;
46474
- this.paymentStatus = paymentStatus;
46475
- this.amountPaid = amountPaid;
46476
- this.site = site;
46477
- this.organization = organization;
46478
- this.paidBy = paidBy;
46479
- this.datePaid = datePaid;
46480
- this.billCategory = billCategory;
46481
- this.billFrom = billFrom;
46482
- this.billTo = billTo;
46483
- this.createdBy = createdBy;
46484
- this.createdAt = createdAt;
46485
- this.updatedAt = updatedAt;
46486
- this.message = message;
46487
- }
46488
- };
46489
-
46490
- // src/repositories/payment.repository.ts
46491
- var import_mongodb126 = require("mongodb");
46492
46741
  var import_node_server_utils216 = require("@7365admin1/node-server-utils");
46493
- var PaymentBillRepo = () => {
46742
+ var useRedDotPaymentRepo = () => {
46494
46743
  const getDB2 = () => {
46495
46744
  const db = import_node_server_utils216.useAtlas.getDb();
46496
46745
  if (!db) {
@@ -46498,347 +46747,75 @@ var PaymentBillRepo = () => {
46498
46747
  }
46499
46748
  return db;
46500
46749
  };
46501
- const collection = () => {
46502
- return getDB2().collection("unit-bill");
46750
+ const paymentCollection = () => {
46751
+ return getDB2().collection("payments");
46503
46752
  };
46504
- const billCollection = () => {
46505
- return getDB2().collection("bill-records");
46753
+ const unitBillingCollection = () => {
46754
+ return getDB2().collection("site.unit.billing");
46506
46755
  };
46507
- const creditCollection = () => {
46508
- return getDB2().collection("credit-info");
46756
+ const orgCollection = () => {
46757
+ return getDB2().collection("organizations");
46509
46758
  };
46510
- const cartCollection = () => {
46511
- return getDB2().collection("checkout-cart");
46759
+ const redDotMerchantCollection = () => {
46760
+ return getDB2().collection("payment-gateways");
46512
46761
  };
46513
- const payUnitBill = async (refId, payload) => {
46762
+ async function paySingleUnitBill(refId, payload) {
46514
46763
  try {
46515
46764
  if (refId)
46516
46765
  refId = refId.toString();
46517
- const unitBillInfo = await collection().findOne({ referenceNumber: refId });
46518
- const unitBillId = unitBillInfo?._id;
46766
+ const unitBillInfo = await unitBillingCollection().findOne({
46767
+ referenceNumber: refId
46768
+ });
46519
46769
  if (!unitBillInfo) {
46520
46770
  throw new Error("Unit bill info not found");
46521
46771
  }
46522
- if (unitBillInfo?.status === "Inactive" /* inactive */) {
46772
+ if (unitBillInfo?.status === "inactive" /* INACTIVE */) {
46523
46773
  throw new Error("This Bill is Inactive!");
46524
46774
  }
46525
- const billId = new import_mongodb126.ObjectId(unitBillInfo?.billId);
46526
- const billInfo = await billCollection().findOne({ _id: billId });
46527
- if (!billInfo) {
46528
- throw new Error("Bill info not found");
46529
- }
46530
- if (payload.paymentStatus === "Partial Payment" /* partial */ && payload.amountPaid) {
46531
- const price = parseInt(billInfo?.price);
46532
- const amount = payload.amountPaid;
46533
- const numericPrice = typeof price === "string" ? parseInt(price) : price;
46534
- const numericAmount = typeof amount === "string" ? parseInt(amount) : amount;
46535
- if (typeof amount !== "number") {
46536
- throw new Error("Amount is not a valid number");
46537
- } else if (typeof price !== "number") {
46538
- throw new Error("Price s not a valid number");
46775
+ if (payload.paymentStatus === "partial-payment" /* PARTIAL */ && payload.amountPaid) {
46776
+ const totalAmount = parseInt(unitBillInfo.totalAmount);
46777
+ const amountPaid = payload.amountPaid;
46778
+ if (typeof totalAmount !== "number") {
46779
+ throw new Error("Total Amount is not a valid number");
46780
+ } else if (typeof amountPaid !== "number") {
46781
+ throw new Error("Amount Paid is not a valid number");
46539
46782
  }
46540
- payload.balance = numericPrice - numericAmount;
46541
- } else if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
46783
+ payload.balanceAmount = totalAmount - amountPaid;
46784
+ } else if (payload.paymentStatus === "paid" /* PAID */ && payload.amountPaid) {
46542
46785
  payload.datePaid = /* @__PURE__ */ new Date();
46543
- payload.paymentStatus = "Paid" /* paid */;
46786
+ payload.paymentStatus = "paid" /* PAID */;
46544
46787
  payload.amountPaid;
46545
46788
  payload.transaction_id;
46546
- } else if (payload.paymentStatus === "Failed" /* failed */) {
46789
+ } else if (payload.paymentStatus === "failed" /* FAILED */) {
46547
46790
  payload.amountPaid = 0;
46548
- payload.paidBy = "";
46549
- payload.datePaid = "";
46550
- payload.paymentStatus = "Failed" /* failed */;
46791
+ payload.paymentStatus = "failed" /* FAILED */;
46551
46792
  payload.transaction_id;
46552
46793
  }
46553
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46554
- payload.updatedAt = updatedAt;
46555
- const result = await collection().findOneAndUpdate({ _id: unitBillId }, { $set: payload }, { returnDocument: "after" });
46556
- return result;
46557
- } catch (error) {
46558
- throw new Error(error.message || error || "Server Internal Error");
46559
- }
46560
- };
46561
- const saveCreditCardInfo = async (payload) => {
46562
- try {
46563
- if (payload.userId)
46564
- payload.userId = new import_mongodb126.ObjectId(payload.userId);
46565
- if (payload.site)
46566
- payload.site = new import_mongodb126.ObjectId(payload.site);
46567
- if (payload.organization)
46568
- payload.organization = new import_mongodb126.ObjectId(payload.organization);
46569
- if (payload.createdBy)
46570
- payload.createdBy = new import_mongodb126.ObjectId(payload.createdBy);
46571
- const createdAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46572
- payload.createdAt = createdAt;
46573
- const result = await creditCollection().insertOne(new MCardInfo(payload));
46574
- return result;
46575
- } catch (error) {
46576
- throw new Error(error.message || error || "Server Internal Error");
46577
- }
46578
- };
46579
- const checkOutUnitBills = async (payload) => {
46580
- try {
46581
- if (payload.unitId)
46582
- payload.unitId = new import_mongodb126.ObjectId(payload.unitId);
46583
- if (payload.site)
46584
- payload.site = new import_mongodb126.ObjectId(payload.site);
46585
- if (payload.organization)
46586
- payload.organization = new import_mongodb126.ObjectId(payload.organization);
46587
- payload.createdAt = await formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46588
- const addToCart = await cartCollection().insertOne(new MUnitBillings(payload));
46589
- const unitId = payload.unitId;
46590
- const dateFormatted = formatDateString(/* @__PURE__ */ new Date(), "for-ref");
46591
- const unit = unitId?.toString().slice(-4);
46592
- const newId = new import_mongodb126.ObjectId(addToCart?.insertedId).toString().slice(-4);
46593
- const referenceNumber = `CRT${unit}${newId}${dateFormatted}`;
46594
- const result = await cartCollection().findOneAndUpdate({ _id: new import_mongodb126.ObjectId(addToCart.insertedId) }, { $set: { referenceNumber } }, { returnDocument: "after" });
46595
- return result;
46596
- } catch (error) {
46597
- throw new Error(error.message || error || "Server Internal Error");
46598
- }
46599
- };
46600
- const payUnitCart = async (refId, payload) => {
46601
- try {
46602
- if (refId)
46603
- refId = refId.toString();
46604
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46605
- const cartInfo = await cartCollection().findOne({ referenceNumber: refId });
46606
- const refNumber = cartInfo?.unitBill;
46607
- if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
46608
- payload.datePaid = /* @__PURE__ */ new Date();
46609
- payload.paymentStatus = "Paid" /* paid */;
46610
- payload.amountPaid;
46611
- } else if (payload.paymentStatus === "Failed" /* failed */) {
46612
- payload.amountPaid = 0;
46613
- payload.paidBy = "";
46614
- payload.datePaid = "";
46615
- payload.paymentStatus = "Failed" /* failed */;
46616
- }
46617
- payload.updatedAt = updatedAt;
46618
- const result = await cartCollection().findOneAndUpdate({ referenceNumber: refId }, { $set: payload }, { returnDocument: "after" });
46619
- if (!result) {
46620
- throw new Error("Failed to Process Transaction. Please Try Again Later");
46621
- } else {
46622
- for (const ref of refNumber) {
46623
- const unitBillInfo = await collection().findOne({ referenceNumber: ref });
46624
- const billId = unitBillInfo?.billId;
46625
- const billInfo = await billCollection().findOne({ _id: new import_mongodb126.ObjectId(billId) });
46626
- const billAmount = billInfo?.price;
46627
- payload.updatedAt = updatedAt;
46628
- payload.amountPaid = billAmount;
46629
- const eachRef = await payUnitBill(ref, payload);
46630
- }
46631
- if (!cartInfo) {
46632
- throw new Error("Cart info not found");
46633
- }
46634
- }
46794
+ payload.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
46795
+ const result = await unitBillingCollection().findOneAndUpdate(
46796
+ { _id: unitBillInfo._id },
46797
+ { $set: payload },
46798
+ { returnDocument: "after" }
46799
+ );
46635
46800
  return result;
46636
46801
  } catch (error) {
46637
46802
  throw new Error(error.message || error || "Server Internal Error");
46638
46803
  }
46639
- };
46640
- const getCheckedOutBillings = async (refId) => {
46641
- try {
46642
- if (refId)
46643
- refId = refId.toString();
46644
- const result = await cartCollection().aggregate([
46645
- { $match: { referenceNumber: refId } },
46646
- {
46647
- $lookup: {
46648
- from: "unit-bill",
46649
- localField: "unitBill",
46650
- foreignField: "referenceNumber",
46651
- as: "unitBill"
46652
- }
46653
- },
46654
- {
46655
- $unwind: "$unitBill"
46656
- },
46657
- {
46658
- $lookup: {
46659
- from: "bill-records",
46660
- localField: "unitBill.billId",
46661
- foreignField: "_id",
46662
- as: "billDetails"
46663
- }
46664
- },
46665
- {
46666
- $unwind: {
46667
- path: "$billDetails",
46668
- preserveNullAndEmptyArrays: true
46669
- }
46670
- },
46671
- {
46672
- $addFields: {
46673
- "unitBill.billItemName": "$billDetails.billItem"
46674
- }
46675
- },
46676
- {
46677
- $project: {
46678
- "unitBill.paidBy": 0,
46679
- "unitBill.preDueDateAlert": 0,
46680
- "unitBill.category": 0,
46681
- "unitBill.contactNumber": 0,
46682
- "unitBill.email": 0,
46683
- "unitBill.site": 0,
46684
- "unitBill.siteName": 0,
46685
- "unitBill.organization": 0,
46686
- "unitBill.billStatus": 0,
46687
- "unitBill.createdBy": 0,
46688
- "unitBill.createdAt": 0,
46689
- "unitBill.updatedAt": 0,
46690
- "billDetails": 0
46691
- // Exclude the full billDetails as it's no longer needed
46692
- }
46693
- },
46694
- {
46695
- $group: {
46696
- _id: "$_id",
46697
- unitId: { $first: "$unitId" },
46698
- referenceNumber: { $first: "$referenceNumber" },
46699
- unitBill: { $push: "$unitBill" },
46700
- paymentStatus: { $first: "$paymentStatus" },
46701
- amountPaid: { $first: "$amountPaid" },
46702
- site: { $first: "$site" },
46703
- organization: { $first: "$organization" },
46704
- paidBy: { $first: "$paidBy" },
46705
- datePaid: { $first: "$referenceNumber" },
46706
- billCategory: { $first: "$billCategory" },
46707
- billFrom: { $first: "$billFrom" },
46708
- billTo: { $first: "$billTo" },
46709
- createdBy: { $first: "$createdBy" },
46710
- createdAt: { $first: "$createdAt" },
46711
- updatedAt: { $first: "$updatedAt" },
46712
- transaction_id: { $first: "$transaction_id" }
46713
- }
46714
- }
46715
- ]).toArray();
46716
- if (!result || result.length === 0) {
46717
- return { success: false, message: "Cart Info Not Found" };
46718
- }
46719
- return result[0];
46720
- } catch (error) {
46721
- throw new Error(error.message || error || "Server Internal Error");
46722
- }
46723
- };
46724
- const cancelCheckedOutBillings = async (refId) => {
46725
- try {
46726
- if (refId)
46727
- refId = refId.toString();
46728
- const result = await cartCollection().findOneAndDelete({ referenceNumber: refId });
46729
- if (!result) {
46730
- return { success: false, message: "Cart Info Not Found" };
46731
- }
46732
- return { success: true, message: "Cart Deleted Successfully!", referenceNumber: result?.referenceNumber };
46733
- } catch (error) {
46734
- throw new Error(error.message || error || "Server Internal Error");
46735
- }
46736
- };
46737
- return {
46738
- saveCreditCardInfo,
46739
- checkOutUnitBills,
46740
- payUnitBill,
46741
- payUnitCart,
46742
- getCheckedOutBillings,
46743
- cancelCheckedOutBillings
46744
- };
46745
- };
46746
-
46747
- // src/repositories/reddot-payment.repository.ts
46748
- var import_node_server_utils217 = require("@7365admin1/node-server-utils");
46749
- var useRedDotPaymentRepo = () => {
46750
- const getDB2 = () => {
46751
- const db = import_node_server_utils217.useAtlas.getDb();
46752
- if (!db) {
46753
- throw new import_node_server_utils217.InternalServerError("Unable to connect to server.");
46754
- }
46755
- return db;
46756
- };
46757
- const collection = () => {
46758
- return getDB2().collection("unit-bill");
46759
- };
46760
- const orgCollection = () => {
46761
- return getDB2().collection("organizations");
46762
- };
46763
- const cartCollection = () => {
46764
- return getDB2().collection("checkout-cart");
46765
- };
46766
- const redDotMerchantCollection = () => {
46767
- return getDB2().collection("reddot-merchant");
46768
- };
46769
- const createRedDotAccount = async (_id, payload) => {
46770
- try {
46771
- const merchant = await redDotMerchantCollection().insertOne(payload);
46772
- if (!merchant) {
46773
- throw new Error("Failed to Add Merchant Details");
46774
- }
46775
- const merchantId = merchant?.insertedId;
46776
- const orgId = new import_mongodb127.ObjectId(_id);
46777
- const result = await orgCollection().findOneAndUpdate({ _id: orgId }, { $push: { merchant: merchantId } }, {
46778
- returnDocument: "after"
46779
- });
46780
- if (!result) {
46781
- throw new Error("Organization not found");
46782
- }
46783
- return {
46784
- success: true,
46785
- message: "Merchant Details successfully added."
46786
- };
46787
- } catch (error) {
46788
- throw new Error(error.message || error || "Server Internal Error");
46789
- }
46790
- };
46791
- const payUnitBillings = async (refId, payload) => {
46792
- const checkCart = await cartCollection().findOne({ referenceNumber: refId });
46793
- if (checkCart) {
46794
- const multiple = await PaymentBillRepo().payUnitCart(refId, payload);
46795
- if (multiple) {
46796
- return await PaymentBillRepo().getCheckedOutBillings(refId);
46797
- }
46798
- }
46799
- const single = await PaymentBillRepo().payUnitBill(refId, payload);
46800
- return single;
46801
- };
46802
- const getMerchantDetailsById = async (_id) => {
46803
- try {
46804
- if (_id)
46805
- _id = new import_mongodb127.ObjectId(_id);
46806
- const result = await redDotMerchantCollection().aggregate([
46807
- {
46808
- $match: {
46809
- _id
46810
- }
46811
- },
46812
- {
46813
- $facet: {
46814
- totalCount: [{ $count: "count" }],
46815
- items: [{ $sort: { _id: -1 } }]
46816
- }
46817
- }
46818
- ]).toArray();
46819
- const items = result[0].items;
46820
- return items;
46821
- } catch (error) {
46822
- throw new Error(error.message || error || "Server Internal Error");
46823
- }
46824
- };
46825
- return {
46826
- createRedDotAccount,
46827
- payUnitBillings,
46828
- getMerchantDetailsById
46829
- };
46804
+ }
46805
+ return { paySingleUnitBill };
46830
46806
  };
46831
46807
 
46832
46808
  // src/services/reddot-payment.service.ts
46833
46809
  var useRedDotPaymentSvc = () => {
46834
- const createRedDotAccount = async (_id, payload) => {
46835
- return useRedDotPaymentRepo().createRedDotAccount(_id, payload);
46836
- };
46810
+ const { paySingleUnitBill } = useRedDotPaymentRepo();
46837
46811
  const redirectPaymentTransaction = async (payload) => {
46838
46812
  try {
46839
46813
  const SECRET_KEY2 = payload.merchant_key;
46840
46814
  if (!payload.mid && !payload.merchant_key) {
46841
- return { success: false, message: "RDP Not Available on this account. Please Contact Management" };
46815
+ return {
46816
+ success: false,
46817
+ message: "RDP Not Available on this account. Please Contact Management"
46818
+ };
46842
46819
  }
46843
46820
  const data = {
46844
46821
  mid: payload.mid,
@@ -46861,7 +46838,9 @@ var useRedDotPaymentSvc = () => {
46861
46838
  "Content-Length": String(dataString.length)
46862
46839
  };
46863
46840
  if (!process.env.MERCHANT_PAYMENT) {
46864
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46841
+ throw new Error(
46842
+ "MERCHANT_PAYMENT environment variable is not defined."
46843
+ );
46865
46844
  }
46866
46845
  const url = process.env.MERCHANT_PAYMENT;
46867
46846
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46875,7 +46854,10 @@ var useRedDotPaymentSvc = () => {
46875
46854
  try {
46876
46855
  const SECRET_KEY2 = payload.merchant_key;
46877
46856
  if (!payload.request_mid && !payload.merchant_key) {
46878
- return { success: false, message: "RDP Not Available on this account. Please Contact Management" };
46857
+ return {
46858
+ success: false,
46859
+ message: "RDP Not Available on this account. Please Contact Management"
46860
+ };
46879
46861
  }
46880
46862
  const data = {
46881
46863
  request_mid: payload.request_mid,
@@ -46890,7 +46872,9 @@ var useRedDotPaymentSvc = () => {
46890
46872
  "Content-Type": "application/json"
46891
46873
  };
46892
46874
  if (!process.env.MERCHANT_ENQUIRY) {
46893
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46875
+ throw new Error(
46876
+ "MERCHANT_PAYMENT environment variable is not defined."
46877
+ );
46894
46878
  }
46895
46879
  const url = process.env.MERCHANT_ENQUIRY;
46896
46880
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46904,25 +46888,24 @@ var useRedDotPaymentSvc = () => {
46904
46888
  if (result.response_code === "0") {
46905
46889
  const success = {
46906
46890
  method: payload.method,
46907
- paymentStatus: "Paid" /* paid */,
46908
- amountPaid: amount,
46909
- paidBy: payer,
46891
+ paymentStatus: "paid" /* PAID */,
46892
+ amountPaid: parseInt(amount),
46910
46893
  updatedAt: invoiceDate,
46911
46894
  transaction_id: transactionId,
46912
46895
  message
46913
46896
  };
46914
- await useRedDotPaymentRepo().payUnitBillings(refId, success);
46897
+ await paySingleUnitBill(refId, success);
46915
46898
  } else if (result.response_code !== "0") {
46916
46899
  const fail = {
46917
46900
  method: payload.method,
46918
- paymentStatus: "Failed" /* failed */,
46901
+ paymentStatus: "failed" /* FAILED */,
46919
46902
  updatedAt: invoiceDate,
46920
46903
  paidBy: "",
46921
- amountPaid: "0",
46904
+ amountPaid: 0,
46922
46905
  transaction_id: transactionId,
46923
46906
  message
46924
46907
  };
46925
- await useRedDotPaymentRepo().payUnitBillings(refId, fail);
46908
+ await paySingleUnitBill(refId, fail);
46926
46909
  }
46927
46910
  return result;
46928
46911
  } catch (error) {
@@ -46942,7 +46925,9 @@ var useRedDotPaymentSvc = () => {
46942
46925
  "Content-Length": String(dataString.length)
46943
46926
  };
46944
46927
  if (!process.env.MERCHANT_PAYMENT) {
46945
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46928
+ throw new Error(
46929
+ "MERCHANT_PAYMENT environment variable is not defined."
46930
+ );
46946
46931
  }
46947
46932
  const url = process.env.MERCHANT_PAYMENT;
46948
46933
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46951,45 +46936,16 @@ var useRedDotPaymentSvc = () => {
46951
46936
  return Promise.reject(error || error.message || "Server Internal Error!");
46952
46937
  }
46953
46938
  };
46954
- const getMerchantDetailsById = async (_id) => {
46955
- return useRedDotPaymentRepo().getMerchantDetailsById(_id);
46956
- };
46957
46939
  return {
46958
- createRedDotAccount,
46959
46940
  redirectPaymentTransaction,
46960
46941
  enquirePaymentTransaction,
46961
- payInvoice,
46962
- getMerchantDetailsById
46942
+ payInvoice
46963
46943
  };
46964
46944
  };
46965
46945
 
46966
46946
  // src/controllers/reddot-payment.controller.ts
46967
46947
  var import_joi124 = __toESM(require("joi"));
46968
46948
  function useRedDotPaymentController() {
46969
- const createRedDotAccount = async (req, res) => {
46970
- try {
46971
- const data = req.body;
46972
- const id = req.params.id;
46973
- const schema2 = import_joi124.default.object({
46974
- id: import_joi124.default.string().hex().required(),
46975
- // organization id
46976
- paymentMethod: import_joi124.default.string().required(),
46977
- // payment method (e.g. "Visa / Mastercard / PayNow QR Code")
46978
- merchant_id: import_joi124.default.string().required(),
46979
- // merchant id
46980
- merchant_key: import_joi124.default.string().required()
46981
- // secret key
46982
- });
46983
- const { error } = schema2.validate({ id, ...data });
46984
- if (error) {
46985
- return res.status(400).json({ data: null, message: error.message });
46986
- }
46987
- const result = await useRedDotPaymentSvc().createRedDotAccount(id, data);
46988
- return res.json(result);
46989
- } catch (error) {
46990
- return res.status(500).json({ message: error.message || error });
46991
- }
46992
- };
46993
46949
  const redirectPaymentTransaction = async (req, res) => {
46994
46950
  try {
46995
46951
  const data = req.body;
@@ -47006,7 +46962,9 @@ function useRedDotPaymentController() {
47006
46962
  if (error) {
47007
46963
  return res.status(400).json({ data: null, message: error.message });
47008
46964
  }
47009
- const result = await useRedDotPaymentSvc().redirectPaymentTransaction(data);
46965
+ const result = await useRedDotPaymentSvc().redirectPaymentTransaction(
46966
+ data
46967
+ );
47010
46968
  return res.json(result);
47011
46969
  } catch (error) {
47012
46970
  return res.status(500).json({ message: error.message || error });
@@ -47025,43 +46983,27 @@ function useRedDotPaymentController() {
47025
46983
  if (error) {
47026
46984
  return res.status(400).json({ data: null, message: error.message });
47027
46985
  }
47028
- const result = await useRedDotPaymentSvc().enquirePaymentTransaction(data);
46986
+ const result = await useRedDotPaymentSvc().enquirePaymentTransaction(
46987
+ data
46988
+ );
47029
46989
  return res.json(result);
47030
46990
  } catch (error) {
47031
46991
  return res.status(500).json({ message: error.message || error });
47032
46992
  }
47033
46993
  };
47034
- const getMerchantDetailsById = async (req, res, next) => {
47035
- try {
47036
- const _id = req.params.id;
47037
- const schema2 = import_joi124.default.object({
47038
- _id: import_joi124.default.string().hex().required()
47039
- });
47040
- const { error } = schema2.validate({ _id });
47041
- if (error) {
47042
- return res.status(400).json({ data: null, message: error.message });
47043
- }
47044
- const result = await useRedDotPaymentSvc().getMerchantDetailsById(_id);
47045
- return res.json(result);
47046
- } catch (error) {
47047
- next(error);
47048
- }
47049
- };
47050
46994
  return {
47051
- createRedDotAccount,
47052
46995
  redirectPaymentTransaction,
47053
- enquirePaymentTransaction,
47054
- getMerchantDetailsById
46996
+ enquirePaymentTransaction
47055
46997
  };
47056
46998
  }
47057
46999
 
47058
47000
  // src/repositories/verification-v2.repo.ts
47059
- var import_node_server_utils218 = require("@7365admin1/node-server-utils");
47060
- var import_mongodb128 = require("mongodb");
47001
+ var import_node_server_utils217 = require("@7365admin1/node-server-utils");
47002
+ var import_mongodb124 = require("mongodb");
47061
47003
  function useVerificationRepoV2() {
47062
- const db = import_node_server_utils218.useAtlas.getDb();
47004
+ const db = import_node_server_utils217.useAtlas.getDb();
47063
47005
  if (!db) {
47064
- throw new import_node_server_utils218.InternalServerError("Unable to connect to server.");
47006
+ throw new import_node_server_utils217.InternalServerError("Unable to connect to server.");
47065
47007
  }
47066
47008
  const namespace_collection = "verifications";
47067
47009
  const collection = db.collection(namespace_collection);
@@ -47074,7 +47016,7 @@ function useVerificationRepoV2() {
47074
47016
  { "metadata.org": 1 }
47075
47017
  ]);
47076
47018
  } catch (error) {
47077
- throw new import_node_server_utils218.InternalServerError("Failed to create index.");
47019
+ throw new import_node_server_utils217.InternalServerError("Failed to create index.");
47078
47020
  }
47079
47021
  }
47080
47022
  async function createTextIndex() {
@@ -47083,36 +47025,36 @@ function useVerificationRepoV2() {
47083
47025
  email: "text"
47084
47026
  });
47085
47027
  } catch (error) {
47086
- throw new import_node_server_utils218.InternalServerError("Failed to create text index on email.");
47028
+ throw new import_node_server_utils217.InternalServerError("Failed to create text index on email.");
47087
47029
  }
47088
47030
  }
47089
- const { delNamespace, setCache, getCache, delCache } = (0, import_node_server_utils218.useCache)(namespace_collection);
47031
+ const { delNamespace, setCache, getCache, delCache } = (0, import_node_server_utils217.useCache)(namespace_collection);
47090
47032
  async function add(value, session) {
47091
47033
  value = new MVerificationV2(value);
47092
47034
  try {
47093
47035
  const res = await collection.insertOne(value, { session });
47094
47036
  delNamespace().then(() => {
47095
- import_node_server_utils218.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47037
+ import_node_server_utils217.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47096
47038
  }).catch((err) => {
47097
- import_node_server_utils218.logger.error(
47039
+ import_node_server_utils217.logger.error(
47098
47040
  `Failed to clear cache for namespace: ${namespace_collection}`,
47099
47041
  err
47100
47042
  );
47101
47043
  });
47102
47044
  return res.insertedId;
47103
47045
  } catch (error) {
47104
- import_node_server_utils218.logger.log({
47046
+ import_node_server_utils217.logger.log({
47105
47047
  level: "info",
47106
47048
  message: String(error)
47107
47049
  });
47108
- throw new import_node_server_utils218.InternalServerError("Server internal error.");
47050
+ throw new import_node_server_utils217.InternalServerError("Server internal error.");
47109
47051
  }
47110
47052
  }
47111
47053
  async function updateVerificationStatusById(_id, status, session) {
47112
47054
  try {
47113
- _id = new import_mongodb128.ObjectId(_id);
47055
+ _id = new import_mongodb124.ObjectId(_id);
47114
47056
  } catch (error) {
47115
- throw new import_node_server_utils218.BadRequestError("Invalid verification ID format.");
47057
+ throw new import_node_server_utils217.BadRequestError("Invalid verification ID format.");
47116
47058
  }
47117
47059
  try {
47118
47060
  const result = await collection.updateOne(
@@ -47121,24 +47063,24 @@ function useVerificationRepoV2() {
47121
47063
  { session }
47122
47064
  );
47123
47065
  delNamespace().then(() => {
47124
- import_node_server_utils218.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47066
+ import_node_server_utils217.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47125
47067
  }).catch((err) => {
47126
- import_node_server_utils218.logger.error(
47068
+ import_node_server_utils217.logger.error(
47127
47069
  `Failed to clear cache for namespace: ${namespace_collection}`,
47128
47070
  err
47129
47071
  );
47130
47072
  });
47131
47073
  return result;
47132
47074
  } catch (error) {
47133
- throw new import_node_server_utils218.InternalServerError("Error updating verification status.");
47075
+ throw new import_node_server_utils217.InternalServerError("Error updating verification status.");
47134
47076
  }
47135
47077
  }
47136
47078
  async function getByVerificationCode(verificationCode) {
47137
47079
  try {
47138
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, { verificationCode });
47080
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, { verificationCode });
47139
47081
  const cachedData = await getCache(cacheKey);
47140
47082
  if (cachedData) {
47141
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47083
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47142
47084
  return cachedData;
47143
47085
  }
47144
47086
  const query = {
@@ -47147,35 +47089,35 @@ function useVerificationRepoV2() {
47147
47089
  };
47148
47090
  const data = await collection.findOne(query);
47149
47091
  setCache(cacheKey, data, 15 * 60).then(() => {
47150
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47092
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47151
47093
  }).catch((err) => {
47152
- import_node_server_utils218.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47094
+ import_node_server_utils217.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47153
47095
  });
47154
47096
  return data;
47155
47097
  } catch (error) {
47156
- throw new import_node_server_utils218.InternalServerError(
47098
+ throw new import_node_server_utils217.InternalServerError(
47157
47099
  "Internal server error, failed to retrieve verification."
47158
47100
  );
47159
47101
  }
47160
47102
  }
47161
47103
  async function getVerificationById(id) {
47162
47104
  try {
47163
- const _id = (0, import_node_server_utils218.toObjectId)(id);
47164
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, { id });
47105
+ const _id = (0, import_node_server_utils217.toObjectId)(id);
47106
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, { id });
47165
47107
  const cachedData = await getCache(cacheKey);
47166
47108
  if (cachedData) {
47167
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47109
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47168
47110
  return cachedData;
47169
47111
  }
47170
47112
  const data = await collection.findOne({ _id });
47171
47113
  setCache(cacheKey, data, 15 * 60).then(() => {
47172
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47114
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47173
47115
  }).catch((err) => {
47174
- import_node_server_utils218.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47116
+ import_node_server_utils217.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47175
47117
  });
47176
47118
  return data;
47177
47119
  } catch (error) {
47178
- throw new import_node_server_utils218.InternalServerError(
47120
+ throw new import_node_server_utils217.InternalServerError(
47179
47121
  "Internal server error, failed to retrieve verification."
47180
47122
  );
47181
47123
  }
@@ -47215,10 +47157,10 @@ function useVerificationRepoV2() {
47215
47157
  query.email = email;
47216
47158
  cacheOptions.email = email;
47217
47159
  }
47218
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, cacheOptions);
47160
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, cacheOptions);
47219
47161
  const cachedData = await getCache(cacheKey);
47220
47162
  if (cachedData) {
47221
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47163
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47222
47164
  return cachedData;
47223
47165
  }
47224
47166
  try {
@@ -47239,23 +47181,23 @@ function useVerificationRepoV2() {
47239
47181
  }
47240
47182
  ]).toArray();
47241
47183
  const length = await collection.countDocuments(query);
47242
- const data = (0, import_node_server_utils218.paginate)(items, page, limit, length);
47184
+ const data = (0, import_node_server_utils217.paginate)(items, page, limit, length);
47243
47185
  setCache(cacheKey, data, 15 * 60).then(() => {
47244
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47186
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47245
47187
  }).catch((err) => {
47246
- import_node_server_utils218.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47188
+ import_node_server_utils217.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
47247
47189
  });
47248
47190
  return data;
47249
47191
  } catch (error) {
47250
- import_node_server_utils218.logger.log({ level: "error", message: `${error}` });
47192
+ import_node_server_utils217.logger.log({ level: "error", message: `${error}` });
47251
47193
  throw error;
47252
47194
  }
47253
47195
  }
47254
47196
  async function updateStatusById(_id, status, session) {
47255
47197
  try {
47256
- _id = new import_mongodb128.ObjectId(_id);
47198
+ _id = new import_mongodb124.ObjectId(_id);
47257
47199
  } catch (error) {
47258
- throw new import_node_server_utils218.BadRequestError("Invalid verification ID format.");
47200
+ throw new import_node_server_utils217.BadRequestError("Invalid verification ID format.");
47259
47201
  }
47260
47202
  try {
47261
47203
  const result = await collection.updateOne(
@@ -47264,22 +47206,22 @@ function useVerificationRepoV2() {
47264
47206
  { session }
47265
47207
  );
47266
47208
  delNamespace().then(() => {
47267
- import_node_server_utils218.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47209
+ import_node_server_utils217.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47268
47210
  }).catch((err) => {
47269
- import_node_server_utils218.logger.error(
47211
+ import_node_server_utils217.logger.error(
47270
47212
  `Failed to clear cache for namespace: ${namespace_collection}`,
47271
47213
  err
47272
47214
  );
47273
47215
  });
47274
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, { _id });
47216
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, { _id });
47275
47217
  delCache(cacheKey).then(() => {
47276
- import_node_server_utils218.logger.info(`Cache deleted for key: ${cacheKey}`);
47218
+ import_node_server_utils217.logger.info(`Cache deleted for key: ${cacheKey}`);
47277
47219
  }).catch((err) => {
47278
- import_node_server_utils218.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
47220
+ import_node_server_utils217.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
47279
47221
  });
47280
47222
  return result;
47281
47223
  } catch (error) {
47282
- throw new import_node_server_utils218.InternalServerError("Error updating verification status.");
47224
+ throw new import_node_server_utils217.InternalServerError("Error updating verification status.");
47283
47225
  }
47284
47226
  }
47285
47227
  return {
@@ -47295,7 +47237,7 @@ function useVerificationRepoV2() {
47295
47237
  }
47296
47238
 
47297
47239
  // src/services/verification-v2.service.ts
47298
- var import_node_server_utils219 = require("@7365admin1/node-server-utils");
47240
+ var import_node_server_utils218 = require("@7365admin1/node-server-utils");
47299
47241
  var import_crypto2 = __toESM(require("crypto"));
47300
47242
  var import_joi125 = __toESM(require("joi"));
47301
47243
  function useVerificationServiceV2() {
@@ -47306,7 +47248,7 @@ function useVerificationServiceV2() {
47306
47248
  email: MAILER_EMAIL,
47307
47249
  password: MAILER_PASSWORD
47308
47250
  };
47309
- const mailer = new import_node_server_utils219.useMailer(MailerConfig);
47251
+ const mailer = new import_node_server_utils218.useMailer(MailerConfig);
47310
47252
  const {
47311
47253
  add: _add,
47312
47254
  updateVerificationStatusById: _updateVerificationStatusById,
@@ -47321,31 +47263,31 @@ function useVerificationServiceV2() {
47321
47263
  const { getSiteById } = useSiteRepo();
47322
47264
  function errorByType(type, status) {
47323
47265
  if ((type === "user-invite" /* USER_INVITE */ || type === "member-invite" /* MEMBER_INVITE */ || type === "service-provider-invite" /* SERVICE_PROVIDER_INVITE */ || type === "service-provider-create-org" /* SERVICE_PROVIDER_CREATE_ORG */) && status === "expired" /* EXPIRED */) {
47324
- throw new import_node_server_utils219.BadRequestError(
47266
+ throw new import_node_server_utils218.BadRequestError(
47325
47267
  "Invitation has already expired, please contact admin to resend the invitation."
47326
47268
  );
47327
47269
  }
47328
47270
  if (type === "user-sign-up" /* USER_SIGN_UP */ && status === "expired" /* EXPIRED */) {
47329
- throw new import_node_server_utils219.BadRequestError(
47271
+ throw new import_node_server_utils218.BadRequestError(
47330
47272
  "Sign up verification has expired, please sign up again to get a new verification link."
47331
47273
  );
47332
47274
  }
47333
47275
  if ((type === "user-invite" /* USER_INVITE */ || type === "member-invite" /* MEMBER_INVITE */ || type === "service-provider-invite" /* SERVICE_PROVIDER_INVITE */ || type === "service-provider-create-org" /* SERVICE_PROVIDER_CREATE_ORG */) && status === "complete" /* COMPLETE */) {
47334
- throw new import_node_server_utils219.BadRequestError(
47276
+ throw new import_node_server_utils218.BadRequestError(
47335
47277
  "User already registered, please login to continue."
47336
47278
  );
47337
47279
  }
47338
47280
  if (type === "forget-password" /* FORGET_PASSWORD */ && status === "complete" /* COMPLETE */) {
47339
- throw new import_node_server_utils219.BadRequestError(
47281
+ throw new import_node_server_utils218.BadRequestError(
47340
47282
  "Forget password verification has already been used, please request a new one."
47341
47283
  );
47342
47284
  }
47343
47285
  if (type === "forget-password" /* FORGET_PASSWORD */ && status === "expired" /* EXPIRED */) {
47344
- throw new import_node_server_utils219.BadRequestError(
47286
+ throw new import_node_server_utils218.BadRequestError(
47345
47287
  "Forget password verification has expired, please request a new one."
47346
47288
  );
47347
47289
  }
47348
- throw new import_node_server_utils219.BadRequestError("Invalid verification.");
47290
+ throw new import_node_server_utils218.BadRequestError("Invalid verification.");
47349
47291
  }
47350
47292
  function generateVerificationCode(length = 8) {
47351
47293
  const chars = "0123456789";
@@ -47360,17 +47302,17 @@ function useVerificationServiceV2() {
47360
47302
  email,
47361
47303
  metadata
47362
47304
  }) {
47363
- const session = import_node_server_utils219.useAtlas.getClient()?.startSession();
47305
+ const session = import_node_server_utils218.useAtlas.getClient()?.startSession();
47364
47306
  try {
47365
47307
  session?.startTransaction();
47366
47308
  const user = await _getUserByEmailStatus(email);
47367
47309
  if (user) {
47368
- throw new import_node_server_utils219.BadRequestError(
47310
+ throw new import_node_server_utils218.BadRequestError(
47369
47311
  `Email ${email} is already registered, please login to continue.`
47370
47312
  );
47371
47313
  }
47372
47314
  const verificationCode = generateVerificationCode(6);
47373
- metadata.password = await (0, import_node_server_utils219.hashPassword)(metadata.password);
47315
+ metadata.password = await (0, import_node_server_utils218.hashPassword)(metadata.password);
47374
47316
  metadata.verificationCode = verificationCode;
47375
47317
  const value = {
47376
47318
  type: "user-sign-up" /* USER_SIGN_UP */,
@@ -47382,8 +47324,8 @@ function useVerificationServiceV2() {
47382
47324
  };
47383
47325
  const res = await _add(value);
47384
47326
  const dir = __dirname;
47385
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, "./public/handlebars/sign-up-v2");
47386
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47327
+ const filePath = (0, import_node_server_utils218.getDirectory)(dir, "./public/handlebars/sign-up-v2");
47328
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47387
47329
  context: {
47388
47330
  email,
47389
47331
  validity: "15 minutes",
@@ -47397,7 +47339,7 @@ function useVerificationServiceV2() {
47397
47339
  html: emailContent,
47398
47340
  sender: "iService365" /* ISERVICE365 */
47399
47341
  }).catch((error) => {
47400
- import_node_server_utils219.logger.log({
47342
+ import_node_server_utils218.logger.log({
47401
47343
  level: "error",
47402
47344
  message: `Error sending user invite email: ${error}`
47403
47345
  });
@@ -47412,21 +47354,21 @@ function useVerificationServiceV2() {
47412
47354
  }
47413
47355
  }
47414
47356
  async function verify(verificationCode) {
47415
- const session = import_node_server_utils219.useAtlas.getClient()?.startSession();
47357
+ const session = import_node_server_utils218.useAtlas.getClient()?.startSession();
47416
47358
  try {
47417
47359
  session?.startTransaction();
47418
47360
  const item = await _getByVerificationCode(verificationCode);
47419
47361
  if (!item) {
47420
- throw new import_node_server_utils219.NotFoundError("Verification not found.");
47362
+ throw new import_node_server_utils218.NotFoundError("Verification not found.");
47421
47363
  }
47422
47364
  switch (item.status) {
47423
47365
  case "expired" /* EXPIRED */:
47424
47366
  errorByType(item.type, "expired" /* EXPIRED */);
47425
47367
  break;
47426
47368
  case "cancelled" /* CANCELLED */:
47427
- throw new import_node_server_utils219.BadRequestError("Verification already cancelled.");
47369
+ throw new import_node_server_utils218.BadRequestError("Verification already cancelled.");
47428
47370
  case "complete" /* COMPLETE */:
47429
- throw new import_node_server_utils219.BadRequestError("Verification already completed.");
47371
+ throw new import_node_server_utils218.BadRequestError("Verification already completed.");
47430
47372
  }
47431
47373
  const expiration = new Date(item.expireAt).getTime();
47432
47374
  const now = (/* @__PURE__ */ new Date()).getTime();
@@ -47442,7 +47384,7 @@ function useVerificationServiceV2() {
47442
47384
  return { _id, type, email, status, expireAt };
47443
47385
  } catch (error) {
47444
47386
  await session?.abortTransaction();
47445
- import_node_server_utils219.logger.log({
47387
+ import_node_server_utils218.logger.log({
47446
47388
  level: "info",
47447
47389
  message: `Error verifying user invitation: ${error}`
47448
47390
  });
@@ -47479,11 +47421,11 @@ function useVerificationServiceV2() {
47479
47421
  value.type = type;
47480
47422
  const res = await _add(value);
47481
47423
  const dir = __dirname;
47482
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, `./public/handlebars/${type}`);
47424
+ const filePath = (0, import_node_server_utils218.getDirectory)(dir, `./public/handlebars/${type}`);
47483
47425
  const isMember = type === "member-invite" /* MEMBER_INVITE */;
47484
47426
  const subject = isMember ? "Member Invite" /* _MEMBER_INVITE */ : "User Invite" /* _USER_INVITE */;
47485
47427
  const link = `${APP_MAIN}/verify/${isMember ? "membership" /* MEMBERSHIP */ : "invitation" /* INVITATION */}/${res}`;
47486
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47428
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47487
47429
  context: {
47488
47430
  email: userName,
47489
47431
  validity: VERIFICATION_USER_INVITE_DURATION,
@@ -47497,7 +47439,7 @@ function useVerificationServiceV2() {
47497
47439
  html: emailContent,
47498
47440
  sender: "iService365" /* ISERVICE365 */
47499
47441
  }).catch((error) => {
47500
- import_node_server_utils219.logger.log({
47442
+ import_node_server_utils218.logger.log({
47501
47443
  level: "error",
47502
47444
  message: `Error sending user ${type} email: ${error}`
47503
47445
  });
@@ -47527,8 +47469,8 @@ function useVerificationServiceV2() {
47527
47469
  });
47528
47470
  if (error) {
47529
47471
  const messages = error.details.map((d) => d.message).join(", ");
47530
- import_node_server_utils219.logger.log({ level: "error", message: messages });
47531
- throw new import_node_server_utils219.BadRequestError(`Invalid input: ${error.message}`);
47472
+ import_node_server_utils218.logger.log({ level: "error", message: messages });
47473
+ throw new import_node_server_utils218.BadRequestError(`Invalid input: ${error.message}`);
47532
47474
  }
47533
47475
  let subject = "Service Provider Invite" /* _SERVICE_PROVIDER_INVITE */;
47534
47476
  const value = {
@@ -47553,9 +47495,9 @@ function useVerificationServiceV2() {
47553
47495
  }
47554
47496
  const res = await _add(value);
47555
47497
  const dir = __dirname;
47556
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, `./public/handlebars/${value.type}`);
47498
+ const filePath = (0, import_node_server_utils218.getDirectory)(dir, `./public/handlebars/${value.type}`);
47557
47499
  const link = org ? `${APP_MAIN}/verify/${value.type}/${res}` : `${APP_ORG}/organizations/create?email=${email}`;
47558
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47500
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47559
47501
  context: {
47560
47502
  email: org?.name || email,
47561
47503
  validity: VERIFICATION_USER_INVITE_DURATION,
@@ -47569,7 +47511,7 @@ function useVerificationServiceV2() {
47569
47511
  html: emailContent,
47570
47512
  sender: "iService365" /* ISERVICE365 */
47571
47513
  }).catch((error2) => {
47572
- import_node_server_utils219.logger.log({
47514
+ import_node_server_utils218.logger.log({
47573
47515
  level: "error",
47574
47516
  message: `Error sending user ${value.type} email: ${error2}`
47575
47517
  });
@@ -47591,8 +47533,8 @@ function useVerificationServiceV2() {
47591
47533
  const user = await _getUserByEmail(email);
47592
47534
  const res = await _add(value);
47593
47535
  const dir = __dirname;
47594
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, "./public/handlebars/forget-password");
47595
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47536
+ const filePath = (0, import_node_server_utils218.getDirectory)(dir, "./public/handlebars/forget-password");
47537
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47596
47538
  context: {
47597
47539
  userName: user?.name,
47598
47540
  validity: VERIFICATION_FORGET_PASSWORD_DURATION,
@@ -47606,21 +47548,21 @@ function useVerificationServiceV2() {
47606
47548
  sender: "iService365" /* ISERVICE365 */,
47607
47549
  html: emailContent
47608
47550
  }).catch((error) => {
47609
- import_node_server_utils219.logger.log({
47551
+ import_node_server_utils218.logger.log({
47610
47552
  level: "error",
47611
47553
  message: `Error sending forget password email: ${error}`
47612
47554
  });
47613
47555
  });
47614
47556
  return "Successfully created a link to reset password. Please check your email.";
47615
47557
  } catch (error) {
47616
- throw new import_node_server_utils219.InternalServerError("Failed to create forget password link.");
47558
+ throw new import_node_server_utils218.InternalServerError("Failed to create forget password link.");
47617
47559
  }
47618
47560
  }
47619
47561
  async function cancelUserInvitation(id) {
47620
47562
  try {
47621
47563
  await _updateStatusById(id, "cancelled");
47622
47564
  } catch (error) {
47623
- throw new import_node_server_utils219.InternalServerError(
47565
+ throw new import_node_server_utils218.InternalServerError(
47624
47566
  `Error cancelling user invitation: ${error}`
47625
47567
  );
47626
47568
  }
@@ -47636,7 +47578,7 @@ function useVerificationServiceV2() {
47636
47578
  }
47637
47579
 
47638
47580
  // src/controllers/verification-v2.controller.ts
47639
- var import_node_server_utils220 = require("@7365admin1/node-server-utils");
47581
+ var import_node_server_utils219 = require("@7365admin1/node-server-utils");
47640
47582
  var import_joi126 = __toESM(require("joi"));
47641
47583
  function useVerificationControllerV2() {
47642
47584
  const {
@@ -47658,15 +47600,15 @@ function useVerificationControllerV2() {
47658
47600
  );
47659
47601
  if (error) {
47660
47602
  const messages = error.details.map((d) => d.message).join(", ");
47661
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47662
- next(new import_node_server_utils220.BadRequestError(messages));
47603
+ import_node_server_utils219.logger.log({ level: "error", message: messages });
47604
+ next(new import_node_server_utils219.BadRequestError(messages));
47663
47605
  return;
47664
47606
  }
47665
47607
  const message = await _verify(value.verificationCode);
47666
47608
  res.json(message);
47667
47609
  return;
47668
47610
  } catch (error) {
47669
- import_node_server_utils220.logger.log({ level: "error", message: `${error.message}` });
47611
+ import_node_server_utils219.logger.log({ level: "error", message: `${error.message}` });
47670
47612
  next(error);
47671
47613
  return;
47672
47614
  }
@@ -47684,8 +47626,8 @@ function useVerificationControllerV2() {
47684
47626
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47685
47627
  if (error) {
47686
47628
  const messages = error.details.map((d) => d.message).join(", ");
47687
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47688
- next(new import_node_server_utils220.BadRequestError(messages));
47629
+ import_node_server_utils219.logger.log({ level: "error", message: messages });
47630
+ next(new import_node_server_utils219.BadRequestError(messages));
47689
47631
  return;
47690
47632
  }
47691
47633
  const { email, app, role, name, org, siteId, siteName } = value;
@@ -47704,7 +47646,7 @@ function useVerificationControllerV2() {
47704
47646
  res.status(201).json({ message: "Successfully invited user." });
47705
47647
  return;
47706
47648
  } catch (error2) {
47707
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47649
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47708
47650
  next(error2);
47709
47651
  return;
47710
47652
  }
@@ -47719,8 +47661,8 @@ function useVerificationControllerV2() {
47719
47661
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47720
47662
  if (error) {
47721
47663
  const messages = error.details.map((d) => d.message).join(", ");
47722
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47723
- next(new import_node_server_utils220.BadRequestError(messages));
47664
+ import_node_server_utils219.logger.log({ level: "error", message: messages });
47665
+ next(new import_node_server_utils219.BadRequestError(messages));
47724
47666
  return;
47725
47667
  }
47726
47668
  try {
@@ -47733,7 +47675,7 @@ function useVerificationControllerV2() {
47733
47675
  res.cookie("service-provider-email", value.email, cookieOptions).json({ message: "Successfully invited service provider." });
47734
47676
  return;
47735
47677
  } catch (error2) {
47736
- import_node_server_utils220.logger.log({ level: "error", message: `controller - ${error2.message}` });
47678
+ import_node_server_utils219.logger.log({ level: "error", message: `controller - ${error2.message}` });
47737
47679
  next(error2);
47738
47680
  return;
47739
47681
  }
@@ -47745,8 +47687,8 @@ function useVerificationControllerV2() {
47745
47687
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47746
47688
  if (error) {
47747
47689
  const messages = error.details.map((d) => d.message).join(", ");
47748
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47749
- next(new import_node_server_utils220.BadRequestError(messages));
47690
+ import_node_server_utils219.logger.log({ level: "error", message: messages });
47691
+ next(new import_node_server_utils219.BadRequestError(messages));
47750
47692
  return;
47751
47693
  }
47752
47694
  const { email } = value;
@@ -47757,7 +47699,7 @@ function useVerificationControllerV2() {
47757
47699
  });
47758
47700
  return;
47759
47701
  } catch (error2) {
47760
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47702
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47761
47703
  next(error2);
47762
47704
  return;
47763
47705
  }
@@ -47777,8 +47719,8 @@ function useVerificationControllerV2() {
47777
47719
  const { error, value } = schema2.validate(req.query);
47778
47720
  if (error) {
47779
47721
  const messages = error.details.map((d) => d.message).join(", ");
47780
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47781
- next(new import_node_server_utils220.BadRequestError(messages));
47722
+ import_node_server_utils219.logger.log({ level: "error", message: messages });
47723
+ next(new import_node_server_utils219.BadRequestError(messages));
47782
47724
  return;
47783
47725
  }
47784
47726
  const { search, page, status, app, email, type } = value;
@@ -47794,7 +47736,7 @@ function useVerificationControllerV2() {
47794
47736
  res.json(data);
47795
47737
  return;
47796
47738
  } catch (error2) {
47797
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47739
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47798
47740
  next(error2);
47799
47741
  return;
47800
47742
  }
@@ -47804,8 +47746,8 @@ function useVerificationControllerV2() {
47804
47746
  const otpId = req.params.id;
47805
47747
  const { error } = validation.validate(otpId);
47806
47748
  if (error) {
47807
- import_node_server_utils220.logger.log({ level: "error", message: `${error.message}` });
47808
- next(new import_node_server_utils220.BadRequestError(error.message));
47749
+ import_node_server_utils219.logger.log({ level: "error", message: `${error.message}` });
47750
+ next(new import_node_server_utils219.BadRequestError(error.message));
47809
47751
  return;
47810
47752
  }
47811
47753
  try {
@@ -47815,7 +47757,7 @@ function useVerificationControllerV2() {
47815
47757
  });
47816
47758
  return;
47817
47759
  } catch (error2) {
47818
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47760
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47819
47761
  next(error2);
47820
47762
  return;
47821
47763
  }
@@ -47832,38 +47774,38 @@ function useVerificationControllerV2() {
47832
47774
 
47833
47775
  // src/controllers/auth-v2.controller.ts
47834
47776
  var import_joi127 = __toESM(require("joi"));
47835
- var import_node_server_utils224 = require("@7365admin1/node-server-utils");
47777
+ var import_node_server_utils223 = require("@7365admin1/node-server-utils");
47836
47778
 
47837
47779
  // src/services/auth-v2.service.ts
47838
- var import_node_server_utils222 = require("@7365admin1/node-server-utils");
47780
+ var import_node_server_utils221 = require("@7365admin1/node-server-utils");
47839
47781
  var import_uuid2 = require("uuid");
47840
47782
 
47841
47783
  // src/repositories/user-v2.repo.ts
47842
- var import_mongodb129 = require("mongodb");
47843
- var import_node_server_utils221 = require("@7365admin1/node-server-utils");
47784
+ var import_mongodb125 = require("mongodb");
47785
+ var import_node_server_utils220 = require("@7365admin1/node-server-utils");
47844
47786
  function useUserRepoV2() {
47845
47787
  const { updateFeedbackCreatedByName } = useFeedbackRepo();
47846
47788
  const { updateWorkOrderCreatedByName } = useWorkOrderRepo();
47847
47789
  const { updateUserNameBySignatureId } = useOccurrenceEntryRepo();
47848
- const db = import_node_server_utils221.useAtlas.getDb();
47790
+ const db = import_node_server_utils220.useAtlas.getDb();
47849
47791
  if (!db) {
47850
- throw new import_node_server_utils221.InternalServerError("Unable to connect to server.");
47792
+ throw new import_node_server_utils220.InternalServerError("Unable to connect to server.");
47851
47793
  }
47852
47794
  const namespace_collection = "users";
47853
47795
  const collection = db.collection(namespace_collection);
47854
- const { delNamespace, setCache, getCache, delCache } = (0, import_node_server_utils221.useCache)(namespace_collection);
47796
+ const { delNamespace, setCache, getCache, delCache } = (0, import_node_server_utils220.useCache)(namespace_collection);
47855
47797
  async function createIndex() {
47856
47798
  try {
47857
47799
  await collection.createIndexes([{ key: { email: 1 } }]);
47858
47800
  } catch (error) {
47859
- throw new import_node_server_utils221.InternalServerError("Failed to create text index on user.");
47801
+ throw new import_node_server_utils220.InternalServerError("Failed to create text index on user.");
47860
47802
  }
47861
47803
  }
47862
47804
  async function createTextIndex() {
47863
47805
  try {
47864
47806
  await collection.createIndex({ name: "text", email: "text" });
47865
47807
  } catch (error) {
47866
- throw new import_node_server_utils221.InternalServerError("Failed to create text index on user.");
47808
+ throw new import_node_server_utils220.InternalServerError("Failed to create text index on user.");
47867
47809
  }
47868
47810
  }
47869
47811
  async function createUniqueIndex() {
@@ -47873,7 +47815,7 @@ function useUserRepoV2() {
47873
47815
  { unique: true }
47874
47816
  );
47875
47817
  } catch (error) {
47876
- throw new import_node_server_utils221.InternalServerError("Failed to create unique index on user.");
47818
+ throw new import_node_server_utils220.InternalServerError("Failed to create unique index on user.");
47877
47819
  }
47878
47820
  }
47879
47821
  async function createUser(value, session) {
@@ -47881,71 +47823,71 @@ function useUserRepoV2() {
47881
47823
  value = MUser(value);
47882
47824
  const res = await collection.insertOne(value, { session });
47883
47825
  delNamespace().then(
47884
- () => import_node_server_utils221.logger.info(`Cache cleared for namespace: ${namespace_collection}`)
47826
+ () => import_node_server_utils220.logger.info(`Cache cleared for namespace: ${namespace_collection}`)
47885
47827
  ).catch(
47886
- (err) => import_node_server_utils221.logger.error(
47828
+ (err) => import_node_server_utils220.logger.error(
47887
47829
  `Failed to clear cache for namespace: ${namespace_collection}`,
47888
47830
  err
47889
47831
  )
47890
47832
  );
47891
47833
  return res.insertedId;
47892
47834
  } catch (error) {
47893
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
47835
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
47894
47836
  if (error.message.includes("duplicate")) {
47895
- throw new import_node_server_utils221.BadRequestError("User already exists.");
47837
+ throw new import_node_server_utils220.BadRequestError("User already exists.");
47896
47838
  }
47897
47839
  throw error;
47898
47840
  }
47899
47841
  }
47900
47842
  async function getUserByEmail(email) {
47901
47843
  try {
47902
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { email });
47844
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { email });
47903
47845
  const cachedData = await getCache(cacheKey);
47904
47846
  if (cachedData) {
47905
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47847
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47906
47848
  return cachedData;
47907
47849
  }
47908
47850
  const data = await collection.findOne({
47909
47851
  email: { $regex: `^${email}$`, $options: "i" }
47910
47852
  });
47911
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47912
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47853
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47854
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47913
47855
  );
47914
47856
  return data;
47915
47857
  } catch (error) {
47916
- throw new import_node_server_utils221.InternalServerError("Failed to get user by email.");
47858
+ throw new import_node_server_utils220.InternalServerError("Failed to get user by email.");
47917
47859
  }
47918
47860
  }
47919
47861
  async function getUserByEmailStatus(email) {
47920
47862
  try {
47921
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, {
47863
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, {
47922
47864
  email,
47923
47865
  status: "complete" /* COMPLETE */
47924
47866
  });
47925
47867
  const cachedData = await getCache(cacheKey);
47926
47868
  if (cachedData) {
47927
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47869
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47928
47870
  return cachedData;
47929
47871
  }
47930
47872
  const data = await collection.findOne({
47931
47873
  email: { $regex: `^${email}$`, $options: "i" },
47932
47874
  status: "complete" /* COMPLETE */
47933
47875
  });
47934
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47935
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47876
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47877
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47936
47878
  );
47937
47879
  return data;
47938
47880
  } catch (error) {
47939
- throw new import_node_server_utils221.InternalServerError("Failed to get user by email.");
47881
+ throw new import_node_server_utils220.InternalServerError("Failed to get user by email.");
47940
47882
  }
47941
47883
  }
47942
47884
  async function getUserById(id) {
47943
- const _id = (0, import_node_server_utils221.toObjectId)(id);
47885
+ const _id = (0, import_node_server_utils220.toObjectId)(id);
47944
47886
  try {
47945
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { id });
47887
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { id });
47946
47888
  const cachedData = await getCache(cacheKey);
47947
47889
  if (cachedData) {
47948
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47890
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47949
47891
  return cachedData;
47950
47892
  }
47951
47893
  const results = await collection.aggregate([
@@ -47968,52 +47910,52 @@ function useUserRepoV2() {
47968
47910
  ]).toArray();
47969
47911
  const data = results.length > 0 ? results[0] : null;
47970
47912
  if (!data)
47971
- throw new import_node_server_utils221.NotFoundError("User not found.");
47972
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47973
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47913
+ throw new import_node_server_utils220.NotFoundError("User not found.");
47914
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47915
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47974
47916
  );
47975
47917
  return data;
47976
47918
  } catch (error) {
47977
- if (error instanceof import_node_server_utils221.AppError)
47919
+ if (error instanceof import_node_server_utils220.AppError)
47978
47920
  throw error;
47979
- throw new import_node_server_utils221.InternalServerError("Failed to get user by id.");
47921
+ throw new import_node_server_utils220.InternalServerError("Failed to get user by id.");
47980
47922
  }
47981
47923
  }
47982
47924
  async function getUserByReferralCode(referralCode) {
47983
47925
  try {
47984
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { referralCode });
47926
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { referralCode });
47985
47927
  const cachedData = await getCache(cacheKey);
47986
47928
  if (cachedData) {
47987
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47929
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47988
47930
  return cachedData;
47989
47931
  }
47990
47932
  const data = await collection.findOne({ referralCode });
47991
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47992
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47933
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47934
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47993
47935
  );
47994
47936
  return data;
47995
47937
  } catch (error) {
47996
- throw new import_node_server_utils221.InternalServerError("Failed to get user by referral code.");
47938
+ throw new import_node_server_utils220.InternalServerError("Failed to get user by referral code.");
47997
47939
  }
47998
47940
  }
47999
47941
  async function getByEmailApp(email, app) {
48000
47942
  try {
48001
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { email, app });
47943
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { email, app });
48002
47944
  const cachedData = await getCache(cacheKey);
48003
47945
  if (cachedData) {
48004
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47946
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
48005
47947
  return cachedData;
48006
47948
  }
48007
47949
  const data = await collection.findOne({
48008
47950
  email,
48009
47951
  "roles.app": app
48010
47952
  });
48011
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
48012
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
47953
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47954
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
48013
47955
  );
48014
47956
  return data;
48015
47957
  } catch (error) {
48016
- throw new import_node_server_utils221.InternalServerError("Failed to get user by email and app.");
47958
+ throw new import_node_server_utils220.InternalServerError("Failed to get user by email and app.");
48017
47959
  }
48018
47960
  }
48019
47961
  async function getUsersByOrgId({
@@ -48040,24 +47982,24 @@ function useUserRepoV2() {
48040
47982
  }
48041
47983
  if (organization) {
48042
47984
  try {
48043
- query.defaultOrg = new import_mongodb129.ObjectId(organization);
47985
+ query.defaultOrg = new import_mongodb125.ObjectId(organization);
48044
47986
  cacheOptions.organization = organization.toString();
48045
47987
  } catch (error) {
48046
- throw new import_node_server_utils221.BadRequestError("Invalid organization ID format.");
47988
+ throw new import_node_server_utils220.BadRequestError("Invalid organization ID format.");
48047
47989
  }
48048
47990
  }
48049
47991
  delNamespace().then(() => {
48050
- import_node_server_utils221.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
47992
+ import_node_server_utils220.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
48051
47993
  }).catch((err) => {
48052
- import_node_server_utils221.logger.error(
47994
+ import_node_server_utils220.logger.error(
48053
47995
  `Failed to clear cache for namespace: ${namespace_collection}`,
48054
47996
  err
48055
47997
  );
48056
47998
  });
48057
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, cacheOptions);
47999
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, cacheOptions);
48058
48000
  const cachedData = await getCache(cacheKey);
48059
48001
  if (cachedData) {
48060
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
48002
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
48061
48003
  return cachedData;
48062
48004
  }
48063
48005
  try {
@@ -48077,15 +48019,15 @@ function useUserRepoV2() {
48077
48019
  }
48078
48020
  ]).toArray();
48079
48021
  const length = await collection.countDocuments(query);
48080
- const data = (0, import_node_server_utils221.paginate)(items, page, limit, length);
48022
+ const data = (0, import_node_server_utils220.paginate)(items, page, limit, length);
48081
48023
  setCache(cacheKey, data, 15 * 60).then(() => {
48082
- import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`);
48024
+ import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`);
48083
48025
  }).catch((err) => {
48084
- import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
48026
+ import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
48085
48027
  });
48086
48028
  return data;
48087
48029
  } catch (error) {
48088
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
48030
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
48089
48031
  throw error;
48090
48032
  }
48091
48033
  }
@@ -48111,17 +48053,17 @@ function useUserRepoV2() {
48111
48053
  cacheOptions.type = type;
48112
48054
  }
48113
48055
  delNamespace().then(
48114
- () => import_node_server_utils221.logger.info(`Cache cleared for namespace: ${namespace_collection}`)
48056
+ () => import_node_server_utils220.logger.info(`Cache cleared for namespace: ${namespace_collection}`)
48115
48057
  ).catch(
48116
- (err) => import_node_server_utils221.logger.error(
48058
+ (err) => import_node_server_utils220.logger.error(
48117
48059
  `Failed to clear cache for namespace: ${namespace_collection}`,
48118
48060
  err
48119
48061
  )
48120
48062
  );
48121
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, cacheOptions);
48063
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, cacheOptions);
48122
48064
  const cachedData = await getCache(cacheKey);
48123
48065
  if (cachedData) {
48124
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
48066
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
48125
48067
  return cachedData;
48126
48068
  }
48127
48069
  try {
@@ -48133,19 +48075,19 @@ function useUserRepoV2() {
48133
48075
  { $project: { _id: 1, name: 1, email: 1, type: 1, status: 1 } }
48134
48076
  ]).toArray();
48135
48077
  const length = await collection.countDocuments(query);
48136
- const data = (0, import_node_server_utils221.paginate)(items, page, limit, length);
48137
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
48138
- (err) => import_node_server_utils221.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
48078
+ const data = (0, import_node_server_utils220.paginate)(items, page, limit, length);
48079
+ setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`)).catch(
48080
+ (err) => import_node_server_utils220.logger.error(`Failed to set cache for key: ${cacheKey}`, err)
48139
48081
  );
48140
48082
  return data;
48141
48083
  } catch (error) {
48142
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
48084
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
48143
48085
  throw error;
48144
48086
  }
48145
48087
  }
48146
48088
  async function updatePasswordById({ _id, password }, session) {
48147
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48148
- _id = (0, import_node_server_utils221.toObjectId)(_id);
48089
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48090
+ _id = (0, import_node_server_utils220.toObjectId)(_id);
48149
48091
  try {
48150
48092
  const result = await collection.updateOne(
48151
48093
  { _id },
@@ -48153,13 +48095,13 @@ function useUserRepoV2() {
48153
48095
  { session }
48154
48096
  );
48155
48097
  delCache(cacheKey).then(() => {
48156
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48098
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48157
48099
  }).catch((err) => {
48158
- import_node_server_utils221.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48100
+ import_node_server_utils220.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48159
48101
  });
48160
48102
  return result;
48161
48103
  } catch (error) {
48162
- throw new import_node_server_utils221.InternalServerError("Failed to update user password.");
48104
+ throw new import_node_server_utils220.InternalServerError("Failed to update user password.");
48163
48105
  }
48164
48106
  }
48165
48107
  async function updateUserFieldById({ _id, field, value } = {}, session) {
@@ -48174,20 +48116,20 @@ function useUserRepoV2() {
48174
48116
  "defaultOrg"
48175
48117
  ];
48176
48118
  if (!allowedFields.includes(field)) {
48177
- throw new import_node_server_utils221.BadRequestError(
48119
+ throw new import_node_server_utils220.BadRequestError(
48178
48120
  `Field "${field}" is not allowed to be updated.`
48179
48121
  );
48180
48122
  }
48181
48123
  try {
48182
- _id = new import_mongodb129.ObjectId(_id);
48124
+ _id = new import_mongodb125.ObjectId(_id);
48183
48125
  } catch (error) {
48184
- throw new import_node_server_utils221.BadRequestError("Invalid ID.");
48126
+ throw new import_node_server_utils220.BadRequestError("Invalid ID.");
48185
48127
  }
48186
48128
  if (field === "defaultOrg") {
48187
48129
  try {
48188
- value = new import_mongodb129.ObjectId(value);
48130
+ value = new import_mongodb125.ObjectId(value);
48189
48131
  } catch (error) {
48190
- throw new import_node_server_utils221.BadRequestError("Invalid organization ID.");
48132
+ throw new import_node_server_utils220.BadRequestError("Invalid organization ID.");
48191
48133
  }
48192
48134
  }
48193
48135
  if (field === "name") {
@@ -48208,15 +48150,15 @@ function useUserRepoV2() {
48208
48150
  // Dynamically set the field
48209
48151
  { session }
48210
48152
  );
48211
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48153
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48212
48154
  delCache(cacheKey).then(() => {
48213
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48155
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48214
48156
  }).catch((err) => {
48215
- import_node_server_utils221.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48157
+ import_node_server_utils220.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48216
48158
  });
48217
48159
  return `Successfully updated user ${field}.`;
48218
48160
  } catch (error) {
48219
- throw new import_node_server_utils221.InternalServerError(`Failed to update user ${field}.`);
48161
+ throw new import_node_server_utils220.InternalServerError(`Failed to update user ${field}.`);
48220
48162
  }
48221
48163
  }
48222
48164
  async function updateBirthday({
@@ -48226,9 +48168,9 @@ function useUserRepoV2() {
48226
48168
  year
48227
48169
  }, session) {
48228
48170
  try {
48229
- _id = new import_mongodb129.ObjectId(_id);
48171
+ _id = new import_mongodb125.ObjectId(_id);
48230
48172
  } catch (error) {
48231
- throw new import_node_server_utils221.BadRequestError("Invalid user ID format.");
48173
+ throw new import_node_server_utils220.BadRequestError("Invalid user ID format.");
48232
48174
  }
48233
48175
  try {
48234
48176
  await collection.updateOne(
@@ -48243,22 +48185,22 @@ function useUserRepoV2() {
48243
48185
  },
48244
48186
  { session }
48245
48187
  );
48246
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48188
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48247
48189
  delCache(cacheKey).then(() => {
48248
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48190
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48249
48191
  }).catch((err) => {
48250
- import_node_server_utils221.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48192
+ import_node_server_utils220.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48251
48193
  });
48252
48194
  return "Successfully updated user birthday.";
48253
48195
  } catch (error) {
48254
- throw new import_node_server_utils221.InternalServerError("Failed to update user birthday.");
48196
+ throw new import_node_server_utils220.InternalServerError("Failed to update user birthday.");
48255
48197
  }
48256
48198
  }
48257
48199
  async function updatePassword({ _id, password }, session) {
48258
48200
  try {
48259
- _id = new import_mongodb129.ObjectId(_id);
48201
+ _id = new import_mongodb125.ObjectId(_id);
48260
48202
  } catch (error) {
48261
- throw new import_node_server_utils221.BadRequestError("Invalid user ID format.");
48203
+ throw new import_node_server_utils220.BadRequestError("Invalid user ID format.");
48262
48204
  }
48263
48205
  try {
48264
48206
  const result = await collection.updateOne(
@@ -48266,15 +48208,15 @@ function useUserRepoV2() {
48266
48208
  { $set: { password, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
48267
48209
  { session }
48268
48210
  );
48269
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48211
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48270
48212
  delCache(cacheKey).then(() => {
48271
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48213
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48272
48214
  }).catch((err) => {
48273
- import_node_server_utils221.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48215
+ import_node_server_utils220.logger.error(`Failed to delete cache for key: ${cacheKey}`, err);
48274
48216
  });
48275
48217
  return result;
48276
48218
  } catch (error) {
48277
- throw new import_node_server_utils221.InternalServerError("Failed to update user password.");
48219
+ throw new import_node_server_utils220.InternalServerError("Failed to update user password.");
48278
48220
  }
48279
48221
  }
48280
48222
  return {
@@ -48298,7 +48240,7 @@ function useUserRepoV2() {
48298
48240
  function useAuthServiceV2() {
48299
48241
  const { getUserByEmail, getUserById: _getUserById } = useUserRepoV2();
48300
48242
  const expiresIn = "15m";
48301
- const { setCache, delCache } = (0, import_node_server_utils222.useCache)("sessions");
48243
+ const { setCache, delCache } = (0, import_node_server_utils221.useCache)("sessions");
48302
48244
  const { getByUserIdType } = useMemberRepo();
48303
48245
  async function login({
48304
48246
  email,
@@ -48309,26 +48251,26 @@ function useAuthServiceV2() {
48309
48251
  try {
48310
48252
  const user = await getUserByEmail(email);
48311
48253
  if (!user) {
48312
- throw new import_node_server_utils222.NotFoundError(
48254
+ throw new import_node_server_utils221.NotFoundError(
48313
48255
  "Invalid user email. Please check your email and try again."
48314
48256
  );
48315
48257
  }
48316
48258
  if (!user._id) {
48317
- throw new import_node_server_utils222.InternalServerError("Valid user ID.");
48259
+ throw new import_node_server_utils221.InternalServerError("Valid user ID.");
48318
48260
  }
48319
48261
  if (user.status === "suspended") {
48320
- throw new import_node_server_utils222.BadRequestError(
48262
+ throw new import_node_server_utils221.BadRequestError(
48321
48263
  "Your account is currently suspended. Please contact support for assistance."
48322
48264
  );
48323
48265
  }
48324
- const isPasswordValid = await (0, import_node_server_utils222.comparePassword)(password, user.password);
48266
+ const isPasswordValid = await (0, import_node_server_utils221.comparePassword)(password, user.password);
48325
48267
  if (!isPasswordValid) {
48326
- throw new import_node_server_utils222.BadRequestError("Invalid password.");
48268
+ throw new import_node_server_utils221.BadRequestError("Invalid password.");
48327
48269
  }
48328
48270
  if (isMobile) {
48329
48271
  const member = await getByUserIdType(user._id, type);
48330
48272
  if (!member) {
48331
- throw new import_node_server_utils222.BadRequestError("No member found.");
48273
+ throw new import_node_server_utils221.BadRequestError("No member found.");
48332
48274
  }
48333
48275
  }
48334
48276
  const sid = (0, import_uuid2.v4)();
@@ -48348,22 +48290,22 @@ function useAuthServiceV2() {
48348
48290
  await delCache(`sid:${sid}`);
48349
48291
  return "Session deleted successfully";
48350
48292
  } catch (error) {
48351
- throw new import_node_server_utils222.InternalServerError("Error deleting token");
48293
+ throw new import_node_server_utils221.InternalServerError("Error deleting token");
48352
48294
  }
48353
48295
  }
48354
48296
  async function verifyPassword(_id, password) {
48355
48297
  try {
48356
48298
  const user = await _getUserById(_id);
48357
- const isPasswordMatch = await (0, import_node_server_utils222.comparePassword)(password, user.password);
48299
+ const isPasswordMatch = await (0, import_node_server_utils221.comparePassword)(password, user.password);
48358
48300
  if (!isPasswordMatch) {
48359
- throw new import_node_server_utils222.BadRequestError("Invalid credentials");
48301
+ throw new import_node_server_utils221.BadRequestError("Invalid credentials");
48360
48302
  }
48361
48303
  return "Verification successful.";
48362
48304
  } catch (error) {
48363
- if (error instanceof import_node_server_utils222.BadRequestError) {
48305
+ if (error instanceof import_node_server_utils221.BadRequestError) {
48364
48306
  throw error;
48365
48307
  }
48366
- throw new import_node_server_utils222.InternalServerError("Error during password verification");
48308
+ throw new import_node_server_utils221.InternalServerError("Error during password verification");
48367
48309
  }
48368
48310
  }
48369
48311
  return {
@@ -48374,7 +48316,7 @@ function useAuthServiceV2() {
48374
48316
  }
48375
48317
 
48376
48318
  // src/services/user-v2.service.ts
48377
- var import_node_server_utils223 = require("@7365admin1/node-server-utils");
48319
+ var import_node_server_utils222 = require("@7365admin1/node-server-utils");
48378
48320
  var import_multer2 = require("multer");
48379
48321
  function useUserServiceV2() {
48380
48322
  const {
@@ -48399,23 +48341,23 @@ function useUserServiceV2() {
48399
48341
  id = "",
48400
48342
  name = ""
48401
48343
  }) {
48402
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48344
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48403
48345
  session?.startTransaction();
48404
48346
  try {
48405
48347
  const signUp = await _getVerificationById(id);
48406
48348
  if (!signUp)
48407
- throw new import_node_server_utils223.BadRequestError("Invalid sign up link.");
48349
+ throw new import_node_server_utils222.BadRequestError("Invalid sign up link.");
48408
48350
  if (signUp.status === "complete" /* COMPLETE */)
48409
- throw new import_node_server_utils223.BadRequestError(
48351
+ throw new import_node_server_utils222.BadRequestError(
48410
48352
  "You have already an account created using this link."
48411
48353
  );
48412
48354
  const expired = signUp.expireAt < (/* @__PURE__ */ new Date()).toISOString();
48413
48355
  if (signUp.status === "expired" || expired)
48414
- throw new import_node_server_utils223.BadRequestError("Sign up link expired.");
48356
+ throw new import_node_server_utils222.BadRequestError("Sign up link expired.");
48415
48357
  const email = signUp.email;
48416
48358
  const _user = await _getUserByEmail(email);
48417
48359
  if (_user)
48418
- throw new import_node_server_utils223.BadRequestError(`User already exists: ${email}.`);
48360
+ throw new import_node_server_utils222.BadRequestError(`User already exists: ${email}.`);
48419
48361
  let org = null;
48420
48362
  if (signUp.metadata?.org) {
48421
48363
  org = await getOrgById(signUp.metadata.org);
@@ -48462,30 +48404,30 @@ function useUserServiceV2() {
48462
48404
  }
48463
48405
  async function resetPassword(id, newPassword, passwordConfirmation) {
48464
48406
  if (newPassword !== passwordConfirmation) {
48465
- throw new import_node_server_utils223.BadRequestError("Passwords do not match.");
48407
+ throw new import_node_server_utils222.BadRequestError("Passwords do not match.");
48466
48408
  }
48467
48409
  let hashedPassword;
48468
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48410
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48469
48411
  session?.startTransaction();
48470
48412
  try {
48471
- hashedPassword = await (0, import_node_server_utils223.hashPassword)(newPassword);
48413
+ hashedPassword = await (0, import_node_server_utils222.hashPassword)(newPassword);
48472
48414
  } catch (error) {
48473
- throw new import_node_server_utils223.InternalServerError(`Error hashing password: ${error}`);
48415
+ throw new import_node_server_utils222.InternalServerError(`Error hashing password: ${error}`);
48474
48416
  }
48475
48417
  try {
48476
48418
  const otpDoc = await _getVerificationById(id);
48477
48419
  if (!otpDoc) {
48478
- throw new import_node_server_utils223.NotFoundError("You are using an invalid reset link.");
48420
+ throw new import_node_server_utils222.NotFoundError("You are using an invalid reset link.");
48479
48421
  }
48480
48422
  if (otpDoc.status === "complete" /* COMPLETE */) {
48481
- throw new import_node_server_utils223.BadRequestError("This link has already been invalidated.");
48423
+ throw new import_node_server_utils222.BadRequestError("This link has already been invalidated.");
48482
48424
  }
48483
48425
  const user = await _getUserByEmail(otpDoc.email);
48484
48426
  if (!user) {
48485
- throw new import_node_server_utils223.NotFoundError("User not found.");
48427
+ throw new import_node_server_utils222.NotFoundError("User not found.");
48486
48428
  }
48487
48429
  if (!user._id) {
48488
- throw new import_node_server_utils223.InternalServerError("Invalid user ID.");
48430
+ throw new import_node_server_utils222.InternalServerError("Invalid user ID.");
48489
48431
  }
48490
48432
  await Promise.all([
48491
48433
  _updateVerificationStatusById(id, "complete" /* COMPLETE */, session),
@@ -48503,7 +48445,7 @@ function useUserServiceV2() {
48503
48445
  session?.endSession();
48504
48446
  }
48505
48447
  }
48506
- const s3 = new import_node_server_utils223.useS3({
48448
+ const s3 = new import_node_server_utils222.useS3({
48507
48449
  accessKeyId: SPACES_ACCESS_KEY,
48508
48450
  secretAccessKey: SPACES_SECRET_KEY,
48509
48451
  endpoint: SPACES_ENDPOINT,
@@ -48516,7 +48458,7 @@ function useUserServiceV2() {
48516
48458
  user,
48517
48459
  previousProfile
48518
48460
  }) {
48519
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48461
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48520
48462
  session?.startTransaction();
48521
48463
  const _file = {
48522
48464
  name: file.originalname,
@@ -48549,18 +48491,18 @@ function useUserServiceV2() {
48549
48491
  async function updatePasswordById(id, currentPassword, newPassword, passwordConfirmation) {
48550
48492
  let hashedPassword;
48551
48493
  const user = await getUserById(id);
48552
- const isPasswordValid = await (0, import_node_server_utils223.comparePassword)(
48494
+ const isPasswordValid = await (0, import_node_server_utils222.comparePassword)(
48553
48495
  currentPassword,
48554
48496
  user.password
48555
48497
  );
48556
48498
  if (!isPasswordValid)
48557
- throw new import_node_server_utils223.BadRequestError("Invalid current password.");
48499
+ throw new import_node_server_utils222.BadRequestError("Invalid current password.");
48558
48500
  if (newPassword !== passwordConfirmation)
48559
- throw new import_node_server_utils223.BadRequestError("Passwords do not match.");
48501
+ throw new import_node_server_utils222.BadRequestError("Passwords do not match.");
48560
48502
  try {
48561
- hashedPassword = await (0, import_node_server_utils223.hashPassword)(newPassword);
48503
+ hashedPassword = await (0, import_node_server_utils222.hashPassword)(newPassword);
48562
48504
  if (!hashedPassword)
48563
- throw new import_node_server_utils223.InternalServerError("Error hashing password.");
48505
+ throw new import_node_server_utils222.InternalServerError("Error hashing password.");
48564
48506
  return await updatePassword({ _id: id, password: hashedPassword });
48565
48507
  } catch (error) {
48566
48508
  throw error;
@@ -48596,8 +48538,8 @@ function useAuthControllerV2() {
48596
48538
  });
48597
48539
  if (error) {
48598
48540
  const messages = error.details.map((d) => d.message);
48599
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48600
- next(new import_node_server_utils224.BadRequestError(messages.join(", ")));
48541
+ import_node_server_utils223.logger.log({ level: "error", message: messages.join(", ") });
48542
+ next(new import_node_server_utils223.BadRequestError(messages.join(", ")));
48601
48543
  return;
48602
48544
  }
48603
48545
  const { email, password, country, orgName } = value;
@@ -48613,7 +48555,7 @@ function useAuthControllerV2() {
48613
48555
  return;
48614
48556
  } catch (error) {
48615
48557
  console.log(error);
48616
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48558
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48617
48559
  next(error);
48618
48560
  return;
48619
48561
  }
@@ -48631,8 +48573,8 @@ function useAuthControllerV2() {
48631
48573
  });
48632
48574
  if (error) {
48633
48575
  const messages = error.details.map((d) => d.message);
48634
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48635
- next(new import_node_server_utils224.BadRequestError(messages.join(", ")));
48576
+ import_node_server_utils223.logger.log({ level: "error", message: messages.join(", ") });
48577
+ next(new import_node_server_utils223.BadRequestError(messages.join(", ")));
48636
48578
  return;
48637
48579
  }
48638
48580
  const session = await _login(value);
@@ -48644,7 +48586,7 @@ function useAuthControllerV2() {
48644
48586
  res.cookie("sid", session.sid, cookieOptions).cookie("user", session.user, cookieOptions).json(session);
48645
48587
  return;
48646
48588
  } catch (error) {
48647
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48589
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48648
48590
  next(error);
48649
48591
  return;
48650
48592
  }
@@ -48652,7 +48594,7 @@ function useAuthControllerV2() {
48652
48594
  async function logout(req, res, next) {
48653
48595
  const sid = req.headers["authorization"] ?? "";
48654
48596
  if (!sid) {
48655
- next(new import_node_server_utils224.BadRequestError("Session ID is required"));
48597
+ next(new import_node_server_utils223.BadRequestError("Session ID is required"));
48656
48598
  return;
48657
48599
  }
48658
48600
  try {
@@ -48660,7 +48602,7 @@ function useAuthControllerV2() {
48660
48602
  res.json({ message: "Logged out successfully" });
48661
48603
  return;
48662
48604
  } catch (error) {
48663
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48605
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48664
48606
  next(error);
48665
48607
  return;
48666
48608
  }
@@ -48676,8 +48618,8 @@ function useAuthControllerV2() {
48676
48618
  });
48677
48619
  if (error) {
48678
48620
  const messages = error.details.map((d) => d.message);
48679
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48680
- next(new import_node_server_utils224.BadRequestError(messages.join(", ")));
48621
+ import_node_server_utils223.logger.log({ level: "error", message: messages.join(", ") });
48622
+ next(new import_node_server_utils223.BadRequestError(messages.join(", ")));
48681
48623
  return;
48682
48624
  }
48683
48625
  const { otp, newPassword, passwordConfirmation } = value;
@@ -48690,7 +48632,7 @@ function useAuthControllerV2() {
48690
48632
  res.json({ message });
48691
48633
  return;
48692
48634
  } catch (error2) {
48693
- import_node_server_utils224.logger.log({ level: "error", message: error2.message });
48635
+ import_node_server_utils223.logger.log({ level: "error", message: error2.message });
48694
48636
  next(error2);
48695
48637
  return;
48696
48638
  }
@@ -48706,8 +48648,8 @@ function useAuthControllerV2() {
48706
48648
  );
48707
48649
  if (error) {
48708
48650
  const messages = error.details.map((d) => d.message);
48709
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48710
- next(new import_node_server_utils224.BadRequestError(messages.join(", ")));
48651
+ import_node_server_utils223.logger.log({ level: "error", message: messages.join(", ") });
48652
+ next(new import_node_server_utils223.BadRequestError(messages.join(", ")));
48711
48653
  return;
48712
48654
  }
48713
48655
  const { _id, password } = value;
@@ -48716,7 +48658,7 @@ function useAuthControllerV2() {
48716
48658
  res.json({ message });
48717
48659
  return;
48718
48660
  } catch (error2) {
48719
- import_node_server_utils224.logger.log({ level: "error", message: error2.message });
48661
+ import_node_server_utils223.logger.log({ level: "error", message: error2.message });
48720
48662
  next(error2);
48721
48663
  return;
48722
48664
  }
@@ -48733,7 +48675,7 @@ function useAuthControllerV2() {
48733
48675
  // src/controllers/user-v2.controller.ts
48734
48676
  var import_joi128 = __toESM(require("joi"));
48735
48677
  var import_multer3 = require("multer");
48736
- var import_node_server_utils225 = require("@7365admin1/node-server-utils");
48678
+ var import_node_server_utils224 = require("@7365admin1/node-server-utils");
48737
48679
  function useUserControllerV2() {
48738
48680
  const {
48739
48681
  updateBirthday: _updateBirthday,
@@ -48747,16 +48689,16 @@ function useUserControllerV2() {
48747
48689
  const { createUserBySignUp, updateUserProfile: _updateUserProfile, updatePasswordById: _updatePasswordById } = useUserServiceV2();
48748
48690
  function rejectValidation(error, next) {
48749
48691
  const message = error.details.map((d) => d.message).join(", ");
48750
- import_node_server_utils225.logger.log({ level: "error", message });
48751
- next(new import_node_server_utils225.BadRequestError(message));
48692
+ import_node_server_utils224.logger.log({ level: "error", message });
48693
+ next(new import_node_server_utils224.BadRequestError(message));
48752
48694
  }
48753
48695
  async function getById(req, res, next) {
48754
48696
  const validation = import_joi128.default.string().hex().required();
48755
48697
  const _id = req.params.id;
48756
48698
  const { error, value } = validation.validate(_id);
48757
48699
  if (error) {
48758
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48759
- next(new import_node_server_utils225.BadRequestError(error.message));
48700
+ import_node_server_utils224.logger.log({ level: "error", message: `${error.message}` });
48701
+ next(new import_node_server_utils224.BadRequestError(error.message));
48760
48702
  return;
48761
48703
  }
48762
48704
  try {
@@ -48764,7 +48706,7 @@ function useUserControllerV2() {
48764
48706
  res.json(user);
48765
48707
  return;
48766
48708
  } catch (error2) {
48767
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48709
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48768
48710
  next(error2);
48769
48711
  return;
48770
48712
  }
@@ -48778,7 +48720,7 @@ function useUserControllerV2() {
48778
48720
  res.json(user);
48779
48721
  return;
48780
48722
  } catch (err) {
48781
- import_node_server_utils225.logger.log({ level: "error", message: `${err.message}` });
48723
+ import_node_server_utils224.logger.log({ level: "error", message: `${err.message}` });
48782
48724
  next(err);
48783
48725
  return;
48784
48726
  }
@@ -48845,8 +48787,8 @@ function useUserControllerV2() {
48845
48787
  const payload = { ...req.body };
48846
48788
  const { error, value } = validation.validate({ id, ...payload });
48847
48789
  if (error) {
48848
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48849
- next(new import_node_server_utils225.BadRequestError(error.message));
48790
+ import_node_server_utils224.logger.log({ level: "error", message: `${error.message}` });
48791
+ next(new import_node_server_utils224.BadRequestError(error.message));
48850
48792
  return;
48851
48793
  }
48852
48794
  try {
@@ -48854,14 +48796,14 @@ function useUserControllerV2() {
48854
48796
  res.status(201).json({ message: "Successfully created account." });
48855
48797
  return;
48856
48798
  } catch (error2) {
48857
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48799
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48858
48800
  next(error2);
48859
48801
  return;
48860
48802
  }
48861
48803
  }
48862
48804
  async function updateUserProfile(req, res, next) {
48863
48805
  if (!req.file) {
48864
- next(new import_node_server_utils225.BadRequestError("File is required!"));
48806
+ next(new import_node_server_utils224.BadRequestError("File is required!"));
48865
48807
  return;
48866
48808
  }
48867
48809
  const validation = import_joi128.default.object({
@@ -48870,8 +48812,8 @@ function useUserControllerV2() {
48870
48812
  const payload = { ...req.body };
48871
48813
  const { error, value } = validation.validate(payload);
48872
48814
  if (error) {
48873
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48874
- next(new import_node_server_utils225.BadRequestError(error.message));
48815
+ import_node_server_utils224.logger.log({ level: "error", message: `${error.message}` });
48816
+ next(new import_node_server_utils224.BadRequestError(error.message));
48875
48817
  return;
48876
48818
  }
48877
48819
  const user = req.headers.user ?? "";
@@ -48884,7 +48826,7 @@ function useUserControllerV2() {
48884
48826
  res.json({ message: "Successfully updated profile picture." });
48885
48827
  return;
48886
48828
  } catch (error2) {
48887
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48829
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48888
48830
  next(error2);
48889
48831
  return;
48890
48832
  }
@@ -48914,8 +48856,8 @@ function useUserControllerV2() {
48914
48856
  const payload = { ...req.body };
48915
48857
  const { error } = validation.validate({ _id, ...payload });
48916
48858
  if (error) {
48917
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48918
- next(new import_node_server_utils225.BadRequestError(error.message));
48859
+ import_node_server_utils224.logger.log({ level: "error", message: `${error.message}` });
48860
+ next(new import_node_server_utils224.BadRequestError(error.message));
48919
48861
  return;
48920
48862
  }
48921
48863
  try {
@@ -48923,7 +48865,7 @@ function useUserControllerV2() {
48923
48865
  res.json({ message });
48924
48866
  return;
48925
48867
  } catch (error2) {
48926
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48868
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48927
48869
  next(error2);
48928
48870
  return;
48929
48871
  }
@@ -48945,8 +48887,8 @@ function useUserControllerV2() {
48945
48887
  const payload = { ...req.body };
48946
48888
  const { error } = validation.validate({ _id, ...payload });
48947
48889
  if (error) {
48948
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48949
- next(new import_node_server_utils225.BadRequestError(error.message));
48890
+ import_node_server_utils224.logger.log({ level: "error", message: `${error.message}` });
48891
+ next(new import_node_server_utils224.BadRequestError(error.message));
48950
48892
  return;
48951
48893
  }
48952
48894
  try {
@@ -48954,7 +48896,7 @@ function useUserControllerV2() {
48954
48896
  res.json({ message });
48955
48897
  return;
48956
48898
  } catch (error2) {
48957
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48899
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48958
48900
  next(error2);
48959
48901
  return;
48960
48902
  }
@@ -48973,7 +48915,7 @@ function useUserControllerV2() {
48973
48915
  ...payload
48974
48916
  });
48975
48917
  if (error) {
48976
- next(new import_node_server_utils225.BadRequestError(error.message));
48918
+ next(new import_node_server_utils224.BadRequestError(error.message));
48977
48919
  return;
48978
48920
  }
48979
48921
  const currentPassword = req.body.currentPassword ?? "";
@@ -49003,6 +48945,172 @@ function useUserControllerV2() {
49003
48945
  updatePasswordById
49004
48946
  };
49005
48947
  }
48948
+
48949
+ // src/models/role-v2.model.ts
48950
+ var import_node_server_utils225 = require("@7365admin1/node-server-utils");
48951
+ var import_mongodb126 = require("mongodb");
48952
+ var MRoleV2 = class {
48953
+ constructor(value) {
48954
+ if (typeof value._id === "string") {
48955
+ try {
48956
+ value._id = new import_mongodb126.ObjectId(value._id);
48957
+ } catch (error) {
48958
+ throw new import_node_server_utils225.BadRequestError("Invalid role-v2 ID format.");
48959
+ }
48960
+ }
48961
+ if (typeof value.site === "string" && value.site.length === 24) {
48962
+ try {
48963
+ value.site = new import_mongodb126.ObjectId(value.site);
48964
+ } catch (error) {
48965
+ throw new import_node_server_utils225.BadRequestError("Invalid site ID format.");
48966
+ }
48967
+ }
48968
+ if (typeof value.org === "string" && value.org.length === 24) {
48969
+ try {
48970
+ value.org = new import_mongodb126.ObjectId(value.org);
48971
+ } catch (error) {
48972
+ throw new import_node_server_utils225.BadRequestError("Invalid org ID format.");
48973
+ }
48974
+ }
48975
+ if (value.createdBy) {
48976
+ try {
48977
+ value.createdBy = new import_mongodb126.ObjectId(value.createdBy);
48978
+ } catch (error) {
48979
+ throw new import_node_server_utils225.BadRequestError("Invalid created by ID format.");
48980
+ }
48981
+ }
48982
+ this._id = value._id ?? new import_mongodb126.ObjectId();
48983
+ this.name = value.name ?? "";
48984
+ this.permissions = value.permissions ?? [];
48985
+ this.site = value.site ?? "";
48986
+ this.platform = value.platform ?? "";
48987
+ this.type = value.type ?? "account";
48988
+ this.org = value.org ?? "";
48989
+ this.status = value.status ?? "active";
48990
+ this.createdBy = value.createdBy ?? "";
48991
+ this.createdAt = value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
48992
+ this.updatedAt = value.updatedAt ?? "";
48993
+ this.deletedAt = value.deletedAt ?? "";
48994
+ }
48995
+ };
48996
+
48997
+ // src/repositories/role-v2.repo.ts
48998
+ var import_node_server_utils226 = require("@7365admin1/node-server-utils");
48999
+ function useRoleRepoV2() {
49000
+ const db = import_node_server_utils226.useAtlas.getDb();
49001
+ if (!db) {
49002
+ throw new import_node_server_utils226.InternalServerError("Unable to connect to server.");
49003
+ }
49004
+ const namespace_collection = "roles.v2";
49005
+ const collection = db.collection(namespace_collection);
49006
+ async function createIndex() {
49007
+ try {
49008
+ await collection.createIndexes([
49009
+ { key: { name: 1 } },
49010
+ { key: { type: 1 } },
49011
+ { key: { status: 1 } }
49012
+ ]);
49013
+ } catch (error) {
49014
+ throw new import_node_server_utils226.InternalServerError("Failed to create index on role.");
49015
+ }
49016
+ }
49017
+ async function createTextIndex() {
49018
+ try {
49019
+ await collection.createIndex({ name: "text" });
49020
+ } catch (error) {
49021
+ throw new import_node_server_utils226.InternalServerError("Failed to create text index on role.");
49022
+ }
49023
+ }
49024
+ async function createUniqueIndex() {
49025
+ try {
49026
+ await collection.createIndex(
49027
+ { name: 1, site: 1, platform: 1, type: 1, org: 1, deletedAt: 1 },
49028
+ { unique: true }
49029
+ );
49030
+ } catch (error) {
49031
+ throw new import_node_server_utils226.InternalServerError("Failed to create unique index on role.");
49032
+ }
49033
+ }
49034
+ const { delNamespace } = (0, import_node_server_utils226.useCache)(namespace_collection);
49035
+ async function addRole(value, session) {
49036
+ value = new MRoleV2(value);
49037
+ try {
49038
+ const res = await collection.insertOne(value, { session });
49039
+ delNamespace().then(() => {
49040
+ import_node_server_utils226.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
49041
+ }).catch((err) => {
49042
+ import_node_server_utils226.logger.error(
49043
+ `Failed to clear cache for namespace: ${namespace_collection}`,
49044
+ err
49045
+ );
49046
+ });
49047
+ return res.insertedId;
49048
+ } catch (error) {
49049
+ import_node_server_utils226.logger.log({ level: "error", message: `${error}` });
49050
+ const isDuplicated = error.message.includes("duplicate");
49051
+ if (isDuplicated) {
49052
+ throw new import_node_server_utils226.BadRequestError("Role already exists.");
49053
+ }
49054
+ throw new import_node_server_utils226.InternalServerError("Failed to create role.");
49055
+ }
49056
+ }
49057
+ return {
49058
+ createIndex,
49059
+ createTextIndex,
49060
+ createUniqueIndex,
49061
+ addRole
49062
+ };
49063
+ }
49064
+
49065
+ // src/services/role-v2.service.ts
49066
+ function useRoleServiceV2() {
49067
+ const { addRole: _addRole } = useRoleRepoV2();
49068
+ async function createRole(value) {
49069
+ try {
49070
+ return await _addRole(value);
49071
+ } catch (error) {
49072
+ throw error;
49073
+ }
49074
+ }
49075
+ return { createRole };
49076
+ }
49077
+
49078
+ // src/controllers/role-v2.controller.ts
49079
+ var import_joi129 = __toESM(require("joi"));
49080
+ var import_node_server_utils227 = require("@7365admin1/node-server-utils");
49081
+ function useRoleControllerV2() {
49082
+ const { createRole: _createRole } = useRoleServiceV2();
49083
+ async function createRole(req, res, next) {
49084
+ const validation = import_joi129.default.object({
49085
+ name: import_joi129.default.string().required(),
49086
+ site: import_joi129.default.string().hex().required(),
49087
+ platform: import_joi129.default.string().required(),
49088
+ permissions: import_joi129.default.array().items(import_joi129.default.string()).required(),
49089
+ type: import_joi129.default.string().optional().allow("", null),
49090
+ org: import_joi129.default.string().hex().optional().allow("", null)
49091
+ });
49092
+ const payload = { ...req.body };
49093
+ const { error, value } = validation.validate(payload, { abortEarly: false });
49094
+ if (error) {
49095
+ const message = error.details.map((item) => item.message).join(", ");
49096
+ import_node_server_utils227.logger.log({ level: "error", message });
49097
+ next(new import_node_server_utils227.BadRequestError(message));
49098
+ return;
49099
+ }
49100
+ try {
49101
+ const role = await _createRole(value);
49102
+ res.status(201).json({ message: "Successfully created role.", data: { role } });
49103
+ return;
49104
+ } catch (error2) {
49105
+ import_node_server_utils227.logger.log({ level: "error", message: error2.message });
49106
+ next(error2);
49107
+ return;
49108
+ }
49109
+ }
49110
+ return {
49111
+ createRole
49112
+ };
49113
+ }
49006
49114
  // Annotate the CommonJS export names for ESM import in node:
49007
49115
  0 && (module.exports = {
49008
49116
  ANPRMode,
@@ -49067,6 +49175,7 @@ function useUserControllerV2() {
49067
49175
  MPromoCode,
49068
49176
  MRobot,
49069
49177
  MRole,
49178
+ MRoleV2,
49070
49179
  MServiceProvider,
49071
49180
  MServiceProviderBilling,
49072
49181
  MSession,
@@ -49089,6 +49198,7 @@ function useUserControllerV2() {
49089
49198
  OvernightParkingRequestStatus,
49090
49199
  PERSON_TYPES,
49091
49200
  PMDashboardCollection,
49201
+ PStatus,
49092
49202
  Period,
49093
49203
  PersonStatus,
49094
49204
  PersonTypes,
@@ -49096,6 +49206,7 @@ function useUserControllerV2() {
49096
49206
  SiteStatus,
49097
49207
  SortFields,
49098
49208
  SortOrder,
49209
+ Status,
49099
49210
  SubscriptionType,
49100
49211
  UseAccessManagementRepo,
49101
49212
  UserStatus,
@@ -49350,7 +49461,10 @@ function useUserControllerV2() {
49350
49461
  useRobotRepo,
49351
49462
  useRobotService,
49352
49463
  useRoleController,
49464
+ useRoleControllerV2,
49353
49465
  useRoleRepo,
49466
+ useRoleRepoV2,
49467
+ useRoleServiceV2,
49354
49468
  useServiceProviderBillingController,
49355
49469
  useServiceProviderBillingRepo,
49356
49470
  useServiceProviderBillingService,