@7365admin1/core 2.36.1 → 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");
@@ -13387,19 +13399,19 @@ var schemaVisitorTransaction = import_joi36.default.object({
13387
13399
  numberOfPassengers: import_joi36.default.number().integer().optional().allow(null, ""),
13388
13400
  visitorPass: import_joi36.default.array().items(
13389
13401
  import_joi36.default.object({
13390
- keyId: import_joi36.default.string().hex().length(24).required()
13402
+ keyId: import_joi36.default.string().hex().length(24).allow(null, "")
13391
13403
  })
13392
13404
  ).optional().allow(null),
13393
13405
  passKeys: import_joi36.default.array().items(
13394
13406
  import_joi36.default.object({
13395
- keyId: import_joi36.default.string().hex().length(24).required()
13407
+ keyId: import_joi36.default.string().hex().length(24).allow(null, "")
13396
13408
  })
13397
13409
  ).optional().allow(null),
13398
13410
  checkInRemarks: import_joi36.default.string().optional().allow("", null),
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,14 +13520,14 @@ 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
- const newDate = (/* @__PURE__ */ new Date()).toISOString();
13530
+ const newDate = /* @__PURE__ */ new Date();
13519
13531
  return {
13520
13532
  _id: value._id,
13521
13533
  name: value.name,
@@ -13530,7 +13542,7 @@ function MVisitorTransaction(value) {
13530
13542
  plateNumber: value.plateNumber,
13531
13543
  recNo: value.recNo,
13532
13544
  checkIn: value.checkIn === void 0 ? newDate : value.checkIn,
13533
- expectedCheckIn: value.expectedCheckIn,
13545
+ expectedCheckIn: value.expectedCheckIn ? new Date(value.expectedCheckIn) : void 0,
13534
13546
  checkOut: value.checkOut,
13535
13547
  status: value.status,
13536
13548
  remarks: value.remarks,
@@ -13555,12 +13567,14 @@ 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 ?? ""
13563
- } : null
13574
+ updatedBy: value.inviterId ?? ""
13575
+ } : null,
13576
+ arrivalTime: value.arrivalTime,
13577
+ duration: value.duration
13564
13578
  };
13565
13579
  }
13566
13580
 
@@ -13608,47 +13622,42 @@ function useVisitorTransactionRepo() {
13608
13622
  page = 1,
13609
13623
  limit = 10,
13610
13624
  sort = {},
13611
- status = "registered",
13625
+ status,
13612
13626
  org = "",
13613
13627
  site = "",
13614
13628
  dateTo = "",
13615
13629
  dateFrom = "",
13616
13630
  type = "",
13617
13631
  checkedOut,
13618
- plateNumber = ""
13632
+ plateNumber = "",
13633
+ tab = ""
13619
13634
  }) {
13620
13635
  page = page > 0 ? page - 1 : 0;
13621
13636
  const skip = page * limit;
13622
- let checkOutFilter;
13623
- const checkIn = dateFrom ? { $gte: new Date(dateFrom).toISOString() } : void 0;
13624
- if (checkedOut === false) {
13625
- checkOutFilter = { checkOut: null };
13626
- } else if (checkedOut === true) {
13627
- checkOutFilter = dateTo ? {
13628
- checkOut: {
13629
- $ne: null,
13630
- $lte: new Date(dateTo).toISOString()
13631
- }
13632
- } : {
13633
- checkOut: { $ne: null }
13634
- };
13635
- } else if (dateTo) {
13636
- checkOutFilter = {
13637
- $or: [
13638
- { checkOut: { $lte: new Date(dateTo).toISOString() } },
13639
- { checkOut: null }
13640
- ]
13641
- };
13637
+ const checkInFilter = {};
13638
+ const expectedCheckInFilter = {};
13639
+ if (status != "approved") {
13640
+ if (dateFrom)
13641
+ checkInFilter.$gte = new Date(dateFrom);
13642
+ if (dateTo)
13643
+ checkInFilter.$lte = new Date(dateTo);
13644
+ } else {
13645
+ if (dateFrom)
13646
+ expectedCheckInFilter.$gte = new Date(dateFrom);
13647
+ if (dateTo)
13648
+ expectedCheckInFilter.$lte = new Date(dateTo);
13642
13649
  }
13643
13650
  const query = {
13644
- status,
13645
13651
  ...import_mongodb40.ObjectId.isValid(org) && { org: new import_mongodb40.ObjectId(org) },
13646
13652
  ...import_mongodb40.ObjectId.isValid(site) && { site: new import_mongodb40.ObjectId(site) },
13647
- ...checkIn && { checkIn },
13653
+ ...Object.keys(checkInFilter).length > 0 && { checkIn: checkInFilter },
13654
+ ...Object.keys(expectedCheckInFilter).length > 0 && { expectedCheckIn: expectedCheckInFilter },
13648
13655
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
13649
- ...checkOutFilter ?? {},
13656
+ ...checkedOut == false && { checkOut: { $eq: null } },
13650
13657
  ...search && { $text: { $search: search } },
13651
- ...plateNumber && { plateNumber }
13658
+ ...plateNumber && { plateNumber },
13659
+ ...status && { status },
13660
+ ...tab == "Overnight Parking" && { isOvernightParking: true }
13652
13661
  };
13653
13662
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
13654
13663
  try {
@@ -13794,7 +13803,31 @@ function useVisitorTransactionRepo() {
13794
13803
  },
13795
13804
  { $sort: sort },
13796
13805
  { $skip: skip },
13797
- { $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
+ }
13798
13831
  ]).toArray(),
13799
13832
  collection.aggregate([...basePipeline, { $count: "total" }]).toArray()
13800
13833
  ]);
@@ -13869,7 +13902,7 @@ function useVisitorTransactionRepo() {
13869
13902
  } catch (error) {
13870
13903
  throw new import_node_server_utils68.BadRequestError("Invalid visitor transaction ID format.");
13871
13904
  }
13872
- value.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
13905
+ value.updatedAt = /* @__PURE__ */ new Date();
13873
13906
  if (value.checkOut) {
13874
13907
  value.manualCheckout = true;
13875
13908
  }
