@7365admin1/core 2.37.0 → 2.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4842,6 +4842,7 @@ function useSiteRepo() {
4842
4842
 
4843
4843
  // src/services/verification.service.ts
4844
4844
  import Joi11 from "joi";
4845
+ import path from "path";
4845
4846
  function useVerificationService() {
4846
4847
  const MailerConfig = {
4847
4848
  host: MAILER_TRANSPORT_HOST,
@@ -4872,7 +4873,6 @@ function useVerificationService() {
4872
4873
  expireAt: new Date(
4873
4874
  (/* @__PURE__ */ new Date()).getTime() + 72 * 60 * 60 * 1e3
4874
4875
  ).toISOString(),
4875
- // 72 hours (3 days) from now
4876
4876
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
4877
4877
  };
4878
4878
  if (value.metadata?.org)
@@ -4960,8 +4960,11 @@ function useVerificationService() {
4960
4960
  subject = "Service Provider Organization Invite";
4961
4961
  }
4962
4962
  const res = await add(value);
4963
- const dir = __dirname;
4964
- const filePath = getDirectory(dir, `./public/handlebars/${value.type}`);
4963
+ const filePath = path.resolve(
4964
+ __dirname,
4965
+ "../public/handlebars",
4966
+ value.type
4967
+ );
4965
4968
  const link = org ? `${APP_MAIN}/verify/${value.type}/${res}` : `${APP_ORG}/organizations/create?email=${email}`;
4966
4969
  const emailContent = compileHandlebar({
4967
4970
  context: {
@@ -4997,6 +5000,9 @@ function useVerificationService() {
4997
5000
  };
4998
5001
  try {
4999
5002
  const user = await getUserByEmail(email);
5003
+ if (!user) {
5004
+ throw new NotFoundError9("Email not found");
5005
+ }
5000
5006
  const res = await add(value);
5001
5007
  const dir = __dirname;
5002
5008
  const filePath = getDirectory(dir, "./public/handlebars/forget-password");
@@ -13197,7 +13203,7 @@ var schemaVisitorTransaction = Joi36.object({
13197
13203
  checkOutRemarks: Joi36.string().optional().allow("", null),
13198
13204
  expectedCheckIn: Joi36.string().isoDate().optional(),
13199
13205
  purpose: Joi36.string().optional().allow(null, ""),
13200
- invitedId: Joi36.any().optional().allow(null, "")
13206
+ inviterId: Joi36.any().optional().allow(null, "")
13201
13207
  });
13202
13208
  var schemaUpdateVisTrans = Joi36.object({
13203
13209
  _id: Joi36.string().hex().length(24).required(),
@@ -13306,11 +13312,11 @@ function MVisitorTransaction(value) {
13306
13312
  return p;
13307
13313
  });
13308
13314
  }
13309
- if (value.invitedId && typeof value.invitedId === "string") {
13315
+ if (value.inviterId && typeof value.inviterId === "string") {
13310
13316
  try {
13311
- value.invitedId = new ObjectId39(value.invitedId);
13317
+ value.inviterId = new ObjectId39(value.inviterId);
13312
13318
  } catch (error2) {
13313
- throw new Error("Invalid invited ID.");
13319
+ throw new Error("Invalid inviter ID.");
13314
13320
  }
13315
13321
  }
13316
13322
  const newDate = /* @__PURE__ */ new Date();
@@ -13353,11 +13359,11 @@ function MVisitorTransaction(value) {
13353
13359
  numberOfPassengers: value.numberOfPassengers ?? null,
13354
13360
  email: value.email,
13355
13361
  isOvernightParking: value.isOvernightParking ?? false,
13356
- invitedId: value.invitedId ?? "",
13362
+ inviterId: value.inviterId ?? "",
13357
13363
  overnightParking: value.isOvernightParking == true ? {
13358
13364
  status: "pending approval",
13359
13365
  remarks: "",
13360
- updatedBy: value.invitedId ?? ""
13366
+ updatedBy: value.inviterId ?? ""
13361
13367
  } : null,
13362
13368
  arrivalTime: value.arrivalTime,
13363
13369
  duration: value.duration
@@ -13408,14 +13414,15 @@ function useVisitorTransactionRepo() {
13408
13414
  page = 1,
13409
13415
  limit = 10,
13410
13416
  sort = {},
13411
- status = "registered",
13417
+ status,
13412
13418
  org = "",
13413
13419
  site = "",
13414
13420
  dateTo = "",
13415
13421
  dateFrom = "",
13416
13422
  type = "",
13417
13423
  checkedOut,
13418
- plateNumber = ""
13424
+ plateNumber = "",
13425
+ tab = ""
13419
13426
  }) {
13420
13427
  page = page > 0 ? page - 1 : 0;
13421
13428
  const skip = page * limit;
@@ -13433,7 +13440,6 @@ function useVisitorTransactionRepo() {
13433
13440
  expectedCheckInFilter.$lte = new Date(dateTo);
13434
13441
  }
13435
13442
  const query = {
13436
- status,
13437
13443
  ...ObjectId40.isValid(org) && { org: new ObjectId40(org) },
13438
13444
  ...ObjectId40.isValid(site) && { site: new ObjectId40(site) },
13439
13445
  ...Object.keys(checkInFilter).length > 0 && { checkIn: checkInFilter },
@@ -13441,7 +13447,9 @@ function useVisitorTransactionRepo() {
13441
13447
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
13442
13448
  ...checkedOut == false && { checkOut: { $eq: null } },
13443
13449
  ...search && { $text: { $search: search } },
13444
- ...plateNumber && { plateNumber }
13450
+ ...plateNumber && { plateNumber },
13451
+ ...status && { status },
13452
+ ...tab == "Overnight Parking" && { isOvernightParking: true }
13445
13453
  };
13446
13454
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
13447
13455
  try {
@@ -13587,7 +13595,31 @@ function useVisitorTransactionRepo() {
13587
13595
  },
13588
13596
  { $sort: sort },
13589
13597
  { $skip: skip },
13590
- { $limit: limit }
13598
+ { $limit: limit },
13599
+ {
13600
+ $lookup: {
13601
+ from: "users",
13602
+ localField: "inviterId",
13603
+ foreignField: "_id",
13604
+ as: "inviterData"
13605
+ }
13606
+ },
13607
+ {
13608
+ $unwind: {
13609
+ path: "$inviterData",
13610
+ preserveNullAndEmptyArrays: true
13611
+ }
13612
+ },
13613
+ {
13614
+ $addFields: {
13615
+ inviterName: "$inviterData.name"
13616
+ }
13617
+ },
13618
+ {
13619
+ $project: {
13620
+ inviterData: 0
13621
+ }
13622
+ }
13591
13623
  ]).toArray(),
13592
13624
  collection.aggregate([...basePipeline, { $count: "total" }]).toArray()
13593
13625
  ]);
@@ -13903,7 +13935,7 @@ function MVehicle(value) {
13903
13935
  block: value.block ?? 0,
13904
13936
  level: value.level ?? "",
13905
13937
  unit: value.unit ?? "",
13906
- nric: value.nric,
13938
+ nric: value.nric ?? "",
13907
13939
  remarks: value.remarks ?? "",
13908
13940
  seasonPassType: value.seasonPassType ?? "",
13909
13941
  start: value.start ?? createdAt,
@@ -13963,7 +13995,7 @@ function MVehicleTransaction(value) {
13963
13995
  import { BadRequestError as BadRequestError71, logger as logger52 } from "@7365admin1/node-server-utils";
13964
13996
  import { promises as fsAsync } from "fs";
13965
13997
  import Joi39 from "joi";
13966
- import * as path from "path";
13998
+ import * as path2 from "path";
13967
13999
  import { request } from "urllib";
13968
14000
 
13969
14001
  // src/repositories/vehicle.repo.ts
@@ -14607,6 +14639,66 @@ function useVehicleRepo() {
14607
14639
  throw error;
14608
14640
  }
14609
14641
  }
14642
+ async function bulkUpsertVehicles(values, session) {
14643
+ try {
14644
+ if (!Array.isArray(values) || values.length === 0) {
14645
+ return {
14646
+ matchedCount: 0,
14647
+ modifiedCount: 0,
14648
+ upsertedCount: 0
14649
+ };
14650
+ }
14651
+ const now = (/* @__PURE__ */ new Date()).toISOString();
14652
+ const operations = values.map((item) => {
14653
+ const vehicle = MVehicle(item);
14654
+ const plateNumber = Array.isArray(vehicle.plateNumber) ? vehicle.plateNumber[0] : vehicle.plateNumber;
14655
+ const { createdAt, ...rest } = vehicle;
14656
+ return {
14657
+ updateOne: {
14658
+ filter: {
14659
+ site: vehicle.site,
14660
+ plateNumber,
14661
+ $or: [
14662
+ { deletedAt: "" },
14663
+ { deletedAt: null },
14664
+ { deletedAt: { $exists: false } }
14665
+ ]
14666
+ },
14667
+ update: {
14668
+ $set: {
14669
+ ...rest,
14670
+ plateNumber,
14671
+ updatedAt: now
14672
+ },
14673
+ $setOnInsert: {
14674
+ createdAt: vehicle.createdAt || now
14675
+ }
14676
+ },
14677
+ upsert: true
14678
+ }
14679
+ };
14680
+ });
14681
+ const res = await collection.bulkWrite(operations, {
14682
+ ordered: false,
14683
+ session
14684
+ });
14685
+ return {
14686
+ matchedCount: res.matchedCount,
14687
+ modifiedCount: res.modifiedCount,
14688
+ upsertedCount: res.upsertedCount,
14689
+ upsertedIds: res.upsertedIds
14690
+ };
14691
+ } catch (error) {
14692
+ logger49.log({
14693
+ level: "error",
14694
+ message: error.message
14695
+ });
14696
+ if (error instanceof AppError9) {
14697
+ throw error;
14698
+ }
14699
+ throw new Error("Failed to bulk upsert vehicles.");
14700
+ }
14701
+ }
14610
14702
  return {
14611
14703
  createIndex,
14612
14704
  createTextIndex,
@@ -14621,7 +14713,8 @@ function useVehicleRepo() {
14621
14713
  getVehiclesByNRIC,
14622
14714
  deleteExpiredVehicles,
14623
14715
  getAllVehiclesByUnitId,
14624
- getAllExpiredVehicles
14716
+ getAllExpiredVehicles,
14717
+ bulkUpsertVehicles
14625
14718
  };
14626
14719
  }
14627
14720
 
@@ -15267,7 +15360,8 @@ function useVehicleService() {
15267
15360
  getVehicleById: _getVehicleById,
15268
15361
  deleteExpiredVehicles: _deleteExpiredVehicles,
15269
15362
  getVehicleByPlateNumber: _getVehicleByPlateNumber,
15270
- getAllExpiredVehicles: _getAllExpiredVehicles
15363
+ getAllExpiredVehicles: _getAllExpiredVehicles,
15364
+ bulkUpsertVehicles: _bulkUpsertVehicles
15271
15365
  } = useVehicleRepo();
15272
15366
  const {
15273
15367
  addPlateNumber: _addPlateNumber,
@@ -15884,13 +15978,38 @@ function useVehicleService() {
15884
15978
  session.endSession();
15885
15979
  }
15886
15980
  }
15981
+ async function bulkUpsertVehicles(values) {
15982
+ const session = useAtlas33.getClient()?.startSession();
15983
+ if (!session) {
15984
+ throw new Error("Unable to start session for vehicle service.");
15985
+ }
15986
+ try {
15987
+ if (!Array.isArray(values) || values.length === 0) {
15988
+ throw new Error("Vehicle list is required.");
15989
+ }
15990
+ const sanitizedValues = values.map((item) => {
15991
+ const plateNumber = Array.isArray(item.plateNumber) ? item.plateNumber[0] : item.plateNumber;
15992
+ return {
15993
+ ...item,
15994
+ plateNumber: typeof plateNumber === "string" ? plateNumber.trim() : plateNumber
15995
+ };
15996
+ }).filter((item) => item.site && item.plateNumber);
15997
+ if (sanitizedValues.length === 0) {
15998
+ throw new Error("No valid vehicle plate numbers found.");
15999
+ }
16000
+ return await _bulkUpsertVehicles(sanitizedValues, session);
16001
+ } catch (error) {
16002
+ throw error;
16003
+ }
16004
+ }
15887
16005
  return {
15888
16006
  add,
15889
16007
  deleteVehicle,
15890
16008
  approveVehicleById,
15891
16009
  processDeletingExpiredVehicles,
15892
16010
  reactivateVehicleById,
15893
- updateVehicleById
16011
+ updateVehicleById,
16012
+ bulkUpsertVehicles
15894
16013
  };
15895
16014
  }
15896
16015
 
@@ -16164,8 +16283,8 @@ function useDahuaService() {
16164
16283
  const utcMs = Number(UTCMs) || Date.now() % 1e3;
16165
16284
  const timeData = createFileNameFromEvent(utcSec, utcMs);
16166
16285
  const filename = plateNumber ? `${gate}-${timeData}-${plateNumber}.jpeg` : `${gate}-${timeData}.jpeg`;
16167
- const snapFolder = path.join(__dirname, `../snap/${site}/${filename}`);
16168
- const dir = path.dirname(snapFolder);
16286
+ const snapFolder = path2.join(__dirname, `../snap/${site}/${filename}`);
16287
+ const dir = path2.dirname(snapFolder);
16169
16288
  try {
16170
16289
  await fsAsync.mkdir(dir, { recursive: true });
16171
16290
  await fsAsync.writeFile(snapFolder, accumulatedImageBuffer);
@@ -18600,13 +18719,18 @@ function useBuildingUnitController() {
18600
18719
  // src/controllers/vehicle.controller.ts
18601
18720
  import { BadRequestError as BadRequestError83, logger as logger65 } from "@7365admin1/node-server-utils";
18602
18721
  import Joi46 from "joi";
18722
+ import ExcelJS from "exceljs";
18723
+ import { Readable } from "stream";
18724
+ import csv from "csv-parser";
18725
+ import fs from "fs";
18603
18726
  function useVehicleController() {
18604
18727
  const {
18605
18728
  add: _add,
18606
18729
  deleteVehicle: _deleteVehicle,
18607
18730
  approveVehicleById: _approveVehicleById,
18608
18731
  reactivateVehicleById: _reactivateVehicleById,
18609
- updateVehicleById: _updateVehicleById
18732
+ updateVehicleById: _updateVehicleById,
18733
+ bulkUpsertVehicles: _bulkUpsertVehicles
18610
18734
  } = useVehicleService();
18611
18735
  const {
18612
18736
  getSeasonPassTypes: _getSeasonPassTypes,
@@ -18615,6 +18739,141 @@ function useVehicleController() {
18615
18739
  getVehiclesByNRIC: _getVehiclesByNRIC,
18616
18740
  getAllVehiclesByUnitId: _getAllVehiclesByUnitId
18617
18741
  } = useVehicleRepo();
18742
+ function normalizeRow(row) {
18743
+ return Object.fromEntries(
18744
+ Object.entries(row).map(([key, value]) => [
18745
+ key,
18746
+ typeof value === "string" ? value.trim() : value
18747
+ ])
18748
+ );
18749
+ }
18750
+ function mapRowToVehicle(row) {
18751
+ const cleanRow = normalizeRow(row);
18752
+ return {
18753
+ name: cleanRow.fullName,
18754
+ category: cleanRow.userType,
18755
+ type: cleanRow.recordType,
18756
+ phoneNumber: cleanRow.phoneNumber || "",
18757
+ block: Number(cleanRow.block),
18758
+ level: String(cleanRow.level || ""),
18759
+ unitName: String(cleanRow.unit || ""),
18760
+ plateNumber: String(cleanRow.plateNumber || "").toUpperCase(),
18761
+ remarks: `Model: ${cleanRow.vehicleModel || ""}, Color: ${cleanRow.vehicleColor || ""}`,
18762
+ org: cleanRow.org,
18763
+ site: cleanRow.site,
18764
+ end: parseExpiryDate(cleanRow.subscriptionExpiry)
18765
+ };
18766
+ }
18767
+ function parseExpiryDate(value) {
18768
+ if (!value)
18769
+ return void 0;
18770
+ const [day, monthStr, yearShort] = value.split("-");
18771
+ const months = {
18772
+ Jan: 0,
18773
+ Feb: 1,
18774
+ Mar: 2,
18775
+ Apr: 3,
18776
+ May: 4,
18777
+ Jun: 5,
18778
+ Jul: 6,
18779
+ Aug: 7,
18780
+ Sep: 8,
18781
+ Oct: 9,
18782
+ Nov: 10,
18783
+ Dec: 11
18784
+ };
18785
+ const month = months[monthStr];
18786
+ if (month === void 0)
18787
+ return void 0;
18788
+ const year = 2e3 + Number(yearShort);
18789
+ const date = new Date(year, month, Number(day));
18790
+ return isNaN(date.getTime()) ? void 0 : date.toISOString();
18791
+ }
18792
+ async function uploadCsvVehicles(req, res, next) {
18793
+ try {
18794
+ if (!req.file) {
18795
+ next(new BadRequestError83("CSV file is required."));
18796
+ return;
18797
+ }
18798
+ if (!req.file.originalname.toLowerCase().endsWith(".csv")) {
18799
+ next(new BadRequestError83("Only .csv files are allowed."));
18800
+ return;
18801
+ }
18802
+ const rows = [];
18803
+ const stream = Readable.from(req.file.buffer);
18804
+ stream.pipe(csv()).on("data", (row) => {
18805
+ rows.push(row);
18806
+ }).on("end", async () => {
18807
+ try {
18808
+ const vehicles = rows.map(mapRowToVehicle);
18809
+ const data = await _bulkUpsertVehicles(vehicles);
18810
+ res.status(200).json({
18811
+ message: "CSV import completed.",
18812
+ count: rows.length,
18813
+ data
18814
+ });
18815
+ } catch (error) {
18816
+ logger65.log({ level: "error", message: error.message });
18817
+ next(error);
18818
+ }
18819
+ }).on("error", (error) => {
18820
+ logger65.log({ level: "error", message: error.message });
18821
+ next(error);
18822
+ });
18823
+ } catch (error) {
18824
+ logger65.log({ level: "error", message: error.message });
18825
+ next(error);
18826
+ }
18827
+ }
18828
+ async function uploadExcelVehicles(req, res, next) {
18829
+ try {
18830
+ if (!req.file) {
18831
+ next(new BadRequestError83("Excel file is required."));
18832
+ return;
18833
+ }
18834
+ if (!req.file.originalname.toLowerCase().endsWith(".xlsx")) {
18835
+ next(new BadRequestError83("Only .xlsx files are allowed."));
18836
+ return;
18837
+ }
18838
+ const workbook = new ExcelJS.Workbook();
18839
+ await workbook.xlsx.readFile(req.file.path);
18840
+ const worksheet = workbook.worksheets[0];
18841
+ if (!worksheet) {
18842
+ next(new BadRequestError83("No worksheet found in uploaded Excel file."));
18843
+ return;
18844
+ }
18845
+ const rows = [];
18846
+ const headerRow = worksheet.getRow(1);
18847
+ const headers = (headerRow.values || []).slice(1).map((header) => String(header ?? "").trim());
18848
+ worksheet.eachRow((row, rowNumber) => {
18849
+ if (rowNumber === 1)
18850
+ return;
18851
+ const rowData = {};
18852
+ headers.forEach((header, index) => {
18853
+ rowData[header] = row.getCell(index + 1).value ?? "";
18854
+ });
18855
+ const hasValue = Object.values(rowData).some(
18856
+ (value) => value !== null && value !== void 0 && value !== ""
18857
+ );
18858
+ if (hasValue) {
18859
+ rows.push(rowData);
18860
+ }
18861
+ });
18862
+ const vehicles = rows.map(mapRowToVehicle);
18863
+ const data = await _bulkUpsertVehicles(vehicles);
18864
+ res.status(200).json({
18865
+ message: "Excel import completed.",
18866
+ sheetName: worksheet.name,
18867
+ count: rows.length,
18868
+ data
18869
+ });
18870
+ fs.unlink(req.file.path, () => {
18871
+ });
18872
+ } catch (error) {
18873
+ logger65.log({ level: "error", message: error.message });
18874
+ next(error);
18875
+ }
18876
+ }
18618
18877
  async function add(req, res, next) {
18619
18878
  const { error, value } = vehicleSchema.validate(req.body, {
18620
18879
  abortEarly: false
@@ -18939,6 +19198,69 @@ function useVehicleController() {
18939
19198
  return;
18940
19199
  }
18941
19200
  }
19201
+ async function bulkUpsertVehicles(req, res, next) {
19202
+ const items = Array.isArray(req.body) ? req.body : req.body?.items;
19203
+ if (!Array.isArray(items) || items.length === 0) {
19204
+ next(new BadRequestError83("A non-empty array of vehicles is required."));
19205
+ return;
19206
+ }
19207
+ const success = [];
19208
+ const failed = [];
19209
+ try {
19210
+ for (let index = 0; index < items.length; index++) {
19211
+ const item = items[index];
19212
+ const schema2 = Joi46.object({
19213
+ fullName: Joi46.string().trim().required(),
19214
+ category: Joi46.string().trim().lowercase().valid(...Object.values(PersonTypes)).required(),
19215
+ type: Joi46.string().trim().lowercase().valid(...Object.values(VehicleType)),
19216
+ phoneNumber: Joi46.string().trim().allow(null, "").optional(),
19217
+ block: Joi46.number().integer().min(1).required(),
19218
+ level: Joi46.string().trim().required(),
19219
+ unit: Joi46.string().trim().required(),
19220
+ plateNumber: Joi46.string().trim().uppercase().required(),
19221
+ vehicleModel: Joi46.string().trim().required(),
19222
+ vehicleColor: Joi46.string().trim().required(),
19223
+ subscriptionExpiry: Joi46.string().trim().allow(null, "").optional()
19224
+ });
19225
+ const { error, value } = schema2.validate(item, {
19226
+ abortEarly: false
19227
+ });
19228
+ if (error) {
19229
+ const message = error.details.map((d) => d.message).join(", ");
19230
+ failed.push({
19231
+ index,
19232
+ item,
19233
+ message
19234
+ });
19235
+ continue;
19236
+ }
19237
+ try {
19238
+ const data = await _bulkUpsertVehicles(value);
19239
+ success.push({
19240
+ index,
19241
+ data
19242
+ });
19243
+ } catch (error2) {
19244
+ failed.push({
19245
+ index,
19246
+ item,
19247
+ message: error2.message
19248
+ });
19249
+ }
19250
+ }
19251
+ res.status(201).json({
19252
+ message: "Bulk vehicle import completed.",
19253
+ successCount: success.length,
19254
+ failedCount: failed.length,
19255
+ success,
19256
+ failed
19257
+ });
19258
+ } catch (error) {
19259
+ logger65.log({ level: "error", message: error.message });
19260
+ next(error);
19261
+ return;
19262
+ }
19263
+ }
18942
19264
  return {
18943
19265
  add,
18944
19266
  getVehicles,
@@ -18949,7 +19271,10 @@ function useVehicleController() {
18949
19271
  approveVehicleById,
18950
19272
  getVehiclesByNRIC,
18951
19273
  reactivateVehicleById,
18952
- getAllVehiclesByUnitId
19274
+ getAllVehiclesByUnitId,
19275
+ bulkUpsertVehicles,
19276
+ uploadCsvVehicles,
19277
+ uploadExcelVehicles
18953
19278
  };
18954
19279
  }
18955
19280
 
@@ -22198,7 +22523,7 @@ function useVisitorTransactionService() {
22198
22523
  org: inviter?.org.toString(),
22199
22524
  site: inviter?.site.toString(),
22200
22525
  status: "approved" /* APPROVED */,
22201
- invitedId: inviter?._id
22526
+ inviterId: userId
22202
22527
  };
22203
22528
  const result = await _add(payload);
22204
22529
  const emailContent = compileHandlebar2({
@@ -22349,7 +22674,8 @@ function useVisitorTransactionController() {
22349
22674
  }).optional().allow(null, ""),
22350
22675
  checkedOut: Joi55.boolean().allow(null, ""),
22351
22676
  plateNumber: Joi55.string().optional().allow(null, ""),
22352
- order: Joi55.string().valid(...Object.values(SortOrder)).default("asc" /* ASC */)
22677
+ order: Joi55.string().valid(...Object.values(SortOrder)).default("asc" /* ASC */),
22678
+ tab: Joi55.string().optional().allow(null, "")
22353
22679
  });
22354
22680
  const { error, value } = validation.validate(req.query, {
22355
22681
  abortEarly: false
@@ -22373,7 +22699,8 @@ function useVisitorTransactionController() {
22373
22699
  checkedOut,
22374
22700
  sort,
22375
22701
  order,
22376
- plateNumber
22702
+ plateNumber,
22703
+ tab
22377
22704
  } = value;
22378
22705
  const sortObj = {
22379
22706
  [sort ? sort : "_id" /* ID */]: order === "asc" /* ASC */ ? 1 : -1
@@ -22390,7 +22717,8 @@ function useVisitorTransactionController() {
22390
22717
  dateFrom,
22391
22718
  type,
22392
22719
  checkedOut,
22393
- plateNumber
22720
+ plateNumber,
22721
+ tab
22394
22722
  });
22395
22723
  res.status(200).json(data);
22396
22724
  return;
@@ -29729,7 +30057,7 @@ function useSiteBillingItemService() {
29729
30057
  }
29730
30058
  try {
29731
30059
  await session.startTransaction();
29732
- const billing_item = await _getBillingItemById(id, session);
30060
+ const billing_item = await _getBillingItemById(id);
29733
30061
  if (!billing_item) {
29734
30062
  throw new BadRequestError131("Billing item not found.");
29735
30063
  }
@@ -30749,10 +31077,32 @@ function useEventManagementController() {
30749
31077
  import { BadRequestError as BadRequestError137, logger as logger116 } from "@7365admin1/node-server-utils";
30750
31078
  import { ObjectId as ObjectId85 } from "mongodb";
30751
31079
  import Joi83 from "joi";
31080
+ var Status = /* @__PURE__ */ ((Status3) => {
31081
+ Status3["PENDING"] = "pending";
31082
+ Status3["COMPLETED"] = "completed";
31083
+ Status3["APPROVED"] = "approved";
31084
+ Status3["REJECTED"] = "rejected";
31085
+ Status3["CANCELLED"] = "cancelled";
31086
+ Status3["RECURRING"] = "recurring";
31087
+ Status3["NONRECURRING"] = "non-recurring";
31088
+ Status3["ACTIVE"] = "active";
31089
+ Status3["INACTIVE"] = "inactive";
31090
+ return Status3;
31091
+ })(Status || {});
31092
+ var PStatus = /* @__PURE__ */ ((PStatus2) => {
31093
+ PStatus2["PROCESSING"] = "processing";
31094
+ PStatus2["UNPAID"] = "unpaid";
31095
+ PStatus2["PAID"] = "paid";
31096
+ PStatus2["OVERDUE"] = "overdue";
31097
+ PStatus2["PARTIAL"] = "partial-payment";
31098
+ PStatus2["AWAITING_PAYMENT"] = "awaiting-payment";
31099
+ PStatus2["FAILED"] = "failed";
31100
+ return PStatus2;
31101
+ })(PStatus || {});
30752
31102
  var schemaUnitBilling = Joi83.object({
30753
31103
  _id: Joi83.string().hex().optional(),
30754
- site: Joi83.string().hex().required(),
30755
- org: Joi83.string().hex().required(),
31104
+ site: Joi83.string().hex().optional().allow(null, ""),
31105
+ org: Joi83.string().hex().optional().allow(null, ""),
30756
31106
  billItem: Joi83.string().hex().optional().allow(null, ""),
30757
31107
  billName: Joi83.string().optional().allow(null, ""),
30758
31108
  unitId: Joi83.string().hex().optional().allow(null, ""),
@@ -30772,6 +31122,7 @@ var schemaUnitBilling = Joi83.object({
30772
31122
  paymentStatus: Joi83.string().optional().allow(null, ""),
30773
31123
  status: Joi83.string().optional().allow(null, ""),
30774
31124
  amountPaid: Joi83.number().optional().allow(null, ""),
31125
+ balanceAmount: Joi83.number().optional().allow(null, ""),
30775
31126
  paidBy: Joi83.string().hex().optional().allow(null, ""),
30776
31127
  datePaid: Joi83.date().optional().allow(null, ""),
30777
31128
  transaction_id: Joi83.string().optional().allow(null, ""),
@@ -30795,6 +31146,7 @@ var schemaUpdateSiteUnitBilling = Joi83.object({
30795
31146
  category: Joi83.string().optional().allow(null, ""),
30796
31147
  frequency: Joi83.string().optional().allow(null, ""),
30797
31148
  totalAmount: Joi83.number().optional().allow(null, ""),
31149
+ balanceAmount: Joi83.number().optional().allow(null, ""),
30798
31150
  taxPercentage: Joi83.number().optional().allow(null, ""),
30799
31151
  taxAmount: Joi83.number().optional().allow(null, ""),
30800
31152
  amount: Joi83.number().optional().allow(null, ""),
@@ -30860,8 +31212,8 @@ function MUnitBilling(value) {
30860
31212
  }
30861
31213
  return {
30862
31214
  _id: value._id ?? new ObjectId85(),
30863
- site: value.site,
30864
- org: value.org,
31215
+ site: value.site ?? "",
31216
+ org: value.org ?? "",
30865
31217
  billItem: value.billItem ?? "",
30866
31218
  billName: value.billName ?? "",
30867
31219
  unitId: value.unitId ?? "",
@@ -30881,6 +31233,7 @@ function MUnitBilling(value) {
30881
31233
  paymentStatus: value.paymentStatus ?? "",
30882
31234
  status: value.status ?? "active",
30883
31235
  amountPaid: value.amountPaid ?? 0,
31236
+ balanceAmount: value.balanceAmount ?? 0,
30884
31237
  paidBy: value.paidBy ?? "",
30885
31238
  datePaid: value.datePaid ?? "",
30886
31239
  transaction_id: value.transaction_id ?? "",
@@ -30933,7 +31286,7 @@ function useSiteUnitBillingRepo() {
30933
31286
  value = MUnitBilling(value);
30934
31287
  const res = await collection.insertOne(value, { session });
30935
31288
  const acronym = createAcronym(value.billName || "NA");
30936
- const dateFormatted = formatDateString2(/* @__PURE__ */ new Date());
31289
+ const dateFormatted = formatDateString(/* @__PURE__ */ new Date());
30937
31290
  const newId = new ObjectId86(res.insertedId).toString().slice(-6);
30938
31291
  const referenceNumber = `${acronym}${newId}${dateFormatted}`;
30939
31292
  await collection.updateOne(
@@ -31359,7 +31712,7 @@ function useSiteUnitBillingRepo() {
31359
31712
  function createAcronym(billName) {
31360
31713
  return billName.split(" ").map((word) => word.charAt(0).toUpperCase()).join("");
31361
31714
  }
31362
- function formatDateString2(today) {
31715
+ function formatDateString(today) {
31363
31716
  today = typeof today === "string" ? new Date(today) : today;
31364
31717
  let month = today.getMonth() + 1;
31365
31718
  let day = today.getDate();
@@ -31884,8 +32237,8 @@ import {
31884
32237
  import { ObjectId as ObjectId89 } from "mongodb";
31885
32238
 
31886
32239
  // src/utils/access-management.ts
31887
- import fs from "fs";
31888
- import path2 from "path";
32240
+ import fs2 from "fs";
32241
+ import path3 from "path";
31889
32242
  import axios from "axios";
31890
32243
  import { parseStringPromise } from "xml2js";
31891
32244
  import crypto from "crypto";
@@ -31914,8 +32267,8 @@ var minifyXml = (xml) => {
31914
32267
  return xml.replace(/>\s+</g, "><").replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").trim();
31915
32268
  };
31916
32269
  var readTemplate = (name, params) => {
31917
- const template = fs.readFileSync(
31918
- path2.join(__dirname, `../src/public/xml-templates/${name}.xml`),
32270
+ const template = fs2.readFileSync(
32271
+ path3.join(__dirname, `../src/public/xml-templates/${name}.xml`),
31919
32272
  "utf-8"
31920
32273
  );
31921
32274
  if (!params)
@@ -32024,14 +32377,14 @@ import { parseStringPromise as parseStringPromise2 } from "xml2js";
32024
32377
 
32025
32378
  // src/utils/rsa-encryption.ts
32026
32379
  import * as crypto2 from "crypto";
32027
- import fs2 from "fs";
32028
- import path3 from "path";
32029
- var pub = path3.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_pub.pem");
32030
- var priv = path3.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_priv.pem");
32380
+ import fs3 from "fs";
32381
+ import path4 from "path";
32382
+ var pub = path4.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_pub.pem");
32383
+ var priv = path4.resolve(process.cwd(), "./src/public/rsa-keys/new_rsa_512_priv.pem");
32031
32384
  var EncryptionCredentials = class {
32032
32385
  };
32033
- EncryptionCredentials.RAW_PUBLIC_KEY = fs2.readFileSync(pub, "utf8");
32034
- EncryptionCredentials.RAW_PRIVATE_KEY = fs2.readFileSync(priv, "utf8");
32386
+ EncryptionCredentials.RAW_PUBLIC_KEY = fs3.readFileSync(pub, "utf8");
32387
+ EncryptionCredentials.RAW_PRIVATE_KEY = fs3.readFileSync(priv, "utf8");
32035
32388
  var EntrypassRSAEncryption = class extends EncryptionCredentials {
32036
32389
  static hexToCardNumber(hex) {
32037
32390
  if (!/^[0-9A-Fa-f]{8}$/.test(hex)) {
@@ -33987,7 +34340,7 @@ import Joi85 from "joi";
33987
34340
 
33988
34341
  // src/services/access-management.service.ts
33989
34342
  import { parseStringPromise as parseStringPromise3 } from "xml2js";
33990
- import { Readable } from "stream";
34343
+ import { Readable as Readable2 } from "stream";
33991
34344
  import * as xlsx from "xlsx";
33992
34345
  function useAccessManagementSvc() {
33993
34346
  const {
@@ -34192,7 +34545,7 @@ function useAccessManagementSvc() {
34192
34545
  };
34193
34546
  const convertBufferFile = async (bufferFile) => {
34194
34547
  return new Promise((resolve, reject) => {
34195
- const fileStream = Readable.from(bufferFile);
34548
+ const fileStream = Readable2.from(bufferFile);
34196
34549
  let fileBuffer = Buffer.alloc(0);
34197
34550
  fileStream.on("data", (chunk) => {
34198
34551
  fileBuffer = Buffer.concat([fileBuffer, chunk]);
@@ -46614,121 +46967,8 @@ function genericSignature(params, secretKey) {
46614
46967
  }
46615
46968
 
46616
46969
  // src/repositories/reddot-payment.repository.ts
46617
- import { ObjectId as ObjectId127 } from "mongodb";
46618
-
46619
- // src/utils/date-format.util.ts
46620
- import moment6 from "moment-timezone";
46621
- function formatDateString(today, format, dateRange) {
46622
- today = typeof today === "string" ? new Date(today) : today;
46623
- let month = today.getMonth() + 1;
46624
- let day = today.getDate();
46625
- let year = today.getFullYear();
46626
- let formattedDate;
46627
- if (format === "mm-dd-yyyy") {
46628
- formattedDate = `${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}-${year}`;
46629
- } else if (format === "dd-mm-yyyy") {
46630
- formattedDate = `${day.toString().padStart(2, "0")}-${month.toString().padStart(2, "0")}-${year}`;
46631
- } else if (format === "for-ref") {
46632
- formattedDate = `${month.toString().padStart(2, "0")}${day.toString().padStart(2, "0")}${year}`;
46633
- } else if (format === "mm/dd/yyyy") {
46634
- formattedDate = `${month.toString().padStart(2, "0")}/${day.toString().padStart(2, "0")}/${year}`;
46635
- } else {
46636
- formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
46637
- }
46638
- return formattedDate;
46639
- }
46640
-
46641
- // src/models/credit-card.model.ts
46642
- import { ObjectId as ObjectId124 } from "mongodb";
46643
- var MCardInfo = class {
46644
- // this is coming from RDP transaction
46645
- constructor({
46646
- _id = new ObjectId124(),
46647
- userId,
46648
- cardType,
46649
- cardNumber,
46650
- cardId,
46651
- fullName,
46652
- expiryDate,
46653
- cvv,
46654
- site,
46655
- siteName,
46656
- organization,
46657
- createdBy,
46658
- createdAt,
46659
- updatedAt,
46660
- transaction_id
46661
- } = {}) {
46662
- this._id = _id;
46663
- this.userId = userId;
46664
- this.cardType = cardType;
46665
- this.cardNumber = cardNumber;
46666
- this.cardId = cardId;
46667
- this.fullName = fullName;
46668
- this.expiryDate = expiryDate;
46669
- this.cvv = cvv;
46670
- this.site = site;
46671
- this.siteName = siteName;
46672
- this.organization = organization;
46673
- this.createdBy = createdBy;
46674
- this.createdAt = createdAt;
46675
- this.updatedAt = updatedAt;
46676
- this.transaction_id = transaction_id;
46677
- }
46678
- };
46679
-
46680
- // src/models/cart.model.ts
46681
- import { ObjectId as ObjectId125 } from "mongodb";
46682
- var MUnitBillings = class {
46683
- // transaction response messages
46684
- constructor({
46685
- _id = new ObjectId125(),
46686
- unit,
46687
- unitId,
46688
- unitBill,
46689
- paymentStatus = "Processing" /* processing */,
46690
- referenceNumber,
46691
- amountPaid,
46692
- paidBy,
46693
- datePaid,
46694
- billCategory,
46695
- billFrom,
46696
- billTo,
46697
- site,
46698
- organization,
46699
- createdBy,
46700
- createdAt,
46701
- updatedAt,
46702
- message
46703
- } = {}) {
46704
- this._id = _id;
46705
- this.unit = unit;
46706
- this.unitId = unitId;
46707
- this.referenceNumber = referenceNumber;
46708
- this.unitBill = unitBill;
46709
- this.paymentStatus = paymentStatus;
46710
- this.amountPaid = amountPaid;
46711
- this.site = site;
46712
- this.organization = organization;
46713
- this.paidBy = paidBy;
46714
- this.datePaid = datePaid;
46715
- this.billCategory = billCategory;
46716
- this.billFrom = billFrom;
46717
- this.billTo = billTo;
46718
- this.createdBy = createdBy;
46719
- this.createdAt = createdAt;
46720
- this.updatedAt = updatedAt;
46721
- this.message = message;
46722
- }
46723
- };
46724
-
46725
- // src/repositories/payment.repository.ts
46726
- import { ObjectId as ObjectId126 } from "mongodb";
46727
- import {
46728
- InternalServerError as InternalServerError66,
46729
- useAtlas as useAtlas110
46730
- } from "@7365admin1/node-server-utils";
46731
- var PaymentBillRepo = () => {
46970
+ import { InternalServerError as InternalServerError66, useAtlas as useAtlas110 } from "@7365admin1/node-server-utils";
46971
+ var useRedDotPaymentRepo = () => {
46732
46972
  const getDB2 = () => {
46733
46973
  const db = useAtlas110.getDb();
46734
46974
  if (!db) {
@@ -46736,350 +46976,75 @@ var PaymentBillRepo = () => {
46736
46976
  }
46737
46977
  return db;
46738
46978
  };
46739
- const collection = () => {
46740
- return getDB2().collection("unit-bill");
46979
+ const paymentCollection = () => {
46980
+ return getDB2().collection("payments");
46741
46981
  };
46742
- const billCollection = () => {
46743
- return getDB2().collection("bill-records");
46982
+ const unitBillingCollection = () => {
46983
+ return getDB2().collection("site.unit.billing");
46744
46984
  };
46745
- const creditCollection = () => {
46746
- return getDB2().collection("credit-info");
46985
+ const orgCollection = () => {
46986
+ return getDB2().collection("organizations");
46747
46987
  };
46748
- const cartCollection = () => {
46749
- return getDB2().collection("checkout-cart");
46988
+ const redDotMerchantCollection = () => {
46989
+ return getDB2().collection("payment-gateways");
46750
46990
  };
46751
- const payUnitBill = async (refId, payload) => {
46991
+ async function paySingleUnitBill(refId, payload) {
46752
46992
  try {
46753
46993
  if (refId)
46754
46994
  refId = refId.toString();
46755
- const unitBillInfo = await collection().findOne({ referenceNumber: refId });
46756
- const unitBillId = unitBillInfo?._id;
46995
+ const unitBillInfo = await unitBillingCollection().findOne({
46996
+ referenceNumber: refId
46997
+ });
46757
46998
  if (!unitBillInfo) {
46758
46999
  throw new Error("Unit bill info not found");
46759
47000
  }
46760
- if (unitBillInfo?.status === "Inactive" /* inactive */) {
47001
+ if (unitBillInfo?.status === "inactive" /* INACTIVE */) {
46761
47002
  throw new Error("This Bill is Inactive!");
46762
47003
  }
46763
- const billId = new ObjectId126(unitBillInfo?.billId);
46764
- const billInfo = await billCollection().findOne({ _id: billId });
46765
- if (!billInfo) {
46766
- throw new Error("Bill info not found");
46767
- }
46768
- if (payload.paymentStatus === "Partial Payment" /* partial */ && payload.amountPaid) {
46769
- const price = parseInt(billInfo?.price);
46770
- const amount = payload.amountPaid;
46771
- const numericPrice = typeof price === "string" ? parseInt(price) : price;
46772
- const numericAmount = typeof amount === "string" ? parseInt(amount) : amount;
46773
- if (typeof amount !== "number") {
46774
- throw new Error("Amount is not a valid number");
46775
- } else if (typeof price !== "number") {
46776
- throw new Error("Price s not a valid number");
47004
+ if (payload.paymentStatus === "partial-payment" /* PARTIAL */ && payload.amountPaid) {
47005
+ const totalAmount = parseInt(unitBillInfo.totalAmount);
47006
+ const amountPaid = payload.amountPaid;
47007
+ if (typeof totalAmount !== "number") {
47008
+ throw new Error("Total Amount is not a valid number");
47009
+ } else if (typeof amountPaid !== "number") {
47010
+ throw new Error("Amount Paid is not a valid number");
46777
47011
  }
46778
- payload.balance = numericPrice - numericAmount;
46779
- } else if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
47012
+ payload.balanceAmount = totalAmount - amountPaid;
47013
+ } else if (payload.paymentStatus === "paid" /* PAID */ && payload.amountPaid) {
46780
47014
  payload.datePaid = /* @__PURE__ */ new Date();
46781
- payload.paymentStatus = "Paid" /* paid */;
47015
+ payload.paymentStatus = "paid" /* PAID */;
46782
47016
  payload.amountPaid;
46783
47017
  payload.transaction_id;
46784
- } else if (payload.paymentStatus === "Failed" /* failed */) {
47018
+ } else if (payload.paymentStatus === "failed" /* FAILED */) {
46785
47019
  payload.amountPaid = 0;
46786
- payload.paidBy = "";
46787
- payload.datePaid = "";
46788
- payload.paymentStatus = "Failed" /* failed */;
47020
+ payload.paymentStatus = "failed" /* FAILED */;
46789
47021
  payload.transaction_id;
46790
47022
  }
46791
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46792
- payload.updatedAt = updatedAt;
46793
- const result = await collection().findOneAndUpdate({ _id: unitBillId }, { $set: payload }, { returnDocument: "after" });
46794
- return result;
46795
- } catch (error) {
46796
- throw new Error(error.message || error || "Server Internal Error");
46797
- }
46798
- };
46799
- const saveCreditCardInfo = async (payload) => {
46800
- try {
46801
- if (payload.userId)
46802
- payload.userId = new ObjectId126(payload.userId);
46803
- if (payload.site)
46804
- payload.site = new ObjectId126(payload.site);
46805
- if (payload.organization)
46806
- payload.organization = new ObjectId126(payload.organization);
46807
- if (payload.createdBy)
46808
- payload.createdBy = new ObjectId126(payload.createdBy);
46809
- const createdAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46810
- payload.createdAt = createdAt;
46811
- const result = await creditCollection().insertOne(new MCardInfo(payload));
46812
- return result;
46813
- } catch (error) {
46814
- throw new Error(error.message || error || "Server Internal Error");
46815
- }
46816
- };
46817
- const checkOutUnitBills = async (payload) => {
46818
- try {
46819
- if (payload.unitId)
46820
- payload.unitId = new ObjectId126(payload.unitId);
46821
- if (payload.site)
46822
- payload.site = new ObjectId126(payload.site);
46823
- if (payload.organization)
46824
- payload.organization = new ObjectId126(payload.organization);
46825
- payload.createdAt = await formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46826
- const addToCart = await cartCollection().insertOne(new MUnitBillings(payload));
46827
- const unitId = payload.unitId;
46828
- const dateFormatted = formatDateString(/* @__PURE__ */ new Date(), "for-ref");
46829
- const unit = unitId?.toString().slice(-4);
46830
- const newId = new ObjectId126(addToCart?.insertedId).toString().slice(-4);
46831
- const referenceNumber = `CRT${unit}${newId}${dateFormatted}`;
46832
- const result = await cartCollection().findOneAndUpdate({ _id: new ObjectId126(addToCart.insertedId) }, { $set: { referenceNumber } }, { returnDocument: "after" });
46833
- return result;
46834
- } catch (error) {
46835
- throw new Error(error.message || error || "Server Internal Error");
46836
- }
46837
- };
46838
- const payUnitCart = async (refId, payload) => {
46839
- try {
46840
- if (refId)
46841
- refId = refId.toString();
46842
- const updatedAt = formatDateString(/* @__PURE__ */ new Date(), "mm-dd-yyyy");
46843
- const cartInfo = await cartCollection().findOne({ referenceNumber: refId });
46844
- const refNumber = cartInfo?.unitBill;
46845
- if (payload.paymentStatus === "Paid" /* paid */ && payload.amountPaid) {
46846
- payload.datePaid = /* @__PURE__ */ new Date();
46847
- payload.paymentStatus = "Paid" /* paid */;
46848
- payload.amountPaid;
46849
- } else if (payload.paymentStatus === "Failed" /* failed */) {
46850
- payload.amountPaid = 0;
46851
- payload.paidBy = "";
46852
- payload.datePaid = "";
46853
- payload.paymentStatus = "Failed" /* failed */;
46854
- }
46855
- payload.updatedAt = updatedAt;
46856
- const result = await cartCollection().findOneAndUpdate({ referenceNumber: refId }, { $set: payload }, { returnDocument: "after" });
46857
- if (!result) {
46858
- throw new Error("Failed to Process Transaction. Please Try Again Later");
46859
- } else {
46860
- for (const ref of refNumber) {
46861
- const unitBillInfo = await collection().findOne({ referenceNumber: ref });
46862
- const billId = unitBillInfo?.billId;
46863
- const billInfo = await billCollection().findOne({ _id: new ObjectId126(billId) });
46864
- const billAmount = billInfo?.price;
46865
- payload.updatedAt = updatedAt;
46866
- payload.amountPaid = billAmount;
46867
- const eachRef = await payUnitBill(ref, payload);
46868
- }
46869
- if (!cartInfo) {
46870
- throw new Error("Cart info not found");
46871
- }
46872
- }
47023
+ payload.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
47024
+ const result = await unitBillingCollection().findOneAndUpdate(
47025
+ { _id: unitBillInfo._id },
47026
+ { $set: payload },
47027
+ { returnDocument: "after" }
47028
+ );
46873
47029
  return result;
46874
47030
  } catch (error) {
46875
47031
  throw new Error(error.message || error || "Server Internal Error");
46876
47032
  }
46877
- };
46878
- const getCheckedOutBillings = async (refId) => {
46879
- try {
46880
- if (refId)
46881
- refId = refId.toString();
46882
- const result = await cartCollection().aggregate([
46883
- { $match: { referenceNumber: refId } },
46884
- {
46885
- $lookup: {
46886
- from: "unit-bill",
46887
- localField: "unitBill",
46888
- foreignField: "referenceNumber",
46889
- as: "unitBill"
46890
- }
46891
- },
46892
- {
46893
- $unwind: "$unitBill"
46894
- },
46895
- {
46896
- $lookup: {
46897
- from: "bill-records",
46898
- localField: "unitBill.billId",
46899
- foreignField: "_id",
46900
- as: "billDetails"
46901
- }
46902
- },
46903
- {
46904
- $unwind: {
46905
- path: "$billDetails",
46906
- preserveNullAndEmptyArrays: true
46907
- }
46908
- },
46909
- {
46910
- $addFields: {
46911
- "unitBill.billItemName": "$billDetails.billItem"
46912
- }
46913
- },
46914
- {
46915
- $project: {
46916
- "unitBill.paidBy": 0,
46917
- "unitBill.preDueDateAlert": 0,
46918
- "unitBill.category": 0,
46919
- "unitBill.contactNumber": 0,
46920
- "unitBill.email": 0,
46921
- "unitBill.site": 0,
46922
- "unitBill.siteName": 0,
46923
- "unitBill.organization": 0,
46924
- "unitBill.billStatus": 0,
46925
- "unitBill.createdBy": 0,
46926
- "unitBill.createdAt": 0,
46927
- "unitBill.updatedAt": 0,
46928
- "billDetails": 0
46929
- // Exclude the full billDetails as it's no longer needed
46930
- }
46931
- },
46932
- {
46933
- $group: {
46934
- _id: "$_id",
46935
- unitId: { $first: "$unitId" },
46936
- referenceNumber: { $first: "$referenceNumber" },
46937
- unitBill: { $push: "$unitBill" },
46938
- paymentStatus: { $first: "$paymentStatus" },
46939
- amountPaid: { $first: "$amountPaid" },
46940
- site: { $first: "$site" },
46941
- organization: { $first: "$organization" },
46942
- paidBy: { $first: "$paidBy" },
46943
- datePaid: { $first: "$referenceNumber" },
46944
- billCategory: { $first: "$billCategory" },
46945
- billFrom: { $first: "$billFrom" },
46946
- billTo: { $first: "$billTo" },
46947
- createdBy: { $first: "$createdBy" },
46948
- createdAt: { $first: "$createdAt" },
46949
- updatedAt: { $first: "$updatedAt" },
46950
- transaction_id: { $first: "$transaction_id" }
46951
- }
46952
- }
46953
- ]).toArray();
46954
- if (!result || result.length === 0) {
46955
- return { success: false, message: "Cart Info Not Found" };
46956
- }
46957
- return result[0];
46958
- } catch (error) {
46959
- throw new Error(error.message || error || "Server Internal Error");
46960
- }
46961
- };
46962
- const cancelCheckedOutBillings = async (refId) => {
46963
- try {
46964
- if (refId)
46965
- refId = refId.toString();
46966
- const result = await cartCollection().findOneAndDelete({ referenceNumber: refId });
46967
- if (!result) {
46968
- return { success: false, message: "Cart Info Not Found" };
46969
- }
46970
- return { success: true, message: "Cart Deleted Successfully!", referenceNumber: result?.referenceNumber };
46971
- } catch (error) {
46972
- throw new Error(error.message || error || "Server Internal Error");
46973
- }
46974
- };
46975
- return {
46976
- saveCreditCardInfo,
46977
- checkOutUnitBills,
46978
- payUnitBill,
46979
- payUnitCart,
46980
- getCheckedOutBillings,
46981
- cancelCheckedOutBillings
46982
- };
46983
- };
46984
-
46985
- // src/repositories/reddot-payment.repository.ts
46986
- import {
46987
- InternalServerError as InternalServerError67,
46988
- useAtlas as useAtlas111
46989
- } from "@7365admin1/node-server-utils";
46990
- var useRedDotPaymentRepo = () => {
46991
- const getDB2 = () => {
46992
- const db = useAtlas111.getDb();
46993
- if (!db) {
46994
- throw new InternalServerError67("Unable to connect to server.");
46995
- }
46996
- return db;
46997
- };
46998
- const collection = () => {
46999
- return getDB2().collection("unit-bill");
47000
- };
47001
- const orgCollection = () => {
47002
- return getDB2().collection("organizations");
47003
- };
47004
- const cartCollection = () => {
47005
- return getDB2().collection("checkout-cart");
47006
- };
47007
- const redDotMerchantCollection = () => {
47008
- return getDB2().collection("reddot-merchant");
47009
- };
47010
- const createRedDotAccount = async (_id, payload) => {
47011
- try {
47012
- const merchant = await redDotMerchantCollection().insertOne(payload);
47013
- if (!merchant) {
47014
- throw new Error("Failed to Add Merchant Details");
47015
- }
47016
- const merchantId = merchant?.insertedId;
47017
- const orgId = new ObjectId127(_id);
47018
- const result = await orgCollection().findOneAndUpdate({ _id: orgId }, { $push: { merchant: merchantId } }, {
47019
- returnDocument: "after"
47020
- });
47021
- if (!result) {
47022
- throw new Error("Organization not found");
47023
- }
47024
- return {
47025
- success: true,
47026
- message: "Merchant Details successfully added."
47027
- };
47028
- } catch (error) {
47029
- throw new Error(error.message || error || "Server Internal Error");
47030
- }
47031
- };
47032
- const payUnitBillings = async (refId, payload) => {
47033
- const checkCart = await cartCollection().findOne({ referenceNumber: refId });
47034
- if (checkCart) {
47035
- const multiple = await PaymentBillRepo().payUnitCart(refId, payload);
47036
- if (multiple) {
47037
- return await PaymentBillRepo().getCheckedOutBillings(refId);
47038
- }
47039
- }
47040
- const single = await PaymentBillRepo().payUnitBill(refId, payload);
47041
- return single;
47042
- };
47043
- const getMerchantDetailsById = async (_id) => {
47044
- try {
47045
- if (_id)
47046
- _id = new ObjectId127(_id);
47047
- const result = await redDotMerchantCollection().aggregate([
47048
- {
47049
- $match: {
47050
- _id
47051
- }
47052
- },
47053
- {
47054
- $facet: {
47055
- totalCount: [{ $count: "count" }],
47056
- items: [{ $sort: { _id: -1 } }]
47057
- }
47058
- }
47059
- ]).toArray();
47060
- const items = result[0].items;
47061
- return items;
47062
- } catch (error) {
47063
- throw new Error(error.message || error || "Server Internal Error");
47064
- }
47065
- };
47066
- return {
47067
- createRedDotAccount,
47068
- payUnitBillings,
47069
- getMerchantDetailsById
47070
- };
47033
+ }
47034
+ return { paySingleUnitBill };
47071
47035
  };
47072
47036
 
47073
47037
  // src/services/reddot-payment.service.ts
47074
47038
  var useRedDotPaymentSvc = () => {
47075
- const createRedDotAccount = async (_id, payload) => {
47076
- return useRedDotPaymentRepo().createRedDotAccount(_id, payload);
47077
- };
47039
+ const { paySingleUnitBill } = useRedDotPaymentRepo();
47078
47040
  const redirectPaymentTransaction = async (payload) => {
47079
47041
  try {
47080
47042
  const SECRET_KEY2 = payload.merchant_key;
47081
47043
  if (!payload.mid && !payload.merchant_key) {
47082
- return { success: false, message: "RDP Not Available on this account. Please Contact Management" };
47044
+ return {
47045
+ success: false,
47046
+ message: "RDP Not Available on this account. Please Contact Management"
47047
+ };
47083
47048
  }
47084
47049
  const data = {
47085
47050
  mid: payload.mid,
@@ -47102,7 +47067,9 @@ var useRedDotPaymentSvc = () => {
47102
47067
  "Content-Length": String(dataString.length)
47103
47068
  };
47104
47069
  if (!process.env.MERCHANT_PAYMENT) {
47105
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
47070
+ throw new Error(
47071
+ "MERCHANT_PAYMENT environment variable is not defined."
47072
+ );
47106
47073
  }
47107
47074
  const url = process.env.MERCHANT_PAYMENT;
47108
47075
  const response = await axios3.post(url, dataString, { headers });
@@ -47116,7 +47083,10 @@ var useRedDotPaymentSvc = () => {
47116
47083
  try {
47117
47084
  const SECRET_KEY2 = payload.merchant_key;
47118
47085
  if (!payload.request_mid && !payload.merchant_key) {
47119
- return { success: false, message: "RDP Not Available on this account. Please Contact Management" };
47086
+ return {
47087
+ success: false,
47088
+ message: "RDP Not Available on this account. Please Contact Management"
47089
+ };
47120
47090
  }
47121
47091
  const data = {
47122
47092
  request_mid: payload.request_mid,
@@ -47131,7 +47101,9 @@ var useRedDotPaymentSvc = () => {
47131
47101
  "Content-Type": "application/json"
47132
47102
  };
47133
47103
  if (!process.env.MERCHANT_ENQUIRY) {
47134
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
47104
+ throw new Error(
47105
+ "MERCHANT_PAYMENT environment variable is not defined."
47106
+ );
47135
47107
  }
47136
47108
  const url = process.env.MERCHANT_ENQUIRY;
47137
47109
  const response = await axios3.post(url, dataString, { headers });
@@ -47145,25 +47117,24 @@ var useRedDotPaymentSvc = () => {
47145
47117
  if (result.response_code === "0") {
47146
47118
  const success = {
47147
47119
  method: payload.method,
47148
- paymentStatus: "Paid" /* paid */,
47149
- amountPaid: amount,
47150
- paidBy: payer,
47120
+ paymentStatus: "paid" /* PAID */,
47121
+ amountPaid: parseInt(amount),
47151
47122
  updatedAt: invoiceDate,
47152
47123
  transaction_id: transactionId,
47153
47124
  message
47154
47125
  };
47155
- await useRedDotPaymentRepo().payUnitBillings(refId, success);
47126
+ await paySingleUnitBill(refId, success);
47156
47127
  } else if (result.response_code !== "0") {
47157
47128
  const fail = {
47158
47129
  method: payload.method,
47159
- paymentStatus: "Failed" /* failed */,
47130
+ paymentStatus: "failed" /* FAILED */,
47160
47131
  updatedAt: invoiceDate,
47161
47132
  paidBy: "",
47162
- amountPaid: "0",
47133
+ amountPaid: 0,
47163
47134
  transaction_id: transactionId,
47164
47135
  message
47165
47136
  };
47166
- await useRedDotPaymentRepo().payUnitBillings(refId, fail);
47137
+ await paySingleUnitBill(refId, fail);
47167
47138
  }
47168
47139
  return result;
47169
47140
  } catch (error) {
@@ -47183,7 +47154,9 @@ var useRedDotPaymentSvc = () => {
47183
47154
  "Content-Length": String(dataString.length)
47184
47155
  };
47185
47156
  if (!process.env.MERCHANT_PAYMENT) {
47186
- throw new Error("MERCHANT_PAYMENT environment variable is not defined.");
47157
+ throw new Error(
47158
+ "MERCHANT_PAYMENT environment variable is not defined."
47159
+ );
47187
47160
  }
47188
47161
  const url = process.env.MERCHANT_PAYMENT;
47189
47162
  const response = await axios3.post(url, dataString, { headers });
@@ -47192,45 +47165,16 @@ var useRedDotPaymentSvc = () => {
47192
47165
  return Promise.reject(error || error.message || "Server Internal Error!");
47193
47166
  }
47194
47167
  };
47195
- const getMerchantDetailsById = async (_id) => {
47196
- return useRedDotPaymentRepo().getMerchantDetailsById(_id);
47197
- };
47198
47168
  return {
47199
- createRedDotAccount,
47200
47169
  redirectPaymentTransaction,
47201
47170
  enquirePaymentTransaction,
47202
- payInvoice,
47203
- getMerchantDetailsById
47171
+ payInvoice
47204
47172
  };
47205
47173
  };
47206
47174
 
47207
47175
  // src/controllers/reddot-payment.controller.ts
47208
47176
  import Joi124 from "joi";
47209
47177
  function useRedDotPaymentController() {
47210
- const createRedDotAccount = async (req, res) => {
47211
- try {
47212
- const data = req.body;
47213
- const id = req.params.id;
47214
- const schema2 = Joi124.object({
47215
- id: Joi124.string().hex().required(),
47216
- // organization id
47217
- paymentMethod: Joi124.string().required(),
47218
- // payment method (e.g. "Visa / Mastercard / PayNow QR Code")
47219
- merchant_id: Joi124.string().required(),
47220
- // merchant id
47221
- merchant_key: Joi124.string().required()
47222
- // secret key
47223
- });
47224
- const { error } = schema2.validate({ id, ...data });
47225
- if (error) {
47226
- return res.status(400).json({ data: null, message: error.message });
47227
- }
47228
- const result = await useRedDotPaymentSvc().createRedDotAccount(id, data);
47229
- return res.json(result);
47230
- } catch (error) {
47231
- return res.status(500).json({ message: error.message || error });
47232
- }
47233
- };
47234
47178
  const redirectPaymentTransaction = async (req, res) => {
47235
47179
  try {
47236
47180
  const data = req.body;
@@ -47247,7 +47191,9 @@ function useRedDotPaymentController() {
47247
47191
  if (error) {
47248
47192
  return res.status(400).json({ data: null, message: error.message });
47249
47193
  }
47250
- const result = await useRedDotPaymentSvc().redirectPaymentTransaction(data);
47194
+ const result = await useRedDotPaymentSvc().redirectPaymentTransaction(
47195
+ data
47196
+ );
47251
47197
  return res.json(result);
47252
47198
  } catch (error) {
47253
47199
  return res.status(500).json({ message: error.message || error });
@@ -47266,52 +47212,36 @@ function useRedDotPaymentController() {
47266
47212
  if (error) {
47267
47213
  return res.status(400).json({ data: null, message: error.message });
47268
47214
  }
47269
- const result = await useRedDotPaymentSvc().enquirePaymentTransaction(data);
47215
+ const result = await useRedDotPaymentSvc().enquirePaymentTransaction(
47216
+ data
47217
+ );
47270
47218
  return res.json(result);
47271
47219
  } catch (error) {
47272
47220
  return res.status(500).json({ message: error.message || error });
47273
47221
  }
47274
47222
  };
47275
- const getMerchantDetailsById = async (req, res, next) => {
47276
- try {
47277
- const _id = req.params.id;
47278
- const schema2 = Joi124.object({
47279
- _id: Joi124.string().hex().required()
47280
- });
47281
- const { error } = schema2.validate({ _id });
47282
- if (error) {
47283
- return res.status(400).json({ data: null, message: error.message });
47284
- }
47285
- const result = await useRedDotPaymentSvc().getMerchantDetailsById(_id);
47286
- return res.json(result);
47287
- } catch (error) {
47288
- next(error);
47289
- }
47290
- };
47291
47223
  return {
47292
- createRedDotAccount,
47293
47224
  redirectPaymentTransaction,
47294
- enquirePaymentTransaction,
47295
- getMerchantDetailsById
47225
+ enquirePaymentTransaction
47296
47226
  };
47297
47227
  }
47298
47228
 
47299
47229
  // src/repositories/verification-v2.repo.ts
47300
47230
  import {
47301
47231
  BadRequestError as BadRequestError195,
47302
- InternalServerError as InternalServerError68,
47232
+ InternalServerError as InternalServerError67,
47303
47233
  logger as logger175,
47304
47234
  makeCacheKey as makeCacheKey64,
47305
47235
  paginate as paginate57,
47306
47236
  toObjectId as toObjectId18,
47307
- useAtlas as useAtlas112,
47237
+ useAtlas as useAtlas111,
47308
47238
  useCache as useCache66
47309
47239
  } from "@7365admin1/node-server-utils";
47310
- import { ObjectId as ObjectId128 } from "mongodb";
47240
+ import { ObjectId as ObjectId124 } from "mongodb";
47311
47241
  function useVerificationRepoV2() {
47312
- const db = useAtlas112.getDb();
47242
+ const db = useAtlas111.getDb();
47313
47243
  if (!db) {
47314
- throw new InternalServerError68("Unable to connect to server.");
47244
+ throw new InternalServerError67("Unable to connect to server.");
47315
47245
  }
47316
47246
  const namespace_collection = "verifications";
47317
47247
  const collection = db.collection(namespace_collection);
@@ -47324,7 +47254,7 @@ function useVerificationRepoV2() {
47324
47254
  { "metadata.org": 1 }
47325
47255
  ]);
47326
47256
  } catch (error) {
47327
- throw new InternalServerError68("Failed to create index.");
47257
+ throw new InternalServerError67("Failed to create index.");
47328
47258
  }
47329
47259
  }
47330
47260
  async function createTextIndex() {
@@ -47333,7 +47263,7 @@ function useVerificationRepoV2() {
47333
47263
  email: "text"
47334
47264
  });
47335
47265
  } catch (error) {
47336
- throw new InternalServerError68("Failed to create text index on email.");
47266
+ throw new InternalServerError67("Failed to create text index on email.");
47337
47267
  }
47338
47268
  }
47339
47269
  const { delNamespace, setCache, getCache, delCache } = useCache66(namespace_collection);
@@ -47355,12 +47285,12 @@ function useVerificationRepoV2() {
47355
47285
  level: "info",
47356
47286
  message: String(error)
47357
47287
  });
47358
- throw new InternalServerError68("Server internal error.");
47288
+ throw new InternalServerError67("Server internal error.");
47359
47289
  }
47360
47290
  }
47361
47291
  async function updateVerificationStatusById(_id, status, session) {
47362
47292
  try {
47363
- _id = new ObjectId128(_id);
47293
+ _id = new ObjectId124(_id);
47364
47294
  } catch (error) {
47365
47295
  throw new BadRequestError195("Invalid verification ID format.");
47366
47296
  }
@@ -47380,7 +47310,7 @@ function useVerificationRepoV2() {
47380
47310
  });
47381
47311
  return result;
47382
47312
  } catch (error) {
47383
- throw new InternalServerError68("Error updating verification status.");
47313
+ throw new InternalServerError67("Error updating verification status.");
47384
47314
  }
47385
47315
  }
47386
47316
  async function getByVerificationCode(verificationCode) {
@@ -47403,7 +47333,7 @@ function useVerificationRepoV2() {
47403
47333
  });
47404
47334
  return data;
47405
47335
  } catch (error) {
47406
- throw new InternalServerError68(
47336
+ throw new InternalServerError67(
47407
47337
  "Internal server error, failed to retrieve verification."
47408
47338
  );
47409
47339
  }
@@ -47425,7 +47355,7 @@ function useVerificationRepoV2() {
47425
47355
  });
47426
47356
  return data;
47427
47357
  } catch (error) {
47428
- throw new InternalServerError68(
47358
+ throw new InternalServerError67(
47429
47359
  "Internal server error, failed to retrieve verification."
47430
47360
  );
47431
47361
  }
@@ -47503,7 +47433,7 @@ function useVerificationRepoV2() {
47503
47433
  }
47504
47434
  async function updateStatusById(_id, status, session) {
47505
47435
  try {
47506
- _id = new ObjectId128(_id);
47436
+ _id = new ObjectId124(_id);
47507
47437
  } catch (error) {
47508
47438
  throw new BadRequestError195("Invalid verification ID format.");
47509
47439
  }
@@ -47529,7 +47459,7 @@ function useVerificationRepoV2() {
47529
47459
  });
47530
47460
  return result;
47531
47461
  } catch (error) {
47532
- throw new InternalServerError68("Error updating verification status.");
47462
+ throw new InternalServerError67("Error updating verification status.");
47533
47463
  }
47534
47464
  }
47535
47465
  return {
@@ -47552,8 +47482,8 @@ import {
47552
47482
  getDirectory as getDirectory4,
47553
47483
  BadRequestError as BadRequestError196,
47554
47484
  NotFoundError as NotFoundError51,
47555
- InternalServerError as InternalServerError69,
47556
- useAtlas as useAtlas113,
47485
+ InternalServerError as InternalServerError68,
47486
+ useAtlas as useAtlas112,
47557
47487
  hashPassword as hashPassword4
47558
47488
  } from "@7365admin1/node-server-utils";
47559
47489
  import crypto4 from "crypto";
@@ -47620,7 +47550,7 @@ function useVerificationServiceV2() {
47620
47550
  email,
47621
47551
  metadata
47622
47552
  }) {
47623
- const session = useAtlas113.getClient()?.startSession();
47553
+ const session = useAtlas112.getClient()?.startSession();
47624
47554
  try {
47625
47555
  session?.startTransaction();
47626
47556
  const user = await _getUserByEmailStatus(email);
@@ -47672,7 +47602,7 @@ function useVerificationServiceV2() {
47672
47602
  }
47673
47603
  }
47674
47604
  async function verify(verificationCode) {
47675
- const session = useAtlas113.getClient()?.startSession();
47605
+ const session = useAtlas112.getClient()?.startSession();
47676
47606
  try {
47677
47607
  session?.startTransaction();
47678
47608
  const item = await _getByVerificationCode(verificationCode);
@@ -47873,14 +47803,14 @@ function useVerificationServiceV2() {
47873
47803
  });
47874
47804
  return "Successfully created a link to reset password. Please check your email.";
47875
47805
  } catch (error) {
47876
- throw new InternalServerError69("Failed to create forget password link.");
47806
+ throw new InternalServerError68("Failed to create forget password link.");
47877
47807
  }
47878
47808
  }
47879
47809
  async function cancelUserInvitation(id) {
47880
47810
  try {
47881
47811
  await _updateStatusById(id, "cancelled");
47882
47812
  } catch (error) {
47883
- throw new InternalServerError69(
47813
+ throw new InternalServerError68(
47884
47814
  `Error cancelling user invitation: ${error}`
47885
47815
  );
47886
47816
  }
@@ -48098,17 +48028,17 @@ import { BadRequestError as BadRequestError201, logger as logger180 } from "@736
48098
48028
  import {
48099
48029
  BadRequestError as BadRequestError199,
48100
48030
  comparePassword as comparePassword3,
48101
- InternalServerError as InternalServerError71,
48031
+ InternalServerError as InternalServerError70,
48102
48032
  NotFoundError as NotFoundError53,
48103
48033
  useCache as useCache68
48104
48034
  } from "@7365admin1/node-server-utils";
48105
48035
  import { v4 as uuidv42 } from "uuid";
48106
48036
 
48107
48037
  // src/repositories/user-v2.repo.ts
48108
- import { ObjectId as ObjectId129 } from "mongodb";
48038
+ import { ObjectId as ObjectId125 } from "mongodb";
48109
48039
  import {
48110
- useAtlas as useAtlas114,
48111
- InternalServerError as InternalServerError70,
48040
+ useAtlas as useAtlas113,
48041
+ InternalServerError as InternalServerError69,
48112
48042
  logger as logger178,
48113
48043
  BadRequestError as BadRequestError198,
48114
48044
  paginate as paginate58,
@@ -48122,9 +48052,9 @@ function useUserRepoV2() {
48122
48052
  const { updateFeedbackCreatedByName } = useFeedbackRepo();
48123
48053
  const { updateWorkOrderCreatedByName } = useWorkOrderRepo();
48124
48054
  const { updateUserNameBySignatureId } = useOccurrenceEntryRepo();
48125
- const db = useAtlas114.getDb();
48055
+ const db = useAtlas113.getDb();
48126
48056
  if (!db) {
48127
- throw new InternalServerError70("Unable to connect to server.");
48057
+ throw new InternalServerError69("Unable to connect to server.");
48128
48058
  }
48129
48059
  const namespace_collection = "users";
48130
48060
  const collection = db.collection(namespace_collection);
@@ -48133,14 +48063,14 @@ function useUserRepoV2() {
48133
48063
  try {
48134
48064
  await collection.createIndexes([{ key: { email: 1 } }]);
48135
48065
  } catch (error) {
48136
- throw new InternalServerError70("Failed to create text index on user.");
48066
+ throw new InternalServerError69("Failed to create text index on user.");
48137
48067
  }
48138
48068
  }
48139
48069
  async function createTextIndex() {
48140
48070
  try {
48141
48071
  await collection.createIndex({ name: "text", email: "text" });
48142
48072
  } catch (error) {
48143
- throw new InternalServerError70("Failed to create text index on user.");
48073
+ throw new InternalServerError69("Failed to create text index on user.");
48144
48074
  }
48145
48075
  }
48146
48076
  async function createUniqueIndex() {
@@ -48150,7 +48080,7 @@ function useUserRepoV2() {
48150
48080
  { unique: true }
48151
48081
  );
48152
48082
  } catch (error) {
48153
- throw new InternalServerError70("Failed to create unique index on user.");
48083
+ throw new InternalServerError69("Failed to create unique index on user.");
48154
48084
  }
48155
48085
  }
48156
48086
  async function createUser(value, session) {
@@ -48190,7 +48120,7 @@ function useUserRepoV2() {
48190
48120
  );
48191
48121
  return data;
48192
48122
  } catch (error) {
48193
- throw new InternalServerError70("Failed to get user by email.");
48123
+ throw new InternalServerError69("Failed to get user by email.");
48194
48124
  }
48195
48125
  }
48196
48126
  async function getUserByEmailStatus(email) {
@@ -48213,7 +48143,7 @@ function useUserRepoV2() {
48213
48143
  );
48214
48144
  return data;
48215
48145
  } catch (error) {
48216
- throw new InternalServerError70("Failed to get user by email.");
48146
+ throw new InternalServerError69("Failed to get user by email.");
48217
48147
  }
48218
48148
  }
48219
48149
  async function getUserById(id) {
@@ -48253,7 +48183,7 @@ function useUserRepoV2() {
48253
48183
  } catch (error) {
48254
48184
  if (error instanceof AppError27)
48255
48185
  throw error;
48256
- throw new InternalServerError70("Failed to get user by id.");
48186
+ throw new InternalServerError69("Failed to get user by id.");
48257
48187
  }
48258
48188
  }
48259
48189
  async function getUserByReferralCode(referralCode) {
@@ -48270,7 +48200,7 @@ function useUserRepoV2() {
48270
48200
  );
48271
48201
  return data;
48272
48202
  } catch (error) {
48273
- throw new InternalServerError70("Failed to get user by referral code.");
48203
+ throw new InternalServerError69("Failed to get user by referral code.");
48274
48204
  }
48275
48205
  }
48276
48206
  async function getByEmailApp(email, app) {
@@ -48290,7 +48220,7 @@ function useUserRepoV2() {
48290
48220
  );
48291
48221
  return data;
48292
48222
  } catch (error) {
48293
- throw new InternalServerError70("Failed to get user by email and app.");
48223
+ throw new InternalServerError69("Failed to get user by email and app.");
48294
48224
  }
48295
48225
  }
48296
48226
  async function getUsersByOrgId({
@@ -48317,7 +48247,7 @@ function useUserRepoV2() {
48317
48247
  }
48318
48248
  if (organization) {
48319
48249
  try {
48320
- query.defaultOrg = new ObjectId129(organization);
48250
+ query.defaultOrg = new ObjectId125(organization);
48321
48251
  cacheOptions.organization = organization.toString();
48322
48252
  } catch (error) {
48323
48253
  throw new BadRequestError198("Invalid organization ID format.");
@@ -48436,7 +48366,7 @@ function useUserRepoV2() {
48436
48366
  });
48437
48367
  return result;
48438
48368
  } catch (error) {
48439
- throw new InternalServerError70("Failed to update user password.");
48369
+ throw new InternalServerError69("Failed to update user password.");
48440
48370
  }
48441
48371
  }
48442
48372
  async function updateUserFieldById({ _id, field, value } = {}, session) {
@@ -48456,13 +48386,13 @@ function useUserRepoV2() {
48456
48386
  );
48457
48387
  }
48458
48388
  try {
48459
- _id = new ObjectId129(_id);
48389
+ _id = new ObjectId125(_id);
48460
48390
  } catch (error) {
48461
48391
  throw new BadRequestError198("Invalid ID.");
48462
48392
  }
48463
48393
  if (field === "defaultOrg") {
48464
48394
  try {
48465
- value = new ObjectId129(value);
48395
+ value = new ObjectId125(value);
48466
48396
  } catch (error) {
48467
48397
  throw new BadRequestError198("Invalid organization ID.");
48468
48398
  }
@@ -48493,7 +48423,7 @@ function useUserRepoV2() {
48493
48423
  });
48494
48424
  return `Successfully updated user ${field}.`;
48495
48425
  } catch (error) {
48496
- throw new InternalServerError70(`Failed to update user ${field}.`);
48426
+ throw new InternalServerError69(`Failed to update user ${field}.`);
48497
48427
  }
48498
48428
  }
48499
48429
  async function updateBirthday({
@@ -48503,7 +48433,7 @@ function useUserRepoV2() {
48503
48433
  year
48504
48434
  }, session) {
48505
48435
  try {
48506
- _id = new ObjectId129(_id);
48436
+ _id = new ObjectId125(_id);
48507
48437
  } catch (error) {
48508
48438
  throw new BadRequestError198("Invalid user ID format.");
48509
48439
  }
@@ -48528,12 +48458,12 @@ function useUserRepoV2() {
48528
48458
  });
48529
48459
  return "Successfully updated user birthday.";
48530
48460
  } catch (error) {
48531
- throw new InternalServerError70("Failed to update user birthday.");
48461
+ throw new InternalServerError69("Failed to update user birthday.");
48532
48462
  }
48533
48463
  }
48534
48464
  async function updatePassword({ _id, password }, session) {
48535
48465
  try {
48536
- _id = new ObjectId129(_id);
48466
+ _id = new ObjectId125(_id);
48537
48467
  } catch (error) {
48538
48468
  throw new BadRequestError198("Invalid user ID format.");
48539
48469
  }
@@ -48551,7 +48481,7 @@ function useUserRepoV2() {
48551
48481
  });
48552
48482
  return result;
48553
48483
  } catch (error) {
48554
- throw new InternalServerError70("Failed to update user password.");
48484
+ throw new InternalServerError69("Failed to update user password.");
48555
48485
  }
48556
48486
  }
48557
48487
  return {
@@ -48591,7 +48521,7 @@ function useAuthServiceV2() {
48591
48521
  );
48592
48522
  }
48593
48523
  if (!user._id) {
48594
- throw new InternalServerError71("Valid user ID.");
48524
+ throw new InternalServerError70("Valid user ID.");
48595
48525
  }
48596
48526
  if (user.status === "suspended") {
48597
48527
  throw new BadRequestError199(
@@ -48625,7 +48555,7 @@ function useAuthServiceV2() {
48625
48555
  await delCache(`sid:${sid}`);
48626
48556
  return "Session deleted successfully";
48627
48557
  } catch (error) {
48628
- throw new InternalServerError71("Error deleting token");
48558
+ throw new InternalServerError70("Error deleting token");
48629
48559
  }
48630
48560
  }
48631
48561
  async function verifyPassword(_id, password) {
@@ -48640,7 +48570,7 @@ function useAuthServiceV2() {
48640
48570
  if (error instanceof BadRequestError199) {
48641
48571
  throw error;
48642
48572
  }
48643
- throw new InternalServerError71("Error during password verification");
48573
+ throw new InternalServerError70("Error during password verification");
48644
48574
  }
48645
48575
  }
48646
48576
  return {
@@ -48655,9 +48585,9 @@ import {
48655
48585
  BadRequestError as BadRequestError200,
48656
48586
  comparePassword as comparePassword4,
48657
48587
  hashPassword as hashPassword5,
48658
- InternalServerError as InternalServerError72,
48588
+ InternalServerError as InternalServerError71,
48659
48589
  NotFoundError as NotFoundError54,
48660
- useAtlas as useAtlas115,
48590
+ useAtlas as useAtlas114,
48661
48591
  useS3 as useS33
48662
48592
  } from "@7365admin1/node-server-utils";
48663
48593
  import "multer";
@@ -48684,7 +48614,7 @@ function useUserServiceV2() {
48684
48614
  id = "",
48685
48615
  name = ""
48686
48616
  }) {
48687
- const session = useAtlas115.getClient()?.startSession();
48617
+ const session = useAtlas114.getClient()?.startSession();
48688
48618
  session?.startTransaction();
48689
48619
  try {
48690
48620
  const signUp = await _getVerificationById(id);
@@ -48750,12 +48680,12 @@ function useUserServiceV2() {
48750
48680
  throw new BadRequestError200("Passwords do not match.");
48751
48681
  }
48752
48682
  let hashedPassword;
48753
- const session = useAtlas115.getClient()?.startSession();
48683
+ const session = useAtlas114.getClient()?.startSession();
48754
48684
  session?.startTransaction();
48755
48685
  try {
48756
48686
  hashedPassword = await hashPassword5(newPassword);
48757
48687
  } catch (error) {
48758
- throw new InternalServerError72(`Error hashing password: ${error}`);
48688
+ throw new InternalServerError71(`Error hashing password: ${error}`);
48759
48689
  }
48760
48690
  try {
48761
48691
  const otpDoc = await _getVerificationById(id);
@@ -48770,7 +48700,7 @@ function useUserServiceV2() {
48770
48700
  throw new NotFoundError54("User not found.");
48771
48701
  }
48772
48702
  if (!user._id) {
48773
- throw new InternalServerError72("Invalid user ID.");
48703
+ throw new InternalServerError71("Invalid user ID.");
48774
48704
  }
48775
48705
  await Promise.all([
48776
48706
  _updateVerificationStatusById(id, "complete" /* COMPLETE */, session),
@@ -48801,7 +48731,7 @@ function useUserServiceV2() {
48801
48731
  user,
48802
48732
  previousProfile
48803
48733
  }) {
48804
- const session = useAtlas115.getClient()?.startSession();
48734
+ const session = useAtlas114.getClient()?.startSession();
48805
48735
  session?.startTransaction();
48806
48736
  const _file = {
48807
48737
  name: file.originalname,
@@ -48845,7 +48775,7 @@ function useUserServiceV2() {
48845
48775
  try {
48846
48776
  hashedPassword = await hashPassword5(newPassword);
48847
48777
  if (!hashedPassword)
48848
- throw new InternalServerError72("Error hashing password.");
48778
+ throw new InternalServerError71("Error hashing password.");
48849
48779
  return await updatePassword({ _id: id, password: hashedPassword });
48850
48780
  } catch (error) {
48851
48781
  throw error;
@@ -49288,6 +49218,178 @@ function useUserControllerV2() {
49288
49218
  updatePasswordById
49289
49219
  };
49290
49220
  }
49221
+
49222
+ // src/models/role-v2.model.ts
49223
+ import { BadRequestError as BadRequestError203 } from "@7365admin1/node-server-utils";
49224
+ import { ObjectId as ObjectId126 } from "mongodb";
49225
+ var MRoleV2 = class {
49226
+ constructor(value) {
49227
+ if (typeof value._id === "string") {
49228
+ try {
49229
+ value._id = new ObjectId126(value._id);
49230
+ } catch (error) {
49231
+ throw new BadRequestError203("Invalid role-v2 ID format.");
49232
+ }
49233
+ }
49234
+ if (typeof value.site === "string" && value.site.length === 24) {
49235
+ try {
49236
+ value.site = new ObjectId126(value.site);
49237
+ } catch (error) {
49238
+ throw new BadRequestError203("Invalid site ID format.");
49239
+ }
49240
+ }
49241
+ if (typeof value.org === "string" && value.org.length === 24) {
49242
+ try {
49243
+ value.org = new ObjectId126(value.org);
49244
+ } catch (error) {
49245
+ throw new BadRequestError203("Invalid org ID format.");
49246
+ }
49247
+ }
49248
+ if (value.createdBy) {
49249
+ try {
49250
+ value.createdBy = new ObjectId126(value.createdBy);
49251
+ } catch (error) {
49252
+ throw new BadRequestError203("Invalid created by ID format.");
49253
+ }
49254
+ }
49255
+ this._id = value._id ?? new ObjectId126();
49256
+ this.name = value.name ?? "";
49257
+ this.permissions = value.permissions ?? [];
49258
+ this.site = value.site ?? "";
49259
+ this.platform = value.platform ?? "";
49260
+ this.type = value.type ?? "account";
49261
+ this.org = value.org ?? "";
49262
+ this.status = value.status ?? "active";
49263
+ this.createdBy = value.createdBy ?? "";
49264
+ this.createdAt = value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
49265
+ this.updatedAt = value.updatedAt ?? "";
49266
+ this.deletedAt = value.deletedAt ?? "";
49267
+ }
49268
+ };
49269
+
49270
+ // src/repositories/role-v2.repo.ts
49271
+ import {
49272
+ BadRequestError as BadRequestError204,
49273
+ InternalServerError as InternalServerError72,
49274
+ useAtlas as useAtlas115,
49275
+ logger as logger182,
49276
+ useCache as useCache69
49277
+ } from "@7365admin1/node-server-utils";
49278
+ function useRoleRepoV2() {
49279
+ const db = useAtlas115.getDb();
49280
+ if (!db) {
49281
+ throw new InternalServerError72("Unable to connect to server.");
49282
+ }
49283
+ const namespace_collection = "roles.v2";
49284
+ const collection = db.collection(namespace_collection);
49285
+ async function createIndex() {
49286
+ try {
49287
+ await collection.createIndexes([
49288
+ { key: { name: 1 } },
49289
+ { key: { type: 1 } },
49290
+ { key: { status: 1 } }
49291
+ ]);
49292
+ } catch (error) {
49293
+ throw new InternalServerError72("Failed to create index on role.");
49294
+ }
49295
+ }
49296
+ async function createTextIndex() {
49297
+ try {
49298
+ await collection.createIndex({ name: "text" });
49299
+ } catch (error) {
49300
+ throw new InternalServerError72("Failed to create text index on role.");
49301
+ }
49302
+ }
49303
+ async function createUniqueIndex() {
49304
+ try {
49305
+ await collection.createIndex(
49306
+ { name: 1, site: 1, platform: 1, type: 1, org: 1, deletedAt: 1 },
49307
+ { unique: true }
49308
+ );
49309
+ } catch (error) {
49310
+ throw new InternalServerError72("Failed to create unique index on role.");
49311
+ }
49312
+ }
49313
+ const { delNamespace } = useCache69(namespace_collection);
49314
+ async function addRole(value, session) {
49315
+ value = new MRoleV2(value);
49316
+ try {
49317
+ const res = await collection.insertOne(value, { session });
49318
+ delNamespace().then(() => {
49319
+ logger182.info(`Cache cleared for namespace: ${namespace_collection}`);
49320
+ }).catch((err) => {
49321
+ logger182.error(
49322
+ `Failed to clear cache for namespace: ${namespace_collection}`,
49323
+ err
49324
+ );
49325
+ });
49326
+ return res.insertedId;
49327
+ } catch (error) {
49328
+ logger182.log({ level: "error", message: `${error}` });
49329
+ const isDuplicated = error.message.includes("duplicate");
49330
+ if (isDuplicated) {
49331
+ throw new BadRequestError204("Role already exists.");
49332
+ }
49333
+ throw new InternalServerError72("Failed to create role.");
49334
+ }
49335
+ }
49336
+ return {
49337
+ createIndex,
49338
+ createTextIndex,
49339
+ createUniqueIndex,
49340
+ addRole
49341
+ };
49342
+ }
49343
+
49344
+ // src/services/role-v2.service.ts
49345
+ function useRoleServiceV2() {
49346
+ const { addRole: _addRole } = useRoleRepoV2();
49347
+ async function createRole(value) {
49348
+ try {
49349
+ return await _addRole(value);
49350
+ } catch (error) {
49351
+ throw error;
49352
+ }
49353
+ }
49354
+ return { createRole };
49355
+ }
49356
+
49357
+ // src/controllers/role-v2.controller.ts
49358
+ import Joi129 from "joi";
49359
+ import { BadRequestError as BadRequestError205, logger as logger183 } from "@7365admin1/node-server-utils";
49360
+ function useRoleControllerV2() {
49361
+ const { createRole: _createRole } = useRoleServiceV2();
49362
+ async function createRole(req, res, next) {
49363
+ const validation = Joi129.object({
49364
+ name: Joi129.string().required(),
49365
+ site: Joi129.string().hex().required(),
49366
+ platform: Joi129.string().required(),
49367
+ permissions: Joi129.array().items(Joi129.string()).required(),
49368
+ type: Joi129.string().optional().allow("", null),
49369
+ org: Joi129.string().hex().optional().allow("", null)
49370
+ });
49371
+ const payload = { ...req.body };
49372
+ const { error, value } = validation.validate(payload, { abortEarly: false });
49373
+ if (error) {
49374
+ const message = error.details.map((item) => item.message).join(", ");
49375
+ logger183.log({ level: "error", message });
49376
+ next(new BadRequestError205(message));
49377
+ return;
49378
+ }
49379
+ try {
49380
+ const role = await _createRole(value);
49381
+ res.status(201).json({ message: "Successfully created role.", data: { role } });
49382
+ return;
49383
+ } catch (error2) {
49384
+ logger183.log({ level: "error", message: error2.message });
49385
+ next(error2);
49386
+ return;
49387
+ }
49388
+ }
49389
+ return {
49390
+ createRole
49391
+ };
49392
+ }
49291
49393
  export {
49292
49394
  ANPRMode,
49293
49395
  AccessTypeProps,
@@ -49351,6 +49453,7 @@ export {
49351
49453
  MPromoCode,
49352
49454
  MRobot,
49353
49455
  MRole,
49456
+ MRoleV2,
49354
49457
  MServiceProvider,
49355
49458
  MServiceProviderBilling,
49356
49459
  MSession,
@@ -49373,6 +49476,7 @@ export {
49373
49476
  OvernightParkingRequestStatus,
49374
49477
  PERSON_TYPES,
49375
49478
  PMDashboardCollection,
49479
+ PStatus,
49376
49480
  Period,
49377
49481
  PersonStatus,
49378
49482
  PersonTypes,
@@ -49380,6 +49484,7 @@ export {
49380
49484
  SiteStatus,
49381
49485
  SortFields,
49382
49486
  SortOrder,
49487
+ Status,
49383
49488
  SubscriptionType,
49384
49489
  UseAccessManagementRepo,
49385
49490
  UserStatus,
@@ -49634,7 +49739,10 @@ export {
49634
49739
  useRobotRepo,
49635
49740
  useRobotService,
49636
49741
  useRoleController,
49742
+ useRoleControllerV2,
49637
49743
  useRoleRepo,
49744
+ useRoleRepoV2,
49745
+ useRoleServiceV2,
49638
49746
  useServiceProviderBillingController,
49639
49747
  useServiceProviderBillingRepo,
49640
49748
  useServiceProviderBillingService,