@@ -13893,8 +13926,8 @@ function useVisitorTransactionRepo() {
13893
13926
  try {
13894
13927
  const updateValue = {
13895
13928
  status: "deleted",
13896
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
13897
- deletedAt: (/* @__PURE__ */ new Date()).toISOString()
13929
+ updatedAt: /* @__PURE__ */ new Date(),
13930
+ deletedAt: /* @__PURE__ */ new Date()
13898
13931
  };
13899
13932
  const res = await collection.updateOne({ _id }, { $set: updateValue });
13900
13933
  if (res.modifiedCount === 0) {
@@ -13907,7 +13940,7 @@ function useVisitorTransactionRepo() {
13907
13940
  }
13908
13941
  async function getDeliveryPickupTransactions() {
13909
13942
  try {
13910
- const now = (/* @__PURE__ */ new Date()).toISOString();
13943
+ const now = /* @__PURE__ */ new Date();
13911
13944
  const result = await collection.find(
13912
13945
  {
13913
13946
  type: {
@@ -13934,7 +13967,7 @@ function useVisitorTransactionRepo() {
13934
13967
  async function getExpiredCheckedOutTransactionsBySite(siteId) {
13935
13968
  const site = (0, import_node_server_utils68.toObjectId)(siteId);
13936
13969
  try {
13937
- const now = (/* @__PURE__ */ new Date()).toISOString();
13970
+ const now = /* @__PURE__ */ new Date();
13938
13971
  const expiredTransactions = await collection.find({
13939
13972
  $or: [
13940
13973
  { expiredAt: { $lte: now } },
@@ -13960,7 +13993,7 @@ function useVisitorTransactionRepo() {
13960
13993
  {
13961
13994
  $set: {
13962
13995
  dahuaSyncStatus,
13963
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
13996
+ updatedAt: /* @__PURE__ */ new Date()
13964
13997
  }
13965
13998
  },
13966
13999
  { session }
@@ -14110,7 +14143,7 @@ function MVehicle(value) {
14110
14143
  block: value.block ?? 0,
14111
14144
  level: value.level ?? "",
14112
14145
  unit: value.unit ?? "",
14113
- nric: value.nric,
14146
+ nric: value.nric ?? "",
14114
14147
  remarks: value.remarks ?? "",
14115
14148
  seasonPassType: value.seasonPassType ?? "",
14116
14149
  start: value.start ?? createdAt,
@@ -14170,7 +14203,7 @@ function MVehicleTransaction(value) {
14170
14203
  var import_node_server_utils73 = require("@7365admin1/node-server-utils");
14171
14204
  var import_fs = require("fs");
14172
14205
  var import_joi39 = __toESM(require("joi"));
14173
- var path = __toESM(require("path"));
14206
+ var path2 = __toESM(require("path"));
14174
14207
  var import_urllib = require("urllib");
14175
14208
 
14176
14209
  // src/repositories/vehicle.repo.ts
@@ -14805,6 +14838,66 @@ function useVehicleRepo() {
14805
14838
  throw error;
14806
14839
  }
14807
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
+ }
14808
14901
  return {
14809
14902
  createIndex,
14810
14903
  createTextIndex,
@@ -14819,7 +14912,8 @@ function useVehicleRepo() {
14819
14912
  getVehiclesByNRIC,
14820
14913
  deleteExpiredVehicles,
14821
14914
  getAllVehiclesByUnitId,
14822
- getAllExpiredVehicles
14915
+ getAllExpiredVehicles,
14916
+ bulkUpsertVehicles
14823
14917
  };
14824
14918
  }
14825
14919
 
@@ -15451,7 +15545,8 @@ function useVehicleService() {
15451
15545
  getVehicleById: _getVehicleById,
15452
15546
  deleteExpiredVehicles: _deleteExpiredVehicles,
15453
15547
  getVehicleByPlateNumber: _getVehicleByPlateNumber,
15454
- getAllExpiredVehicles: _getAllExpiredVehicles
15548
+ getAllExpiredVehicles: _getAllExpiredVehicles,
15549
+ bulkUpsertVehicles: _bulkUpsertVehicles
15455
15550
  } = useVehicleRepo();
15456
15551
  const {
15457
15552
  addPlateNumber: _addPlateNumber,
@@ -16068,13 +16163,38 @@ function useVehicleService() {
16068
16163
  session.endSession();
16069
16164
  }
16070
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
+ }
16071
16190
  return {
16072
16191
  add,
16073
16192
  deleteVehicle,
16074
16193
  approveVehicleById,
16075
16194
  processDeletingExpiredVehicles,
16076
16195
  reactivateVehicleById,
16077
- updateVehicleById
16196
+ updateVehicleById,
16197
+ bulkUpsertVehicles
16078
16198
  };
16079
16199
  }
16080
16200
 
@@ -16348,8 +16468,8 @@ function useDahuaService() {
16348
16468
  const utcMs = Number(UTCMs) || Date.now() % 1e3;
16349
16469
  const timeData = createFileNameFromEvent(utcSec, utcMs);
16350
16470
  const filename = plateNumber ? `${gate}-${timeData}-${plateNumber}.jpeg` : `${gate}-${timeData}.jpeg`;
16351
- const snapFolder = path.join(__dirname, `../snap/${site}/${filename}`);
16352
- const dir = path.dirname(snapFolder);
16471
+ const snapFolder = path2.join(__dirname, `../snap/${site}/${filename}`);
16472
+ const dir = path2.dirname(snapFolder);
16353
16473
  try {
16354
16474
  await import_fs.promises.mkdir(dir, { recursive: true });
16355
16475
  await import_fs.promises.writeFile(snapFolder, accumulatedImageBuffer);
@@ -17171,13 +17291,15 @@ var schemaBuilding = import_joi43.default.object({
17171
17291
  updatedAt: import_joi43.default.date().optional().allow("", null),
17172
17292
  deletedAt: import_joi43.default.date().optional().allow("", null),
17173
17293
  status: import_joi43.default.string().optional().allow("", null),
17174
- buildingFloorPlan: import_joi43.default.array().items(import_joi43.default.string()).optional()
17294
+ // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
17295
+ buildingFiles: import_joi43.default.array().items({ id: import_joi43.default.string().hex().optional().allow("", null), name: import_joi43.default.string().optional().allow("", null) }).optional().allow("", null)
17175
17296
  });
17176
17297
  var schemaBuildingUpdateOptions = import_joi43.default.object({
17177
17298
  name: import_joi43.default.string().optional().allow("", null),
17178
17299
  levels: import_joi43.default.array().items(import_joi43.default.string().required()).min(1).required(),
17179
17300
  block: import_joi43.default.number().integer().min(1).required(),
17180
- buildingFloorPlan: import_joi43.default.array().items(import_joi43.default.string()).optional()
17301
+ // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
17302
+ buildingFiles: import_joi43.default.array().items({ id: import_joi43.default.string().hex().optional().allow("", null), name: import_joi43.default.string().optional().allow("", null) }).optional().allow("", null)
17181
17303
  });
17182
17304
  var schemaBilling = import_joi43.default.object({
17183
17305
  _id: import_joi43.default.string().hex().optional(),
@@ -17243,7 +17365,8 @@ function MBuilding(value) {
17243
17365
  block: value.block ?? 0,
17244
17366
  levels: value.levels ?? "",
17245
17367
  status: value.status ?? "active",
17246
- buildingFloorPlan: value.buildingFloorPlan ?? [],
17368
+ // buildingFloorPlan: value.buildingFloorPlan ?? [],
17369
+ buildingFiles: value.buildingFiles ?? [],
17247
17370
  createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
17248
17371
  updatedAt: value.updatedAt ?? "",
17249
17372
  deletedAt: value.deletedAt ?? ""
@@ -18149,11 +18272,11 @@ function useBuildingService() {
18149
18272
  }
18150
18273
  try {
18151
18274
  await session.startTransaction();
18152
- const buildingFloorPlans = value?.buildingFloorPlan ?? [];
18153
- if (buildingFloorPlans.length > 0) {
18154
- for (const buildingFloorPlan of buildingFloorPlans) {
18275
+ const buildingFiles = value?.buildingFiles ?? [];
18276
+ if (buildingFiles.length > 0) {
18277
+ for (const buildingFile of buildingFiles) {
18155
18278
  const file = await updateStatusById(
18156
- buildingFloorPlan,
18279
+ buildingFile.id,
18157
18280
  { status: "active" },
18158
18281
  session
18159
18282
  );
@@ -18187,12 +18310,12 @@ function useBuildingService() {
18187
18310
  if (!building) {
18188
18311
  throw new import_node_server_utils82.NotFoundError("Building not found.");
18189
18312
  }
18190
- const dataFloorPlans = data?.buildingFloorPlan || [];
18191
- const buildingFloorPlans = building?.buildingFloorPlan || [];
18313
+ const dataFiles = data?.buildingFiles || [];
18314
+ const buildingFiles = building?.buildingFiles || [];
18192
18315
  const deletedFiles = [];
18193
- buildingFloorPlans.forEach((id2) => {
18194
- if (!dataFloorPlans.includes(id2)) {
18195
- deletedFiles.push(id2);
18316
+ buildingFiles.forEach((file) => {
18317
+ if (!dataFiles.find((f) => f.id === file.id)) {
18318
+ deletedFiles.push(file.id);
18196
18319
  }
18197
18320
  });
18198
18321
  if (deletedFiles.length > 0) {
@@ -18288,7 +18411,8 @@ function useBuildingController() {
18288
18411
  levels: import_joi44.default.array().items(import_joi44.default.string().required()).min(1).required(),
18289
18412
  serial: import_joi44.default.string().optional().allow("", null),
18290
18413
  status: import_joi44.default.string().optional().allow("", null),
18291
- buildingFloorPlan: import_joi44.default.array().items(import_joi44.default.string()).optional()
18414
+ // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
18415
+ buildingFiles: import_joi44.default.array().items({ id: import_joi44.default.string().hex().optional().allow("", null), name: import_joi44.default.string().optional().allow("", null) }).optional().allow("", null)
18292
18416
  });
18293
18417
  const { error } = validation.validate(value);
18294
18418
  if (error) {
@@ -18746,13 +18870,18 @@ function useBuildingUnitController() {
18746
18870
  // src/controllers/vehicle.controller.ts
18747
18871
  var import_node_server_utils86 = require("@7365admin1/node-server-utils");
18748
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"));
18749
18877
  function useVehicleController() {
18750
18878
  const {
18751
18879
  add: _add,
18752
18880
  deleteVehicle: _deleteVehicle,
18753
18881
  approveVehicleById: _approveVehicleById,
18754
18882
  reactivateVehicleById: _reactivateVehicleById,
18755
- updateVehicleById: _updateVehicleById
18883
+ updateVehicleById: _updateVehicleById,
18884
+ bulkUpsertVehicles: _bulkUpsertVehicles
18756
18885
  } = useVehicleService();
18757
18886
  const {
18758
18887
  getSeasonPassTypes: _getSeasonPassTypes,
@@ -18761,6 +18890,141 @@ function useVehicleController() {
18761
18890
  getVehiclesByNRIC: _getVehiclesByNRIC,
18762
18891
  getAllVehiclesByUnitId: _getAllVehiclesByUnitId
18763
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
+ }
18764
19028
  async function add(req, res, next) {
18765
19029
  const { error, value } = vehicleSchema.validate(req.body, {
18766
19030
  abortEarly: false
@@ -19085,6 +19349,69 @@ function useVehicleController() {
19085
19349
  return;
19086
19350
  }
19087
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
+ }
19088
19415
  return {
19089
19416
  add,
19090
19417
  getVehicles,
@@ -19095,7 +19422,10 @@ function useVehicleController() {
19095
19422
  approveVehicleById,
19096
19423
  getVehiclesByNRIC,
19097
19424
  reactivateVehicleById,
19098
- getAllVehiclesByUnitId
19425
+ getAllVehiclesByUnitId,
19426
+ bulkUpsertVehicles,
19427
+ uploadCsvVehicles,
19428
+ uploadExcelVehicles
19099
19429
  };
19100
19430
  }
19101
19431
 
@@ -21976,6 +22306,8 @@ function useVisitorTransactionService() {
21976
22306
  try {
21977
22307
  const updatePayload = { status: "In Use" /* IN_USE */ };
21978
22308
  const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb58.ObjectId ? vp : vp.keyId;
22309
+ if (!visitorPassId)
22310
+ value.visitorPass = [];
21979
22311
  await KeyRepo.updateKeyById(
21980
22312
  visitorPassId,
21981
22313
  updatePayload,
@@ -21991,6 +22323,8 @@ function useVisitorTransactionService() {
21991
22323
  try {
21992
22324
  const updatePayload = { status: "In Use" /* IN_USE */ };
21993
22325
  const passKeyId = typeof pk === "string" || pk instanceof import_mongodb58.ObjectId ? pk : pk.keyId;
22326
+ if (!passKeyId)
22327
+ value.passKeys = [];
21994
22328
  await KeyRepo.updateKeyById(
21995
22329
  passKeyId,
21996
22330
  updatePayload,
@@ -22102,11 +22436,13 @@ function useVisitorTransactionService() {
22102
22436
  value.recNo = parsed.recNo;
22103
22437
  }
22104
22438
  }
22105
- if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
22439
+ if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0 && value.visitorPass) {
22106
22440
  for (const vp of value.visitorPass) {
22107
22441
  try {
22108
22442
  const updatePayload = { status: "In Use" /* IN_USE */ };
22109
22443
  const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb58.ObjectId ? vp : vp.keyId;
22444
+ if (!visitorPassId)
22445
+ value.visitorPass = [];
22110
22446
  await KeyRepo.updateKeyById(
22111
22447
  visitorPassId,
22112
22448
  updatePayload,
@@ -22122,6 +22458,8 @@ function useVisitorTransactionService() {
22122
22458
  try {
22123
22459
  const updatePayload = { status: "In Use" /* IN_USE */ };
22124
22460
  const passKeyId = typeof pk === "string" || pk instanceof import_mongodb58.ObjectId ? pk : pk.keyId;
22461
+ if (!passKeyId)
22462
+ value.passKeys = [];
22125
22463
  await KeyRepo.updateKeyById(
22126
22464
  passKeyId,
22127
22465
  updatePayload,
@@ -22293,7 +22631,7 @@ function useVisitorTransactionService() {
22293
22631
  org: inviter?.org.toString(),
22294
22632
  site: inviter?.site.toString(),
22295
22633
  status: "approved" /* APPROVED */,
22296
- invitedId: inviter?._id
22634
+ inviterId: userId
22297
22635
  };
22298
22636
  const result = await _add(payload);
22299
22637
  const emailContent = (0, import_node_server_utils101.compileHandlebar)({
@@ -22444,7 +22782,8 @@ function useVisitorTransactionController() {
22444
22782
  }).optional().allow(null, ""),
22445
22783
  checkedOut: import_joi55.default.boolean().allow(null, ""),
22446
22784
  plateNumber: import_joi55.default.string().optional().allow(null, ""),
22447
- 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, "")
22448
22787
  });
22449
22788
  const { error, value } = validation.validate(req.query, {
22450
22789
  abortEarly: false
@@ -22468,7 +22807,8 @@ function useVisitorTransactionController() {
22468
22807
  checkedOut,
22469
22808
  sort,
22470
22809
  order,
22471
- plateNumber
22810
+ plateNumber,
22811
+ tab
22472
22812
  } = value;
22473
22813
  const sortObj = {
22474
22814
  [sort ? sort : "_id" /* ID */]: order === "asc" /* ASC */ ? 1 : -1
@@ -22485,7 +22825,8 @@ function useVisitorTransactionController() {
22485
22825
  dateFrom,
22486
22826
  type,
22487
22827
  checkedOut,
22488
- plateNumber
22828
+ plateNumber,
22829
+ tab
22489
22830
  });
22490
22831
  res.status(200).json(data);
22491
22832
  return;
@@ -29698,7 +30039,7 @@ function useSiteBillingItemService() {
29698
30039
  }
29699
30040
  try {
29700
30041
  await session.startTransaction();
29701
- const billing_item = await _getBillingItemById(id, session);
30042
+ const billing_item = await _getBillingItemById(id);
29702
30043
  if (!billing_item) {
29703
30044
  throw new import_node_server_utils141.BadRequestError("Billing item not found.");
29704
30045
  }
@@ -30705,10 +31046,32 @@ function useEventManagementController() {
30705
31046
  var import_node_server_utils148 = require("@7365admin1/node-server-utils");
30706
31047
  var import_mongodb85 = require("mongodb");
30707
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 || {});
30708
31071
  var schemaUnitBilling = import_joi83.default.object({
30709
31072
  _id: import_joi83.default.string().hex().optional(),
30710
- site: import_joi83.default.string().hex().required(),
30711
- 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, ""),
30712
31075
  billItem: import_joi83.default.string().hex().optional().allow(null, ""),
30713
31076
  billName: import_joi83.default.string().optional().allow(null, ""),
30714
31077
  unitId: import_joi83.default.string().hex().optional().allow(null, ""),
@@ -30728,6 +31091,7 @@ var schemaUnitBilling = import_joi83.default.object({
30728
31091
  paymentStatus: import_joi83.default.string().optional().allow(null, ""),
30729
31092
  status: import_joi83.default.string().optional().allow(null, ""),
30730
31093
  amountPaid: import_joi83.default.number().optional().allow(null, ""),
31094
+ balanceAmount: import_joi83.default.number().optional().allow(null, ""),
30731
31095
  paidBy: import_joi83.default.string().hex().optional().allow(null, ""),
30732
31096
  datePaid: import_joi83.default.date().optional().allow(null, ""),
30733
31097
  transaction_id: import_joi83.default.string().optional().allow(null, ""),
@@ -30751,6 +31115,7 @@ var schemaUpdateSiteUnitBilling = import_joi83.default.object({
30751
31115
  category: import_joi83.default.string().optional().allow(null, ""),
30752
31116
  frequency: import_joi83.default.string().optional().allow(null, ""),
30753
31117
  totalAmount: import_joi83.default.number().optional().allow(null, ""),
31118
+ balanceAmount: import_joi83.default.number().optional().allow(null, ""),
30754
31119
  taxPercentage: import_joi83.default.number().optional().allow(null, ""),
30755
31120
  taxAmount: import_joi83.default.number().optional().allow(null, ""),
30756
31121
  amount: import_joi83.default.number().optional().allow(null, ""),
@@ -30816,8 +31181,8 @@ function MUnitBilling(value) {
30816
31181
  }
30817
31182
  return {
30818
31183
  _id: value._id ?? new import_mongodb85.ObjectId(),
30819
- site: value.site,
30820
- org: value.org,
31184
+ site: value.site ?? "",
31185
+ org: value.org ?? "",
30821
31186
  billItem: value.billItem ?? "",
30822
31187
  billName: value.billName ?? "",
30823
31188
  unitId: value.unitId ?? "",
@@ -30837,6 +31202,7 @@ function MUnitBilling(value) {
30837
31202
  paymentStatus: value.paymentStatus ?? "",
30838
31203
  status: value.status ?? "active",
30839
31204
  amountPaid: value.amountPaid ?? 0,
31205
+ balanceAmount: value.balanceAmount ?? 0,
30840
31206
  paidBy: value.paidBy ?? "",
30841
31207
  datePaid: value.datePaid ?? "",
30842
31208
  transaction_id: value.transaction_id ?? "",
@@ -30880,7 +31246,7 @@ function useSiteUnitBillingRepo() {
30880
31246
  value = MUnitBilling(value);
30881
31247
  const res = await collection.insertOne(value, { session });
30882
31248
  const acronym = createAcronym(value.billName || "NA");
30883
- const dateFormatted = formatDateString2(/* @__PURE__ */ new Date());
31249
+ const dateFormatted = formatDateString(/* @__PURE__ */ new Date());
30884
31250
  const newId = new import_mongodb86.ObjectId(res.insertedId).toString().slice(-6);
30885
31251
  const referenceNumber = `${acronym}${newId}${dateFormatted}`;
30886
31252
  await collection.updateOne(
@@ -31306,7 +31672,7 @@ function useSiteUnitBillingRepo() {
31306
31672
  function createAcronym(billName) {
31307
31673
  return billName.split(" ").map((word) => word.charAt(0).toUpperCase()).join("");
31308
31674
  }
31309
- function formatDateString2(today) {
31675
+ function formatDateString(today) {
31310
31676
  today = typeof today === "string" ? new Date(today) : today;
31311
31677
  let month = today.getMonth() + 1;
31312
31678
  let day = today.getDate();
@@ -31823,8 +32189,8 @@ var import_node_server_utils152 = require("@7365admin1/node-server-utils");
31823
32189
  var import_mongodb89 = require("mongodb");
31824
32190
 
31825
32191
  // src/utils/access-management.ts
31826
- var import_fs2 = __toESM(require("fs"));
31827
- var import_path = __toESM(require("path"));
32192
+ var import_fs3 = __toESM(require("fs"));
32193
+ var import_path2 = __toESM(require("path"));
31828
32194
  var import_axios = __toESM(require("axios"));
31829
32195
  var import_xml2js = require("xml2js");
31830
32196
  var import_crypto = __toESM(require("crypto"));
@@ -31853,8 +32219,8 @@ var minifyXml = (xml) => {
31853
32219
  return xml.replace(/>\s+</g, "><").replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").trim();
31854
32220
  };
31855
32221
  var readTemplate = (name, params) => {
31856
- const template = import_fs2.default.readFileSync(
31857
- 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`),
31858
32224
  "utf-8"
31859
32225
  );
31860
32226
  if (!params)
@@ -31963,14 +32329,14 @@ var import_xml2js2 = require("xml2js");
31963
32329
 
31964
32330
  // src/utils/rsa-encryption.ts
31965
32331
  var crypto2 = __toESM(require("crypto"));
31966
- var import_fs3 = __toESM(require("fs"));
31967
- var import_path2 = __toESM(require("path"));
31968
- var pub = import_path2.default.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_pub.pem");
31969
- 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");
31970
32336
  var EncryptionCredentials = class {
31971
32337
  };
31972
- EncryptionCredentials.RAW_PUBLIC_KEY = import_fs3.default.readFileSync(pub, "utf8");
31973
- 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");
31974
32340
  var EntrypassRSAEncryption = class extends EncryptionCredentials {
31975
32341
  static hexToCardNumber(hex) {
31976
32342
  if (!/^[0-9A-Fa-f]{8}$/.test(hex)) {
@@ -33926,7 +34292,7 @@ var import_joi85 = __toESM(require("joi"));
33926
34292
 
33927
34293
  // src/services/access-management.service.ts
33928
34294
  var import_xml2js3 = require("xml2js");
33929
- var import_stream = require("stream");
34295
+ var import_stream2 = require("stream");
33930
34296
  var xlsx = __toESM(require("xlsx"));
33931
34297
  function useAccessManagementSvc() {
33932
34298
  const {
@@ -34131,7 +34497,7 @@ function useAccessManagementSvc() {
34131
34497
  };
34132
34498
  const convertBufferFile = async (bufferFile) => {
34133
34499
  return new Promise((resolve, reject) => {
34134
- const fileStream = import_stream.Readable.from(bufferFile);
34500
+ const fileStream = import_stream2.Readable.from(bufferFile);
34135
34501
  let fileBuffer = Buffer.alloc(0);
34136
34502
  fileStream.on("data", (chunk) => {
34137
34503
  fileBuffer = Buffer.concat([fileBuffer, chunk]);
@@ -46372,118 +46738,8 @@ function genericSignature(params, secretKey) {
46372
46738
  }
46373
46739
 
46374
46740
  // src/repositories/reddot-payment.repository.ts
46375
- var import_mongodb127 = require("mongodb");
46376
-
46377
- // src/utils/date-format.util.ts
46378
- var import_moment_timezone6 = __toESM(require("moment-timezone"));
46379
- function formatDateString(today, format, dateRange) {
46380
- today = typeof today === "string" ? new Date(today) : today;
46381
- let month = today.getMonth() + 1;
46382
- let day = today.getDate();
46383
- let year = today.getFullYear();
46384
- let formattedDate;
46385
- if (format === "mm-dd-yyyy") {
46386
- formattedDate = `${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}-${year}`;
46387
- } else if (format === "dd-mm-yyyy") {
46388
- formattedDate = `${day.toString().padStart(2, "0")}-${month.toString().padStart(2, "0")}-${year}`;
46389
- } else if (format === "for-ref") {
46390
- formattedDate = `${month.toString().padStart(2, "0")}${day.toString().padStart(2, "0")}${year}`;
46391
- } else if (format === "mm/dd/yyyy") {
46392
- formattedDate = `${month.toString().padStart(2, "0")}/${day.toString().padStart(2, "0")}/${year}`;
46393
- } else {
46394
- formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
46395
- }
46396
- return formattedDate;
46397
- }
46398
-
46399
- // src/models/credit-card.model.ts
46400
- var import_mongodb124 = require("mongodb");
46401
- var MCardInfo = class {
46402
- // this is coming from RDP transaction
46403
- constructor({
46404
- _id = new import_mongodb124.ObjectId(),
46405
- userId,
46406
- cardType,
46407
- cardNumber,
46408
- cardId,
46409
- fullName,
46410
- expiryDate,
46411
- cvv,
46412
- site,
46413
- siteName,
46414
- organization,
46415
- createdBy,
46416
- createdAt,
46417
- updatedAt,
46418
- transaction_id
46419
- } = {}) {
46420
- this._id = _id;
46421
- this.userId = userId;
46422
- this.cardType = cardType;
46423
- this.cardNumber = cardNumber;
46424
- this.cardId = cardId;
46425
- this.fullName = fullName;
46426
- this.expiryDate = expiryDate;
46427
- this.cvv = cvv;
46428
- this.site = site;
46429
- this.siteName = siteName;
46430
- this.organization = organization;
46431
- this.createdBy = createdBy;
46432
- this.createdAt = createdAt;
46433
- this.updatedAt = updatedAt;
46434
- this.transaction_id = transaction_id;
46435
- }
46436
- };
46437
-
46438
- // src/models/cart.model.ts
46439
- var import_mongodb125 = require("mongodb");
46440
- var MUnitBillings = class {
46441
- // transaction response messages
46442
- constructor({
46443
- _id = new import_mongodb125.ObjectId(),
46444
- unit,
46445
- unitId,
46446
- unitBill,
46447
- paymentStatus = "Processing" /* processing */,
46448
- referenceNumber,
46449
- amountPaid,
46450
- paidBy,
46451
- datePaid,
46452
- billCategory,
46453
- billFrom,
46454
- billTo,
46455
- site,
46456
- organization,
46457
- createdBy,
46458
- createdAt,
46459
- updatedAt,
46460
- message
46461
- } = {}) {
46462
- this._id = _id;
46463
- this.unit = unit;
46464
- this.unitId = unitId;
46465
- this.referenceNumber = referenceNumber;
46466
- this.unitBill = unitBill;
46467
- this.paymentStatus = paymentStatus;
46468
- this.amountPaid = amountPaid;
46469
- this.site = site;
46470
- this.organization = organization;
46471
- this.paidBy = paidBy;
46472
- this.datePaid = datePaid;
46473
- this.billCategory = billCategory;
46474
- this.billFrom = billFrom;
46475
- this.billTo = billTo;
46476
- this.createdBy = createdBy;
46477
- this.createdAt = createdAt;
46478
- this.updatedAt = updatedAt;
46479
- this.message = message;
46480
- }
46481
- };
46482
-
46483
- // src/repositories/payment.repository.ts
46484
- var import_mongodb126 = require("mongodb");
46485
46741
  var import_node_server_utils216 = require("@7365admin1/node-server-utils");
46486
- var PaymentBillRepo = () => {
46742
+ var useRedDotPaymentRepo = () => {
46487
46743
  const getDB2 = () => {
46488
46744
  const db = import_node_server_utils216.useAtlas.getDb();
46489
46745
  if (!db) {
@@ -46491,347 +46747,75 @@ var PaymentBillRepo = () => {
46491
46747
  }
46492
46748
  return db;
46493
46749
  };
46494
- const collection = () => {
46495
- return getDB2().collection("unit-bill");
46750
+ const paymentCollection = () => {
46751
+ return getDB2().collection("payments");
46496
46752
  };
46497
- const billCollection = () => {
46498
- return getDB2().collection("bill-records");
46753
+ const unitBillingCollection = () => {
46754
+ return getDB2().collection("site.unit.billing");
46499
46755
  };
46500
- const creditCollection = () => {
46501
- return getDB2().collection("credit-info");
46756
+ const orgCollection = () => {
46757
+ return getDB2().collection("organizations");
46502
46758
  };
46503
- const cartCollection = () => {
46504
- return getDB2().collection("checkout-cart");
46759
+ const redDotMerchantCollection = () => {
46760
+ return getDB2().collection("payment-gateways");
46505
46761
  };
46506
- const payUnitBill = async (refId, payload) => {
46762
+ async function paySingleUnitBill(refId, payload) {
46507
46763
  try {
46508
46764
  if (refId)
46509
46765
  refId = refId.toString();
46510
- const unitBillInfo = await collection().findOne({ referenceNumber: refId });
46511
- const unitBillId = unitBillInfo?._id;
46766
+ const unitBillInfo = await unitBillingCollection().findOne({
46767
+ referenceNumber: refId
46768
+ });
46512
46769
  if (!unitBillInfo) {
46513
46770
  throw new Error("Unit bill info not found");
46514
46771
  }
46515
- if (unitBillInfo?.status === "Inactive" /* inactive */) {
46772
+ if (unitBillInfo?.status === "inactive" /* INACTIVE */) {
46516
46773
  throw new Error("This Bill is Inactive!");
46517
46774
  }
46518
- const billId = new import_mongodb126.ObjectId(unitBillInfo?.billId);
46519
- const billInfo = await billCollection().findOne({ _id: billId });
46520
- if (!billInfo) {
46521
- throw new Error("Bill info not found");
46522
- }
46523
- if (payload.paymentStatus === "Partial Payment" /* partial */ && payload.amountPaid) {
46524
- const price = parseInt(billInfo?.price);
46525
- const amount = payload.amountPaid;
46526
- const numericPrice = typeof price === "string" ? parseInt(price) : price;
46527
- const numericAmount = typeof amount === "string" ? parseInt(amount) : amount;
46528
- if (typeof amount !== "number") {
46529
- throw new Error("Amount is not a valid number");
46530
- } else if (typeof price !== "number") {
46531
- 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");
46532
46782
  }
46533
- payload.balance = numericPrice - numericAmount;
46534
- } else if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
46783
+ payload.balanceAmount = totalAmount - amountPaid;
46784
+ } else if (payload.paymentStatus === "paid" /* PAID */ && payload.amountPaid) {
46535
46785
  payload.datePaid = /* @__PURE__ */ new Date();
46536
- payload.paymentStatus = "Paid" /* paid */;
46786
+ payload.paymentStatus = "paid" /* PAID */;
46537
46787
  payload.amountPaid;
46538
46788
  payload.transaction_id;
46539
- } else if (payload.paymentStatus === "Failed" /* failed */) {
46789
+ } else if (payload.paymentStatus === "failed" /* FAILED */) {
46540
46790
  payload.amountPaid = 0;
46541
- payload.paidBy = "";
46542
- payload.datePaid = "";
46543
- payload.paymentStatus = "Failed" /* failed */;
46791
+ payload.paymentStatus = "failed" /* FAILED */;
46544
46792
  payload.transaction_id;
46545
46793
  }
46546
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46547
- payload.updatedAt = updatedAt;
46548
- const result = await collection().findOneAndUpdate({ _id: unitBillId }, { $set: payload }, { returnDocument: "after" });
46549
- return result;
46550
- } catch (error) {
46551
- throw new Error(error.message || error || "Server Internal Error");
46552
- }
46553
- };
46554
- const saveCreditCardInfo = async (payload) => {
46555
- try {
46556
- if (payload.userId)
46557
- payload.userId = new import_mongodb126.ObjectId(payload.userId);
46558
- if (payload.site)
46559
- payload.site = new import_mongodb126.ObjectId(payload.site);
46560
- if (payload.organization)
46561
- payload.organization = new import_mongodb126.ObjectId(payload.organization);
46562
- if (payload.createdBy)
46563
- payload.createdBy = new import_mongodb126.ObjectId(payload.createdBy);
46564
- const createdAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46565
- payload.createdAt = createdAt;
46566
- const result = await creditCollection().insertOne(new MCardInfo(payload));
46567
- return result;
46568
- } catch (error) {
46569
- throw new Error(error.message || error || "Server Internal Error");
46570
- }
46571
- };
46572
- const checkOutUnitBills = async (payload) => {
46573
- try {
46574
- if (payload.unitId)
46575
- payload.unitId = new import_mongodb126.ObjectId(payload.unitId);
46576
- if (payload.site)
46577
- payload.site = new import_mongodb126.ObjectId(payload.site);
46578
- if (payload.organization)
46579
- payload.organization = new import_mongodb126.ObjectId(payload.organization);
46580
- payload.createdAt = await formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46581
- const addToCart = await cartCollection().insertOne(new MUnitBillings(payload));
46582
- const unitId = payload.unitId;
46583
- const dateFormatted = formatDateString(/* @__PURE__ */ new Date(), "for-ref");
46584
- const unit = unitId?.toString().slice(-4);
46585
- const newId = new import_mongodb126.ObjectId(addToCart?.insertedId).toString().slice(-4);
46586
- const referenceNumber = `CRT${unit}${newId}${dateFormatted}`;
46587
- const result = await cartCollection().findOneAndUpdate({ _id: new import_mongodb126.ObjectId(addToCart.insertedId) }, { $set: { referenceNumber } }, { returnDocument: "after" });
46588
- return result;
46589
- } catch (error) {
46590
- throw new Error(error.message || error || "Server Internal Error");
46591
- }
46592
- };
46593
- const payUnitCart = async (refId, payload) => {
46594
- try {
46595
- if (refId)
46596
- refId = refId.toString();
46597
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46598
- const cartInfo = await cartCollection().findOne({ referenceNumber: refId });
46599
- const refNumber = cartInfo?.unitBill;
46600
- if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
46601
- payload.datePaid = /* @__PURE__ */ new Date();
46602
- payload.paymentStatus = "Paid" /* paid */;
46603
- payload.amountPaid;
46604
- } else if (payload.paymentStatus === "Failed" /* failed */) {
46605
- payload.amountPaid = 0;
46606
- payload.paidBy = "";
46607
- payload.datePaid = "";
46608
- payload.paymentStatus = "Failed" /* failed */;
46609
- }
46610
- payload.updatedAt = updatedAt;
46611
- const result = await cartCollection().findOneAndUpdate({ referenceNumber: refId }, { $set: payload }, { returnDocument: "after" });
46612
- if (!result) {
46613
- throw new Error("Failed to Process Transaction. Please Try Again Later");
46614
- } else {
46615
- for (const ref of refNumber) {
46616
- const unitBillInfo = await collection().findOne({ referenceNumber: ref });
46617
- const billId = unitBillInfo?.billId;
46618
- const billInfo = await billCollection().findOne({ _id: new import_mongodb126.ObjectId(billId) });
46619
- const billAmount = billInfo?.price;
46620
- payload.updatedAt = updatedAt;
46621
- payload.amountPaid = billAmount;
46622
- const eachRef = await payUnitBill(ref, payload);
46623
- }
46624
- if (!cartInfo) {
46625
- throw new Error("Cart info not found");
46626
- }
46627
- }
46794
+ payload.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
46795
+ const result = await unitBillingCollection().findOneAndUpdate(
46796
+ { _id: unitBillInfo._id },
46797
+ { $set: payload },
46798
+ { returnDocument: "after" }
46799
+ );
46628
46800
  return result;
46629
46801
  } catch (error) {
46630
46802
  throw new Error(error.message || error || "Server Internal Error");
46631
46803
  }
46632
- };
46633
- const getCheckedOutBillings = async (refId) => {
46634
- try {
46635
- if (refId)
46636
- refId = refId.toString();
46637
- const result = await cartCollection().aggregate([
46638
- { $match: { referenceNumber: refId } },
46639
- {
46640
- $lookup: {
46641
- from: "unit-bill",
46642
- localField: "unitBill",
46643
- foreignField: "referenceNumber",
46644
- as: "unitBill"
46645
- }
46646
- },
46647
- {
46648
- $unwind: "$unitBill"
46649
- },
46650
- {
46651
- $lookup: {
46652
- from: "bill-records",
46653
- localField: "unitBill.billId",
46654
- foreignField: "_id",
46655
- as: "billDetails"
46656
- }
46657
- },
46658
- {
46659
- $unwind: {
46660
- path: "$billDetails",
46661
- preserveNullAndEmptyArrays: true
46662
- }
46663
- },
46664
- {
46665
- $addFields: {
46666
- "unitBill.billItemName": "$billDetails.billItem"
46667
- }
46668
- },
46669
- {
46670
- $project: {
46671
- "unitBill.paidBy": 0,
46672
- "unitBill.preDueDateAlert": 0,
46673
- "unitBill.category": 0,
46674
- "unitBill.contactNumber": 0,
46675
- "unitBill.email": 0,
46676
- "unitBill.site": 0,
46677
- "unitBill.siteName": 0,
46678
- "unitBill.organization": 0,
46679
- "unitBill.billStatus": 0,
46680
- "unitBill.createdBy": 0,
46681
- "unitBill.createdAt": 0,
46682
- "unitBill.updatedAt": 0,
46683
- "billDetails": 0
46684
- // Exclude the full billDetails as it's no longer needed
46685
- }
46686
- },
46687
- {
46688
- $group: {
46689
- _id: "$_id",
46690
- unitId: { $first: "$unitId" },
46691
- referenceNumber: { $first: "$referenceNumber" },
46692
- unitBill: { $push: "$unitBill" },
46693
- paymentStatus: { $first: "$paymentStatus" },
46694
- amountPaid: { $first: "$amountPaid" },
46695
- site: { $first: "$site" },
46696
- organization: { $first: "$organization" },
46697
- paidBy: { $first: "$paidBy" },
46698
- datePaid: { $first: "$referenceNumber" },
46699
- billCategory: { $first: "$billCategory" },
46700
- billFrom: { $first: "$billFrom" },
46701
- billTo: { $first: "$billTo" },
46702
- createdBy: { $first: "$createdBy" },
46703
- createdAt: { $first: "$createdAt" },
46704
- updatedAt: { $first: "$updatedAt" },
46705
- transaction_id: { $first: "$transaction_id" }
46706
- }
46707
- }
46708
- ]).toArray();
46709
- if (!result || result.length === 0) {
46710
- return { success: false, message: "Cart Info Not Found" };
46711
- }
46712
- return result[0];
46713
- } catch (error) {
46714
- throw new Error(error.message || error || "Server Internal Error");
46715
- }
46716
- };
46717
- const cancelCheckedOutBillings = async (refId) => {
46718
- try {
46719
- if (refId)
46720
- refId = refId.toString();
46721
- const result = await cartCollection().findOneAndDelete({ referenceNumber: refId });
46722
- if (!result) {
46723
- return { success: false, message: "Cart Info Not Found" };
46724
- }
46725
- return { success: true, message: "Cart Deleted Successfully!", referenceNumber: result?.referenceNumber };
46726
- } catch (error) {
46727
- throw new Error(error.message || error || "Server Internal Error");
46728
- }
46729
- };
46730
- return {
46731
- saveCreditCardInfo,
46732
- checkOutUnitBills,
46733
- payUnitBill,
46734
- payUnitCart,
46735
- getCheckedOutBillings,
46736
- cancelCheckedOutBillings
46737
- };
46738
- };
46739
-
46740
- // src/repositories/reddot-payment.repository.ts
46741
- var import_node_server_utils217 = require("@7365admin1/node-server-utils");
46742
- var useRedDotPaymentRepo = () => {
46743
- const getDB2 = () => {
46744
- const db = import_node_server_utils217.useAtlas.getDb();
46745
- if (!db) {
46746
- throw new import_node_server_utils217.InternalServerError("Unable to connect to server.");
46747
- }
46748
- return db;
46749
- };
46750
- const collection = () => {
46751
- return getDB2().collection("unit-bill");
46752
- };
46753
- const orgCollection = () => {
46754
- return getDB2().collection("organizations");
46755
- };
46756
- const cartCollection = () => {
46757
- return getDB2().collection("checkout-cart");
46758
- };
46759
- const redDotMerchantCollection = () => {
46760
- return getDB2().collection("reddot-merchant");
46761
- };
46762
- const createRedDotAccount = async (_id, payload) => {
46763
- try {
46764
- const merchant = await redDotMerchantCollection().insertOne(payload);
46765
- if (!merchant) {
46766
- throw new Error("Failed to Add Merchant Details");
46767
- }
46768
- const merchantId = merchant?.insertedId;
46769
- const orgId = new import_mongodb127.ObjectId(_id);
46770
- const result = await orgCollection().findOneAndUpdate({ _id: orgId }, { $push: { merchant: merchantId } }, {
46771
- returnDocument: "after"
46772
- });
46773
- if (!result) {
46774
- throw new Error("Organization not found");
46775
- }
46776
- return {
46777
- success: true,
46778
- message: "Merchant Details successfully added."
46779
- };
46780
- } catch (error) {
46781
- throw new Error(error.message || error || "Server Internal Error");
46782
- }
46783
- };
46784
- const payUnitBillings = async (refId, payload) => {
46785
- const checkCart = await cartCollection().findOne({ referenceNumber: refId });
46786
- if (checkCart) {
46787
- const multiple = await PaymentBillRepo().payUnitCart(refId, payload);
46788
- if (multiple) {
46789
- return await PaymentBillRepo().getCheckedOutBillings(refId);
46790
- }
46791
- }
46792
- const single = await PaymentBillRepo().payUnitBill(refId, payload);
46793
- return single;
46794
- };
46795
- const getMerchantDetailsById = async (_id) => {
46796
- try {
46797
- if (_id)
46798
- _id = new import_mongodb127.ObjectId(_id);
46799
- const result = await redDotMerchantCollection().aggregate([
46800
- {
46801
- $match: {
46802
- _id
46803
- }
46804
- },
46805
- {
46806
- $facet: {
46807
- totalCount: [{ $count: "count" }],
46808
- items: [{ $sort: { _id: -1 } }]
46809
- }
46810
- }
46811
- ]).toArray();
46812
- const items = result[0].items;
46813
- return items;
46814
- } catch (error) {
46815
- throw new Error(error.message || error || "Server Internal Error");
46816
- }
46817
- };
46818
- return {
46819
- createRedDotAccount,
46820
- payUnitBillings,
46821
- getMerchantDetailsById
46822
- };
46804
+ }
46805
+ return { paySingleUnitBill };
46823
46806
  };
46824
46807
 
46825
46808
  // src/services/reddot-payment.service.ts
46826
46809
  var useRedDotPaymentSvc = () => {
46827
- const createRedDotAccount = async (_id, payload) => {
46828
- return useRedDotPaymentRepo().createRedDotAccount(_id, payload);
46829
- };
46810
+ const { paySingleUnitBill } = useRedDotPaymentRepo();
46830
46811
  const redirectPaymentTransaction = async (payload) => {
46831
46812
  try {
46832
46813
  const SECRET_KEY2 = payload.merchant_key;
46833
46814
  if (!payload.mid && !payload.merchant_key) {
46834
- 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
+ };
46835
46819
  }
46836
46820
  const data = {
46837
46821
  mid: payload.mid,
@@ -46854,7 +46838,9 @@ var useRedDotPaymentSvc = () => {
46854
46838
  "Content-Length": String(dataString.length)
46855
46839
  };
46856
46840
  if (!process.env.MERCHANT_PAYMENT) {
46857
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46841
+ throw new Error(
46842
+ "MERCHANT_PAYMENT environment variable is not defined."
46843
+ );
46858
46844
  }
46859
46845
  const url = process.env.MERCHANT_PAYMENT;
46860
46846
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46868,7 +46854,10 @@ var useRedDotPaymentSvc = () => {
46868
46854
  try {
46869
46855
  const SECRET_KEY2 = payload.merchant_key;
46870
46856
  if (!payload.request_mid && !payload.merchant_key) {
46871
- 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
+ };
46872
46861
  }
46873
46862
  const data = {
46874
46863
  request_mid: payload.request_mid,
@@ -46883,7 +46872,9 @@ var useRedDotPaymentSvc = () => {
46883
46872
  "Content-Type": "application/json"
46884
46873
  };
46885
46874
  if (!process.env.MERCHANT_ENQUIRY) {
46886
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46875
+ throw new Error(
46876
+ "MERCHANT_PAYMENT environment variable is not defined."
46877
+ );
46887
46878
  }
46888
46879
  const url = process.env.MERCHANT_ENQUIRY;
46889
46880
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46897,25 +46888,24 @@ var useRedDotPaymentSvc = () => {
46897
46888
  if (result.response_code === "0") {
46898
46889
  const success = {
46899
46890
  method: payload.method,
46900
- paymentStatus: "Paid" /* paid */,
46901
- amountPaid: amount,
46902
- paidBy: payer,
46891
+ paymentStatus: "paid" /* PAID */,
46892
+ amountPaid: parseInt(amount),
46903
46893
  updatedAt: invoiceDate,
46904
46894
  transaction_id: transactionId,
46905
46895
  message
46906
46896
  };
46907
- await useRedDotPaymentRepo().payUnitBillings(refId, success);
46897
+ await paySingleUnitBill(refId, success);
46908
46898
  } else if (result.response_code !== "0") {
46909
46899
  const fail = {
46910
46900
  method: payload.method,
46911
- paymentStatus: "Failed" /* failed */,
46901
+ paymentStatus: "failed" /* FAILED */,
46912
46902
  updatedAt: invoiceDate,
46913
46903
  paidBy: "",
46914
- amountPaid: "0",
46904
+ amountPaid: 0,
46915
46905
  transaction_id: transactionId,
46916
46906
  message
46917
46907
  };
46918
- await useRedDotPaymentRepo().payUnitBillings(refId, fail);
46908
+ await paySingleUnitBill(refId, fail);
46919
46909
  }
46920
46910
  return result;
46921
46911
  } catch (error) {
@@ -46935,7 +46925,9 @@ var useRedDotPaymentSvc = () => {
46935
46925
  "Content-Length": String(dataString.length)
46936
46926
  };
46937
46927
  if (!process.env.MERCHANT_PAYMENT) {
46938
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
46928
+ throw new Error(
46929
+ "MERCHANT_PAYMENT environment variable is not defined."
46930
+ );
46939
46931
  }
46940
46932
  const url = process.env.MERCHANT_PAYMENT;
46941
46933
  const response = await import_axios3.default.post(url, dataString, { headers });
@@ -46944,45 +46936,16 @@ var useRedDotPaymentSvc = () => {
46944
46936
  return Promise.reject(error || error.message || "Server Internal Error!");
46945
46937
  }
46946
46938
  };
46947
- const getMerchantDetailsById = async (_id) => {
46948
- return useRedDotPaymentRepo().getMerchantDetailsById(_id);
46949
- };
46950
46939
  return {
46951
- createRedDotAccount,
46952
46940
  redirectPaymentTransaction,
46953
46941
  enquirePaymentTransaction,
46954
- payInvoice,
46955
- getMerchantDetailsById
46942
+ payInvoice
46956
46943
  };
46957
46944
  };
46958
46945
 
46959
46946
  // src/controllers/reddot-payment.controller.ts
46960
46947
  var import_joi124 = __toESM(require("joi"));
46961
46948
  function useRedDotPaymentController() {
46962
- const createRedDotAccount = async (req, res) => {
46963
- try {
46964
- const data = req.body;
46965
- const id = req.params.id;
46966
- const schema2 = import_joi124.default.object({
46967
- id: import_joi124.default.string().hex().required(),
46968
- // organization id
46969
- paymentMethod: import_joi124.default.string().required(),
46970
- // payment method (e.g. "Visa / Mastercard / PayNow QR Code")
46971
- merchant_id: import_joi124.default.string().required(),
46972
- // merchant id
46973
- merchant_key: import_joi124.default.string().required()
46974
- // secret key
46975
- });
46976
- const { error } = schema2.validate({ id, ...data });
46977
- if (error) {
46978
- return res.status(400).json({ data: null, message: error.message });
46979
- }
46980
- const result = await useRedDotPaymentSvc().createRedDotAccount(id, data);
46981
- return res.json(result);
46982
- } catch (error) {
46983
- return res.status(500).json({ message: error.message || error });
46984
- }
46985
- };
46986
46949
  const redirectPaymentTransaction = async (req, res) => {
46987
46950
  try {
46988
46951
  const data = req.body;
@@ -46999,7 +46962,9 @@ function useRedDotPaymentController() {
46999
46962
  if (error) {
47000
46963
  return res.status(400).json({ data: null, message: error.message });
47001
46964
  }
47002
- const result = await useRedDotPaymentSvc().redirectPaymentTransaction(data);
46965
+ const result = await useRedDotPaymentSvc().redirectPaymentTransaction(
46966
+ data
46967
+ );
47003
46968
  return res.json(result);
47004
46969
  } catch (error) {
47005
46970
  return res.status(500).json({ message: error.message || error });
@@ -47018,43 +46983,27 @@ function useRedDotPaymentController() {
47018
46983
  if (error) {
47019
46984
  return res.status(400).json({ data: null, message: error.message });
47020
46985
  }
47021
- const result = await useRedDotPaymentSvc().enquirePaymentTransaction(data);
46986
+ const result = await useRedDotPaymentSvc().enquirePaymentTransaction(
46987
+ data
46988
+ );
47022
46989
  return res.json(result);
47023
46990
  } catch (error) {
47024
46991
  return res.status(500).json({ message: error.message || error });
47025
46992
  }
47026
46993
  };
47027
- const getMerchantDetailsById = async (req, res, next) => {
47028
- try {
47029
- const _id = req.params.id;
47030
- const schema2 = import_joi124.default.object({
47031
- _id: import_joi124.default.string().hex().required()
47032
- });
47033
- const { error } = schema2.validate({ _id });
47034
- if (error) {
47035
- return res.status(400).json({ data: null, message: error.message });
47036
- }
47037
- const result = await useRedDotPaymentSvc().getMerchantDetailsById(_id);
47038
- return res.json(result);
47039
- } catch (error) {
47040
- next(error);
47041
- }
47042
- };
47043
46994
  return {
47044
- createRedDotAccount,
47045
46995
  redirectPaymentTransaction,
47046
- enquirePaymentTransaction,
47047
- getMerchantDetailsById
46996
+ enquirePaymentTransaction
47048
46997
  };
47049
46998
  }
47050
46999
 
47051
47000
  // src/repositories/verification-v2.repo.ts
47052
- var import_node_server_utils218 = require("@7365admin1/node-server-utils");
47053
- var import_mongodb128 = require("mongodb");
47001
+ var import_node_server_utils217 = require("@7365admin1/node-server-utils");
47002
+ var import_mongodb124 = require("mongodb");
47054
47003
  function useVerificationRepoV2() {
47055
- const db = import_node_server_utils218.useAtlas.getDb();
47004
+ const db = import_node_server_utils217.useAtlas.getDb();
47056
47005
  if (!db) {
47057
- 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.");
47058
47007
  }
47059
47008
  const namespace_collection = "verifications";
47060
47009
  const collection = db.collection(namespace_collection);
@@ -47067,7 +47016,7 @@ function useVerificationRepoV2() {
47067
47016
  { "metadata.org": 1 }
47068
47017
  ]);
47069
47018
  } catch (error) {
47070
- throw new import_node_server_utils218.InternalServerError("Failed to create index.");
47019
+ throw new import_node_server_utils217.InternalServerError("Failed to create index.");
47071
47020
  }
47072
47021
  }
47073
47022
  async function createTextIndex() {
@@ -47076,36 +47025,36 @@ function useVerificationRepoV2() {
47076
47025
  email: "text"
47077
47026
  });
47078
47027
  } catch (error) {
47079
- 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.");
47080
47029
  }
47081
47030
  }
47082
- 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);
47083
47032
  async function add(value, session) {
47084
47033
  value = new MVerificationV2(value);
47085
47034
  try {
47086
47035
  const res = await collection.insertOne(value, { session });
47087
47036
  delNamespace().then(() => {
47088
- 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}`);
47089
47038
  }).catch((err) => {
47090
- import_node_server_utils218.logger.error(
47039
+ import_node_server_utils217.logger.error(
47091
47040
  `Failed to clear cache for namespace: ${namespace_collection}`,
47092
47041
  err
47093
47042
  );
47094
47043
  });
47095
47044
  return res.insertedId;
47096
47045
  } catch (error) {
47097
- import_node_server_utils218.logger.log({
47046
+ import_node_server_utils217.logger.log({
47098
47047
  level: "info",
47099
47048
  message: String(error)
47100
47049
  });
47101
- throw new import_node_server_utils218.InternalServerError("Server internal error.");
47050
+ throw new import_node_server_utils217.InternalServerError("Server internal error.");
47102
47051
  }
47103
47052
  }
47104
47053
  async function updateVerificationStatusById(_id, status, session) {
47105
47054
  try {
47106
- _id = new import_mongodb128.ObjectId(_id);
47055
+ _id = new import_mongodb124.ObjectId(_id);
47107
47056
  } catch (error) {
47108
- throw new import_node_server_utils218.BadRequestError("Invalid verification ID format.");
47057
+ throw new import_node_server_utils217.BadRequestError("Invalid verification ID format.");
47109
47058
  }
47110
47059
  try {
47111
47060
  const result = await collection.updateOne(
@@ -47114,24 +47063,24 @@ function useVerificationRepoV2() {
47114
47063
  { session }
47115
47064
  );
47116
47065
  delNamespace().then(() => {
47117
- 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}`);
47118
47067
  }).catch((err) => {
47119
- import_node_server_utils218.logger.error(
47068
+ import_node_server_utils217.logger.error(
47120
47069
  `Failed to clear cache for namespace: ${namespace_collection}`,
47121
47070
  err
47122
47071
  );
47123
47072
  });
47124
47073
  return result;
47125
47074
  } catch (error) {
47126
- throw new import_node_server_utils218.InternalServerError("Error updating verification status.");
47075
+ throw new import_node_server_utils217.InternalServerError("Error updating verification status.");
47127
47076
  }
47128
47077
  }
47129
47078
  async function getByVerificationCode(verificationCode) {
47130
47079
  try {
47131
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, { verificationCode });
47080
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, { verificationCode });
47132
47081
  const cachedData = await getCache(cacheKey);
47133
47082
  if (cachedData) {
47134
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47083
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47135
47084
  return cachedData;
47136
47085
  }
47137
47086
  const query = {
@@ -47140,35 +47089,35 @@ function useVerificationRepoV2() {
47140
47089
  };
47141
47090
  const data = await collection.findOne(query);
47142
47091
  setCache(cacheKey, data, 15 * 60).then(() => {
47143
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47092
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47144
47093
  }).catch((err) => {
47145
- 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);
47146
47095
  });
47147
47096
  return data;
47148
47097
  } catch (error) {
47149
- throw new import_node_server_utils218.InternalServerError(
47098
+ throw new import_node_server_utils217.InternalServerError(
47150
47099
  "Internal server error, failed to retrieve verification."
47151
47100
  );
47152
47101
  }
47153
47102
  }
47154
47103
  async function getVerificationById(id) {
47155
47104
  try {
47156
- const _id = (0, import_node_server_utils218.toObjectId)(id);
47157
- 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 });
47158
47107
  const cachedData = await getCache(cacheKey);
47159
47108
  if (cachedData) {
47160
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47109
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47161
47110
  return cachedData;
47162
47111
  }
47163
47112
  const data = await collection.findOne({ _id });
47164
47113
  setCache(cacheKey, data, 15 * 60).then(() => {
47165
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47114
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47166
47115
  }).catch((err) => {
47167
- 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);
47168
47117
  });
47169
47118
  return data;
47170
47119
  } catch (error) {
47171
- throw new import_node_server_utils218.InternalServerError(
47120
+ throw new import_node_server_utils217.InternalServerError(
47172
47121
  "Internal server error, failed to retrieve verification."
47173
47122
  );
47174
47123
  }
@@ -47208,10 +47157,10 @@ function useVerificationRepoV2() {
47208
47157
  query.email = email;
47209
47158
  cacheOptions.email = email;
47210
47159
  }
47211
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, cacheOptions);
47160
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, cacheOptions);
47212
47161
  const cachedData = await getCache(cacheKey);
47213
47162
  if (cachedData) {
47214
- import_node_server_utils218.logger.info(`Cache hit for key: ${cacheKey}`);
47163
+ import_node_server_utils217.logger.info(`Cache hit for key: ${cacheKey}`);
47215
47164
  return cachedData;
47216
47165
  }
47217
47166
  try {
@@ -47232,23 +47181,23 @@ function useVerificationRepoV2() {
47232
47181
  }
47233
47182
  ]).toArray();
47234
47183
  const length = await collection.countDocuments(query);
47235
- 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);
47236
47185
  setCache(cacheKey, data, 15 * 60).then(() => {
47237
- import_node_server_utils218.logger.info(`Cache set for key: ${cacheKey}`);
47186
+ import_node_server_utils217.logger.info(`Cache set for key: ${cacheKey}`);
47238
47187
  }).catch((err) => {
47239
- 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);
47240
47189
  });
47241
47190
  return data;
47242
47191
  } catch (error) {
47243
- import_node_server_utils218.logger.log({ level: "error", message: `${error}` });
47192
+ import_node_server_utils217.logger.log({ level: "error", message: `${error}` });
47244
47193
  throw error;
47245
47194
  }
47246
47195
  }
47247
47196
  async function updateStatusById(_id, status, session) {
47248
47197
  try {
47249
- _id = new import_mongodb128.ObjectId(_id);
47198
+ _id = new import_mongodb124.ObjectId(_id);
47250
47199
  } catch (error) {
47251
- throw new import_node_server_utils218.BadRequestError("Invalid verification ID format.");
47200
+ throw new import_node_server_utils217.BadRequestError("Invalid verification ID format.");
47252
47201
  }
47253
47202
  try {
47254
47203
  const result = await collection.updateOne(
@@ -47257,22 +47206,22 @@ function useVerificationRepoV2() {
47257
47206
  { session }
47258
47207
  );
47259
47208
  delNamespace().then(() => {
47260
- 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}`);
47261
47210
  }).catch((err) => {
47262
- import_node_server_utils218.logger.error(
47211
+ import_node_server_utils217.logger.error(
47263
47212
  `Failed to clear cache for namespace: ${namespace_collection}`,
47264
47213
  err
47265
47214
  );
47266
47215
  });
47267
- const cacheKey = (0, import_node_server_utils218.makeCacheKey)(namespace_collection, { _id });
47216
+ const cacheKey = (0, import_node_server_utils217.makeCacheKey)(namespace_collection, { _id });
47268
47217
  delCache(cacheKey).then(() => {
47269
- import_node_server_utils218.logger.info(`Cache deleted for key: ${cacheKey}`);
47218
+ import_node_server_utils217.logger.info(`Cache deleted for key: ${cacheKey}`);
47270
47219
  }).catch((err) => {
47271
- 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);
47272
47221
  });
47273
47222
  return result;
47274
47223
  } catch (error) {
47275
- throw new import_node_server_utils218.InternalServerError("Error updating verification status.");
47224
+ throw new import_node_server_utils217.InternalServerError("Error updating verification status.");
47276
47225
  }
47277
47226
  }
47278
47227
  return {
@@ -47288,7 +47237,7 @@ function useVerificationRepoV2() {
47288
47237
  }
47289
47238
 
47290
47239
  // src/services/verification-v2.service.ts
47291
- var import_node_server_utils219 = require("@7365admin1/node-server-utils");
47240
+ var import_node_server_utils218 = require("@7365admin1/node-server-utils");
47292
47241
  var import_crypto2 = __toESM(require("crypto"));
47293
47242
  var import_joi125 = __toESM(require("joi"));
47294
47243
  function useVerificationServiceV2() {
@@ -47299,7 +47248,7 @@ function useVerificationServiceV2() {
47299
47248
  email: MAILER_EMAIL,
47300
47249
  password: MAILER_PASSWORD
47301
47250
  };
47302
- const mailer = new import_node_server_utils219.useMailer(MailerConfig);
47251
+ const mailer = new import_node_server_utils218.useMailer(MailerConfig);
47303
47252
  const {
47304
47253
  add: _add,
47305
47254
  updateVerificationStatusById: _updateVerificationStatusById,
@@ -47314,31 +47263,31 @@ function useVerificationServiceV2() {
47314
47263
  const { getSiteById } = useSiteRepo();
47315
47264
  function errorByType(type, status) {
47316
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 */) {
47317
- throw new import_node_server_utils219.BadRequestError(
47266
+ throw new import_node_server_utils218.BadRequestError(
47318
47267
  "Invitation has already expired, please contact admin to resend the invitation."
47319
47268
  );
47320
47269
  }
47321
47270
  if (type === "user-sign-up" /* USER_SIGN_UP */ && status === "expired" /* EXPIRED */) {
47322
- throw new import_node_server_utils219.BadRequestError(
47271
+ throw new import_node_server_utils218.BadRequestError(
47323
47272
  "Sign up verification has expired, please sign up again to get a new verification link."
47324
47273
  );
47325
47274
  }
47326
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 */) {
47327
- throw new import_node_server_utils219.BadRequestError(
47276
+ throw new import_node_server_utils218.BadRequestError(
47328
47277
  "User already registered, please login to continue."
47329
47278
  );
47330
47279
  }
47331
47280
  if (type === "forget-password" /* FORGET_PASSWORD */ && status === "complete" /* COMPLETE */) {
47332
- throw new import_node_server_utils219.BadRequestError(
47281
+ throw new import_node_server_utils218.BadRequestError(
47333
47282
  "Forget password verification has already been used, please request a new one."
47334
47283
  );
47335
47284
  }
47336
47285
  if (type === "forget-password" /* FORGET_PASSWORD */ && status === "expired" /* EXPIRED */) {
47337
- throw new import_node_server_utils219.BadRequestError(
47286
+ throw new import_node_server_utils218.BadRequestError(
47338
47287
  "Forget password verification has expired, please request a new one."
47339
47288
  );
47340
47289
  }
47341
- throw new import_node_server_utils219.BadRequestError("Invalid verification.");
47290
+ throw new import_node_server_utils218.BadRequestError("Invalid verification.");
47342
47291
  }
47343
47292
  function generateVerificationCode(length = 8) {
47344
47293
  const chars = "0123456789";
@@ -47353,17 +47302,17 @@ function useVerificationServiceV2() {
47353
47302
  email,
47354
47303
  metadata
47355
47304
  }) {
47356
- const session = import_node_server_utils219.useAtlas.getClient()?.startSession();
47305
+ const session = import_node_server_utils218.useAtlas.getClient()?.startSession();
47357
47306
  try {
47358
47307
  session?.startTransaction();
47359
47308
  const user = await _getUserByEmailStatus(email);
47360
47309
  if (user) {
47361
- throw new import_node_server_utils219.BadRequestError(
47310
+ throw new import_node_server_utils218.BadRequestError(
47362
47311
  `Email ${email} is already registered, please login to continue.`
47363
47312
  );
47364
47313
  }
47365
47314
  const verificationCode = generateVerificationCode(6);
47366
- metadata.password = await (0, import_node_server_utils219.hashPassword)(metadata.password);
47315
+ metadata.password = await (0, import_node_server_utils218.hashPassword)(metadata.password);
47367
47316
  metadata.verificationCode = verificationCode;
47368
47317
  const value = {
47369
47318
  type: "user-sign-up" /* USER_SIGN_UP */,
@@ -47375,8 +47324,8 @@ function useVerificationServiceV2() {
47375
47324
  };
47376
47325
  const res = await _add(value);
47377
47326
  const dir = __dirname;
47378
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, "./public/handlebars/sign-up-v2");
47379
- 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)({
47380
47329
  context: {
47381
47330
  email,
47382
47331
  validity: "15 minutes",
@@ -47390,7 +47339,7 @@ function useVerificationServiceV2() {
47390
47339
  html: emailContent,
47391
47340
  sender: "iService365" /* ISERVICE365 */
47392
47341
  }).catch((error) => {
47393
- import_node_server_utils219.logger.log({
47342
+ import_node_server_utils218.logger.log({
47394
47343
  level: "error",
47395
47344
  message: `Error sending user invite email: ${error}`
47396
47345
  });
@@ -47405,21 +47354,21 @@ function useVerificationServiceV2() {
47405
47354
  }
47406
47355
  }
47407
47356
  async function verify(verificationCode) {
47408
- const session = import_node_server_utils219.useAtlas.getClient()?.startSession();
47357
+ const session = import_node_server_utils218.useAtlas.getClient()?.startSession();
47409
47358
  try {
47410
47359
  session?.startTransaction();
47411
47360
  const item = await _getByVerificationCode(verificationCode);
47412
47361
  if (!item) {
47413
- throw new import_node_server_utils219.NotFoundError("Verification not found.");
47362
+ throw new import_node_server_utils218.NotFoundError("Verification not found.");
47414
47363
  }
47415
47364
  switch (item.status) {
47416
47365
  case "expired" /* EXPIRED */:
47417
47366
  errorByType(item.type, "expired" /* EXPIRED */);
47418
47367
  break;
47419
47368
  case "cancelled" /* CANCELLED */:
47420
- throw new import_node_server_utils219.BadRequestError("Verification already cancelled.");
47369
+ throw new import_node_server_utils218.BadRequestError("Verification already cancelled.");
47421
47370
  case "complete" /* COMPLETE */:
47422
- throw new import_node_server_utils219.BadRequestError("Verification already completed.");
47371
+ throw new import_node_server_utils218.BadRequestError("Verification already completed.");
47423
47372
  }
47424
47373
  const expiration = new Date(item.expireAt).getTime();
47425
47374
  const now = (/* @__PURE__ */ new Date()).getTime();
@@ -47435,7 +47384,7 @@ function useVerificationServiceV2() {
47435
47384
  return { _id, type, email, status, expireAt };
47436
47385
  } catch (error) {
47437
47386
  await session?.abortTransaction();
47438
- import_node_server_utils219.logger.log({
47387
+ import_node_server_utils218.logger.log({
47439
47388
  level: "info",
47440
47389
  message: `Error verifying user invitation: ${error}`
47441
47390
  });
@@ -47472,11 +47421,11 @@ function useVerificationServiceV2() {
47472
47421
  value.type = type;
47473
47422
  const res = await _add(value);
47474
47423
  const dir = __dirname;
47475
- 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}`);
47476
47425
  const isMember = type === "member-invite" /* MEMBER_INVITE */;
47477
47426
  const subject = isMember ? "Member Invite" /* _MEMBER_INVITE */ : "User Invite" /* _USER_INVITE */;
47478
47427
  const link = `${APP_MAIN}/verify/${isMember ? "membership" /* MEMBERSHIP */ : "invitation" /* INVITATION */}/${res}`;
47479
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47428
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47480
47429
  context: {
47481
47430
  email: userName,
47482
47431
  validity: VERIFICATION_USER_INVITE_DURATION,
@@ -47490,7 +47439,7 @@ function useVerificationServiceV2() {
47490
47439
  html: emailContent,
47491
47440
  sender: "iService365" /* ISERVICE365 */
47492
47441
  }).catch((error) => {
47493
- import_node_server_utils219.logger.log({
47442
+ import_node_server_utils218.logger.log({
47494
47443
  level: "error",
47495
47444
  message: `Error sending user ${type} email: ${error}`
47496
47445
  });
@@ -47520,8 +47469,8 @@ function useVerificationServiceV2() {
47520
47469
  });
47521
47470
  if (error) {
47522
47471
  const messages = error.details.map((d) => d.message).join(", ");
47523
- import_node_server_utils219.logger.log({ level: "error", message: messages });
47524
- 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}`);
47525
47474
  }
47526
47475
  let subject = "Service Provider Invite" /* _SERVICE_PROVIDER_INVITE */;
47527
47476
  const value = {
@@ -47546,9 +47495,9 @@ function useVerificationServiceV2() {
47546
47495
  }
47547
47496
  const res = await _add(value);
47548
47497
  const dir = __dirname;
47549
- 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}`);
47550
47499
  const link = org ? `${APP_MAIN}/verify/${value.type}/${res}` : `${APP_ORG}/organizations/create?email=${email}`;
47551
- const emailContent = (0, import_node_server_utils219.compileHandlebar)({
47500
+ const emailContent = (0, import_node_server_utils218.compileHandlebar)({
47552
47501
  context: {
47553
47502
  email: org?.name || email,
47554
47503
  validity: VERIFICATION_USER_INVITE_DURATION,
@@ -47562,7 +47511,7 @@ function useVerificationServiceV2() {
47562
47511
  html: emailContent,
47563
47512
  sender: "iService365" /* ISERVICE365 */
47564
47513
  }).catch((error2) => {
47565
- import_node_server_utils219.logger.log({
47514
+ import_node_server_utils218.logger.log({
47566
47515
  level: "error",
47567
47516
  message: `Error sending user ${value.type} email: ${error2}`
47568
47517
  });
@@ -47584,8 +47533,8 @@ function useVerificationServiceV2() {
47584
47533
  const user = await _getUserByEmail(email);
47585
47534
  const res = await _add(value);
47586
47535
  const dir = __dirname;
47587
- const filePath = (0, import_node_server_utils219.getDirectory)(dir, "./public/handlebars/forget-password");
47588
- 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)({
47589
47538
  context: {
47590
47539
  userName: user?.name,
47591
47540
  validity: VERIFICATION_FORGET_PASSWORD_DURATION,
@@ -47599,21 +47548,21 @@ function useVerificationServiceV2() {
47599
47548
  sender: "iService365" /* ISERVICE365 */,
47600
47549
  html: emailContent
47601
47550
  }).catch((error) => {
47602
- import_node_server_utils219.logger.log({
47551
+ import_node_server_utils218.logger.log({
47603
47552
  level: "error",
47604
47553
  message: `Error sending forget password email: ${error}`
47605
47554
  });
47606
47555
  });
47607
47556
  return "Successfully created a link to reset password. Please check your email.";
47608
47557
  } catch (error) {
47609
- 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.");
47610
47559
  }
47611
47560
  }
47612
47561
  async function cancelUserInvitation(id) {
47613
47562
  try {
47614
47563
  await _updateStatusById(id, "cancelled");
47615
47564
  } catch (error) {
47616
- throw new import_node_server_utils219.InternalServerError(
47565
+ throw new import_node_server_utils218.InternalServerError(
47617
47566
  `Error cancelling user invitation: ${error}`
47618
47567
  );
47619
47568
  }
@@ -47629,7 +47578,7 @@ function useVerificationServiceV2() {
47629
47578
  }
47630
47579
 
47631
47580
  // src/controllers/verification-v2.controller.ts
47632
- var import_node_server_utils220 = require("@7365admin1/node-server-utils");
47581
+ var import_node_server_utils219 = require("@7365admin1/node-server-utils");
47633
47582
  var import_joi126 = __toESM(require("joi"));
47634
47583
  function useVerificationControllerV2() {
47635
47584
  const {
@@ -47651,15 +47600,15 @@ function useVerificationControllerV2() {
47651
47600
  );
47652
47601
  if (error) {
47653
47602
  const messages = error.details.map((d) => d.message).join(", ");
47654
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47655
- 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));
47656
47605
  return;
47657
47606
  }
47658
47607
  const message = await _verify(value.verificationCode);
47659
47608
  res.json(message);
47660
47609
  return;
47661
47610
  } catch (error) {
47662
- import_node_server_utils220.logger.log({ level: "error", message: `${error.message}` });
47611
+ import_node_server_utils219.logger.log({ level: "error", message: `${error.message}` });
47663
47612
  next(error);
47664
47613
  return;
47665
47614
  }
@@ -47677,8 +47626,8 @@ function useVerificationControllerV2() {
47677
47626
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47678
47627
  if (error) {
47679
47628
  const messages = error.details.map((d) => d.message).join(", ");
47680
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47681
- 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));
47682
47631
  return;
47683
47632
  }
47684
47633
  const { email, app, role, name, org, siteId, siteName } = value;
@@ -47697,7 +47646,7 @@ function useVerificationControllerV2() {
47697
47646
  res.status(201).json({ message: "Successfully invited user." });
47698
47647
  return;
47699
47648
  } catch (error2) {
47700
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47649
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47701
47650
  next(error2);
47702
47651
  return;
47703
47652
  }
@@ -47712,8 +47661,8 @@ function useVerificationControllerV2() {
47712
47661
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47713
47662
  if (error) {
47714
47663
  const messages = error.details.map((d) => d.message).join(", ");
47715
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47716
- 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));
47717
47666
  return;
47718
47667
  }
47719
47668
  try {
@@ -47726,7 +47675,7 @@ function useVerificationControllerV2() {
47726
47675
  res.cookie("service-provider-email", value.email, cookieOptions).json({ message: "Successfully invited service provider." });
47727
47676
  return;
47728
47677
  } catch (error2) {
47729
- 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}` });
47730
47679
  next(error2);
47731
47680
  return;
47732
47681
  }
@@ -47738,8 +47687,8 @@ function useVerificationControllerV2() {
47738
47687
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
47739
47688
  if (error) {
47740
47689
  const messages = error.details.map((d) => d.message).join(", ");
47741
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47742
- 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));
47743
47692
  return;
47744
47693
  }
47745
47694
  const { email } = value;
@@ -47750,7 +47699,7 @@ function useVerificationControllerV2() {
47750
47699
  });
47751
47700
  return;
47752
47701
  } catch (error2) {
47753
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47702
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47754
47703
  next(error2);
47755
47704
  return;
47756
47705
  }
@@ -47770,8 +47719,8 @@ function useVerificationControllerV2() {
47770
47719
  const { error, value } = schema2.validate(req.query);
47771
47720
  if (error) {
47772
47721
  const messages = error.details.map((d) => d.message).join(", ");
47773
- import_node_server_utils220.logger.log({ level: "error", message: messages });
47774
- 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));
47775
47724
  return;
47776
47725
  }
47777
47726
  const { search, page, status, app, email, type } = value;
@@ -47787,7 +47736,7 @@ function useVerificationControllerV2() {
47787
47736
  res.json(data);
47788
47737
  return;
47789
47738
  } catch (error2) {
47790
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47739
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47791
47740
  next(error2);
47792
47741
  return;
47793
47742
  }
@@ -47797,8 +47746,8 @@ function useVerificationControllerV2() {
47797
47746
  const otpId = req.params.id;
47798
47747
  const { error } = validation.validate(otpId);
47799
47748
  if (error) {
47800
- import_node_server_utils220.logger.log({ level: "error", message: `${error.message}` });
47801
- 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));
47802
47751
  return;
47803
47752
  }
47804
47753
  try {
@@ -47808,7 +47757,7 @@ function useVerificationControllerV2() {
47808
47757
  });
47809
47758
  return;
47810
47759
  } catch (error2) {
47811
- import_node_server_utils220.logger.log({ level: "error", message: `${error2.message}` });
47760
+ import_node_server_utils219.logger.log({ level: "error", message: `${error2.message}` });
47812
47761
  next(error2);
47813
47762
  return;
47814
47763
  }
@@ -47825,38 +47774,38 @@ function useVerificationControllerV2() {
47825
47774
 
47826
47775
  // src/controllers/auth-v2.controller.ts
47827
47776
  var import_joi127 = __toESM(require("joi"));
47828
- var import_node_server_utils224 = require("@7365admin1/node-server-utils");
47777
+ var import_node_server_utils223 = require("@7365admin1/node-server-utils");
47829
47778
 
47830
47779
  // src/services/auth-v2.service.ts
47831
- var import_node_server_utils222 = require("@7365admin1/node-server-utils");
47780
+ var import_node_server_utils221 = require("@7365admin1/node-server-utils");
47832
47781
  var import_uuid2 = require("uuid");
47833
47782
 
47834
47783
  // src/repositories/user-v2.repo.ts
47835
- var import_mongodb129 = require("mongodb");
47836
- 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");
47837
47786
  function useUserRepoV2() {
47838
47787
  const { updateFeedbackCreatedByName } = useFeedbackRepo();
47839
47788
  const { updateWorkOrderCreatedByName } = useWorkOrderRepo();
47840
47789
  const { updateUserNameBySignatureId } = useOccurrenceEntryRepo();
47841
- const db = import_node_server_utils221.useAtlas.getDb();
47790
+ const db = import_node_server_utils220.useAtlas.getDb();
47842
47791
  if (!db) {
47843
- 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.");
47844
47793
  }
47845
47794
  const namespace_collection = "users";
47846
47795
  const collection = db.collection(namespace_collection);
47847
- 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);
47848
47797
  async function createIndex() {
47849
47798
  try {
47850
47799
  await collection.createIndexes([{ key: { email: 1 } }]);
47851
47800
  } catch (error) {
47852
- 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.");
47853
47802
  }
47854
47803
  }
47855
47804
  async function createTextIndex() {
47856
47805
  try {
47857
47806
  await collection.createIndex({ name: "text", email: "text" });
47858
47807
  } catch (error) {
47859
- 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.");
47860
47809
  }
47861
47810
  }
47862
47811
  async function createUniqueIndex() {
@@ -47866,7 +47815,7 @@ function useUserRepoV2() {
47866
47815
  { unique: true }
47867
47816
  );
47868
47817
  } catch (error) {
47869
- 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.");
47870
47819
  }
47871
47820
  }
47872
47821
  async function createUser(value, session) {
@@ -47874,71 +47823,71 @@ function useUserRepoV2() {
47874
47823
  value = MUser(value);
47875
47824
  const res = await collection.insertOne(value, { session });
47876
47825
  delNamespace().then(
47877
- () => 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}`)
47878
47827
  ).catch(
47879
- (err) => import_node_server_utils221.logger.error(
47828
+ (err) => import_node_server_utils220.logger.error(
47880
47829
  `Failed to clear cache for namespace: ${namespace_collection}`,
47881
47830
  err
47882
47831
  )
47883
47832
  );
47884
47833
  return res.insertedId;
47885
47834
  } catch (error) {
47886
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
47835
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
47887
47836
  if (error.message.includes("duplicate")) {
47888
- throw new import_node_server_utils221.BadRequestError("User already exists.");
47837
+ throw new import_node_server_utils220.BadRequestError("User already exists.");
47889
47838
  }
47890
47839
  throw error;
47891
47840
  }
47892
47841
  }
47893
47842
  async function getUserByEmail(email) {
47894
47843
  try {
47895
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { email });
47844
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { email });
47896
47845
  const cachedData = await getCache(cacheKey);
47897
47846
  if (cachedData) {
47898
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47847
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47899
47848
  return cachedData;
47900
47849
  }
47901
47850
  const data = await collection.findOne({
47902
47851
  email: { $regex: `^${email}$`, $options: "i" }
47903
47852
  });
47904
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47905
- (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)
47906
47855
  );
47907
47856
  return data;
47908
47857
  } catch (error) {
47909
- 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.");
47910
47859
  }
47911
47860
  }
47912
47861
  async function getUserByEmailStatus(email) {
47913
47862
  try {
47914
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, {
47863
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, {
47915
47864
  email,
47916
47865
  status: "complete" /* COMPLETE */
47917
47866
  });
47918
47867
  const cachedData = await getCache(cacheKey);
47919
47868
  if (cachedData) {
47920
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47869
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47921
47870
  return cachedData;
47922
47871
  }
47923
47872
  const data = await collection.findOne({
47924
47873
  email: { $regex: `^${email}$`, $options: "i" },
47925
47874
  status: "complete" /* COMPLETE */
47926
47875
  });
47927
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47928
- (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)
47929
47878
  );
47930
47879
  return data;
47931
47880
  } catch (error) {
47932
- 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.");
47933
47882
  }
47934
47883
  }
47935
47884
  async function getUserById(id) {
47936
- const _id = (0, import_node_server_utils221.toObjectId)(id);
47885
+ const _id = (0, import_node_server_utils220.toObjectId)(id);
47937
47886
  try {
47938
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { id });
47887
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { id });
47939
47888
  const cachedData = await getCache(cacheKey);
47940
47889
  if (cachedData) {
47941
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47890
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47942
47891
  return cachedData;
47943
47892
  }
47944
47893
  const results = await collection.aggregate([
@@ -47961,52 +47910,52 @@ function useUserRepoV2() {
47961
47910
  ]).toArray();
47962
47911
  const data = results.length > 0 ? results[0] : null;
47963
47912
  if (!data)
47964
- throw new import_node_server_utils221.NotFoundError("User not found.");
47965
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47966
- (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)
47967
47916
  );
47968
47917
  return data;
47969
47918
  } catch (error) {
47970
- if (error instanceof import_node_server_utils221.AppError)
47919
+ if (error instanceof import_node_server_utils220.AppError)
47971
47920
  throw error;
47972
- 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.");
47973
47922
  }
47974
47923
  }
47975
47924
  async function getUserByReferralCode(referralCode) {
47976
47925
  try {
47977
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { referralCode });
47926
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { referralCode });
47978
47927
  const cachedData = await getCache(cacheKey);
47979
47928
  if (cachedData) {
47980
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47929
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47981
47930
  return cachedData;
47982
47931
  }
47983
47932
  const data = await collection.findOne({ referralCode });
47984
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
47985
- (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)
47986
47935
  );
47987
47936
  return data;
47988
47937
  } catch (error) {
47989
- 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.");
47990
47939
  }
47991
47940
  }
47992
47941
  async function getByEmailApp(email, app) {
47993
47942
  try {
47994
- 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 });
47995
47944
  const cachedData = await getCache(cacheKey);
47996
47945
  if (cachedData) {
47997
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
47946
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
47998
47947
  return cachedData;
47999
47948
  }
48000
47949
  const data = await collection.findOne({
48001
47950
  email,
48002
47951
  "roles.app": app
48003
47952
  });
48004
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
48005
- (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)
48006
47955
  );
48007
47956
  return data;
48008
47957
  } catch (error) {
48009
- 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.");
48010
47959
  }
48011
47960
  }
48012
47961
  async function getUsersByOrgId({
@@ -48033,24 +47982,24 @@ function useUserRepoV2() {
48033
47982
  }
48034
47983
  if (organization) {
48035
47984
  try {
48036
- query.defaultOrg = new import_mongodb129.ObjectId(organization);
47985
+ query.defaultOrg = new import_mongodb125.ObjectId(organization);
48037
47986
  cacheOptions.organization = organization.toString();
48038
47987
  } catch (error) {
48039
- throw new import_node_server_utils221.BadRequestError("Invalid organization ID format.");
47988
+ throw new import_node_server_utils220.BadRequestError("Invalid organization ID format.");
48040
47989
  }
48041
47990
  }
48042
47991
  delNamespace().then(() => {
48043
- 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}`);
48044
47993
  }).catch((err) => {
48045
- import_node_server_utils221.logger.error(
47994
+ import_node_server_utils220.logger.error(
48046
47995
  `Failed to clear cache for namespace: ${namespace_collection}`,
48047
47996
  err
48048
47997
  );
48049
47998
  });
48050
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, cacheOptions);
47999
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, cacheOptions);
48051
48000
  const cachedData = await getCache(cacheKey);
48052
48001
  if (cachedData) {
48053
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
48002
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
48054
48003
  return cachedData;
48055
48004
  }
48056
48005
  try {
@@ -48070,15 +48019,15 @@ function useUserRepoV2() {
48070
48019
  }
48071
48020
  ]).toArray();
48072
48021
  const length = await collection.countDocuments(query);
48073
- 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);
48074
48023
  setCache(cacheKey, data, 15 * 60).then(() => {
48075
- import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`);
48024
+ import_node_server_utils220.logger.info(`Cache set for key: ${cacheKey}`);
48076
48025
  }).catch((err) => {
48077
- 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);
48078
48027
  });
48079
48028
  return data;
48080
48029
  } catch (error) {
48081
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
48030
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
48082
48031
  throw error;
48083
48032
  }
48084
48033
  }
@@ -48104,17 +48053,17 @@ function useUserRepoV2() {
48104
48053
  cacheOptions.type = type;
48105
48054
  }
48106
48055
  delNamespace().then(
48107
- () => 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}`)
48108
48057
  ).catch(
48109
- (err) => import_node_server_utils221.logger.error(
48058
+ (err) => import_node_server_utils220.logger.error(
48110
48059
  `Failed to clear cache for namespace: ${namespace_collection}`,
48111
48060
  err
48112
48061
  )
48113
48062
  );
48114
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, cacheOptions);
48063
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, cacheOptions);
48115
48064
  const cachedData = await getCache(cacheKey);
48116
48065
  if (cachedData) {
48117
- import_node_server_utils221.logger.info(`Cache hit for key: ${cacheKey}`);
48066
+ import_node_server_utils220.logger.info(`Cache hit for key: ${cacheKey}`);
48118
48067
  return cachedData;
48119
48068
  }
48120
48069
  try {
@@ -48126,19 +48075,19 @@ function useUserRepoV2() {
48126
48075
  { $project: { _id: 1, name: 1, email: 1, type: 1, status: 1 } }
48127
48076
  ]).toArray();
48128
48077
  const length = await collection.countDocuments(query);
48129
- const data = (0, import_node_server_utils221.paginate)(items, page, limit, length);
48130
- setCache(cacheKey, data, 15 * 60).then(() => import_node_server_utils221.logger.info(`Cache set for key: ${cacheKey}`)).catch(
48131
- (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)
48132
48081
  );
48133
48082
  return data;
48134
48083
  } catch (error) {
48135
- import_node_server_utils221.logger.log({ level: "error", message: `${error}` });
48084
+ import_node_server_utils220.logger.log({ level: "error", message: `${error}` });
48136
48085
  throw error;
48137
48086
  }
48138
48087
  }
48139
48088
  async function updatePasswordById({ _id, password }, session) {
48140
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48141
- _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);
48142
48091
  try {
48143
48092
  const result = await collection.updateOne(
48144
48093
  { _id },
@@ -48146,13 +48095,13 @@ function useUserRepoV2() {
48146
48095
  { session }
48147
48096
  );
48148
48097
  delCache(cacheKey).then(() => {
48149
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48098
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48150
48099
  }).catch((err) => {
48151
- 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);
48152
48101
  });
48153
48102
  return result;
48154
48103
  } catch (error) {
48155
- 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.");
48156
48105
  }
48157
48106
  }
48158
48107
  async function updateUserFieldById({ _id, field, value } = {}, session) {
@@ -48167,20 +48116,20 @@ function useUserRepoV2() {
48167
48116
  "defaultOrg"
48168
48117
  ];
48169
48118
  if (!allowedFields.includes(field)) {
48170
- throw new import_node_server_utils221.BadRequestError(
48119
+ throw new import_node_server_utils220.BadRequestError(
48171
48120
  `Field "${field}" is not allowed to be updated.`
48172
48121
  );
48173
48122
  }
48174
48123
  try {
48175
- _id = new import_mongodb129.ObjectId(_id);
48124
+ _id = new import_mongodb125.ObjectId(_id);
48176
48125
  } catch (error) {
48177
- throw new import_node_server_utils221.BadRequestError("Invalid ID.");
48126
+ throw new import_node_server_utils220.BadRequestError("Invalid ID.");
48178
48127
  }
48179
48128
  if (field === "defaultOrg") {
48180
48129
  try {
48181
- value = new import_mongodb129.ObjectId(value);
48130
+ value = new import_mongodb125.ObjectId(value);
48182
48131
  } catch (error) {
48183
- throw new import_node_server_utils221.BadRequestError("Invalid organization ID.");
48132
+ throw new import_node_server_utils220.BadRequestError("Invalid organization ID.");
48184
48133
  }
48185
48134
  }
48186
48135
  if (field === "name") {
@@ -48201,15 +48150,15 @@ function useUserRepoV2() {
48201
48150
  // Dynamically set the field
48202
48151
  { session }
48203
48152
  );
48204
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48153
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48205
48154
  delCache(cacheKey).then(() => {
48206
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48155
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48207
48156
  }).catch((err) => {
48208
- 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);
48209
48158
  });
48210
48159
  return `Successfully updated user ${field}.`;
48211
48160
  } catch (error) {
48212
- 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}.`);
48213
48162
  }
48214
48163
  }
48215
48164
  async function updateBirthday({
@@ -48219,9 +48168,9 @@ function useUserRepoV2() {
48219
48168
  year
48220
48169
  }, session) {
48221
48170
  try {
48222
- _id = new import_mongodb129.ObjectId(_id);
48171
+ _id = new import_mongodb125.ObjectId(_id);
48223
48172
  } catch (error) {
48224
- throw new import_node_server_utils221.BadRequestError("Invalid user ID format.");
48173
+ throw new import_node_server_utils220.BadRequestError("Invalid user ID format.");
48225
48174
  }
48226
48175
  try {
48227
48176
  await collection.updateOne(
@@ -48236,22 +48185,22 @@ function useUserRepoV2() {
48236
48185
  },
48237
48186
  { session }
48238
48187
  );
48239
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48188
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48240
48189
  delCache(cacheKey).then(() => {
48241
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48190
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48242
48191
  }).catch((err) => {
48243
- 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);
48244
48193
  });
48245
48194
  return "Successfully updated user birthday.";
48246
48195
  } catch (error) {
48247
- 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.");
48248
48197
  }
48249
48198
  }
48250
48199
  async function updatePassword({ _id, password }, session) {
48251
48200
  try {
48252
- _id = new import_mongodb129.ObjectId(_id);
48201
+ _id = new import_mongodb125.ObjectId(_id);
48253
48202
  } catch (error) {
48254
- throw new import_node_server_utils221.BadRequestError("Invalid user ID format.");
48203
+ throw new import_node_server_utils220.BadRequestError("Invalid user ID format.");
48255
48204
  }
48256
48205
  try {
48257
48206
  const result = await collection.updateOne(
@@ -48259,15 +48208,15 @@ function useUserRepoV2() {
48259
48208
  { $set: { password, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
48260
48209
  { session }
48261
48210
  );
48262
- const cacheKey = (0, import_node_server_utils221.makeCacheKey)(namespace_collection, { _id });
48211
+ const cacheKey = (0, import_node_server_utils220.makeCacheKey)(namespace_collection, { _id });
48263
48212
  delCache(cacheKey).then(() => {
48264
- import_node_server_utils221.logger.info(`Cache deleted for key: ${cacheKey}`);
48213
+ import_node_server_utils220.logger.info(`Cache deleted for key: ${cacheKey}`);
48265
48214
  }).catch((err) => {
48266
- 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);
48267
48216
  });
48268
48217
  return result;
48269
48218
  } catch (error) {
48270
- 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.");
48271
48220
  }
48272
48221
  }
48273
48222
  return {
@@ -48291,7 +48240,7 @@ function useUserRepoV2() {
48291
48240
  function useAuthServiceV2() {
48292
48241
  const { getUserByEmail, getUserById: _getUserById } = useUserRepoV2();
48293
48242
  const expiresIn = "15m";
48294
- const { setCache, delCache } = (0, import_node_server_utils222.useCache)("sessions");
48243
+ const { setCache, delCache } = (0, import_node_server_utils221.useCache)("sessions");
48295
48244
  const { getByUserIdType } = useMemberRepo();
48296
48245
  async function login({
48297
48246
  email,
@@ -48302,26 +48251,26 @@ function useAuthServiceV2() {
48302
48251
  try {
48303
48252
  const user = await getUserByEmail(email);
48304
48253
  if (!user) {
48305
- throw new import_node_server_utils222.NotFoundError(
48254
+ throw new import_node_server_utils221.NotFoundError(
48306
48255
  "Invalid user email. Please check your email and try again."
48307
48256
  );
48308
48257
  }
48309
48258
  if (!user._id) {
48310
- throw new import_node_server_utils222.InternalServerError("Valid user ID.");
48259
+ throw new import_node_server_utils221.InternalServerError("Valid user ID.");
48311
48260
  }
48312
48261
  if (user.status === "suspended") {
48313
- throw new import_node_server_utils222.BadRequestError(
48262
+ throw new import_node_server_utils221.BadRequestError(
48314
48263
  "Your account is currently suspended. Please contact support for assistance."
48315
48264
  );
48316
48265
  }
48317
- 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);
48318
48267
  if (!isPasswordValid) {
48319
- throw new import_node_server_utils222.BadRequestError("Invalid password.");
48268
+ throw new import_node_server_utils221.BadRequestError("Invalid password.");
48320
48269
  }
48321
48270
  if (isMobile) {
48322
48271
  const member = await getByUserIdType(user._id, type);
48323
48272
  if (!member) {
48324
- throw new import_node_server_utils222.BadRequestError("No member found.");
48273
+ throw new import_node_server_utils221.BadRequestError("No member found.");
48325
48274
  }
48326
48275
  }
48327
48276
  const sid = (0, import_uuid2.v4)();
@@ -48341,22 +48290,22 @@ function useAuthServiceV2() {
48341
48290
  await delCache(`sid:${sid}`);
48342
48291
  return "Session deleted successfully";
48343
48292
  } catch (error) {
48344
- throw new import_node_server_utils222.InternalServerError("Error deleting token");
48293
+ throw new import_node_server_utils221.InternalServerError("Error deleting token");
48345
48294
  }
48346
48295
  }
48347
48296
  async function verifyPassword(_id, password) {
48348
48297
  try {
48349
48298
  const user = await _getUserById(_id);
48350
- 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);
48351
48300
  if (!isPasswordMatch) {
48352
- throw new import_node_server_utils222.BadRequestError("Invalid credentials");
48301
+ throw new import_node_server_utils221.BadRequestError("Invalid credentials");
48353
48302
  }
48354
48303
  return "Verification successful.";
48355
48304
  } catch (error) {
48356
- if (error instanceof import_node_server_utils222.BadRequestError) {
48305
+ if (error instanceof import_node_server_utils221.BadRequestError) {
48357
48306
  throw error;
48358
48307
  }
48359
- throw new import_node_server_utils222.InternalServerError("Error during password verification");
48308
+ throw new import_node_server_utils221.InternalServerError("Error during password verification");
48360
48309
  }
48361
48310
  }
48362
48311
  return {
@@ -48367,7 +48316,7 @@ function useAuthServiceV2() {
48367
48316
  }
48368
48317
 
48369
48318
  // src/services/user-v2.service.ts
48370
- var import_node_server_utils223 = require("@7365admin1/node-server-utils");
48319
+ var import_node_server_utils222 = require("@7365admin1/node-server-utils");
48371
48320
  var import_multer2 = require("multer");
48372
48321
  function useUserServiceV2() {
48373
48322
  const {
@@ -48392,23 +48341,23 @@ function useUserServiceV2() {
48392
48341
  id = "",
48393
48342
  name = ""
48394
48343
  }) {
48395
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48344
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48396
48345
  session?.startTransaction();
48397
48346
  try {
48398
48347
  const signUp = await _getVerificationById(id);
48399
48348
  if (!signUp)
48400
- throw new import_node_server_utils223.BadRequestError("Invalid sign up link.");
48349
+ throw new import_node_server_utils222.BadRequestError("Invalid sign up link.");
48401
48350
  if (signUp.status === "complete" /* COMPLETE */)
48402
- throw new import_node_server_utils223.BadRequestError(
48351
+ throw new import_node_server_utils222.BadRequestError(
48403
48352
  "You have already an account created using this link."
48404
48353
  );
48405
48354
  const expired = signUp.expireAt < (/* @__PURE__ */ new Date()).toISOString();
48406
48355
  if (signUp.status === "expired" || expired)
48407
- throw new import_node_server_utils223.BadRequestError("Sign up link expired.");
48356
+ throw new import_node_server_utils222.BadRequestError("Sign up link expired.");
48408
48357
  const email = signUp.email;
48409
48358
  const _user = await _getUserByEmail(email);
48410
48359
  if (_user)
48411
- throw new import_node_server_utils223.BadRequestError(`User already exists: ${email}.`);
48360
+ throw new import_node_server_utils222.BadRequestError(`User already exists: ${email}.`);
48412
48361
  let org = null;
48413
48362
  if (signUp.metadata?.org) {
48414
48363
  org = await getOrgById(signUp.metadata.org);
@@ -48455,30 +48404,30 @@ function useUserServiceV2() {
48455
48404
  }
48456
48405
  async function resetPassword(id, newPassword, passwordConfirmation) {
48457
48406
  if (newPassword !== passwordConfirmation) {
48458
- throw new import_node_server_utils223.BadRequestError("Passwords do not match.");
48407
+ throw new import_node_server_utils222.BadRequestError("Passwords do not match.");
48459
48408
  }
48460
48409
  let hashedPassword;
48461
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48410
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48462
48411
  session?.startTransaction();
48463
48412
  try {
48464
- hashedPassword = await (0, import_node_server_utils223.hashPassword)(newPassword);
48413
+ hashedPassword = await (0, import_node_server_utils222.hashPassword)(newPassword);
48465
48414
  } catch (error) {
48466
- throw new import_node_server_utils223.InternalServerError(`Error hashing password: ${error}`);
48415
+ throw new import_node_server_utils222.InternalServerError(`Error hashing password: ${error}`);
48467
48416
  }
48468
48417
  try {
48469
48418
  const otpDoc = await _getVerificationById(id);
48470
48419
  if (!otpDoc) {
48471
- 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.");
48472
48421
  }
48473
48422
  if (otpDoc.status === "complete" /* COMPLETE */) {
48474
- 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.");
48475
48424
  }
48476
48425
  const user = await _getUserByEmail(otpDoc.email);
48477
48426
  if (!user) {
48478
- throw new import_node_server_utils223.NotFoundError("User not found.");
48427
+ throw new import_node_server_utils222.NotFoundError("User not found.");
48479
48428
  }
48480
48429
  if (!user._id) {
48481
- throw new import_node_server_utils223.InternalServerError("Invalid user ID.");
48430
+ throw new import_node_server_utils222.InternalServerError("Invalid user ID.");
48482
48431
  }
48483
48432
  await Promise.all([
48484
48433
  _updateVerificationStatusById(id, "complete" /* COMPLETE */, session),
@@ -48496,7 +48445,7 @@ function useUserServiceV2() {
48496
48445
  session?.endSession();
48497
48446
  }
48498
48447
  }
48499
- const s3 = new import_node_server_utils223.useS3({
48448
+ const s3 = new import_node_server_utils222.useS3({
48500
48449
  accessKeyId: SPACES_ACCESS_KEY,
48501
48450
  secretAccessKey: SPACES_SECRET_KEY,
48502
48451
  endpoint: SPACES_ENDPOINT,
@@ -48509,7 +48458,7 @@ function useUserServiceV2() {
48509
48458
  user,
48510
48459
  previousProfile
48511
48460
  }) {
48512
- const session = import_node_server_utils223.useAtlas.getClient()?.startSession();
48461
+ const session = import_node_server_utils222.useAtlas.getClient()?.startSession();
48513
48462
  session?.startTransaction();
48514
48463
  const _file = {
48515
48464
  name: file.originalname,
@@ -48542,18 +48491,18 @@ function useUserServiceV2() {
48542
48491
  async function updatePasswordById(id, currentPassword, newPassword, passwordConfirmation) {
48543
48492
  let hashedPassword;
48544
48493
  const user = await getUserById(id);
48545
- const isPasswordValid = await (0, import_node_server_utils223.comparePassword)(
48494
+ const isPasswordValid = await (0, import_node_server_utils222.comparePassword)(
48546
48495
  currentPassword,
48547
48496
  user.password
48548
48497
  );
48549
48498
  if (!isPasswordValid)
48550
- throw new import_node_server_utils223.BadRequestError("Invalid current password.");
48499
+ throw new import_node_server_utils222.BadRequestError("Invalid current password.");
48551
48500
  if (newPassword !== passwordConfirmation)
48552
- throw new import_node_server_utils223.BadRequestError("Passwords do not match.");
48501
+ throw new import_node_server_utils222.BadRequestError("Passwords do not match.");
48553
48502
  try {
48554
- hashedPassword = await (0, import_node_server_utils223.hashPassword)(newPassword);
48503
+ hashedPassword = await (0, import_node_server_utils222.hashPassword)(newPassword);
48555
48504
  if (!hashedPassword)
48556
- throw new import_node_server_utils223.InternalServerError("Error hashing password.");
48505
+ throw new import_node_server_utils222.InternalServerError("Error hashing password.");
48557
48506
  return await updatePassword({ _id: id, password: hashedPassword });
48558
48507
  } catch (error) {
48559
48508
  throw error;
@@ -48589,8 +48538,8 @@ function useAuthControllerV2() {
48589
48538
  });
48590
48539
  if (error) {
48591
48540
  const messages = error.details.map((d) => d.message);
48592
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48593
- 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(", ")));
48594
48543
  return;
48595
48544
  }
48596
48545
  const { email, password, country, orgName } = value;
@@ -48606,7 +48555,7 @@ function useAuthControllerV2() {
48606
48555
  return;
48607
48556
  } catch (error) {
48608
48557
  console.log(error);
48609
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48558
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48610
48559
  next(error);
48611
48560
  return;
48612
48561
  }
@@ -48624,8 +48573,8 @@ function useAuthControllerV2() {
48624
48573
  });
48625
48574
  if (error) {
48626
48575
  const messages = error.details.map((d) => d.message);
48627
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48628
- 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(", ")));
48629
48578
  return;
48630
48579
  }
48631
48580
  const session = await _login(value);
@@ -48637,7 +48586,7 @@ function useAuthControllerV2() {
48637
48586
  res.cookie("sid", session.sid, cookieOptions).cookie("user", session.user, cookieOptions).json(session);
48638
48587
  return;
48639
48588
  } catch (error) {
48640
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48589
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48641
48590
  next(error);
48642
48591
  return;
48643
48592
  }
@@ -48645,7 +48594,7 @@ function useAuthControllerV2() {
48645
48594
  async function logout(req, res, next) {
48646
48595
  const sid = req.headers["authorization"] ?? "";
48647
48596
  if (!sid) {
48648
- next(new import_node_server_utils224.BadRequestError("Session ID is required"));
48597
+ next(new import_node_server_utils223.BadRequestError("Session ID is required"));
48649
48598
  return;
48650
48599
  }
48651
48600
  try {
@@ -48653,7 +48602,7 @@ function useAuthControllerV2() {
48653
48602
  res.json({ message: "Logged out successfully" });
48654
48603
  return;
48655
48604
  } catch (error) {
48656
- import_node_server_utils224.logger.log({ level: "error", message: error.message });
48605
+ import_node_server_utils223.logger.log({ level: "error", message: error.message });
48657
48606
  next(error);
48658
48607
  return;
48659
48608
  }
@@ -48669,8 +48618,8 @@ function useAuthControllerV2() {
48669
48618
  });
48670
48619
  if (error) {
48671
48620
  const messages = error.details.map((d) => d.message);
48672
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48673
- 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(", ")));
48674
48623
  return;
48675
48624
  }
48676
48625
  const { otp, newPassword, passwordConfirmation } = value;
@@ -48683,7 +48632,7 @@ function useAuthControllerV2() {
48683
48632
  res.json({ message });
48684
48633
  return;
48685
48634
  } catch (error2) {
48686
- import_node_server_utils224.logger.log({ level: "error", message: error2.message });
48635
+ import_node_server_utils223.logger.log({ level: "error", message: error2.message });
48687
48636
  next(error2);
48688
48637
  return;
48689
48638
  }
@@ -48699,8 +48648,8 @@ function useAuthControllerV2() {
48699
48648
  );
48700
48649
  if (error) {
48701
48650
  const messages = error.details.map((d) => d.message);
48702
- import_node_server_utils224.logger.log({ level: "error", message: messages.join(", ") });
48703
- 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(", ")));
48704
48653
  return;
48705
48654
  }
48706
48655
  const { _id, password } = value;
@@ -48709,7 +48658,7 @@ function useAuthControllerV2() {
48709
48658
  res.json({ message });
48710
48659
  return;
48711
48660
  } catch (error2) {
48712
- import_node_server_utils224.logger.log({ level: "error", message: error2.message });
48661
+ import_node_server_utils223.logger.log({ level: "error", message: error2.message });
48713
48662
  next(error2);
48714
48663
  return;
48715
48664
  }
@@ -48726,7 +48675,7 @@ function useAuthControllerV2() {
48726
48675
  // src/controllers/user-v2.controller.ts
48727
48676
  var import_joi128 = __toESM(require("joi"));
48728
48677
  var import_multer3 = require("multer");
48729
- var import_node_server_utils225 = require("@7365admin1/node-server-utils");
48678
+ var import_node_server_utils224 = require("@7365admin1/node-server-utils");
48730
48679
  function useUserControllerV2() {
48731
48680
  const {
48732
48681
  updateBirthday: _updateBirthday,
@@ -48740,16 +48689,16 @@ function useUserControllerV2() {
48740
48689
  const { createUserBySignUp, updateUserProfile: _updateUserProfile, updatePasswordById: _updatePasswordById } = useUserServiceV2();
48741
48690
  function rejectValidation(error, next) {
48742
48691
  const message = error.details.map((d) => d.message).join(", ");
48743
- import_node_server_utils225.logger.log({ level: "error", message });
48744
- 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));
48745
48694
  }
48746
48695
  async function getById(req, res, next) {
48747
48696
  const validation = import_joi128.default.string().hex().required();
48748
48697
  const _id = req.params.id;
48749
48698
  const { error, value } = validation.validate(_id);
48750
48699
  if (error) {
48751
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48752
- 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));
48753
48702
  return;
48754
48703
  }
48755
48704
  try {
@@ -48757,7 +48706,7 @@ function useUserControllerV2() {
48757
48706
  res.json(user);
48758
48707
  return;
48759
48708
  } catch (error2) {
48760
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48709
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48761
48710
  next(error2);
48762
48711
  return;
48763
48712
  }
@@ -48771,7 +48720,7 @@ function useUserControllerV2() {
48771
48720
  res.json(user);
48772
48721
  return;
48773
48722
  } catch (err) {
48774
- import_node_server_utils225.logger.log({ level: "error", message: `${err.message}` });
48723
+ import_node_server_utils224.logger.log({ level: "error", message: `${err.message}` });
48775
48724
  next(err);
48776
48725
  return;
48777
48726
  }
@@ -48838,8 +48787,8 @@ function useUserControllerV2() {
48838
48787
  const payload = { ...req.body };
48839
48788
  const { error, value } = validation.validate({ id, ...payload });
48840
48789
  if (error) {
48841
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48842
- 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));
48843
48792
  return;
48844
48793
  }
48845
48794
  try {
@@ -48847,14 +48796,14 @@ function useUserControllerV2() {
48847
48796
  res.status(201).json({ message: "Successfully created account." });
48848
48797
  return;
48849
48798
  } catch (error2) {
48850
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48799
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48851
48800
  next(error2);
48852
48801
  return;
48853
48802
  }
48854
48803
  }
48855
48804
  async function updateUserProfile(req, res, next) {
48856
48805
  if (!req.file) {
48857
- next(new import_node_server_utils225.BadRequestError("File is required!"));
48806
+ next(new import_node_server_utils224.BadRequestError("File is required!"));
48858
48807
  return;
48859
48808
  }
48860
48809
  const validation = import_joi128.default.object({
@@ -48863,8 +48812,8 @@ function useUserControllerV2() {
48863
48812
  const payload = { ...req.body };
48864
48813
  const { error, value } = validation.validate(payload);
48865
48814
  if (error) {
48866
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48867
- 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));
48868
48817
  return;
48869
48818
  }
48870
48819
  const user = req.headers.user ?? "";
@@ -48877,7 +48826,7 @@ function useUserControllerV2() {
48877
48826
  res.json({ message: "Successfully updated profile picture." });
48878
48827
  return;
48879
48828
  } catch (error2) {
48880
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48829
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48881
48830
  next(error2);
48882
48831
  return;
48883
48832
  }
@@ -48907,8 +48856,8 @@ function useUserControllerV2() {
48907
48856
  const payload = { ...req.body };
48908
48857
  const { error } = validation.validate({ _id, ...payload });
48909
48858
  if (error) {
48910
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48911
- 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));
48912
48861
  return;
48913
48862
  }
48914
48863
  try {
@@ -48916,7 +48865,7 @@ function useUserControllerV2() {
48916
48865
  res.json({ message });
48917
48866
  return;
48918
48867
  } catch (error2) {
48919
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48868
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48920
48869
  next(error2);
48921
48870
  return;
48922
48871
  }
@@ -48938,8 +48887,8 @@ function useUserControllerV2() {
48938
48887
  const payload = { ...req.body };
48939
48888
  const { error } = validation.validate({ _id, ...payload });
48940
48889
  if (error) {
48941
- import_node_server_utils225.logger.log({ level: "error", message: `${error.message}` });
48942
- 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));
48943
48892
  return;
48944
48893
  }
48945
48894
  try {
@@ -48947,7 +48896,7 @@ function useUserControllerV2() {
48947
48896
  res.json({ message });
48948
48897
  return;
48949
48898
  } catch (error2) {
48950
- import_node_server_utils225.logger.log({ level: "error", message: `${error2.message}` });
48899
+ import_node_server_utils224.logger.log({ level: "error", message: `${error2.message}` });
48951
48900
  next(error2);
48952
48901
  return;
48953
48902
  }
@@ -48966,7 +48915,7 @@ function useUserControllerV2() {
48966
48915
  ...payload
48967
48916
  });
48968
48917
  if (error) {
48969
- next(new import_node_server_utils225.BadRequestError(error.message));
48918
+ next(new import_node_server_utils224.BadRequestError(error.message));
48970
48919
  return;
48971
48920
  }
48972
48921
  const currentPassword = req.body.currentPassword ?? "";
@@ -48996,6 +48945,172 @@ function useUserControllerV2() {
48996
48945
  updatePasswordById
48997
48946
  };
48998
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
+ }
48999
49114
  // Annotate the CommonJS export names for ESM import in node:
49000
49115
  0 && (module.exports = {
49001
49116
  ANPRMode,
@@ -49060,6 +49175,7 @@ function useUserControllerV2() {
49060
49175
  MPromoCode,
49061
49176
  MRobot,
49062
49177
  MRole,
49178
+ MRoleV2,
49063
49179
  MServiceProvider,
49064
49180
  MServiceProviderBilling,
49065
49181
  MSession,
@@ -49082,6 +49198,7 @@ function useUserControllerV2() {
49082
49198
  OvernightParkingRequestStatus,
49083
49199
  PERSON_TYPES,
49084
49200
  PMDashboardCollection,
49201
+ PStatus,
49085
49202
  Period,
49086
49203
  PersonStatus,
49087
49204
  PersonTypes,
@@ -49089,6 +49206,7 @@ function useUserControllerV2() {
49089
49206
  SiteStatus,
49090
49207
  SortFields,
49091
49208
  SortOrder,
49209
+ Status,
49092
49210
  SubscriptionType,
49093
49211
  UseAccessManagementRepo,
49094
49212
  UserStatus,
@@ -49343,7 +49461,10 @@ function useUserControllerV2() {
49343
49461
  useRobotRepo,
49344
49462
  useRobotService,
49345
49463
  useRoleController,
49464
+ useRoleControllerV2,
49346
49465
  useRoleRepo,
49466
+ useRoleRepoV2,
49467
+ useRoleServiceV2,
49347
49468
  useServiceProviderBillingController,
49348
49469
  useServiceProviderBillingRepo,
49349
49470
  useServiceProviderBillingService,