@7365admin1/core 2.40.0 → 2.41.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
@@ -12757,10 +12757,10 @@ function useCustomerController() {
12757
12757
 
12758
12758
  // src/services/site.service.ts
12759
12759
  import {
12760
- AppError as AppError11,
12761
- BadRequestError as BadRequestError73,
12762
- logger as logger54,
12763
- useAtlas as useAtlas35
12760
+ AppError as AppError12,
12761
+ BadRequestError as BadRequestError75,
12762
+ logger as logger56,
12763
+ useAtlas as useAtlas36
12764
12764
  } from "@7365admin1/node-server-utils";
12765
12765
 
12766
12766
  // src/repositories/site-camera.repo.ts
@@ -13225,7 +13225,7 @@ function useSiteCameraRepo() {
13225
13225
  }
13226
13226
 
13227
13227
  // src/services/site.service.ts
13228
- import Joi40 from "joi";
13228
+ import Joi41 from "joi";
13229
13229
 
13230
13230
  // src/repositories/visitor-transaction.repo.ts
13231
13231
  import {
@@ -13714,7 +13714,9 @@ function useVisitorTransactionRepo() {
13714
13714
  ...ObjectId41.isValid(org) && { org: new ObjectId41(org) },
13715
13715
  ...ObjectId41.isValid(site) && { site: new ObjectId41(site) },
13716
13716
  ...Object.keys(checkInFilter).length > 0 && { checkIn: checkInFilter },
13717
- ...Object.keys(expectedCheckInFilter).length > 0 && { expectedCheckIn: expectedCheckInFilter },
13717
+ ...Object.keys(expectedCheckInFilter).length > 0 && {
13718
+ expectedCheckIn: expectedCheckInFilter
13719
+ },
13718
13720
  ...Array.isArray(type) ? { type: { $in: type } } : type ? { type } : {},
13719
13721
  ...checkedOut == false && { checkOut: { $eq: null } },
13720
13722
  ...search && { $text: { $search: search } },
@@ -13722,6 +13724,7 @@ function useVisitorTransactionRepo() {
13722
13724
  ...status && { status },
13723
13725
  ...tab == "Overnight Parking" && { isOvernightParking: true }
13724
13726
  };
13727
+ console.log(query);
13725
13728
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
13726
13729
  try {
13727
13730
  const basePipeline = [{ $match: query }];
@@ -14141,7 +14144,7 @@ var vehicleSchema = Joi37.object({
14141
14144
  name: Joi37.string().optional().allow(null, ""),
14142
14145
  phoneNumber: Joi37.string().optional().allow("", null),
14143
14146
  recNo: Joi37.string().optional().allow("", null),
14144
- org: Joi37.string().hex().required(),
14147
+ org: Joi37.string().hex().optional().allow(null, ""),
14145
14148
  site: Joi37.string().hex().required(),
14146
14149
  block: Joi37.number().integer().optional().allow(0, null),
14147
14150
  level: Joi37.string().optional().allow("", null),
@@ -14153,7 +14156,9 @@ var vehicleSchema = Joi37.object({
14153
14156
  end: Joi37.date().optional().allow("", null),
14154
14157
  unitName: Joi37.string().optional().allow("", null),
14155
14158
  status: Joi37.string().optional().valid(...Object.values(VehicleStatus)).allow(""),
14156
- peopleId: Joi37.string().hex().length(24).optional().allow(null, "")
14159
+ peopleId: Joi37.string().hex().length(24).optional().allow(null, ""),
14160
+ vehicleModel: Joi37.string().optional().allow(null, ""),
14161
+ vehicleColor: Joi37.string().optional().allow(null, "")
14157
14162
  });
14158
14163
  function MVehicle(value) {
14159
14164
  const { error } = vehicleSchema.validate(value);
@@ -14214,6 +14219,7 @@ function MVehicle(value) {
14214
14219
  status: value.status ?? "active" /* ACTIVE */,
14215
14220
  unitName: value.unitName ?? "",
14216
14221
  peopleId: value.peopleId ?? "",
14222
+ vehicleModel: value.vehicleModel ?? "",
14217
14223
  createdAt,
14218
14224
  updatedAt: value.updatedAt ?? createdAt,
14219
14225
  deletedAt: value.deletedAt ?? ""
@@ -14263,9 +14269,9 @@ function MVehicleTransaction(value) {
14263
14269
  }
14264
14270
 
14265
14271
  // src/services/dahua.service.ts
14266
- import { BadRequestError as BadRequestError72, logger as logger53 } from "@7365admin1/node-server-utils";
14272
+ import { BadRequestError as BadRequestError74, logger as logger55 } from "@7365admin1/node-server-utils";
14267
14273
  import { promises as fsAsync } from "fs";
14268
- import Joi39 from "joi";
14274
+ import Joi40 from "joi";
14269
14275
  import * as path from "path";
14270
14276
  import { request } from "urllib";
14271
14277
 
@@ -14991,9 +14997,9 @@ function useVehicleRepo() {
14991
14997
 
14992
14998
  // src/services/vehicle.service.ts
14993
14999
  import {
14994
- BadRequestError as BadRequestError71,
14995
- logger as logger52,
14996
- useAtlas as useAtlas34
15000
+ BadRequestError as BadRequestError73,
15001
+ logger as logger54,
15002
+ useAtlas as useAtlas35
14997
15003
  } from "@7365admin1/node-server-utils";
14998
15004
 
14999
15005
  // src/repositories/person.repo.ts
@@ -15603,7 +15609,798 @@ function usePersonRepo() {
15603
15609
  }
15604
15610
 
15605
15611
  // src/services/vehicle.service.ts
15612
+ import { ObjectId as ObjectId47 } from "mongodb";
15613
+
15614
+ // src/repositories/building-unit.repository.ts
15615
+ import {
15616
+ AppError as AppError11,
15617
+ BadRequestError as BadRequestError72,
15618
+ InternalServerError as InternalServerError27,
15619
+ logger as logger53,
15620
+ makeCacheKey as makeCacheKey26,
15621
+ paginate as paginate21,
15622
+ toObjectId as toObjectId11,
15623
+ useAtlas as useAtlas34,
15624
+ useCache as useCache27
15625
+ } from "@7365admin1/node-server-utils";
15626
+
15627
+ // src/models/building.model.ts
15628
+ import { BadRequestError as BadRequestError71, logger as logger52 } from "@7365admin1/node-server-utils";
15629
+ import Joi39 from "joi";
15606
15630
  import { ObjectId as ObjectId45 } from "mongodb";
15631
+ var SortFields = /* @__PURE__ */ ((SortFields2) => {
15632
+ SortFields2["ID"] = "_id";
15633
+ SortFields2["CREATED_AT"] = "createdAt";
15634
+ SortFields2["NAME"] = "name";
15635
+ return SortFields2;
15636
+ })(SortFields || {});
15637
+ var SortOrder = /* @__PURE__ */ ((SortOrder2) => {
15638
+ SortOrder2["ASC"] = "asc";
15639
+ SortOrder2["DESC"] = "desc";
15640
+ return SortOrder2;
15641
+ })(SortOrder || {});
15642
+ var BuildingStatus = /* @__PURE__ */ ((BuildingStatus2) => {
15643
+ BuildingStatus2["ACTIVE"] = "active";
15644
+ BuildingStatus2["PENDING"] = "pending";
15645
+ return BuildingStatus2;
15646
+ })(BuildingStatus || {});
15647
+ var schemaBuilding = Joi39.object({
15648
+ _id: Joi39.string().hex().optional(),
15649
+ site: Joi39.string().hex().required(),
15650
+ name: Joi39.string().required(),
15651
+ block: Joi39.number().integer().min(1).required(),
15652
+ levels: Joi39.array().items(Joi39.string().required()).min(1).required(),
15653
+ createdAt: Joi39.date().optional().allow("", null),
15654
+ updatedAt: Joi39.date().optional().allow("", null),
15655
+ deletedAt: Joi39.date().optional().allow("", null),
15656
+ status: Joi39.string().optional().allow("", null),
15657
+ // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
15658
+ buildingFiles: Joi39.array().items({
15659
+ id: Joi39.string().hex().optional().allow("", null),
15660
+ name: Joi39.string().optional().allow("", null)
15661
+ }).optional().allow("", null)
15662
+ });
15663
+ var schemaBuildingUpdateOptions = Joi39.object({
15664
+ name: Joi39.string().optional().allow("", null),
15665
+ levels: Joi39.array().items(Joi39.string().required()).min(1).required(),
15666
+ block: Joi39.number().integer().min(1).required(),
15667
+ // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
15668
+ buildingFiles: Joi39.array().items({
15669
+ id: Joi39.string().hex().optional().allow("", null),
15670
+ name: Joi39.string().optional().allow("", null)
15671
+ }).optional().allow("", null)
15672
+ });
15673
+ var schemaBilling = Joi39.object({
15674
+ _id: Joi39.string().hex().optional(),
15675
+ name: Joi39.string().optional().allow("", null)
15676
+ });
15677
+ var schemaBuildingUnit = Joi39.object({
15678
+ _id: Joi39.string().hex().optional(),
15679
+ site: Joi39.string().hex().required(),
15680
+ name: Joi39.string().optional().allow("", null),
15681
+ building: Joi39.string().hex().required(),
15682
+ buildingName: Joi39.string().optional().allow("", null),
15683
+ block: Joi39.number().integer().min(1).required(),
15684
+ level: Joi39.string().required(),
15685
+ category: Joi39.string().optional().allow(null, ""),
15686
+ status: Joi39.string().optional().allow("", null),
15687
+ buildingUnitFiles: Joi39.array().items(Joi39.string()).optional().allow("", null),
15688
+ companyName: Joi39.string().optional().allow("", null),
15689
+ companyRegistrationNumber: Joi39.string().optional().allow("", null),
15690
+ leaseStart: Joi39.date().optional(),
15691
+ leaseEnd: Joi39.date().optional(),
15692
+ owner: Joi39.string().hex().optional().allow("", null),
15693
+ ownerName: Joi39.string().optional().allow("", null),
15694
+ billing: Joi39.array().items(schemaBilling).optional().allow("", null),
15695
+ unitNumber: Joi39.number().integer().min(1).optional().allow(null)
15696
+ });
15697
+ var schemaUpdateOptions = Joi39.object({
15698
+ name: Joi39.string().optional().allow("", null),
15699
+ building: Joi39.string().hex().optional().allow("", null),
15700
+ buildingName: Joi39.string().optional().allow("", null),
15701
+ block: Joi39.number().integer().min(1).optional().allow("", null),
15702
+ level: Joi39.string().optional().allow("", null),
15703
+ category: Joi39.string().optional().allow("", null),
15704
+ buildingUnitFiles: Joi39.array().items({
15705
+ id: Joi39.string().hex().optional().allow("", null),
15706
+ name: Joi39.string().optional().allow("", null)
15707
+ }).optional().allow("", null),
15708
+ companyName: Joi39.string().optional().allow("", null),
15709
+ companyRegistrationNumber: Joi39.string().optional().allow("", null),
15710
+ leaseStart: Joi39.date().optional().allow("", null),
15711
+ leaseEnd: Joi39.date().optional().allow("", null),
15712
+ owner: Joi39.string().hex().optional().allow("", null),
15713
+ ownerName: Joi39.string().optional().allow("", null),
15714
+ billing: Joi39.array().items(schemaBilling).optional().allow("", null)
15715
+ });
15716
+ function MBuilding(value) {
15717
+ const { error } = schemaBuilding.validate(value);
15718
+ if (error) {
15719
+ logger52.info(`Building Model: ${error.message}`);
15720
+ throw new BadRequestError71(error.message);
15721
+ }
15722
+ if (value._id && typeof value._id === "string") {
15723
+ try {
15724
+ value._id = new ObjectId45(value._id);
15725
+ } catch (error2) {
15726
+ throw new BadRequestError71("Invalid _id format");
15727
+ }
15728
+ }
15729
+ try {
15730
+ value.site = new ObjectId45(value.site);
15731
+ } catch (error2) {
15732
+ throw new BadRequestError71("Invalid site format");
15733
+ }
15734
+ return {
15735
+ _id: value._id ?? void 0,
15736
+ site: value.site,
15737
+ name: value.name ?? "",
15738
+ block: value.block ?? 0,
15739
+ levels: value.levels ?? "",
15740
+ status: value.status ?? "active",
15741
+ // buildingFloorPlan: value.buildingFloorPlan ?? [],
15742
+ buildingFiles: value.buildingFiles ?? [],
15743
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
15744
+ updatedAt: value.updatedAt ?? "",
15745
+ deletedAt: value.deletedAt ?? ""
15746
+ };
15747
+ }
15748
+ function MBuildingUnit(value) {
15749
+ const { error } = schemaBuildingUnit.validate(value);
15750
+ if (error) {
15751
+ logger52.info(`Building Unit Model: ${error.message}`);
15752
+ throw new BadRequestError71(error.message);
15753
+ }
15754
+ if (value._id && typeof value._id === "string") {
15755
+ try {
15756
+ value._id = new ObjectId45(value._id);
15757
+ } catch (error2) {
15758
+ throw new BadRequestError71("Invalid ID");
15759
+ }
15760
+ }
15761
+ try {
15762
+ value.site = new ObjectId45(value.site);
15763
+ } catch (error2) {
15764
+ throw new BadRequestError71("Invalid site ID");
15765
+ }
15766
+ try {
15767
+ value.building = new ObjectId45(value.building);
15768
+ } catch (error2) {
15769
+ throw new BadRequestError71("Invalid building ID");
15770
+ }
15771
+ if (value.owner && typeof value.owner === "string") {
15772
+ try {
15773
+ value.owner = new ObjectId45(value.owner);
15774
+ } catch (error2) {
15775
+ throw new BadRequestError71("Invalid Owner ID");
15776
+ }
15777
+ }
15778
+ if (value.billing && Array.isArray(value.billing)) {
15779
+ value.billing = value.billing.map((billing) => {
15780
+ if (billing._id && typeof billing._id === "string") {
15781
+ try {
15782
+ billing._id = new ObjectId45(billing._id);
15783
+ } catch {
15784
+ throw new BadRequestError71("Invalid billing id format");
15785
+ }
15786
+ }
15787
+ return billing;
15788
+ });
15789
+ }
15790
+ return {
15791
+ _id: value._id ?? void 0,
15792
+ site: value.site,
15793
+ name: value.name ?? "",
15794
+ building: value.building,
15795
+ buildingName: value.buildingName ?? "",
15796
+ block: value.block ?? 0,
15797
+ level: value.level ?? "",
15798
+ category: value.category ?? "",
15799
+ status: value.status ?? "active",
15800
+ buildingUnitFiles: value.buildingUnitFiles ?? [],
15801
+ owner: value.owner ?? "",
15802
+ ownerName: value.ownerName ?? "",
15803
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
15804
+ updatedAt: value.updatedAt ?? "",
15805
+ deletedAt: value.deletedAt ?? "",
15806
+ companyName: value.companyName ?? "",
15807
+ companyRegistrationNumber: value.companyRegistrationNumber ?? "",
15808
+ leaseStart: value.leaseStart ?? "",
15809
+ leaseEnd: value.leaseEnd ?? "",
15810
+ billing: value.billing ?? [],
15811
+ unitNumber: value.unitNumber ?? null
15812
+ };
15813
+ }
15814
+
15815
+ // src/repositories/building-unit.repository.ts
15816
+ import { ObjectId as ObjectId46 } from "mongodb";
15817
+ function useBuildingUnitRepo() {
15818
+ const db = useAtlas34.getDb();
15819
+ if (!db) {
15820
+ throw new Error("Unable to connect to server.");
15821
+ }
15822
+ const namespace_collection = "building-units";
15823
+ const collection = db.collection(namespace_collection);
15824
+ const { getCache, setCache, delNamespace, delCache } = useCache27(namespace_collection);
15825
+ async function createIndexes() {
15826
+ try {
15827
+ await collection.createIndexes([
15828
+ { key: { name: 1, building: 1, level: 1 }, unique: true },
15829
+ { key: { site: 1 } },
15830
+ { key: { building: 1 } },
15831
+ { key: { status: 1 } },
15832
+ { key: { createdAt: 1 } },
15833
+ {
15834
+ key: {
15835
+ name: "text",
15836
+ buildingName: "text",
15837
+ category: "text",
15838
+ block: "text"
15839
+ }
15840
+ }
15841
+ ]);
15842
+ } catch (error) {
15843
+ throw new Error("Failed to create index on building units.");
15844
+ }
15845
+ }
15846
+ function delCachedData() {
15847
+ delNamespace().then(() => {
15848
+ logger53.log({
15849
+ level: "info",
15850
+ message: `Cache namespace cleared for ${namespace_collection}`
15851
+ });
15852
+ }).catch((err) => {
15853
+ logger53.log({
15854
+ level: "error",
15855
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
15856
+ });
15857
+ });
15858
+ }
15859
+ function normalizeLevel(level) {
15860
+ if (/^\d+$/.test(level)) {
15861
+ return [
15862
+ `level${level}`,
15863
+ `Level${level}`,
15864
+ `lvl${level}`,
15865
+ `Lvl${level}`,
15866
+ `LVL${level}`
15867
+ ];
15868
+ }
15869
+ return [level];
15870
+ }
15871
+ async function add(value, session) {
15872
+ try {
15873
+ value = MBuildingUnit(value);
15874
+ const res = await collection.insertOne(value, { session });
15875
+ delCachedData();
15876
+ return res.insertedId;
15877
+ } catch (error) {
15878
+ logger53.log({
15879
+ level: "error",
15880
+ message: error.message
15881
+ });
15882
+ const isDuplicated = error.message.includes("duplicate");
15883
+ if (isDuplicated) {
15884
+ throw new BadRequestError72("Building unit already exists.");
15885
+ }
15886
+ if (error instanceof AppError11) {
15887
+ throw error;
15888
+ } else {
15889
+ throw new Error("Failed to create building unit.");
15890
+ }
15891
+ }
15892
+ }
15893
+ async function updateById(_id, value, session) {
15894
+ const { error } = schemaUpdateOptions.validate(value);
15895
+ if (error) {
15896
+ throw new BadRequestError72(error.message);
15897
+ }
15898
+ try {
15899
+ _id = new ObjectId46(_id);
15900
+ } catch (error2) {
15901
+ throw new BadRequestError72("Invalid ID.");
15902
+ }
15903
+ if (value.billing && Array.isArray(value.billing)) {
15904
+ value.billing = value.billing.map((billing) => {
15905
+ if (billing._id && typeof billing._id === "string") {
15906
+ try {
15907
+ billing._id = new ObjectId46(billing._id);
15908
+ } catch {
15909
+ throw new BadRequestError72("Invalid billing id format");
15910
+ }
15911
+ }
15912
+ return billing;
15913
+ });
15914
+ }
15915
+ if (value.owner) {
15916
+ value.owner = new ObjectId46(value.owner);
15917
+ }
15918
+ try {
15919
+ const res = await collection.updateOne(
15920
+ { _id },
15921
+ { $set: value },
15922
+ { session }
15923
+ );
15924
+ delCachedData();
15925
+ return res;
15926
+ } catch (error2) {
15927
+ logger53.log({
15928
+ level: "error",
15929
+ message: error2.message
15930
+ });
15931
+ const isDuplicated = error2.message.includes("duplicate");
15932
+ if (isDuplicated) {
15933
+ throw new BadRequestError72("Building unit already exists.");
15934
+ }
15935
+ if (error2 instanceof AppError11) {
15936
+ throw error2;
15937
+ } else {
15938
+ throw new Error("Failed to create building unit.");
15939
+ }
15940
+ }
15941
+ }
15942
+ async function updateByBuildingId(building, value, session) {
15943
+ const { error } = schemaUpdateOptions.validate(value);
15944
+ if (error) {
15945
+ throw new BadRequestError72(error.message);
15946
+ }
15947
+ try {
15948
+ building = new ObjectId46(building);
15949
+ } catch (error2) {
15950
+ throw new BadRequestError72("Invalid building ID.");
15951
+ }
15952
+ try {
15953
+ const res = await collection.updateMany(
15954
+ { building },
15955
+ { $set: value },
15956
+ { session }
15957
+ );
15958
+ delCachedData();
15959
+ return res;
15960
+ } catch (error2) {
15961
+ logger53.log({
15962
+ level: "error",
15963
+ message: error2.message
15964
+ });
15965
+ const isDuplicated = error2.message.includes("duplicate");
15966
+ if (isDuplicated) {
15967
+ throw new BadRequestError72("Building unit already exists.");
15968
+ }
15969
+ if (error2 instanceof AppError11) {
15970
+ throw error2;
15971
+ } else {
15972
+ throw new Error("Failed to create building unit.");
15973
+ }
15974
+ }
15975
+ }
15976
+ async function getAll({
15977
+ search = "",
15978
+ page = 1,
15979
+ limit = 10,
15980
+ sort = {},
15981
+ site = "",
15982
+ building = "",
15983
+ status = "active"
15984
+ } = {}) {
15985
+ page = page > 0 ? page - 1 : 0;
15986
+ const query = {
15987
+ status,
15988
+ ...search && { $text: { $search: search } },
15989
+ ...site && { site: toObjectId11(site) },
15990
+ ...building && { building: toObjectId11(building) }
15991
+ };
15992
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
15993
+ const cacheParams = {
15994
+ page,
15995
+ limit,
15996
+ sort: JSON.stringify(sort),
15997
+ ...search && { search },
15998
+ ...site && { site },
15999
+ ...building && { building },
16000
+ ...status && { status }
16001
+ };
16002
+ const cacheKey = makeCacheKey26(namespace_collection, cacheParams);
16003
+ logger53.log({
16004
+ level: "info",
16005
+ message: `Cache key for getAll building units: ${cacheKey}`
16006
+ });
16007
+ try {
16008
+ const cached = await getCache(cacheKey);
16009
+ if (cached) {
16010
+ logger53.log({
16011
+ level: "info",
16012
+ message: `Cache hit for getAll building units: ${cacheKey}`
16013
+ });
16014
+ return cached;
16015
+ }
16016
+ const items = await collection.aggregate([
16017
+ { $match: query },
16018
+ {
16019
+ $lookup: {
16020
+ from: "sites",
16021
+ let: { siteId: "$site" },
16022
+ pipeline: [
16023
+ {
16024
+ $match: {
16025
+ $expr: { $eq: ["$_id", "$$siteId"] },
16026
+ status: "active" /* ACTIVE */
16027
+ }
16028
+ },
16029
+ {
16030
+ $project: {
16031
+ name: 1,
16032
+ description: 1,
16033
+ orgId: 1,
16034
+ metadata: 1,
16035
+ status: 1,
16036
+ address: 1
16037
+ }
16038
+ }
16039
+ ],
16040
+ as: "site"
16041
+ }
16042
+ },
16043
+ { $set: { site: { $first: "$site" } } },
16044
+ { $sort: sort },
16045
+ { $skip: page * limit },
16046
+ { $limit: limit }
16047
+ ]).toArray();
16048
+ const length = await collection.countDocuments(query);
16049
+ const data = paginate21(items, page, limit, length);
16050
+ setCache(cacheKey, data, 600).then(() => {
16051
+ logger53.log({
16052
+ level: "info",
16053
+ message: `Cache set for getAll building units: ${cacheKey}`
16054
+ });
16055
+ }).catch((err) => {
16056
+ logger53.log({
16057
+ level: "error",
16058
+ message: `Failed to set cache for getAll building units: ${err.message}`
16059
+ });
16060
+ });
16061
+ return data;
16062
+ } catch (error) {
16063
+ logger53.log({ level: "error", message: `${error}` });
16064
+ throw error;
16065
+ }
16066
+ }
16067
+ async function getById(_id, session) {
16068
+ try {
16069
+ _id = new ObjectId46(_id);
16070
+ } catch (error) {
16071
+ throw new BadRequestError72("Invalid ID.");
16072
+ }
16073
+ const cacheKey = makeCacheKey26(namespace_collection, { _id: String(_id) });
16074
+ try {
16075
+ const cached = await getCache(cacheKey);
16076
+ if (cached) {
16077
+ logger53.log({
16078
+ level: "info",
16079
+ message: `Cache hit for getById building unit: ${cacheKey}`
16080
+ });
16081
+ return cached;
16082
+ }
16083
+ const result = await collection.findOne({
16084
+ _id,
16085
+ deletedAt: { $in: ["", null] }
16086
+ });
16087
+ if (!result) {
16088
+ throw new BadRequestError72("Building unit not found.");
16089
+ }
16090
+ setCache(cacheKey, result, 300).then(() => {
16091
+ logger53.log({
16092
+ level: "info",
16093
+ message: `Cache set for building unit by id: ${cacheKey}`
16094
+ });
16095
+ }).catch((err) => {
16096
+ logger53.log({
16097
+ level: "error",
16098
+ message: `Failed to set cache for building unit by id: ${err.message}`
16099
+ });
16100
+ });
16101
+ return result;
16102
+ } catch (error) {
16103
+ if (error instanceof AppError11) {
16104
+ throw error;
16105
+ } else {
16106
+ throw new InternalServerError27("Failed to get building unit.");
16107
+ }
16108
+ }
16109
+ }
16110
+ async function getByBuildingLevel(building, level) {
16111
+ try {
16112
+ building = new ObjectId46(building);
16113
+ } catch (error) {
16114
+ throw new BadRequestError72("Invalid building ID.");
16115
+ }
16116
+ const cacheKey = makeCacheKey26(namespace_collection, {
16117
+ building: String(building),
16118
+ level
16119
+ });
16120
+ try {
16121
+ const cached = await getCache(cacheKey);
16122
+ if (cached) {
16123
+ logger53.log({
16124
+ level: "info",
16125
+ message: `Cache hit for getById building unit: ${cacheKey}`
16126
+ });
16127
+ return cached;
16128
+ }
16129
+ const result = await collection.findOne({
16130
+ building,
16131
+ level,
16132
+ status: "active"
16133
+ });
16134
+ setCache(cacheKey, result, 300).then(() => {
16135
+ logger53.log({
16136
+ level: "info",
16137
+ message: `Cache set for building unit by id: ${cacheKey}`
16138
+ });
16139
+ }).catch((err) => {
16140
+ logger53.log({
16141
+ level: "error",
16142
+ message: `Failed to set cache for building unit by id: ${err.message}`
16143
+ });
16144
+ });
16145
+ return result;
16146
+ } catch (error) {
16147
+ if (error instanceof AppError11) {
16148
+ throw error;
16149
+ } else {
16150
+ throw new InternalServerError27("Failed to get building unit.");
16151
+ }
16152
+ }
16153
+ }
16154
+ async function updateLevelByBuildingLevel(building, level, newLevel, session) {
16155
+ try {
16156
+ building = new ObjectId46(building);
16157
+ } catch (error) {
16158
+ throw new BadRequestError72("Invalid building ID.");
16159
+ }
16160
+ try {
16161
+ const result = await collection.updateMany(
16162
+ {
16163
+ building,
16164
+ level,
16165
+ status: "active"
16166
+ },
16167
+ {
16168
+ $set: { level: newLevel }
16169
+ },
16170
+ {
16171
+ session
16172
+ }
16173
+ );
16174
+ delCachedData();
16175
+ return result;
16176
+ } catch (error) {
16177
+ if (error instanceof AppError11) {
16178
+ throw error;
16179
+ } else {
16180
+ throw new InternalServerError27("Failed to update building unit level.");
16181
+ }
16182
+ }
16183
+ }
16184
+ async function getByBuilding(building) {
16185
+ try {
16186
+ building = new ObjectId46(building);
16187
+ } catch (error) {
16188
+ throw new BadRequestError72("Invalid building ID.");
16189
+ }
16190
+ const cacheKey = makeCacheKey26(namespace_collection, {
16191
+ building: String(building)
16192
+ });
16193
+ try {
16194
+ const cached = await getCache(cacheKey);
16195
+ if (cached) {
16196
+ logger53.log({
16197
+ level: "info",
16198
+ message: `Cache hit for getById building unit: ${cacheKey}`
16199
+ });
16200
+ return cached;
16201
+ }
16202
+ const result = await collection.findOne({
16203
+ building,
16204
+ status: "active"
16205
+ });
16206
+ setCache(cacheKey, result, 300).then(() => {
16207
+ logger53.log({
16208
+ level: "info",
16209
+ message: `Cache set for building unit by id: ${cacheKey}`
16210
+ });
16211
+ }).catch((err) => {
16212
+ logger53.log({
16213
+ level: "error",
16214
+ message: `Failed to set cache for building unit by id: ${err.message}`
16215
+ });
16216
+ });
16217
+ return result;
16218
+ } catch (error) {
16219
+ if (error instanceof AppError11) {
16220
+ throw error;
16221
+ } else {
16222
+ throw new InternalServerError27("Failed to get building unit.");
16223
+ }
16224
+ }
16225
+ }
16226
+ async function deleteById(_id, session) {
16227
+ try {
16228
+ _id = new ObjectId46(_id);
16229
+ } catch (error) {
16230
+ throw new BadRequestError72("Invalid ID.");
16231
+ }
16232
+ try {
16233
+ const res = await collection.updateOne(
16234
+ { _id },
16235
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
16236
+ { session }
16237
+ );
16238
+ delCachedData();
16239
+ return "Room/Facility deleted successfully.";
16240
+ } catch (error) {
16241
+ logger53.log({
16242
+ level: "error",
16243
+ message: error.message
16244
+ });
16245
+ if (error instanceof AppError11) {
16246
+ throw error;
16247
+ } else {
16248
+ throw new Error("Failed to deleted room/facility.");
16249
+ }
16250
+ }
16251
+ }
16252
+ async function getBuildingUnits(site, block, level) {
16253
+ try {
16254
+ site = new ObjectId46(site);
16255
+ } catch (error) {
16256
+ throw new BadRequestError72("Invalid site ID format.");
16257
+ }
16258
+ const query = { site, block, level };
16259
+ const cacheOptions = {
16260
+ site: site.toString(),
16261
+ block,
16262
+ level
16263
+ };
16264
+ const cacheKey = makeCacheKey26(namespace_collection, cacheOptions);
16265
+ const cachedData = await getCache(cacheKey);
16266
+ if (cachedData) {
16267
+ logger53.info(`Cache hit for key: ${cacheKey}`);
16268
+ return cachedData;
16269
+ }
16270
+ try {
16271
+ const data = await collection.aggregate([{ $match: query }, { $project: { name: 1 } }]).toArray();
16272
+ setCache(cacheKey, data, 15 * 60).then(() => {
16273
+ logger53.info(`Cache set for key: ${cacheKey}`);
16274
+ }).catch((err) => {
16275
+ logger53.error(`Failed to set cache for key: ${cacheKey}`, err);
16276
+ });
16277
+ return data;
16278
+ } catch (error) {
16279
+ if (error instanceof AppError11) {
16280
+ throw error;
16281
+ } else {
16282
+ throw new InternalServerError27("Failed to get building units.");
16283
+ }
16284
+ }
16285
+ }
16286
+ async function getBuildingUnitsWithOwner(site, unitIds) {
16287
+ try {
16288
+ site = new ObjectId46(site);
16289
+ } catch (error) {
16290
+ throw new BadRequestError72("Invalid site ID format.");
16291
+ }
16292
+ const query = {
16293
+ site,
16294
+ owner: { $nin: [null, ""] }
16295
+ };
16296
+ if (unitIds && unitIds.length > 0) {
16297
+ query._id = { $in: unitIds };
16298
+ }
16299
+ const cacheOptions = {
16300
+ site: site.toString()
16301
+ };
16302
+ const cacheKey = makeCacheKey26(namespace_collection, cacheOptions);
16303
+ const cachedData = await getCache(cacheKey);
16304
+ if (cachedData) {
16305
+ logger53.info(`Cache hit for key: ${cacheKey}`);
16306
+ return cachedData;
16307
+ }
16308
+ try {
16309
+ const data = await collection.aggregate([{ $match: query }]).toArray();
16310
+ setCache(cacheKey, data, 15 * 60).then(() => {
16311
+ logger53.info(`Cache set for key: ${cacheKey}`);
16312
+ }).catch((err) => {
16313
+ logger53.error(`Failed to set cache for key: ${cacheKey}`, err);
16314
+ });
16315
+ return data;
16316
+ } catch (error) {
16317
+ if (error instanceof AppError11) {
16318
+ throw error;
16319
+ } else {
16320
+ throw new InternalServerError27(
16321
+ "Failed to get building units with owner."
16322
+ );
16323
+ }
16324
+ }
16325
+ }
16326
+ async function getUnitByBlockLevelUnitNumber(block, level, unitNumber, site, session) {
16327
+ let _site;
16328
+ try {
16329
+ _site = new ObjectId46(site);
16330
+ } catch (error) {
16331
+ throw new BadRequestError72("Invalid ID.");
16332
+ }
16333
+ const cacheOptions = {
16334
+ block,
16335
+ level,
16336
+ unitNumber,
16337
+ site
16338
+ };
16339
+ const query = {
16340
+ block,
16341
+ level: { $in: normalizeLevel(level) },
16342
+ unitNumber: Number(unitNumber),
16343
+ site: _site,
16344
+ $or: [
16345
+ { deletedAt: { $exists: false } },
16346
+ { deletedAt: null },
16347
+ { deletedAt: "" }
16348
+ ]
16349
+ };
16350
+ const cacheKey = makeCacheKey26(namespace_collection, cacheOptions);
16351
+ try {
16352
+ const cached = await getCache(cacheKey);
16353
+ if (cached) {
16354
+ logger53.log({
16355
+ level: "info",
16356
+ message: `Cache hit for getById building unit: ${cacheKey}`
16357
+ });
16358
+ return cached;
16359
+ }
16360
+ const result = await collection.findOne(query, {
16361
+ session
16362
+ });
16363
+ if (!result) {
16364
+ throw new BadRequestError72("Building unit not found.");
16365
+ }
16366
+ setCache(cacheKey, result, 300).then(() => {
16367
+ logger53.log({
16368
+ level: "info",
16369
+ message: `Cache set for building unit by id: ${cacheKey}`
16370
+ });
16371
+ }).catch((err) => {
16372
+ logger53.log({
16373
+ level: "error",
16374
+ message: `Failed to set cache for building unit by id: ${err.message}`
16375
+ });
16376
+ });
16377
+ return result;
16378
+ } catch (error) {
16379
+ if (error instanceof AppError11) {
16380
+ throw error;
16381
+ } else {
16382
+ throw new InternalServerError27("Failed to get building unit.");
16383
+ }
16384
+ }
16385
+ }
16386
+ return {
16387
+ createIndexes,
16388
+ add,
16389
+ getAll,
16390
+ getById,
16391
+ getByBuildingLevel,
16392
+ updateById,
16393
+ getByBuilding,
16394
+ deleteById,
16395
+ updateLevelByBuildingLevel,
16396
+ updateByBuildingId,
16397
+ getBuildingUnits,
16398
+ getBuildingUnitsWithOwner,
16399
+ getUnitByBlockLevelUnitNumber
16400
+ };
16401
+ }
16402
+
16403
+ // src/services/vehicle.service.ts
15607
16404
  function formatDahuaDate(date) {
15608
16405
  const pad = (n) => String(n).padStart(2, "0");
15609
16406
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
@@ -15638,14 +16435,18 @@ function useVehicleService() {
15638
16435
  addPlateNumber: _addPlateNumber,
15639
16436
  removePlateNumber: _removePlateNumber,
15640
16437
  updatePlateNumber: _updatePlateNumber,
15641
- getPlateNumber: _getPlateNumber
16438
+ getPlateNumber: _getPlateNumber,
16439
+ bulkInsertPlateNumber: _bulkInsertPlateNumber
15642
16440
  } = useDahuaService();
15643
16441
  const { getAllCameraWithPassword: _getAllSiteCameras } = useSiteCameraRepo();
15644
16442
  const { getById: _getById } = useOrgRepo();
15645
- const { pushVehicleById: _pushVehicleById } = usePersonRepo();
15646
- const { pullVehicleByRecNo: _pullVehicleByRecNo } = usePersonRepo();
16443
+ const {
16444
+ pushVehicleById: _pushVehicleById,
16445
+ pullVehicleByRecNo: _pullVehicleByRecNo
16446
+ } = usePersonRepo();
16447
+ const { getUnitByBlockLevelUnitNumber: _getUnitByBlockLevelUnitNumber } = useBuildingUnitRepo();
15647
16448
  async function add(value) {
15648
- const session = useAtlas34.getClient()?.startSession();
16449
+ const session = useAtlas35.getClient()?.startSession();
15649
16450
  if (!session) {
15650
16451
  throw new Error("Unable to start session for vehicle service.");
15651
16452
  }
@@ -15655,11 +16456,11 @@ function useVehicleService() {
15655
16456
  _getById(value.org)
15656
16457
  ]);
15657
16458
  if (!org)
15658
- throw new BadRequestError71("Org not found");
16459
+ throw new BadRequestError73("Org not found");
15659
16460
  if (existingPlateNumber)
15660
- throw new BadRequestError71("Vehicle plate number already exists");
16461
+ throw new BadRequestError73("Vehicle plate number already exists");
15661
16462
  if (!Object.values(OrgNature).includes(org.nature)) {
15662
- throw new BadRequestError71(
16463
+ throw new BadRequestError73(
15663
16464
  "This organization is not allowed to add vehicles."
15664
16465
  );
15665
16466
  }
@@ -15724,7 +16525,7 @@ function useVehicleService() {
15724
16525
  page++;
15725
16526
  } while (page <= pages);
15726
16527
  if (!siteCameras.length) {
15727
- throw new BadRequestError71("No site cameras found.");
16528
+ throw new BadRequestError73("No site cameras found.");
15728
16529
  }
15729
16530
  }
15730
16531
  for (const plateNumber of plateNumbers) {
@@ -15760,7 +16561,7 @@ function useVehicleService() {
15760
16561
  };
15761
16562
  const dahuaResponse = await _addPlateNumber(dahuaPayload);
15762
16563
  if (dahuaResponse?.statusCode !== 200) {
15763
- throw new BadRequestError71(
16564
+ throw new BadRequestError73(
15764
16565
  `Failed to add plate number to ANPR ${_type}`
15765
16566
  );
15766
16567
  }
@@ -15781,7 +16582,7 @@ function useVehicleService() {
15781
16582
  };
15782
16583
  const dahuaResponse = await _updatePlateNumber(dahuaPayload);
15783
16584
  if (dahuaResponse?.statusCode !== 200) {
15784
- throw new BadRequestError71(
16585
+ throw new BadRequestError73(
15785
16586
  `Failed to update plate number to ANPR ${_type}`
15786
16587
  );
15787
16588
  }
@@ -15805,7 +16606,7 @@ function useVehicleService() {
15805
16606
  await session.commitTransaction();
15806
16607
  return message;
15807
16608
  } catch (error) {
15808
- logger52.error("Error in vehicle service add:", error);
16609
+ logger54.error("Error in vehicle service add:", error);
15809
16610
  await session.abortTransaction();
15810
16611
  throw error;
15811
16612
  } finally {
@@ -15813,7 +16614,7 @@ function useVehicleService() {
15813
16614
  }
15814
16615
  }
15815
16616
  async function deleteVehicle(_id, recno, site, type, bypass = false) {
15816
- const session = useAtlas34.getClient()?.startSession();
16617
+ const session = useAtlas35.getClient()?.startSession();
15817
16618
  if (!session) {
15818
16619
  throw new Error("Unable to start session for vehicle service.");
15819
16620
  }
@@ -15836,7 +16637,7 @@ function useVehicleService() {
15836
16637
  page++;
15837
16638
  } while (page < pages);
15838
16639
  if (!siteCameras.length) {
15839
- throw new BadRequestError71("No site cameras found.");
16640
+ throw new BadRequestError73("No site cameras found.");
15840
16641
  }
15841
16642
  for (const camera of siteCameras) {
15842
16643
  const host = camera.host;
@@ -15851,7 +16652,7 @@ function useVehicleService() {
15851
16652
  };
15852
16653
  const dahuaResponse = await _removePlateNumber(dahuaPayload);
15853
16654
  if (!bypass && dahuaResponse?.statusCode !== 200) {
15854
- throw new BadRequestError71(
16655
+ throw new BadRequestError73(
15855
16656
  `Failed to remove plate number to ANPR from ${type}`
15856
16657
  );
15857
16658
  }
@@ -15863,7 +16664,7 @@ function useVehicleService() {
15863
16664
  await session.commitTransaction();
15864
16665
  return `Vehicle plate number deleted from ${type} record successfully.`;
15865
16666
  } catch (error) {
15866
- logger52.error("Error in vehicle service delete:", error);
16667
+ logger54.error("Error in vehicle service delete:", error);
15867
16668
  await session.abortTransaction();
15868
16669
  throw error;
15869
16670
  } finally {
@@ -15871,16 +16672,16 @@ function useVehicleService() {
15871
16672
  }
15872
16673
  }
15873
16674
  async function approveVehicleById(id, orgId, siteId) {
15874
- const session = useAtlas34.getClient()?.startSession();
16675
+ const session = useAtlas35.getClient()?.startSession();
15875
16676
  if (!session) {
15876
16677
  throw new Error("Unable to start session for vehicle service.");
15877
16678
  }
15878
16679
  const org = await _getById(orgId);
15879
16680
  if (!org)
15880
- throw new BadRequestError71("Org not found");
16681
+ throw new BadRequestError73("Org not found");
15881
16682
  const allowedNatures2 = "property_management_agency" /* PROPERTY_MANAGEMENT_AGENCY */;
15882
16683
  if (!allowedNatures2.includes(org.nature)) {
15883
- throw new BadRequestError71(
16684
+ throw new BadRequestError73(
15884
16685
  "Only property management can approve vehicles."
15885
16686
  );
15886
16687
  }
@@ -15888,7 +16689,7 @@ function useVehicleService() {
15888
16689
  const plate = vehicle.plates.find((p) => p._id.toString() === id);
15889
16690
  const _plateNumber = plate?.plateNumber;
15890
16691
  if (!vehicle) {
15891
- throw new BadRequestError71("Vehicle not found");
16692
+ throw new BadRequestError73("Vehicle not found");
15892
16693
  }
15893
16694
  const owner = vehicle.name;
15894
16695
  const hasStart = typeof vehicle.start === "string" ? vehicle.start.trim() !== "" : !!vehicle.start;
@@ -15927,7 +16728,7 @@ function useVehicleService() {
15927
16728
  page++;
15928
16729
  } while (page < pages);
15929
16730
  if (!siteCameras.length) {
15930
- throw new BadRequestError71("No site cameras found.");
16731
+ throw new BadRequestError73("No site cameras found.");
15931
16732
  }
15932
16733
  for (const camera of siteCameras) {
15933
16734
  const { host, username, password } = camera;
@@ -15943,7 +16744,7 @@ function useVehicleService() {
15943
16744
  };
15944
16745
  const dahuaResponse = await _addPlateNumber(dahuaPayload);
15945
16746
  if (dahuaResponse?.statusCode !== 200) {
15946
- throw new BadRequestError71("Failed to add plate number to ANPR");
16747
+ throw new BadRequestError73("Failed to add plate number to ANPR");
15947
16748
  }
15948
16749
  const responseData = dahuaResponse?.data.toString("utf-8");
15949
16750
  value.recNo = responseData.split("=")[1]?.trim();
@@ -15968,7 +16769,7 @@ function useVehicleService() {
15968
16769
  await session.commitTransaction();
15969
16770
  return "Vehicle plate number approved and added successfully.";
15970
16771
  } catch (error) {
15971
- logger52.error("Error in vehicle service approving and adding:", error);
16772
+ logger54.error("Error in vehicle service approving and adding:", error);
15972
16773
  await session.abortTransaction();
15973
16774
  throw error;
15974
16775
  } finally {
@@ -15976,7 +16777,7 @@ function useVehicleService() {
15976
16777
  }
15977
16778
  }
15978
16779
  async function processDeletingExpiredVehicles() {
15979
- const session = useAtlas34.getClient()?.startSession();
16780
+ const session = useAtlas35.getClient()?.startSession();
15980
16781
  if (!session) {
15981
16782
  throw new Error("Unable to start session for vehicle service.");
15982
16783
  }
@@ -16003,7 +16804,7 @@ function useVehicleService() {
16003
16804
  page++;
16004
16805
  } while (page < pages);
16005
16806
  if (!siteCameras.length) {
16006
- throw new BadRequestError71("No site cameras found.");
16807
+ throw new BadRequestError73("No site cameras found.");
16007
16808
  }
16008
16809
  for (const camera of siteCameras) {
16009
16810
  const host = camera.host;
@@ -16023,7 +16824,7 @@ function useVehicleService() {
16023
16824
  await session.commitTransaction();
16024
16825
  return `Expired Vehicle plate numbers deleted successfully.`;
16025
16826
  } catch (error) {
16026
- logger52.error(
16827
+ logger54.error(
16027
16828
  "Error in vehicle service process deleting expired vehicles:",
16028
16829
  error
16029
16830
  );
@@ -16034,16 +16835,16 @@ function useVehicleService() {
16034
16835
  }
16035
16836
  }
16036
16837
  async function reactivateVehicleById(id, orgId, siteId) {
16037
- const session = useAtlas34.getClient()?.startSession();
16838
+ const session = useAtlas35.getClient()?.startSession();
16038
16839
  if (!session) {
16039
16840
  throw new Error("Unable to start session for vehicle service.");
16040
16841
  }
16041
16842
  const org = await _getById(orgId);
16042
16843
  if (!org)
16043
- throw new BadRequestError71("Org not found");
16844
+ throw new BadRequestError73("Org not found");
16044
16845
  const allowedNatures2 = "property_management_agency" /* PROPERTY_MANAGEMENT_AGENCY */;
16045
16846
  if (!allowedNatures2.includes(org.nature)) {
16046
- throw new BadRequestError71(
16847
+ throw new BadRequestError73(
16047
16848
  "Only property management can reactivate vehicles."
16048
16849
  );
16049
16850
  }
@@ -16051,7 +16852,7 @@ function useVehicleService() {
16051
16852
  const plate = vehicle.plates.find((p) => p._id.toString() === id);
16052
16853
  const _plateNumber = plate?.plateNumber;
16053
16854
  if (!vehicle) {
16054
- throw new BadRequestError71("Vehicle not found");
16855
+ throw new BadRequestError73("Vehicle not found");
16055
16856
  }
16056
16857
  const owner = vehicle.name;
16057
16858
  let startDate = /* @__PURE__ */ new Date();
@@ -16081,7 +16882,7 @@ function useVehicleService() {
16081
16882
  page++;
16082
16883
  } while (page < pages);
16083
16884
  if (!siteCameras.length) {
16084
- throw new BadRequestError71("No site cameras found.");
16885
+ throw new BadRequestError73("No site cameras found.");
16085
16886
  }
16086
16887
  for (const camera of siteCameras) {
16087
16888
  const { host, username, password } = camera;
@@ -16097,7 +16898,7 @@ function useVehicleService() {
16097
16898
  };
16098
16899
  const dahuaResponse = await _addPlateNumber(dahuaPayload);
16099
16900
  if (dahuaResponse?.statusCode !== 200) {
16100
- throw new BadRequestError71("Failed to add plate number to ANPR");
16901
+ throw new BadRequestError73("Failed to add plate number to ANPR");
16101
16902
  }
16102
16903
  const responseData = dahuaResponse?.data.toString("utf-8");
16103
16904
  value.recNo = responseData.split("=")[1]?.trim();
@@ -16123,7 +16924,7 @@ function useVehicleService() {
16123
16924
  await session.commitTransaction();
16124
16925
  return "Vehicle reactivated successfully.";
16125
16926
  } catch (error) {
16126
- logger52.error("Error in vehicle service reactivation:", error);
16927
+ logger54.error("Error in vehicle service reactivation:", error);
16127
16928
  await session.abortTransaction();
16128
16929
  throw error;
16129
16930
  } finally {
@@ -16131,7 +16932,7 @@ function useVehicleService() {
16131
16932
  }
16132
16933
  }
16133
16934
  async function updateVehicleById(_id, value) {
16134
- const session = useAtlas34.getClient()?.startSession();
16935
+ const session = useAtlas35.getClient()?.startSession();
16135
16936
  if (!session) {
16136
16937
  throw new Error("Unable to start session for vehicle service.");
16137
16938
  }
@@ -16166,7 +16967,7 @@ function useVehicleService() {
16166
16967
  page++;
16167
16968
  } while (page < pages);
16168
16969
  if (!siteCameras.length) {
16169
- throw new BadRequestError71("No site cameras found.");
16970
+ throw new BadRequestError73("No site cameras found.");
16170
16971
  }
16171
16972
  for (const camera of siteCameras) {
16172
16973
  const { host, username, password } = camera;
@@ -16183,7 +16984,7 @@ function useVehicleService() {
16183
16984
  removePlateNumber
16184
16985
  );
16185
16986
  if (responseForDeletion?.statusCode !== 200) {
16186
- throw new BadRequestError71(
16987
+ throw new BadRequestError73(
16187
16988
  "Failed to delete plate number to ANPR"
16188
16989
  );
16189
16990
  }
@@ -16200,7 +17001,7 @@ function useVehicleService() {
16200
17001
  };
16201
17002
  const dahuaResponse = await _addPlateNumber(dahuaPayload);
16202
17003
  if (dahuaResponse?.statusCode !== 200) {
16203
- throw new BadRequestError71(
17004
+ throw new BadRequestError73(
16204
17005
  "Failed to update plate number to ANPR"
16205
17006
  );
16206
17007
  }
@@ -16220,7 +17021,7 @@ function useVehicleService() {
16220
17021
  };
16221
17022
  const dahuaResponse = await _updatePlateNumber(dahuaPayload);
16222
17023
  if (dahuaResponse?.statusCode !== 200) {
16223
- throw new BadRequestError71(
17024
+ throw new BadRequestError73(
16224
17025
  "Failed to update plate number to ANPR"
16225
17026
  );
16226
17027
  }
@@ -16234,7 +17035,7 @@ function useVehicleService() {
16234
17035
  ...start && { start },
16235
17036
  ...end && { end },
16236
17037
  ...unit && {
16237
- unit: typeof unit === "string" ? new ObjectId45(unit) : unit
17038
+ unit: typeof unit === "string" ? new ObjectId47(unit) : unit
16238
17039
  },
16239
17040
  ...value.recNo && { recNo: value.recNo },
16240
17041
  ...type && { type: value.type }
@@ -16242,15 +17043,15 @@ function useVehicleService() {
16242
17043
  await _updateVehicleById(_id, formattedValue, session);
16243
17044
  await session.commitTransaction();
16244
17045
  } catch (error) {
16245
- logger52.error("Error in vehicle service update:", error);
17046
+ logger54.error("Error in vehicle service update:", error);
16246
17047
  await session.abortTransaction();
16247
17048
  throw error;
16248
17049
  } finally {
16249
17050
  session.endSession();
16250
17051
  }
16251
17052
  }
16252
- async function bulkUpsertVehicles(values) {
16253
- const session = useAtlas34.getClient()?.startSession();
17053
+ async function bulkUpsertVehicles(values, site, org) {
17054
+ const session = useAtlas35.getClient()?.startSession();
16254
17055
  if (!session) {
16255
17056
  throw new Error("Unable to start session for vehicle service.");
16256
17057
  }
@@ -16258,19 +17059,78 @@ function useVehicleService() {
16258
17059
  if (!Array.isArray(values) || values.length === 0) {
16259
17060
  throw new Error("Vehicle list is required.");
16260
17061
  }
16261
- const sanitizedValues = values.map((item) => {
16262
- const plateNumber = Array.isArray(item.plateNumber) ? item.plateNumber[0] : item.plateNumber;
16263
- return {
16264
- ...item,
16265
- plateNumber: typeof plateNumber === "string" ? plateNumber.trim() : plateNumber
16266
- };
16267
- }).filter((item) => item.site && item.plateNumber);
17062
+ const now = (/* @__PURE__ */ new Date()).toISOString();
17063
+ const sanitizedValues = (await Promise.all(
17064
+ values.map(async (item) => {
17065
+ const plateNumber = Array.isArray(item.plateNumber) ? item.plateNumber[0] : item.plateNumber;
17066
+ const unit = await _getUnitByBlockLevelUnitNumber(
17067
+ item.block,
17068
+ item.level,
17069
+ item.unit,
17070
+ site
17071
+ );
17072
+ const unitId = unit && unit._id && ObjectId47.isValid(unit._id) ? unit._id.toString() : unit?._id;
17073
+ return {
17074
+ ...item,
17075
+ org,
17076
+ site,
17077
+ start: item.start ?? now,
17078
+ unit: unitId,
17079
+ plateNumber: typeof plateNumber === "string" ? plateNumber.trim().toUpperCase() : plateNumber
17080
+ };
17081
+ })
17082
+ )).filter((item) => item.plateNumber);
16268
17083
  if (sanitizedValues.length === 0) {
16269
17084
  throw new Error("No valid vehicle plate numbers found.");
16270
17085
  }
17086
+ let siteCameras = [];
17087
+ if (site) {
17088
+ let page = 1;
17089
+ let pages = 1;
17090
+ const limit = 20;
17091
+ do {
17092
+ const siteCameraReq = await _getAllSiteCameras({
17093
+ site,
17094
+ type: "anpr",
17095
+ direction: ["both", "entry"],
17096
+ page,
17097
+ limit
17098
+ });
17099
+ pages = siteCameraReq.pages || 1;
17100
+ siteCameras.push(...siteCameraReq.items);
17101
+ page++;
17102
+ } while (page <= pages);
17103
+ }
17104
+ if (!siteCameras.length) {
17105
+ throw new Error("No site cameras found.");
17106
+ }
17107
+ for (const vehicleValue of sanitizedValues) {
17108
+ const plateNumber = vehicleValue.plateNumber;
17109
+ const _mode = vehicleValue.type === "whitelist" /* WHITELIST */ ? "TrafficRedList" /* TRAFFIC_REDLIST */ : "TrafficBlackList" /* TRAFFIC_BLACKLIST */;
17110
+ for (const camera of siteCameras) {
17111
+ const { host, username, password } = camera;
17112
+ const dahuaPayload = {
17113
+ host,
17114
+ username,
17115
+ password,
17116
+ plateNumber,
17117
+ mode: _mode,
17118
+ ...vehicleValue.start ? { start: String(vehicleValue.start) } : {},
17119
+ ...vehicleValue.end ? { end: String(vehicleValue.end) } : {},
17120
+ ...vehicleValue.name ? { owner: vehicleValue.name } : {},
17121
+ ...vehicleValue.vehicleModel ? { vehicleType: vehicleValue.vehicleModel } : {},
17122
+ ...vehicleValue.vehicleColor ? { vehicleColor: vehicleValue.vehicleColor } : {}
17123
+ };
17124
+ const dahuaResponse = await _bulkInsertPlateNumber(dahuaPayload);
17125
+ const responseData = dahuaResponse?.data?.toString("utf-8") ?? "";
17126
+ vehicleValue.recNo = responseData.split("=")[1]?.trim();
17127
+ }
17128
+ }
16271
17129
  return await _bulkUpsertVehicles(sanitizedValues, session);
16272
17130
  } catch (error) {
16273
17131
  throw error;
17132
+ } finally {
17133
+ session.endSession();
16274
17134
  }
16275
17135
  }
16276
17136
  return {
@@ -16341,14 +17201,14 @@ function useDahuaService() {
16341
17201
  function enqueue(buffer) {
16342
17202
  if (queue.length >= MAX_QUEUE_SIZE) {
16343
17203
  droppedChunks++;
16344
- logger53.error(
17204
+ logger55.error(
16345
17205
  `[${site}][${gate}] Queue overflow. Dropped: ${droppedChunks}`
16346
17206
  );
16347
17207
  return;
16348
17208
  }
16349
17209
  queue.push(buffer);
16350
17210
  if (queue.length >= BACKPRESSURE_THRESHOLD && streamRef && !streamRef.isPaused()) {
16351
- logger53.warn(
17211
+ logger55.warn(
16352
17212
  `[${site}][${gate}] Queue at ${queue.length}/${MAX_QUEUE_SIZE}, pausing stream`
16353
17213
  );
16354
17214
  streamRef.pause();
@@ -16365,7 +17225,7 @@ function useDahuaService() {
16365
17225
  if (streamRef && streamRef.isPaused()) {
16366
17226
  streamRef.resume();
16367
17227
  }
16368
- logger53.info(
17228
+ logger55.info(
16369
17229
  `[${site}][${gate}] BufferQueue destroyed. Processed=${processedChunks}, Dropped=${droppedChunks}`
16370
17230
  );
16371
17231
  }
@@ -16378,20 +17238,20 @@ function useDahuaService() {
16378
17238
  await handleBuffer(buffer);
16379
17239
  processedChunks++;
16380
17240
  if (queue.length <= RESUME_THRESHOLD && streamRef && streamRef.isPaused()) {
16381
- logger53.info(
17241
+ logger55.info(
16382
17242
  `[${site}][${gate}] Queue at ${queue.length}/${MAX_QUEUE_SIZE}, resuming stream`
16383
17243
  );
16384
17244
  streamRef.resume();
16385
17245
  }
16386
17246
  } catch (err) {
16387
- logger53.error(`[${site}][${gate}] Error processing buffer:`, err);
17247
+ logger55.error(`[${site}][${gate}] Error processing buffer:`, err);
16388
17248
  } finally {
16389
17249
  processing = false;
16390
17250
  processNext();
16391
17251
  }
16392
17252
  }
16393
17253
  async function processVehicleTransaction() {
16394
- logger53.info(
17254
+ logger55.info(
16395
17255
  `[${site}][${gate}] Vehicle transaction: Plate=${plateNumber}, UTC=${UTCData}, UTCMs=${UTCMs}`
16396
17256
  );
16397
17257
  let org = "";
@@ -16399,7 +17259,7 @@ function useDahuaService() {
16399
17259
  const theSite = await getSiteById(site);
16400
17260
  org = theSite?.orgId.toString() || "unknown";
16401
17261
  } catch (error) {
16402
- logger53.error(
17262
+ logger55.error(
16403
17263
  `[${site}][${gate}] Error fetching site for orgId:`,
16404
17264
  error
16405
17265
  );
@@ -16419,7 +17279,7 @@ function useDahuaService() {
16419
17279
  });
16420
17280
  }
16421
17281
  } catch (error) {
16422
- logger53.error(
17282
+ logger55.error(
16423
17283
  `[${site}][${gate}] Error closing existing open transaction:`,
16424
17284
  error
16425
17285
  );
@@ -16475,7 +17335,7 @@ function useDahuaService() {
16475
17335
  currentSnapshotField = "snapshotEntryImage";
16476
17336
  } catch (error) {
16477
17337
  console.log("failed to create visitor transaction", error);
16478
- logger53.error(
17338
+ logger55.error(
16479
17339
  `[${site}][${gate}] Error creating visitor transaction:`,
16480
17340
  error
16481
17341
  );
@@ -16559,7 +17419,7 @@ function useDahuaService() {
16559
17419
  try {
16560
17420
  await fsAsync.mkdir(dir, { recursive: true });
16561
17421
  await fsAsync.writeFile(snapFolder, accumulatedImageBuffer);
16562
- logger53.debug(`[${site}][${gate}] Saved image locally: ${filename}`);
17422
+ logger55.debug(`[${site}][${gate}] Saved image locally: ${filename}`);
16563
17423
  const fileId = await _createFile(
16564
17424
  {
16565
17425
  originalname: filename,
@@ -16568,7 +17428,7 @@ function useDahuaService() {
16568
17428
  },
16569
17429
  `anpr/${site}`
16570
17430
  );
16571
- logger53.info(
17431
+ logger55.info(
16572
17432
  `[${site}][${gate}] Created file record for image: ${fileId.toString()}`
16573
17433
  );
16574
17434
  if (currentTransactionId && currentSnapshotField) {
@@ -16576,23 +17436,23 @@ function useDahuaService() {
16576
17436
  [currentSnapshotField]: fileId.toString()
16577
17437
  });
16578
17438
  }
16579
- logger53.info(
17439
+ logger55.info(
16580
17440
  `[${site}][${gate}] Image stored with fileId: ${fileId.toString()}`
16581
17441
  );
16582
17442
  await fsAsync.unlink(snapFolder);
16583
- logger53.debug(`[${site}][${gate}] Deleted local file: ${filename}`);
17443
+ logger55.debug(`[${site}][${gate}] Deleted local file: ${filename}`);
16584
17444
  } catch (err) {
16585
- logger53.error(
17445
+ logger55.error(
16586
17446
  `[${site}][${gate}] Failed to process image ${filename}:`,
16587
17447
  err
16588
17448
  );
16589
17449
  try {
16590
17450
  await fsAsync.unlink(snapFolder);
16591
- logger53.debug(
17451
+ logger55.debug(
16592
17452
  `[${site}][${gate}] Cleaned up local file after error: ${filename}`
16593
17453
  );
16594
17454
  } catch (unlinkErr) {
16595
- logger53.error(
17455
+ logger55.error(
16596
17456
  `[${site}][${gate}] Failed to clean up local file: ${filename}`,
16597
17457
  unlinkErr
16598
17458
  );
@@ -16627,7 +17487,7 @@ function useDahuaService() {
16627
17487
  },
16628
17488
  "snapshots"
16629
17489
  );
16630
- logger53.info(`Successfully saved snapshot fileId: ${fileId.toString()}`);
17490
+ logger55.info(`Successfully saved snapshot fileId: ${fileId.toString()}`);
16631
17491
  return fileId;
16632
17492
  } catch (error) {
16633
17493
  throw error;
@@ -16646,7 +17506,7 @@ function useDahuaService() {
16646
17506
  const contentType = response.res.headers["content-type"];
16647
17507
  const boundaryMatch = contentType?.match(/boundary=(.*)$/i);
16648
17508
  const boundary = boundaryMatch ? `--${boundaryMatch[1]}` : "--myboundary";
16649
- logger53.debug(`[${site}][${gate}] Using boundary: ${boundary}`);
17509
+ logger55.debug(`[${site}][${gate}] Using boundary: ${boundary}`);
16650
17510
  const bufferQueue = useBufferQueue(
16651
17511
  boundary,
16652
17512
  site,
@@ -16658,23 +17518,23 @@ function useDahuaService() {
16658
17518
  );
16659
17519
  bufferQueue.setStream(response.res);
16660
17520
  if ([400, 401, 403, 500].includes(response.statusCode)) {
16661
- logger53.error(
17521
+ logger55.error(
16662
17522
  `[${site}][${gate}] Connection error:`,
16663
17523
  response.statusCode
16664
17524
  );
16665
- throw new BadRequestError72(
17525
+ throw new BadRequestError74(
16666
17526
  `Failed to connect to ANPR: ${response.statusCode}`
16667
17527
  );
16668
17528
  }
16669
17529
  if ([200, 201, 202].includes(response.statusCode)) {
16670
- logger53.info(`[${site}][${gate}] Successfully connected to ANPR.`);
17530
+ logger55.info(`[${site}][${gate}] Successfully connected to ANPR.`);
16671
17531
  console.log(`[${site}][${gate}] Successfully connected to ANPR.`);
16672
17532
  }
16673
17533
  response.res.on("data", (chunk) => {
16674
17534
  bufferQueue.enqueue(chunk);
16675
17535
  });
16676
17536
  const handleDisconnect = async (reason, err) => {
16677
- logger53.error(
17537
+ logger55.error(
16678
17538
  `[${site}][${gate}] ${reason}`,
16679
17539
  err ? err.code || err : ""
16680
17540
  );
@@ -16697,7 +17557,7 @@ function useDahuaService() {
16697
17557
  (err) => handleDisconnect("Connection error:", err)
16698
17558
  );
16699
17559
  } catch (error) {
16700
- logger53.error(
17560
+ logger55.error(
16701
17561
  `[${site}][${gate}] Initial connect error:`,
16702
17562
  error.code || error
16703
17563
  );
@@ -16706,20 +17566,20 @@ function useDahuaService() {
16706
17566
  }
16707
17567
  }
16708
17568
  async function addPlateNumber(value) {
16709
- const validation = Joi39.object({
16710
- host: Joi39.string().required(),
16711
- username: Joi39.string().required(),
16712
- password: Joi39.string().required(),
16713
- plateNumber: Joi39.string().required(),
16714
- mode: Joi39.string().valid(...Object.values(ANPRMode)).required(),
16715
- start: Joi39.string().isoDate().optional().allow("", null),
16716
- end: Joi39.string().isoDate().optional().allow("", null),
16717
- owner: Joi39.string().optional().allow("", null),
16718
- isOpenGate: Joi39.boolean().optional().allow(null)
17569
+ const validation = Joi40.object({
17570
+ host: Joi40.string().required(),
17571
+ username: Joi40.string().required(),
17572
+ password: Joi40.string().required(),
17573
+ plateNumber: Joi40.string().required(),
17574
+ mode: Joi40.string().valid(...Object.values(ANPRMode)).required(),
17575
+ start: Joi40.string().isoDate().optional().allow("", null),
17576
+ end: Joi40.string().isoDate().optional().allow("", null),
17577
+ owner: Joi40.string().optional().allow("", null),
17578
+ isOpenGate: Joi40.boolean().optional().allow(null)
16719
17579
  });
16720
17580
  const { error } = validation.validate(value);
16721
17581
  if (error) {
16722
- throw new BadRequestError72(`Validation error: ${error.message}`);
17582
+ throw new BadRequestError74(`Validation error: ${error.message}`);
16723
17583
  }
16724
17584
  value.owner = String(value.owner ?? "").substring(0, 15) || "unknown";
16725
17585
  const _openGate = String(value.isOpenGate);
@@ -16734,26 +17594,26 @@ function useDahuaService() {
16734
17594
  });
16735
17595
  return response;
16736
17596
  } catch (error2) {
16737
- logger53.error(`[${value.host}] Error adding plate number:`, error2);
16738
- throw new BadRequestError72(`Failed to add plate number: ${error2.message}`);
17597
+ logger55.error(`[${value.host}] Error adding plate number:`, error2);
17598
+ throw new BadRequestError74(`Failed to add plate number: ${error2.message}`);
16739
17599
  }
16740
17600
  }
16741
17601
  async function updatePlateNumber(value) {
16742
- const validation = Joi39.object({
16743
- host: Joi39.string().required(),
16744
- username: Joi39.string().required(),
16745
- password: Joi39.string().required(),
16746
- plateNumber: Joi39.string().required(),
16747
- mode: Joi39.string().valid(...Object.values(ANPRMode)).required(),
16748
- recno: Joi39.string().required(),
16749
- start: Joi39.string().isoDate().optional().allow("", null),
16750
- end: Joi39.string().isoDate().optional().allow("", null),
16751
- owner: Joi39.string().optional().allow("", null),
16752
- isOpenGate: Joi39.boolean().optional()
17602
+ const validation = Joi40.object({
17603
+ host: Joi40.string().required(),
17604
+ username: Joi40.string().required(),
17605
+ password: Joi40.string().required(),
17606
+ plateNumber: Joi40.string().required(),
17607
+ mode: Joi40.string().valid(...Object.values(ANPRMode)).required(),
17608
+ recno: Joi40.string().required(),
17609
+ start: Joi40.string().isoDate().optional().allow("", null),
17610
+ end: Joi40.string().isoDate().optional().allow("", null),
17611
+ owner: Joi40.string().optional().allow("", null),
17612
+ isOpenGate: Joi40.boolean().optional()
16753
17613
  });
16754
17614
  const { error } = validation.validate(value);
16755
17615
  if (error) {
16756
- throw new BadRequestError72(`Validation error: ${error.message}`);
17616
+ throw new BadRequestError74(`Validation error: ${error.message}`);
16757
17617
  }
16758
17618
  value.owner = value.owner || "unknown";
16759
17619
  let _isOpenGate;
@@ -16771,23 +17631,23 @@ function useDahuaService() {
16771
17631
  });
16772
17632
  return response;
16773
17633
  } catch (error2) {
16774
- logger53.error(`[${value.host}] Error updating plate number:`, error2);
16775
- throw new BadRequestError72(
17634
+ logger55.error(`[${value.host}] Error updating plate number:`, error2);
17635
+ throw new BadRequestError74(
16776
17636
  `Failed to update plate number: ${error2.message}`
16777
17637
  );
16778
17638
  }
16779
17639
  }
16780
17640
  async function removePlateNumber(value) {
16781
- const validation = Joi39.object({
16782
- host: Joi39.string().required(),
16783
- username: Joi39.string().required(),
16784
- password: Joi39.string().required(),
16785
- recno: Joi39.string().required(),
16786
- mode: Joi39.string().valid(...Object.values(ANPRMode)).required()
17641
+ const validation = Joi40.object({
17642
+ host: Joi40.string().required(),
17643
+ username: Joi40.string().required(),
17644
+ password: Joi40.string().required(),
17645
+ recno: Joi40.string().required(),
17646
+ mode: Joi40.string().valid(...Object.values(ANPRMode)).required()
16787
17647
  });
16788
17648
  const { error } = validation.validate(value);
16789
17649
  if (error) {
16790
- throw new BadRequestError72(`Validation error: ${error.message}`);
17650
+ throw new BadRequestError74(`Validation error: ${error.message}`);
16791
17651
  }
16792
17652
  try {
16793
17653
  const response = await useDahuaDigest({
@@ -16798,20 +17658,20 @@ function useDahuaService() {
16798
17658
  });
16799
17659
  return response;
16800
17660
  } catch (error2) {
16801
- logger53.error(`[${value.host}] Error removing plate number:`, error2);
17661
+ logger55.error(`[${value.host}] Error removing plate number:`, error2);
16802
17662
  }
16803
17663
  }
16804
17664
  async function getPlateNumber(value) {
16805
- const validation = Joi39.object({
16806
- host: Joi39.string().required(),
16807
- username: Joi39.string().required(),
16808
- password: Joi39.string().required(),
16809
- plateNumber: Joi39.string().required(),
16810
- mode: Joi39.string().valid(...Object.values(ANPRMode)).required()
17665
+ const validation = Joi40.object({
17666
+ host: Joi40.string().required(),
17667
+ username: Joi40.string().required(),
17668
+ password: Joi40.string().required(),
17669
+ plateNumber: Joi40.string().required(),
17670
+ mode: Joi40.string().valid(...Object.values(ANPRMode)).required()
16811
17671
  });
16812
17672
  const { error } = validation.validate(value);
16813
17673
  if (error) {
16814
- throw new BadRequestError72(`Validation error: ${error.message}`);
17674
+ throw new BadRequestError74(`Validation error: ${error.message}`);
16815
17675
  }
16816
17676
  try {
16817
17677
  const response = await useDahuaDigest({
@@ -16823,27 +17683,27 @@ function useDahuaService() {
16823
17683
  const text = response?.data?.toString?.("utf-8");
16824
17684
  return text;
16825
17685
  } catch (error2) {
16826
- logger53.error(`[${value.host}] Error finding plate number:`, error2);
17686
+ logger55.error(`[${value.host}] Error finding plate number:`, error2);
16827
17687
  throw error2;
16828
17688
  }
16829
17689
  }
16830
17690
  async function bulkInsertPlateNumber(value) {
16831
- const validation = Joi39.object({
16832
- host: Joi39.string().required(),
16833
- username: Joi39.string().required(),
16834
- password: Joi39.string().required(),
16835
- plateNumber: Joi39.string().required(),
16836
- mode: Joi39.string().valid(...Object.values(ANPRMode)).required(),
16837
- start: Joi39.string().isoDate().optional().allow("", null),
16838
- end: Joi39.string().isoDate().optional().allow("", null),
16839
- owner: Joi39.string().optional().allow("", null),
16840
- isOpenGate: Joi39.boolean().optional().allow(null),
16841
- vehicleType: Joi39.string().optional().allow("", null),
16842
- vehicleColor: Joi39.string().optional().allow("", null)
17691
+ const validation = Joi40.object({
17692
+ host: Joi40.string().required(),
17693
+ username: Joi40.string().required(),
17694
+ password: Joi40.string().required(),
17695
+ plateNumber: Joi40.string().required(),
17696
+ mode: Joi40.string().valid(...Object.values(ANPRMode)).required(),
17697
+ start: Joi40.string().isoDate().optional().allow("", null),
17698
+ end: Joi40.string().isoDate().optional().allow("", null),
17699
+ owner: Joi40.string().optional().allow("", null),
17700
+ isOpenGate: Joi40.boolean().optional().allow(null),
17701
+ vehicleType: Joi40.string().optional().allow("", null),
17702
+ vehicleColor: Joi40.string().optional().allow("", null)
16843
17703
  });
16844
17704
  const { error } = validation.validate(value);
16845
17705
  if (error) {
16846
- throw new BadRequestError72(`Validation error: ${error.message}`);
17706
+ throw new BadRequestError74(`Validation error: ${error.message}`);
16847
17707
  }
16848
17708
  value.owner = String(value.owner ?? "").substring(0, 15) || "unknown";
16849
17709
  value.vehicleType = String(value.vehicleType ?? "").substring(0, 31) || "unknown";
@@ -16860,8 +17720,8 @@ function useDahuaService() {
16860
17720
  });
16861
17721
  return response;
16862
17722
  } catch (error2) {
16863
- logger53.error(`[${value.host}] Error bulk add plate number:`, error2);
16864
- throw new BadRequestError72(
17723
+ logger55.error(`[${value.host}] Error bulk add plate number:`, error2);
17724
+ throw new BadRequestError74(
16865
17725
  `Failed bulk adding plate number: ${error2.message}`
16866
17726
  );
16867
17727
  }
@@ -16900,10 +17760,10 @@ function useSiteService() {
16900
17760
  } = useVisitorTransactionRepo();
16901
17761
  const { updatePlateNumber: _updatePlateNumber } = useDahuaService();
16902
17762
  async function createSite(value) {
16903
- const session = useAtlas35.getClient()?.startSession();
17763
+ const session = useAtlas36.getClient()?.startSession();
16904
17764
  session?.startTransaction();
16905
17765
  if (value.orgId && typeof value.orgId === "string" && value.orgId.length !== 24) {
16906
- throw new BadRequestError73("Invalid orgId format.");
17766
+ throw new BadRequestError75("Invalid orgId format.");
16907
17767
  }
16908
17768
  try {
16909
17769
  if (value.orgId)
@@ -16932,27 +17792,27 @@ function useSiteService() {
16932
17792
  }
16933
17793
  }
16934
17794
  async function updateGuardPostById(site, guardPost) {
16935
- const { error } = Joi40.object({
16936
- site: Joi40.string().hex().required(),
16937
- guardPost: Joi40.number().integer().min(0).required()
17795
+ const { error } = Joi41.object({
17796
+ site: Joi41.string().hex().required(),
17797
+ guardPost: Joi41.number().integer().min(0).required()
16938
17798
  }).validate({ site, guardPost });
16939
17799
  if (error) {
16940
- throw new BadRequestError73(error.message);
17800
+ throw new BadRequestError75(error.message);
16941
17801
  }
16942
17802
  try {
16943
17803
  const siteData = await _getSiteById(site);
16944
17804
  if (!siteData) {
16945
- throw new BadRequestError73("Site does not exist.");
17805
+ throw new BadRequestError75("Site does not exist.");
16946
17806
  }
16947
17807
  if (siteData.metadata?.guardPosts === guardPost) {
16948
- throw new BadRequestError73(`Guard post is already set to ${guardPost}.`);
17808
+ throw new BadRequestError75(`Guard post is already set to ${guardPost}.`);
16949
17809
  }
16950
17810
  const guardPosts = siteData?.metadata?.guardPosts ?? 0;
16951
17811
  if (guardPost < guardPosts) {
16952
17812
  const siteCamera = await getBySiteGuardPost(site, guardPost);
16953
- logger54.info("siteCamera: " + JSON.stringify(siteCamera));
17813
+ logger56.info("siteCamera: " + JSON.stringify(siteCamera));
16954
17814
  if (siteCamera) {
16955
- throw new BadRequestError73(
17815
+ throw new BadRequestError75(
16956
17816
  `Failed to update guard post, an ANPR camera is assigned to guard post 1-${siteData?.metadata?.guardPosts}.`
16957
17817
  );
16958
17818
  }
@@ -16964,14 +17824,14 @@ function useSiteService() {
16964
17824
  });
16965
17825
  await deleteSiteCameraCache();
16966
17826
  } catch (error2) {
16967
- if (error2 instanceof AppError11) {
17827
+ if (error2 instanceof AppError12) {
16968
17828
  throw error2;
16969
17829
  }
16970
- throw new BadRequestError73("Failed to update guard post.");
17830
+ throw new BadRequestError75("Failed to update guard post.");
16971
17831
  }
16972
17832
  }
16973
17833
  async function updateById(_id, payload) {
16974
- const session = useAtlas35.getClient()?.startSession();
17834
+ const session = useAtlas36.getClient()?.startSession();
16975
17835
  if (!session) {
16976
17836
  throw new Error("Unable to start session for vehicle service.");
16977
17837
  }
@@ -17029,7 +17889,7 @@ function useSiteService() {
17029
17889
  } catch (error) {
17030
17890
  console.log(error);
17031
17891
  session?.abortTransaction();
17032
- throw new BadRequestError73("Failed to update site.");
17892
+ throw new BadRequestError75("Failed to update site.");
17033
17893
  } finally {
17034
17894
  session.endSession();
17035
17895
  }
@@ -17039,7 +17899,7 @@ function useSiteService() {
17039
17899
  const result = await _siteInformation({ id, payload });
17040
17900
  return result;
17041
17901
  } catch (error) {
17042
- throw new BadRequestError73("Failed to update site information.");
17902
+ throw new BadRequestError75("Failed to update site information.");
17043
17903
  }
17044
17904
  }
17045
17905
  return {
@@ -17051,8 +17911,8 @@ function useSiteService() {
17051
17911
  }
17052
17912
 
17053
17913
  // src/controllers/site.controller.ts
17054
- import { BadRequestError as BadRequestError74, logger as logger55 } from "@7365admin1/node-server-utils";
17055
- import Joi41 from "joi";
17914
+ import { BadRequestError as BadRequestError76, logger as logger57 } from "@7365admin1/node-server-utils";
17915
+ import Joi42 from "joi";
17056
17916
  function useSiteController() {
17057
17917
  const { createSite: _createSite, updateById: _updateById } = useSiteService();
17058
17918
  const {
@@ -17069,8 +17929,8 @@ function useSiteController() {
17069
17929
  });
17070
17930
  if (error) {
17071
17931
  const messages = error.details.map((d) => d.message);
17072
- logger55.log({ level: "error", message: messages.join(", ") });
17073
- next(new BadRequestError74(messages.join(", ")));
17932
+ logger57.log({ level: "error", message: messages.join(", ") });
17933
+ next(new BadRequestError76(messages.join(", ")));
17074
17934
  return;
17075
17935
  }
17076
17936
  try {
@@ -17078,7 +17938,7 @@ function useSiteController() {
17078
17938
  res.status(201).json(data);
17079
17939
  return;
17080
17940
  } catch (error2) {
17081
- logger55.log({ level: "error", message: error2.message });
17941
+ logger57.log({ level: "error", message: error2.message });
17082
17942
  next(error2);
17083
17943
  return;
17084
17944
  }
@@ -17086,19 +17946,19 @@ function useSiteController() {
17086
17946
  async function getSites(req, res, next) {
17087
17947
  const allowedFields = ["createdAt", "name"];
17088
17948
  const allowedOrder = ["asc", "desc"];
17089
- const validation = Joi41.object({
17090
- search: Joi41.string().optional().allow("", null),
17091
- page: Joi41.number().integer().min(1).allow("", null).default(1),
17092
- limit: Joi41.number().integer().min(1).max(100).allow("", null).default(10),
17093
- sort: Joi41.string().pattern(/^([a-zA-Z0-9_]+)(,[a-zA-Z0-9_]+)*$/).optional().allow("", ...allowedFields),
17094
- order: Joi41.string().pattern(/^(asc|desc)(,(asc|desc))*$/).optional().allow("", ...allowedOrder),
17095
- org: Joi41.string().hex().required()
17949
+ const validation = Joi42.object({
17950
+ search: Joi42.string().optional().allow("", null),
17951
+ page: Joi42.number().integer().min(1).allow("", null).default(1),
17952
+ limit: Joi42.number().integer().min(1).max(100).allow("", null).default(10),
17953
+ sort: Joi42.string().pattern(/^([a-zA-Z0-9_]+)(,[a-zA-Z0-9_]+)*$/).optional().allow("", ...allowedFields),
17954
+ order: Joi42.string().pattern(/^(asc|desc)(,(asc|desc))*$/).optional().allow("", ...allowedOrder),
17955
+ org: Joi42.string().hex().required()
17096
17956
  });
17097
17957
  const query = { ...req.query };
17098
17958
  const { error } = validation.validate(query);
17099
17959
  if (error) {
17100
- logger55.log({ level: "error", message: error.message });
17101
- next(new BadRequestError74(error.message));
17960
+ logger57.log({ level: "error", message: error.message });
17961
+ next(new BadRequestError76(error.message));
17102
17962
  return;
17103
17963
  }
17104
17964
  const search = req.query.search ?? "";
@@ -17125,18 +17985,18 @@ function useSiteController() {
17125
17985
  res.json(data);
17126
17986
  return;
17127
17987
  } catch (error2) {
17128
- logger55.log({ level: "error", message: error2.message });
17988
+ logger57.log({ level: "error", message: error2.message });
17129
17989
  next(error2);
17130
17990
  return;
17131
17991
  }
17132
17992
  }
17133
17993
  async function getSiteById(req, res, next) {
17134
- const validation = Joi41.string().hex().required();
17994
+ const validation = Joi42.string().hex().required();
17135
17995
  const _id = req.params.id;
17136
17996
  const { error } = validation.validate(_id);
17137
17997
  if (error) {
17138
- logger55.log({ level: "error", message: error.message });
17139
- next(new BadRequestError74(error.message));
17998
+ logger57.log({ level: "error", message: error.message });
17999
+ next(new BadRequestError76(error.message));
17140
18000
  return;
17141
18001
  }
17142
18002
  try {
@@ -17144,22 +18004,22 @@ function useSiteController() {
17144
18004
  res.json(site);
17145
18005
  return;
17146
18006
  } catch (error2) {
17147
- logger55.log({ level: "error", message: error2.message });
18007
+ logger57.log({ level: "error", message: error2.message });
17148
18008
  next(error2);
17149
18009
  return;
17150
18010
  }
17151
18011
  }
17152
18012
  async function updateSiteBlock(req, res, next) {
17153
- const validation = Joi41.object({
17154
- _id: Joi41.string().hex().required(),
17155
- block: Joi41.number().integer().min(0).required()
18013
+ const validation = Joi42.object({
18014
+ _id: Joi42.string().hex().required(),
18015
+ block: Joi42.number().integer().min(0).required()
17156
18016
  });
17157
18017
  const _id = req.params.id;
17158
18018
  const block = req.body.block;
17159
18019
  const { error } = validation.validate({ _id, block });
17160
18020
  if (error) {
17161
- logger55.log({ level: "error", message: error.message });
17162
- next(new BadRequestError74(error.message));
18021
+ logger57.log({ level: "error", message: error.message });
18022
+ next(new BadRequestError76(error.message));
17163
18023
  return;
17164
18024
  }
17165
18025
  try {
@@ -17167,18 +18027,18 @@ function useSiteController() {
17167
18027
  res.json({ message: "Successfully updated site block." });
17168
18028
  return;
17169
18029
  } catch (error2) {
17170
- logger55.log({ level: "error", message: error2.message });
18030
+ logger57.log({ level: "error", message: error2.message });
17171
18031
  next(error2);
17172
18032
  return;
17173
18033
  }
17174
18034
  }
17175
18035
  async function deleteSite(req, res, next) {
17176
- const validation = Joi41.string().hex().required();
18036
+ const validation = Joi42.string().hex().required();
17177
18037
  const _id = req.params.id;
17178
18038
  const { error } = validation.validate(_id);
17179
18039
  if (error) {
17180
- logger55.log({ level: "error", message: error.message });
17181
- next(new BadRequestError74(error.message));
18040
+ logger57.log({ level: "error", message: error.message });
18041
+ next(new BadRequestError76(error.message));
17182
18042
  return;
17183
18043
  }
17184
18044
  try {
@@ -17186,7 +18046,7 @@ function useSiteController() {
17186
18046
  res.json({ message: "Successfully deleted site." });
17187
18047
  return;
17188
18048
  } catch (error2) {
17189
- logger55.log({ level: "error", message: error2.message });
18049
+ logger57.log({ level: "error", message: error2.message });
17190
18050
  next(error2);
17191
18051
  return;
17192
18052
  }
@@ -17199,8 +18059,8 @@ function useSiteController() {
17199
18059
  );
17200
18060
  if (error) {
17201
18061
  const messages = error.details.map((d) => d.message);
17202
- logger55.log({ level: "error", message: messages.join(", ") });
17203
- next(new BadRequestError74(messages.join(", ")));
18062
+ logger57.log({ level: "error", message: messages.join(", ") });
18063
+ next(new BadRequestError76(messages.join(", ")));
17204
18064
  return;
17205
18065
  }
17206
18066
  const { _id, ...rest } = value;
@@ -17208,22 +18068,22 @@ function useSiteController() {
17208
18068
  res.json({ message: "Successfully updated site." });
17209
18069
  return;
17210
18070
  } catch (error) {
17211
- logger55.log({ level: "error", message: error.message });
18071
+ logger57.log({ level: "error", message: error.message });
17212
18072
  next(error);
17213
18073
  return;
17214
18074
  }
17215
18075
  }
17216
18076
  async function updateGuardPostsById(req, res, next) {
17217
- const validation = Joi41.object({
17218
- _id: Joi41.string().hex().required(),
17219
- guardPost: Joi41.number().integer().min(0).required()
18077
+ const validation = Joi42.object({
18078
+ _id: Joi42.string().hex().required(),
18079
+ guardPost: Joi42.number().integer().min(0).required()
17220
18080
  });
17221
18081
  const _id = req.params.id ?? "";
17222
18082
  const guardPost = req.body.guardPost ?? 0;
17223
18083
  const { error } = validation.validate({ _id, guardPost });
17224
18084
  if (error) {
17225
- logger55.log({ level: "error", message: error.message });
17226
- next(new BadRequestError74(error.message));
18085
+ logger57.log({ level: "error", message: error.message });
18086
+ next(new BadRequestError76(error.message));
17227
18087
  return;
17228
18088
  }
17229
18089
  try {
@@ -17231,7 +18091,7 @@ function useSiteController() {
17231
18091
  res.json({ message: "Successfully updated site." });
17232
18092
  return;
17233
18093
  } catch (error2) {
17234
- logger55.log({ level: "error", message: error2.message });
18094
+ logger57.log({ level: "error", message: error2.message });
17235
18095
  next(error2);
17236
18096
  return;
17237
18097
  }
@@ -17240,21 +18100,21 @@ function useSiteController() {
17240
18100
  try {
17241
18101
  const payload = req.body;
17242
18102
  const id = req.params.id;
17243
- const { error, value } = Joi41.object({
17244
- id: Joi41.string().hex().required(),
17245
- bgImage: Joi41.string().optional().allow("", null),
17246
- description: Joi41.string().optional().allow("", null),
17247
- docs: Joi41.array().items(Joi41.object({
17248
- id: Joi41.string().hex().optional().allow("", null),
17249
- name: Joi41.string().optional().allow("", null)
18103
+ const { error, value } = Joi42.object({
18104
+ id: Joi42.string().hex().required(),
18105
+ bgImage: Joi42.string().optional().allow("", null),
18106
+ description: Joi42.string().optional().allow("", null),
18107
+ docs: Joi42.array().items(Joi42.object({
18108
+ id: Joi42.string().hex().optional().allow("", null),
18109
+ name: Joi42.string().optional().allow("", null)
17250
18110
  })).optional().allow("", null)
17251
18111
  }).validate(
17252
18112
  { id, ...payload },
17253
18113
  { abortEarly: false }
17254
18114
  );
17255
18115
  if (error) {
17256
- logger55.log({ level: "error", message: error.message });
17257
- next(new BadRequestError74(error.message));
18116
+ logger57.log({ level: "error", message: error.message });
18117
+ next(new BadRequestError76(error.message));
17258
18118
  return;
17259
18119
  }
17260
18120
  const { id: siteId, ...rest } = value;
@@ -17262,7 +18122,7 @@ function useSiteController() {
17262
18122
  res.json({ message: "Successfully updated site.", data: result });
17263
18123
  return;
17264
18124
  } catch (error) {
17265
- logger55.log({ level: "error", message: error.message });
18125
+ logger57.log({ level: "error", message: error.message });
17266
18126
  next(error);
17267
18127
  return;
17268
18128
  }
@@ -17280,42 +18140,42 @@ function useSiteController() {
17280
18140
  }
17281
18141
 
17282
18142
  // src/models/chat.model.ts
17283
- import { BadRequestError as BadRequestError75, logger as logger56 } from "@7365admin1/node-server-utils";
17284
- import Joi42 from "joi";
17285
- import { ObjectId as ObjectId46 } from "mongodb";
17286
- var chatSchema = Joi42.object({
17287
- attachments: Joi42.array().items(Joi42.string()).optional(),
17288
- type: Joi42.string().required(),
17289
- comment: Joi42.string().required(),
17290
- feedbackId: Joi42.string().hex().optional().allow("", null),
17291
- workOrderId: Joi42.string().hex().optional().allow("", null),
17292
- createdBy: Joi42.string().hex().required()
18143
+ import { BadRequestError as BadRequestError77, logger as logger58 } from "@7365admin1/node-server-utils";
18144
+ import Joi43 from "joi";
18145
+ import { ObjectId as ObjectId48 } from "mongodb";
18146
+ var chatSchema = Joi43.object({
18147
+ attachments: Joi43.array().items(Joi43.string()).optional(),
18148
+ type: Joi43.string().required(),
18149
+ comment: Joi43.string().required(),
18150
+ feedbackId: Joi43.string().hex().optional().allow("", null),
18151
+ workOrderId: Joi43.string().hex().optional().allow("", null),
18152
+ createdBy: Joi43.string().hex().required()
17293
18153
  });
17294
18154
  function MChat(value) {
17295
18155
  const { error } = chatSchema.validate(value);
17296
18156
  if (error) {
17297
- logger56.log({ level: "error", message: error.message });
17298
- throw new BadRequestError75(error.message);
18157
+ logger58.log({ level: "error", message: error.message });
18158
+ throw new BadRequestError77(error.message);
17299
18159
  }
17300
18160
  if (value.feedbackId) {
17301
18161
  try {
17302
- value.feedbackId = new ObjectId46(value.feedbackId);
18162
+ value.feedbackId = new ObjectId48(value.feedbackId);
17303
18163
  } catch (error2) {
17304
- throw new BadRequestError75("Invalid feedback ID format.");
18164
+ throw new BadRequestError77("Invalid feedback ID format.");
17305
18165
  }
17306
18166
  }
17307
18167
  if (value.workOrderId) {
17308
18168
  try {
17309
- value.workOrderId = new ObjectId46(value.workOrderId);
18169
+ value.workOrderId = new ObjectId48(value.workOrderId);
17310
18170
  } catch (error2) {
17311
- throw new BadRequestError75("Invalid work order ID format.");
18171
+ throw new BadRequestError77("Invalid work order ID format.");
17312
18172
  }
17313
18173
  }
17314
18174
  if (value.createdBy) {
17315
18175
  try {
17316
- value.createdBy = new ObjectId46(value.createdBy);
18176
+ value.createdBy = new ObjectId48(value.createdBy);
17317
18177
  } catch (error2) {
17318
- throw new BadRequestError75("Invalid created by ID format.");
18178
+ throw new BadRequestError77("Invalid created by ID format.");
17319
18179
  }
17320
18180
  }
17321
18181
  return {
@@ -17332,553 +18192,67 @@ function MChat(value) {
17332
18192
 
17333
18193
  // src/repositories/chat.repo.ts
17334
18194
  import {
17335
- useAtlas as useAtlas36,
17336
- InternalServerError as InternalServerError27,
17337
- useCache as useCache27,
17338
- logger as logger57
18195
+ useAtlas as useAtlas37,
18196
+ InternalServerError as InternalServerError28,
18197
+ useCache as useCache28,
18198
+ logger as logger59
17339
18199
  } from "@7365admin1/node-server-utils";
17340
18200
  function useChatRepo() {
17341
- const db = useAtlas36.getDb();
18201
+ const db = useAtlas37.getDb();
17342
18202
  if (!db) {
17343
- throw new InternalServerError27("Unable to connect to server.");
18203
+ throw new InternalServerError28("Unable to connect to server.");
17344
18204
  }
17345
18205
  const namespace_collection = "chats";
17346
18206
  const collection = db.collection(namespace_collection);
17347
- const { delNamespace } = useCache27(namespace_collection);
18207
+ const { delNamespace } = useCache28(namespace_collection);
17348
18208
  async function createChat(value, session) {
17349
18209
  try {
17350
18210
  value = MChat(value);
17351
18211
  const res = await collection.insertOne(value, { session });
17352
18212
  delNamespace().then(() => {
17353
- logger57.info(`Cache cleared for namespace: ${namespace_collection}`);
18213
+ logger59.info(`Cache cleared for namespace: ${namespace_collection}`);
17354
18214
  }).catch((err) => {
17355
- logger57.error(
18215
+ logger59.error(
17356
18216
  `Failed to clear cache for namespace: ${namespace_collection}`,
17357
18217
  err
17358
- );
17359
- });
17360
- return res.insertedId;
17361
- } catch (error) {
17362
- throw error;
17363
- }
17364
- }
17365
- return {
17366
- createChat
17367
- };
17368
- }
17369
-
17370
- // src/controllers/chat.controller.ts
17371
- import { BadRequestError as BadRequestError76, logger as logger58 } from "@7365admin1/node-server-utils";
17372
- function useChatController() {
17373
- const { createChat: _createChat } = useChatRepo();
17374
- async function createChat(req, res, next) {
17375
- const payload = { ...req.body };
17376
- const { error } = chatSchema.validate(payload);
17377
- if (error) {
17378
- logger58.log({ level: "error", message: error.message });
17379
- next(new BadRequestError76(error.message));
17380
- return;
17381
- }
17382
- try {
17383
- await _createChat({ ...payload });
17384
- res.status(201).json({ message: "Successfully created chat." });
17385
- return;
17386
- } catch (error2) {
17387
- logger58.log({ level: "error", message: error2.message });
17388
- next(error2);
17389
- return;
17390
- }
17391
- }
17392
- return { createChat };
17393
- }
17394
-
17395
- // src/models/building.model.ts
17396
- import { BadRequestError as BadRequestError77, logger as logger59 } from "@7365admin1/node-server-utils";
17397
- import Joi43 from "joi";
17398
- import { ObjectId as ObjectId47 } from "mongodb";
17399
- var SortFields = /* @__PURE__ */ ((SortFields2) => {
17400
- SortFields2["ID"] = "_id";
17401
- SortFields2["CREATED_AT"] = "createdAt";
17402
- SortFields2["NAME"] = "name";
17403
- return SortFields2;
17404
- })(SortFields || {});
17405
- var SortOrder = /* @__PURE__ */ ((SortOrder2) => {
17406
- SortOrder2["ASC"] = "asc";
17407
- SortOrder2["DESC"] = "desc";
17408
- return SortOrder2;
17409
- })(SortOrder || {});
17410
- var BuildingStatus = /* @__PURE__ */ ((BuildingStatus2) => {
17411
- BuildingStatus2["ACTIVE"] = "active";
17412
- BuildingStatus2["PENDING"] = "pending";
17413
- return BuildingStatus2;
17414
- })(BuildingStatus || {});
17415
- var schemaBuilding = Joi43.object({
17416
- _id: Joi43.string().hex().optional(),
17417
- site: Joi43.string().hex().required(),
17418
- name: Joi43.string().required(),
17419
- block: Joi43.number().integer().min(1).required(),
17420
- levels: Joi43.array().items(Joi43.string().required()).min(1).required(),
17421
- createdAt: Joi43.date().optional().allow("", null),
17422
- updatedAt: Joi43.date().optional().allow("", null),
17423
- deletedAt: Joi43.date().optional().allow("", null),
17424
- status: Joi43.string().optional().allow("", null),
17425
- // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
17426
- buildingFiles: Joi43.array().items({ id: Joi43.string().hex().optional().allow("", null), name: Joi43.string().optional().allow("", null) }).optional().allow("", null)
17427
- });
17428
- var schemaBuildingUpdateOptions = Joi43.object({
17429
- name: Joi43.string().optional().allow("", null),
17430
- levels: Joi43.array().items(Joi43.string().required()).min(1).required(),
17431
- block: Joi43.number().integer().min(1).required(),
17432
- // buildingFloorPlan: Joi.array().items(Joi.string()).optional(),
17433
- buildingFiles: Joi43.array().items({ id: Joi43.string().hex().optional().allow("", null), name: Joi43.string().optional().allow("", null) }).optional().allow("", null)
17434
- });
17435
- var schemaBilling = Joi43.object({
17436
- _id: Joi43.string().hex().optional(),
17437
- name: Joi43.string().optional().allow("", null)
17438
- });
17439
- var schemaBuildingUnit = Joi43.object({
17440
- _id: Joi43.string().hex().optional(),
17441
- site: Joi43.string().hex().required(),
17442
- name: Joi43.string().optional().allow("", null),
17443
- building: Joi43.string().hex().required(),
17444
- buildingName: Joi43.string().optional().allow("", null),
17445
- block: Joi43.number().integer().min(1).required(),
17446
- level: Joi43.string().required(),
17447
- category: Joi43.string().optional().allow(null, ""),
17448
- status: Joi43.string().optional().allow("", null),
17449
- buildingUnitFiles: Joi43.array().items(Joi43.string()).optional().allow("", null),
17450
- companyName: Joi43.string().optional().allow("", null),
17451
- companyRegistrationNumber: Joi43.string().optional().allow("", null),
17452
- leaseStart: Joi43.date().optional(),
17453
- leaseEnd: Joi43.date().optional(),
17454
- owner: Joi43.string().hex().optional().allow("", null),
17455
- ownerName: Joi43.string().optional().allow("", null),
17456
- billing: Joi43.array().items(schemaBilling).optional().allow("", null)
17457
- });
17458
- var schemaUpdateOptions = Joi43.object({
17459
- name: Joi43.string().optional().allow("", null),
17460
- building: Joi43.string().hex().optional().allow("", null),
17461
- buildingName: Joi43.string().optional().allow("", null),
17462
- block: Joi43.number().integer().min(1).optional().allow("", null),
17463
- level: Joi43.string().optional().allow("", null),
17464
- category: Joi43.string().optional().allow("", null),
17465
- buildingUnitFiles: Joi43.array().items({ id: Joi43.string().hex().optional().allow("", null), name: Joi43.string().optional().allow("", null) }).optional().allow("", null),
17466
- companyName: Joi43.string().optional().allow("", null),
17467
- companyRegistrationNumber: Joi43.string().optional().allow("", null),
17468
- leaseStart: Joi43.date().optional().allow("", null),
17469
- leaseEnd: Joi43.date().optional().allow("", null),
17470
- owner: Joi43.string().hex().optional().allow("", null),
17471
- ownerName: Joi43.string().optional().allow("", null),
17472
- billing: Joi43.array().items(schemaBilling).optional().allow("", null)
17473
- });
17474
- function MBuilding(value) {
17475
- const { error } = schemaBuilding.validate(value);
17476
- if (error) {
17477
- logger59.info(`Building Model: ${error.message}`);
17478
- throw new BadRequestError77(error.message);
17479
- }
17480
- if (value._id && typeof value._id === "string") {
17481
- try {
17482
- value._id = new ObjectId47(value._id);
17483
- } catch (error2) {
17484
- throw new BadRequestError77("Invalid _id format");
17485
- }
17486
- }
17487
- try {
17488
- value.site = new ObjectId47(value.site);
17489
- } catch (error2) {
17490
- throw new BadRequestError77("Invalid site format");
17491
- }
17492
- return {
17493
- _id: value._id ?? void 0,
17494
- site: value.site,
17495
- name: value.name ?? "",
17496
- block: value.block ?? 0,
17497
- levels: value.levels ?? "",
17498
- status: value.status ?? "active",
17499
- // buildingFloorPlan: value.buildingFloorPlan ?? [],
17500
- buildingFiles: value.buildingFiles ?? [],
17501
- createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
17502
- updatedAt: value.updatedAt ?? "",
17503
- deletedAt: value.deletedAt ?? ""
17504
- };
17505
- }
17506
- function MBuildingUnit(value) {
17507
- const { error } = schemaBuildingUnit.validate(value);
17508
- if (error) {
17509
- logger59.info(`Building Unit Model: ${error.message}`);
17510
- throw new BadRequestError77(error.message);
17511
- }
17512
- if (value._id && typeof value._id === "string") {
17513
- try {
17514
- value._id = new ObjectId47(value._id);
17515
- } catch (error2) {
17516
- throw new BadRequestError77("Invalid ID");
17517
- }
17518
- }
17519
- try {
17520
- value.site = new ObjectId47(value.site);
17521
- } catch (error2) {
17522
- throw new BadRequestError77("Invalid site ID");
17523
- }
17524
- try {
17525
- value.building = new ObjectId47(value.building);
17526
- } catch (error2) {
17527
- throw new BadRequestError77("Invalid building ID");
17528
- }
17529
- if (value.owner && typeof value.owner === "string") {
17530
- try {
17531
- value.owner = new ObjectId47(value.owner);
17532
- } catch (error2) {
17533
- throw new BadRequestError77("Invalid Owner ID");
17534
- }
17535
- }
17536
- if (value.billing && Array.isArray(value.billing)) {
17537
- value.billing = value.billing.map((billing) => {
17538
- if (billing._id && typeof billing._id === "string") {
17539
- try {
17540
- billing._id = new ObjectId47(billing._id);
17541
- } catch {
17542
- throw new BadRequestError77("Invalid billing id format");
17543
- }
17544
- }
17545
- return billing;
17546
- });
17547
- }
17548
- return {
17549
- _id: value._id ?? void 0,
17550
- site: value.site,
17551
- name: value.name ?? "",
17552
- building: value.building,
17553
- buildingName: value.buildingName ?? "",
17554
- block: value.block ?? 0,
17555
- level: value.level ?? "",
17556
- category: value.category ?? "",
17557
- status: value.status ?? "active",
17558
- buildingUnitFiles: value.buildingUnitFiles ?? [],
17559
- owner: value.owner ?? "",
17560
- ownerName: value.ownerName ?? "",
17561
- createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
17562
- updatedAt: value.updatedAt ?? "",
17563
- deletedAt: value.deletedAt ?? "",
17564
- companyName: value.companyName ?? "",
17565
- companyRegistrationNumber: value.companyRegistrationNumber ?? "",
17566
- leaseStart: value.leaseStart ?? "",
17567
- leaseEnd: value.leaseEnd ?? "",
17568
- billing: value.billing ?? []
17569
- };
17570
- }
17571
-
17572
- // src/repositories/building.repository.ts
17573
- import {
17574
- AppError as AppError12,
17575
- BadRequestError as BadRequestError78,
17576
- InternalServerError as InternalServerError28,
17577
- logger as logger60,
17578
- makeCacheKey as makeCacheKey26,
17579
- paginate as paginate21,
17580
- useAtlas as useAtlas37,
17581
- useCache as useCache28
17582
- } from "@7365admin1/node-server-utils";
17583
- import { ObjectId as ObjectId48 } from "mongodb";
17584
- var buildings_namespace_collection = "buildings";
17585
- function useBuildingRepo() {
17586
- const db = useAtlas37.getDb();
17587
- if (!db) {
17588
- throw new Error("Unable to connect to server.");
17589
- }
17590
- const collection = db.collection(buildings_namespace_collection);
17591
- const { getCache, setCache, delNamespace } = useCache28(
17592
- buildings_namespace_collection
17593
- );
17594
- async function createIndexes() {
17595
- try {
17596
- await collection.createIndexes([
17597
- { key: { name: "text" }, name: "text-index" },
17598
- { key: { name: 1 }, unique: true, name: "unique-name-index" },
17599
- { key: { site: 1 } },
17600
- { key: { createdAt: 1 } },
17601
- {
17602
- key: { site: 1, block: 1 },
17603
- unique: true,
17604
- name: "unique-site-block-active",
17605
- partialFilterExpression: {
17606
- status: "active" /* ACTIVE */
17607
- }
17608
- }
17609
- ]);
17610
- } catch (error) {
17611
- throw new Error("Failed to create index on buildings. " + error.message);
17612
- }
17613
- }
17614
- async function add(value, session) {
17615
- try {
17616
- value = MBuilding(value);
17617
- const res = await collection.insertOne(value, { session });
17618
- delCachedData();
17619
- return res.insertedId;
17620
- } catch (error) {
17621
- logger60.log({
17622
- level: "error",
17623
- message: error.message
17624
- });
17625
- const isDuplicated = error.message.includes("duplicate");
17626
- if (isDuplicated) {
17627
- throw new BadRequestError78("Building already exists.");
17628
- }
17629
- if (error instanceof AppError12) {
17630
- throw error;
17631
- } else {
17632
- throw new Error("Failed to create building.");
17633
- }
17634
- }
17635
- }
17636
- async function updateById(_id, value, session) {
17637
- const { error } = schemaBuildingUpdateOptions.validate(value);
17638
- if (error) {
17639
- logger60.info(`Building Repository: ${error.message}`);
17640
- throw new BadRequestError78(error.message);
17641
- }
17642
- try {
17643
- _id = new ObjectId48(_id);
17644
- } catch (error2) {
17645
- throw new BadRequestError78("Invalid ID.");
17646
- }
17647
- try {
17648
- const res = await collection.updateOne(
17649
- { _id },
17650
- { $set: value },
17651
- { session }
17652
- );
17653
- delCachedData();
17654
- return res;
17655
- } catch (error2) {
17656
- logger60.log({
17657
- level: "error",
17658
- message: error2.message
17659
- });
17660
- const isDuplicated = error2.message.includes("duplicate");
17661
- if (isDuplicated) {
17662
- throw new BadRequestError78("Building already exists.");
17663
- }
17664
- if (error2 instanceof AppError12) {
17665
- throw error2;
17666
- } else {
17667
- throw new Error("Failed to update building.");
17668
- }
17669
- }
17670
- }
17671
- async function getAll({
17672
- search = "",
17673
- page = 1,
17674
- limit = 10,
17675
- sort = {},
17676
- site = "",
17677
- status = "active" /* ACTIVE */
17678
- } = {}) {
17679
- page = page > 0 ? page - 1 : 0;
17680
- let siteId;
17681
- if (site) {
17682
- try {
17683
- siteId = new ObjectId48(site);
17684
- } catch (error) {
17685
- throw new BadRequestError78("Invalid site ID.");
17686
- }
17687
- }
17688
- const query = {
17689
- status,
17690
- ...search && { $text: { $search: search } },
17691
- ...siteId && { site: siteId }
17692
- };
17693
- sort = Object.keys(sort).length ? sort : { _id: -1 };
17694
- const cacheParams = {
17695
- page,
17696
- limit,
17697
- sort: JSON.stringify(sort),
17698
- ...search && { search },
17699
- ...site && { site },
17700
- ...status && { status }
17701
- };
17702
- const cacheKey = makeCacheKey26(buildings_namespace_collection, cacheParams);
17703
- logger60.log({
17704
- level: "info",
17705
- message: `Cache key for getAll buildings: ${cacheKey}`
17706
- });
17707
- try {
17708
- const cached = await getCache(cacheKey);
17709
- if (cached) {
17710
- logger60.log({
17711
- level: "info",
17712
- message: `Cache hit for getAll buildings: ${cacheKey}`
17713
- });
17714
- return cached;
17715
- }
17716
- const items = await collection.aggregate([
17717
- { $match: query },
17718
- { $sort: sort },
17719
- { $skip: page * limit },
17720
- { $limit: limit }
17721
- ]).toArray();
17722
- const length = await collection.countDocuments(query);
17723
- const data = paginate21(items, page, limit, length);
17724
- setCache(cacheKey, data, 600).then(() => {
17725
- logger60.log({
17726
- level: "info",
17727
- message: `Cache set for getAll buildings: ${cacheKey}`
17728
- });
17729
- }).catch((err) => {
17730
- logger60.log({
17731
- level: "error",
17732
- message: `Failed to set cache for getAll buildings: ${err.message}`
17733
- });
17734
- });
17735
- return data;
17736
- } catch (error) {
17737
- logger60.log({ level: "error", message: `${error}` });
17738
- throw error;
17739
- }
17740
- }
17741
- async function getById(_id) {
17742
- try {
17743
- _id = new ObjectId48(_id);
17744
- } catch (error) {
17745
- throw new BadRequestError78("Invalid ID.");
17746
- }
17747
- const cacheKey = makeCacheKey26(buildings_namespace_collection, {
17748
- _id: String(_id)
17749
- });
17750
- try {
17751
- const cached = await getCache(cacheKey);
17752
- if (cached) {
17753
- logger60.log({
17754
- level: "info",
17755
- message: `Cache hit for getById building: ${cacheKey}`
17756
- });
17757
- return cached;
17758
- }
17759
- const result = await collection.findOne({
17760
- _id
17761
- });
17762
- setCache(cacheKey, result, 300).then(() => {
17763
- logger60.log({
17764
- level: "info",
17765
- message: `Cache set for building by id: ${cacheKey}`
17766
- });
17767
- }).catch((err) => {
17768
- logger60.log({
17769
- level: "error",
17770
- message: `Failed to set cache for building by id: ${err.message}`
17771
- });
17772
- });
17773
- return result;
17774
- } catch (error) {
17775
- if (error instanceof AppError12) {
17776
- throw error;
17777
- } else {
17778
- throw new InternalServerError28("Failed to get building.");
17779
- }
17780
- }
17781
- }
17782
- async function deleteById(_id, session) {
17783
- try {
17784
- _id = new ObjectId48(_id);
17785
- } catch (error) {
17786
- throw new BadRequestError78("Invalid ID.");
17787
- }
17788
- try {
17789
- const res = await collection.updateOne(
17790
- { _id },
17791
- { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } }
17792
- );
17793
- delCachedData();
17794
- return res;
17795
- } catch (error) {
17796
- logger60.log({
17797
- level: "error",
17798
- message: error.message
17799
- });
17800
- if (error instanceof AppError12) {
17801
- throw error;
17802
- } else {
17803
- throw new InternalServerError28("Failed to delete building.");
17804
- }
17805
- }
17806
- }
17807
- async function getBuildingLevel(site, block) {
17808
- try {
17809
- site = new ObjectId48(site);
17810
- } catch (error) {
17811
- throw new BadRequestError78("Invalid ID.");
17812
- }
17813
- const query = {
17814
- site,
17815
- block
17816
- };
17817
- const cacheOptions = { ...query };
17818
- const cacheKey = makeCacheKey26(buildings_namespace_collection, cacheOptions);
17819
- try {
17820
- const cached = await getCache(cacheKey);
17821
- if (cached) {
17822
- logger60.log({
17823
- level: "info",
17824
- message: `Cache hit for getById building: ${cacheKey}`
17825
- });
17826
- return cached;
17827
- }
17828
- const result = await collection.findOne(query);
17829
- setCache(cacheKey, result, 300).then(() => {
17830
- logger60.log({
17831
- level: "info",
17832
- message: `Cache set for building by id: ${cacheKey}`
17833
- });
17834
- }).catch((err) => {
17835
- logger60.log({
17836
- level: "error",
17837
- message: `Failed to set cache for building by id: ${err.message}`
17838
- });
17839
- });
17840
- return result;
17841
- } catch (error) {
17842
- if (error instanceof AppError12) {
17843
- throw error;
17844
- } else {
17845
- throw new InternalServerError28("Failed to get building.");
17846
- }
17847
- }
17848
- }
17849
- function delCachedData() {
17850
- delNamespace().then(() => {
17851
- logger60.log({
17852
- level: "info",
17853
- message: `Cache namespace cleared for ${buildings_namespace_collection}`
17854
- });
17855
- }).catch((err) => {
17856
- logger60.log({
17857
- level: "error",
17858
- message: `Failed to clear cache namespace for ${buildings_namespace_collection}: ${err.message}`
18218
+ );
17859
18219
  });
17860
- });
18220
+ return res.insertedId;
18221
+ } catch (error) {
18222
+ throw error;
18223
+ }
17861
18224
  }
17862
18225
  return {
17863
- createIndexes,
17864
- add,
17865
- getAll,
17866
- getById,
17867
- updateById,
17868
- deleteById,
17869
- getBuildingLevel
18226
+ createChat
17870
18227
  };
17871
18228
  }
17872
18229
 
17873
- // src/services/building.service.ts
17874
- import {
17875
- BadRequestError as BadRequestError80,
17876
- logger as logger62,
17877
- NotFoundError as NotFoundError18,
17878
- useAtlas as useAtlas39
17879
- } from "@7365admin1/node-server-utils";
18230
+ // src/controllers/chat.controller.ts
18231
+ import { BadRequestError as BadRequestError78, logger as logger60 } from "@7365admin1/node-server-utils";
18232
+ function useChatController() {
18233
+ const { createChat: _createChat } = useChatRepo();
18234
+ async function createChat(req, res, next) {
18235
+ const payload = { ...req.body };
18236
+ const { error } = chatSchema.validate(payload);
18237
+ if (error) {
18238
+ logger60.log({ level: "error", message: error.message });
18239
+ next(new BadRequestError78(error.message));
18240
+ return;
18241
+ }
18242
+ try {
18243
+ await _createChat({ ...payload });
18244
+ res.status(201).json({ message: "Successfully created chat." });
18245
+ return;
18246
+ } catch (error2) {
18247
+ logger60.log({ level: "error", message: error2.message });
18248
+ next(error2);
18249
+ return;
18250
+ }
18251
+ }
18252
+ return { createChat };
18253
+ }
17880
18254
 
17881
- // src/repositories/building-unit.repository.ts
18255
+ // src/repositories/building.repository.ts
17882
18256
  import {
17883
18257
  AppError as AppError13,
17884
18258
  BadRequestError as BadRequestError79,
@@ -17886,56 +18260,43 @@ import {
17886
18260
  logger as logger61,
17887
18261
  makeCacheKey as makeCacheKey27,
17888
18262
  paginate as paginate22,
17889
- toObjectId as toObjectId12,
17890
18263
  useAtlas as useAtlas38,
17891
18264
  useCache as useCache29
17892
18265
  } from "@7365admin1/node-server-utils";
17893
18266
  import { ObjectId as ObjectId49 } from "mongodb";
17894
- function useBuildingUnitRepo() {
18267
+ var buildings_namespace_collection = "buildings";
18268
+ function useBuildingRepo() {
17895
18269
  const db = useAtlas38.getDb();
17896
18270
  if (!db) {
17897
18271
  throw new Error("Unable to connect to server.");
17898
18272
  }
17899
- const namespace_collection = "building-units";
17900
- const collection = db.collection(namespace_collection);
17901
- const { getCache, setCache, delNamespace, delCache } = useCache29(namespace_collection);
18273
+ const collection = db.collection(buildings_namespace_collection);
18274
+ const { getCache, setCache, delNamespace } = useCache29(
18275
+ buildings_namespace_collection
18276
+ );
17902
18277
  async function createIndexes() {
17903
18278
  try {
17904
18279
  await collection.createIndexes([
17905
- { key: { name: 1, building: 1, level: 1 }, unique: true },
18280
+ { key: { name: "text" }, name: "text-index" },
18281
+ { key: { name: 1 }, unique: true, name: "unique-name-index" },
17906
18282
  { key: { site: 1 } },
17907
- { key: { building: 1 } },
17908
- { key: { status: 1 } },
17909
18283
  { key: { createdAt: 1 } },
17910
18284
  {
17911
- key: {
17912
- name: "text",
17913
- buildingName: "text",
17914
- category: "text",
17915
- block: "text"
18285
+ key: { site: 1, block: 1 },
18286
+ unique: true,
18287
+ name: "unique-site-block-active",
18288
+ partialFilterExpression: {
18289
+ status: "active" /* ACTIVE */
17916
18290
  }
17917
18291
  }
17918
18292
  ]);
17919
18293
  } catch (error) {
17920
- throw new Error("Failed to create index on building units.");
18294
+ throw new Error("Failed to create index on buildings. " + error.message);
17921
18295
  }
17922
18296
  }
17923
- function delCachedData() {
17924
- delNamespace().then(() => {
17925
- logger61.log({
17926
- level: "info",
17927
- message: `Cache namespace cleared for ${namespace_collection}`
17928
- });
17929
- }).catch((err) => {
17930
- logger61.log({
17931
- level: "error",
17932
- message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
17933
- });
17934
- });
17935
- }
17936
18297
  async function add(value, session) {
17937
18298
  try {
17938
- value = MBuildingUnit(value);
18299
+ value = MBuilding(value);
17939
18300
  const res = await collection.insertOne(value, { session });
17940
18301
  delCachedData();
17941
18302
  return res.insertedId;
@@ -17946,18 +18307,19 @@ function useBuildingUnitRepo() {
17946
18307
  });
17947
18308
  const isDuplicated = error.message.includes("duplicate");
17948
18309
  if (isDuplicated) {
17949
- throw new BadRequestError79("Building unit already exists.");
18310
+ throw new BadRequestError79("Building already exists.");
17950
18311
  }
17951
18312
  if (error instanceof AppError13) {
17952
18313
  throw error;
17953
18314
  } else {
17954
- throw new Error("Failed to create building unit.");
18315
+ throw new Error("Failed to create building.");
17955
18316
  }
17956
18317
  }
17957
18318
  }
17958
18319
  async function updateById(_id, value, session) {
17959
- const { error } = schemaUpdateOptions.validate(value);
18320
+ const { error } = schemaBuildingUpdateOptions.validate(value);
17960
18321
  if (error) {
18322
+ logger61.info(`Building Repository: ${error.message}`);
17961
18323
  throw new BadRequestError79(error.message);
17962
18324
  }
17963
18325
  try {
@@ -17965,21 +18327,6 @@ function useBuildingUnitRepo() {
17965
18327
  } catch (error2) {
17966
18328
  throw new BadRequestError79("Invalid ID.");
17967
18329
  }
17968
- if (value.billing && Array.isArray(value.billing)) {
17969
- value.billing = value.billing.map((billing) => {
17970
- if (billing._id && typeof billing._id === "string") {
17971
- try {
17972
- billing._id = new ObjectId49(billing._id);
17973
- } catch {
17974
- throw new BadRequestError79("Invalid billing id format");
17975
- }
17976
- }
17977
- return billing;
17978
- });
17979
- }
17980
- if (value.owner) {
17981
- value.owner = new ObjectId49(value.owner);
17982
- }
17983
18330
  try {
17984
18331
  const res = await collection.updateOne(
17985
18332
  { _id },
@@ -17995,46 +18342,12 @@ function useBuildingUnitRepo() {
17995
18342
  });
17996
18343
  const isDuplicated = error2.message.includes("duplicate");
17997
18344
  if (isDuplicated) {
17998
- throw new BadRequestError79("Building unit already exists.");
17999
- }
18000
- if (error2 instanceof AppError13) {
18001
- throw error2;
18002
- } else {
18003
- throw new Error("Failed to create building unit.");
18004
- }
18005
- }
18006
- }
18007
- async function updateByBuildingId(building, value, session) {
18008
- const { error } = schemaUpdateOptions.validate(value);
18009
- if (error) {
18010
- throw new BadRequestError79(error.message);
18011
- }
18012
- try {
18013
- building = new ObjectId49(building);
18014
- } catch (error2) {
18015
- throw new BadRequestError79("Invalid building ID.");
18016
- }
18017
- try {
18018
- const res = await collection.updateMany(
18019
- { building },
18020
- { $set: value },
18021
- { session }
18022
- );
18023
- delCachedData();
18024
- return res;
18025
- } catch (error2) {
18026
- logger61.log({
18027
- level: "error",
18028
- message: error2.message
18029
- });
18030
- const isDuplicated = error2.message.includes("duplicate");
18031
- if (isDuplicated) {
18032
- throw new BadRequestError79("Building unit already exists.");
18345
+ throw new BadRequestError79("Building already exists.");
18033
18346
  }
18034
18347
  if (error2 instanceof AppError13) {
18035
18348
  throw error2;
18036
18349
  } else {
18037
- throw new Error("Failed to create building unit.");
18350
+ throw new Error("Failed to update building.");
18038
18351
  }
18039
18352
  }
18040
18353
  }
@@ -18044,68 +18357,47 @@ function useBuildingUnitRepo() {
18044
18357
  limit = 10,
18045
18358
  sort = {},
18046
18359
  site = "",
18047
- building = "",
18048
- status = "active"
18360
+ status = "active" /* ACTIVE */
18049
18361
  } = {}) {
18050
18362
  page = page > 0 ? page - 1 : 0;
18363
+ let siteId;
18364
+ if (site) {
18365
+ try {
18366
+ siteId = new ObjectId49(site);
18367
+ } catch (error) {
18368
+ throw new BadRequestError79("Invalid site ID.");
18369
+ }
18370
+ }
18051
18371
  const query = {
18052
18372
  status,
18053
18373
  ...search && { $text: { $search: search } },
18054
- ...site && { site: toObjectId12(site) },
18055
- ...building && { building: toObjectId12(building) }
18374
+ ...siteId && { site: siteId }
18056
18375
  };
18057
- sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
18376
+ sort = Object.keys(sort).length ? sort : { _id: -1 };
18058
18377
  const cacheParams = {
18059
18378
  page,
18060
18379
  limit,
18061
18380
  sort: JSON.stringify(sort),
18062
18381
  ...search && { search },
18063
18382
  ...site && { site },
18064
- ...building && { building },
18065
18383
  ...status && { status }
18066
18384
  };
18067
- const cacheKey = makeCacheKey27(namespace_collection, cacheParams);
18385
+ const cacheKey = makeCacheKey27(buildings_namespace_collection, cacheParams);
18068
18386
  logger61.log({
18069
18387
  level: "info",
18070
- message: `Cache key for getAll building units: ${cacheKey}`
18388
+ message: `Cache key for getAll buildings: ${cacheKey}`
18071
18389
  });
18072
18390
  try {
18073
18391
  const cached = await getCache(cacheKey);
18074
18392
  if (cached) {
18075
18393
  logger61.log({
18076
18394
  level: "info",
18077
- message: `Cache hit for getAll building units: ${cacheKey}`
18395
+ message: `Cache hit for getAll buildings: ${cacheKey}`
18078
18396
  });
18079
18397
  return cached;
18080
18398
  }
18081
18399
  const items = await collection.aggregate([
18082
18400
  { $match: query },
18083
- {
18084
- $lookup: {
18085
- from: "sites",
18086
- let: { siteId: "$site" },
18087
- pipeline: [
18088
- {
18089
- $match: {
18090
- $expr: { $eq: ["$_id", "$$siteId"] },
18091
- status: "active" /* ACTIVE */
18092
- }
18093
- },
18094
- {
18095
- $project: {
18096
- name: 1,
18097
- description: 1,
18098
- orgId: 1,
18099
- metadata: 1,
18100
- status: 1,
18101
- address: 1
18102
- }
18103
- }
18104
- ],
18105
- as: "site"
18106
- }
18107
- },
18108
- { $set: { site: { $first: "$site" } } },
18109
18401
  { $sort: sort },
18110
18402
  { $skip: page * limit },
18111
18403
  { $limit: limit }
@@ -18115,12 +18407,12 @@ function useBuildingUnitRepo() {
18115
18407
  setCache(cacheKey, data, 600).then(() => {
18116
18408
  logger61.log({
18117
18409
  level: "info",
18118
- message: `Cache set for getAll building units: ${cacheKey}`
18410
+ message: `Cache set for getAll buildings: ${cacheKey}`
18119
18411
  });
18120
18412
  }).catch((err) => {
18121
18413
  logger61.log({
18122
18414
  level: "error",
18123
- message: `Failed to set cache for getAll building units: ${err.message}`
18415
+ message: `Failed to set cache for getAll buildings: ${err.message}`
18124
18416
  });
18125
18417
  });
18126
18418
  return data;
@@ -18129,82 +18421,36 @@ function useBuildingUnitRepo() {
18129
18421
  throw error;
18130
18422
  }
18131
18423
  }
18132
- async function getById(_id, session) {
18424
+ async function getById(_id) {
18133
18425
  try {
18134
18426
  _id = new ObjectId49(_id);
18135
18427
  } catch (error) {
18136
18428
  throw new BadRequestError79("Invalid ID.");
18137
18429
  }
18138
- const cacheKey = makeCacheKey27(namespace_collection, { _id: String(_id) });
18139
- try {
18140
- const cached = await getCache(cacheKey);
18141
- if (cached) {
18142
- logger61.log({
18143
- level: "info",
18144
- message: `Cache hit for getById building unit: ${cacheKey}`
18145
- });
18146
- return cached;
18147
- }
18148
- const result = await collection.findOne({
18149
- _id,
18150
- deletedAt: { $in: ["", null] }
18151
- });
18152
- if (!result) {
18153
- throw new BadRequestError79("Building unit not found.");
18154
- }
18155
- setCache(cacheKey, result, 300).then(() => {
18156
- logger61.log({
18157
- level: "info",
18158
- message: `Cache set for building unit by id: ${cacheKey}`
18159
- });
18160
- }).catch((err) => {
18161
- logger61.log({
18162
- level: "error",
18163
- message: `Failed to set cache for building unit by id: ${err.message}`
18164
- });
18165
- });
18166
- return result;
18167
- } catch (error) {
18168
- if (error instanceof AppError13) {
18169
- throw error;
18170
- } else {
18171
- throw new InternalServerError29("Failed to get building unit.");
18172
- }
18173
- }
18174
- }
18175
- async function getByBuildingLevel(building, level) {
18176
- try {
18177
- building = new ObjectId49(building);
18178
- } catch (error) {
18179
- throw new BadRequestError79("Invalid building ID.");
18180
- }
18181
- const cacheKey = makeCacheKey27(namespace_collection, {
18182
- building: String(building),
18183
- level
18430
+ const cacheKey = makeCacheKey27(buildings_namespace_collection, {
18431
+ _id: String(_id)
18184
18432
  });
18185
18433
  try {
18186
18434
  const cached = await getCache(cacheKey);
18187
18435
  if (cached) {
18188
18436
  logger61.log({
18189
18437
  level: "info",
18190
- message: `Cache hit for getById building unit: ${cacheKey}`
18438
+ message: `Cache hit for getById building: ${cacheKey}`
18191
18439
  });
18192
18440
  return cached;
18193
18441
  }
18194
18442
  const result = await collection.findOne({
18195
- building,
18196
- level,
18197
- status: "active"
18443
+ _id
18198
18444
  });
18199
18445
  setCache(cacheKey, result, 300).then(() => {
18200
18446
  logger61.log({
18201
18447
  level: "info",
18202
- message: `Cache set for building unit by id: ${cacheKey}`
18448
+ message: `Cache set for building by id: ${cacheKey}`
18203
18449
  });
18204
18450
  }).catch((err) => {
18205
18451
  logger61.log({
18206
18452
  level: "error",
18207
- message: `Failed to set cache for building unit by id: ${err.message}`
18453
+ message: `Failed to set cache for building by id: ${err.message}`
18208
18454
  });
18209
18455
  });
18210
18456
  return result;
@@ -18212,71 +18458,66 @@ function useBuildingUnitRepo() {
18212
18458
  if (error instanceof AppError13) {
18213
18459
  throw error;
18214
18460
  } else {
18215
- throw new InternalServerError29("Failed to get building unit.");
18461
+ throw new InternalServerError29("Failed to get building.");
18216
18462
  }
18217
18463
  }
18218
18464
  }
18219
- async function updateLevelByBuildingLevel(building, level, newLevel, session) {
18465
+ async function deleteById(_id, session) {
18220
18466
  try {
18221
- building = new ObjectId49(building);
18467
+ _id = new ObjectId49(_id);
18222
18468
  } catch (error) {
18223
- throw new BadRequestError79("Invalid building ID.");
18469
+ throw new BadRequestError79("Invalid ID.");
18224
18470
  }
18225
18471
  try {
18226
- const result = await collection.updateMany(
18227
- {
18228
- building,
18229
- level,
18230
- status: "active"
18231
- },
18232
- {
18233
- $set: { level: newLevel }
18234
- },
18235
- {
18236
- session
18237
- }
18472
+ const res = await collection.updateOne(
18473
+ { _id },
18474
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } }
18238
18475
  );
18239
18476
  delCachedData();
18240
- return result;
18477
+ return res;
18241
18478
  } catch (error) {
18479
+ logger61.log({
18480
+ level: "error",
18481
+ message: error.message
18482
+ });
18242
18483
  if (error instanceof AppError13) {
18243
18484
  throw error;
18244
18485
  } else {
18245
- throw new InternalServerError29("Failed to update building unit level.");
18486
+ throw new InternalServerError29("Failed to delete building.");
18246
18487
  }
18247
18488
  }
18248
18489
  }
18249
- async function getByBuilding(building) {
18490
+ async function getBuildingLevel(site, block) {
18250
18491
  try {
18251
- building = new ObjectId49(building);
18492
+ site = new ObjectId49(site);
18252
18493
  } catch (error) {
18253
- throw new BadRequestError79("Invalid building ID.");
18494
+ throw new BadRequestError79("Invalid ID.");
18254
18495
  }
18255
- const cacheKey = makeCacheKey27(namespace_collection, {
18256
- building: String(building)
18257
- });
18496
+ const query = {
18497
+ site,
18498
+ block
18499
+ };
18500
+ const cacheOptions = { ...query };
18501
+ const cacheKey = makeCacheKey27(buildings_namespace_collection, cacheOptions);
18258
18502
  try {
18259
18503
  const cached = await getCache(cacheKey);
18260
18504
  if (cached) {
18261
18505
  logger61.log({
18262
18506
  level: "info",
18263
- message: `Cache hit for getById building unit: ${cacheKey}`
18507
+ message: `Cache hit for getById building: ${cacheKey}`
18264
18508
  });
18265
18509
  return cached;
18266
18510
  }
18267
- const result = await collection.findOne({
18268
- building,
18269
- status: "active"
18270
- });
18511
+ const result = await collection.findOne(query);
18271
18512
  setCache(cacheKey, result, 300).then(() => {
18272
18513
  logger61.log({
18273
18514
  level: "info",
18274
- message: `Cache set for building unit by id: ${cacheKey}`
18515
+ message: `Cache set for building by id: ${cacheKey}`
18275
18516
  });
18276
18517
  }).catch((err) => {
18277
18518
  logger61.log({
18278
18519
  level: "error",
18279
- message: `Failed to set cache for building unit by id: ${err.message}`
18520
+ message: `Failed to set cache for building by id: ${err.message}`
18280
18521
  });
18281
18522
  });
18282
18523
  return result;
@@ -18284,127 +18525,41 @@ function useBuildingUnitRepo() {
18284
18525
  if (error instanceof AppError13) {
18285
18526
  throw error;
18286
18527
  } else {
18287
- throw new InternalServerError29("Failed to get building unit.");
18528
+ throw new InternalServerError29("Failed to get building.");
18288
18529
  }
18289
18530
  }
18290
18531
  }
18291
- async function deleteById(_id, session) {
18292
- try {
18293
- _id = new ObjectId49(_id);
18294
- } catch (error) {
18295
- throw new BadRequestError79("Invalid ID.");
18296
- }
18297
- try {
18298
- const res = await collection.updateOne(
18299
- { _id },
18300
- { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
18301
- { session }
18302
- );
18303
- delCachedData();
18304
- return "Room/Facility deleted successfully.";
18305
- } catch (error) {
18532
+ function delCachedData() {
18533
+ delNamespace().then(() => {
18306
18534
  logger61.log({
18307
- level: "error",
18308
- message: error.message
18309
- });
18310
- if (error instanceof AppError13) {
18311
- throw error;
18312
- } else {
18313
- throw new Error("Failed to deleted room/facility.");
18314
- }
18315
- }
18316
- }
18317
- async function getBuildingUnits(site, block, level) {
18318
- try {
18319
- site = new ObjectId49(site);
18320
- } catch (error) {
18321
- throw new BadRequestError79("Invalid site ID format.");
18322
- }
18323
- const query = { site, block, level };
18324
- const cacheOptions = {
18325
- site: site.toString(),
18326
- block,
18327
- level
18328
- };
18329
- const cacheKey = makeCacheKey27(namespace_collection, cacheOptions);
18330
- const cachedData = await getCache(cacheKey);
18331
- if (cachedData) {
18332
- logger61.info(`Cache hit for key: ${cacheKey}`);
18333
- return cachedData;
18334
- }
18335
- try {
18336
- const data = await collection.aggregate([{ $match: query }, { $project: { name: 1 } }]).toArray();
18337
- setCache(cacheKey, data, 15 * 60).then(() => {
18338
- logger61.info(`Cache set for key: ${cacheKey}`);
18339
- }).catch((err) => {
18340
- logger61.error(`Failed to set cache for key: ${cacheKey}`, err);
18535
+ level: "info",
18536
+ message: `Cache namespace cleared for ${buildings_namespace_collection}`
18341
18537
  });
18342
- return data;
18343
- } catch (error) {
18344
- if (error instanceof AppError13) {
18345
- throw error;
18346
- } else {
18347
- throw new InternalServerError29("Failed to get building units.");
18348
- }
18349
- }
18350
- }
18351
- async function getBuildingUnitsWithOwner(site, unitIds) {
18352
- try {
18353
- site = new ObjectId49(site);
18354
- } catch (error) {
18355
- throw new BadRequestError79("Invalid site ID format.");
18356
- }
18357
- const query = {
18358
- site,
18359
- owner: { $nin: [null, ""] }
18360
- };
18361
- if (unitIds && unitIds.length > 0) {
18362
- query._id = { $in: unitIds };
18363
- }
18364
- const cacheOptions = {
18365
- site: site.toString()
18366
- };
18367
- const cacheKey = makeCacheKey27(namespace_collection, cacheOptions);
18368
- const cachedData = await getCache(cacheKey);
18369
- if (cachedData) {
18370
- logger61.info(`Cache hit for key: ${cacheKey}`);
18371
- return cachedData;
18372
- }
18373
- try {
18374
- const data = await collection.aggregate([{ $match: query }]).toArray();
18375
- setCache(cacheKey, data, 15 * 60).then(() => {
18376
- logger61.info(`Cache set for key: ${cacheKey}`);
18377
- }).catch((err) => {
18378
- logger61.error(`Failed to set cache for key: ${cacheKey}`, err);
18538
+ }).catch((err) => {
18539
+ logger61.log({
18540
+ level: "error",
18541
+ message: `Failed to clear cache namespace for ${buildings_namespace_collection}: ${err.message}`
18379
18542
  });
18380
- return data;
18381
- } catch (error) {
18382
- if (error instanceof AppError13) {
18383
- throw error;
18384
- } else {
18385
- throw new InternalServerError29(
18386
- "Failed to get building units with owner."
18387
- );
18388
- }
18389
- }
18543
+ });
18390
18544
  }
18391
18545
  return {
18392
18546
  createIndexes,
18393
18547
  add,
18394
18548
  getAll,
18395
18549
  getById,
18396
- getByBuildingLevel,
18397
18550
  updateById,
18398
- getByBuilding,
18399
18551
  deleteById,
18400
- updateLevelByBuildingLevel,
18401
- updateByBuildingId,
18402
- getBuildingUnits,
18403
- getBuildingUnitsWithOwner
18552
+ getBuildingLevel
18404
18553
  };
18405
18554
  }
18406
18555
 
18407
18556
  // src/services/building.service.ts
18557
+ import {
18558
+ BadRequestError as BadRequestError80,
18559
+ logger as logger62,
18560
+ NotFoundError as NotFoundError18,
18561
+ useAtlas as useAtlas39
18562
+ } from "@7365admin1/node-server-utils";
18408
18563
  function useBuildingService() {
18409
18564
  const {
18410
18565
  updateById: _updateById,
@@ -18747,11 +18902,13 @@ function useBuildingUnitService() {
18747
18902
  }
18748
18903
  }
18749
18904
  for (let index = 0; index < value.qty; index++) {
18905
+ const unitNumber = index + 1;
18750
18906
  const label = value.labels[index] || `${value.unit.name} ${index + 1}`;
18751
18907
  await _add(
18752
18908
  {
18753
18909
  ...value.unit,
18754
- name: value.qty > 1 ? label : value.unit.name
18910
+ name: value.qty > 1 ? label : value.unit.name,
18911
+ unitNumber
18755
18912
  },
18756
18913
  session
18757
18914
  );
@@ -19031,8 +19188,6 @@ function useBuildingUnitController() {
19031
19188
  import { BadRequestError as BadRequestError84, logger as logger66 } from "@7365admin1/node-server-utils";
19032
19189
  import Joi46 from "joi";
19033
19190
  import ExcelJS from "exceljs";
19034
- import { Readable } from "stream";
19035
- import csv from "csv-parser";
19036
19191
  import fs from "fs";
19037
19192
  function useVehicleController() {
19038
19193
  const {
@@ -19058,7 +19213,7 @@ function useVehicleController() {
19058
19213
  ])
19059
19214
  );
19060
19215
  }
19061
- function mapRowToVehicle(row) {
19216
+ function mapRowToVehicle(row, site, org) {
19062
19217
  const cleanRow = normalizeRow(row);
19063
19218
  return {
19064
19219
  name: cleanRow.fullName,
@@ -19067,11 +19222,12 @@ function useVehicleController() {
19067
19222
  phoneNumber: cleanRow.phoneNumber || "",
19068
19223
  block: Number(cleanRow.block),
19069
19224
  level: String(cleanRow.level || ""),
19070
- unitName: String(cleanRow.unit || ""),
19225
+ unit: String(cleanRow.unit || ""),
19071
19226
  plateNumber: String(cleanRow.plateNumber || "").toUpperCase(),
19072
- remarks: `Model: ${cleanRow.vehicleModel || ""}, Color: ${cleanRow.vehicleColor || ""}`,
19073
- org: cleanRow.org,
19074
- site: cleanRow.site,
19227
+ vehicleModel: cleanRow.vehicleModel || "",
19228
+ vehicleColor: cleanRow.vehicleColor || "",
19229
+ org,
19230
+ site,
19075
19231
  end: parseExpiryDate(cleanRow.subscriptionExpiry)
19076
19232
  };
19077
19233
  }
@@ -19100,42 +19256,6 @@ function useVehicleController() {
19100
19256
  const date = new Date(year, month, Number(day));
19101
19257
  return isNaN(date.getTime()) ? void 0 : date.toISOString();
19102
19258
  }
19103
- async function uploadCsvVehicles(req, res, next) {
19104
- try {
19105
- if (!req.file) {
19106
- next(new BadRequestError84("CSV file is required."));
19107
- return;
19108
- }
19109
- if (!req.file.originalname.toLowerCase().endsWith(".csv")) {
19110
- next(new BadRequestError84("Only .csv files are allowed."));
19111
- return;
19112
- }
19113
- const rows = [];
19114
- const stream = Readable.from(req.file.buffer);
19115
- stream.pipe(csv()).on("data", (row) => {
19116
- rows.push(row);
19117
- }).on("end", async () => {
19118
- try {
19119
- const vehicles = rows.map(mapRowToVehicle);
19120
- const data = await _bulkUpsertVehicles(vehicles);
19121
- res.status(200).json({
19122
- message: "CSV import completed.",
19123
- count: rows.length,
19124
- data
19125
- });
19126
- } catch (error) {
19127
- logger66.log({ level: "error", message: error.message });
19128
- next(error);
19129
- }
19130
- }).on("error", (error) => {
19131
- logger66.log({ level: "error", message: error.message });
19132
- next(error);
19133
- });
19134
- } catch (error) {
19135
- logger66.log({ level: "error", message: error.message });
19136
- next(error);
19137
- }
19138
- }
19139
19259
  async function uploadExcelVehicles(req, res, next) {
19140
19260
  try {
19141
19261
  if (!req.file) {
@@ -19146,7 +19266,7 @@ function useVehicleController() {
19146
19266
  next(new BadRequestError84("Only .xlsx files are allowed."));
19147
19267
  return;
19148
19268
  }
19149
- const schema2 = Joi46.object({
19269
+ const rowSchema = Joi46.object({
19150
19270
  fullName: Joi46.string().trim().required(),
19151
19271
  userType: Joi46.string().trim().required(),
19152
19272
  recordType: Joi46.string().trim().required(),
@@ -19157,10 +19277,28 @@ function useVehicleController() {
19157
19277
  plateNumber: Joi46.string().trim().uppercase().required(),
19158
19278
  vehicleModel: Joi46.string().trim().allow("", null).optional(),
19159
19279
  vehicleColor: Joi46.string().trim().allow("", null).optional(),
19160
- subscriptionExpiry: Joi46.string().trim().allow("", null).optional(),
19280
+ subscriptionExpiry: Joi46.string().trim().allow("", null).optional()
19281
+ });
19282
+ const querySchema = Joi46.object({
19161
19283
  site: Joi46.string().hex().length(24).required(),
19162
- org: Joi46.string().hex().length(24).required()
19284
+ org: Joi46.string().hex().length(24).optional().allow(null, "")
19163
19285
  });
19286
+ const { error: queryError, value: queryValue } = querySchema.validate(
19287
+ req.query,
19288
+ {
19289
+ abortEarly: false,
19290
+ convert: true
19291
+ }
19292
+ );
19293
+ if (queryError) {
19294
+ next(
19295
+ new BadRequestError84(
19296
+ queryError.details.map((d) => d.message).join(", ")
19297
+ )
19298
+ );
19299
+ return;
19300
+ }
19301
+ const { site, org } = queryValue;
19164
19302
  const workbook = new ExcelJS.Workbook();
19165
19303
  await workbook.xlsx.readFile(req.file.path);
19166
19304
  const worksheet = workbook.worksheets[0];
@@ -19188,9 +19326,9 @@ function useVehicleController() {
19188
19326
  const validRows = [];
19189
19327
  const invalidRows = [];
19190
19328
  rows.forEach((row, index) => {
19191
- const { error, value } = schema2.validate(row, {
19329
+ const { error, value } = rowSchema.validate(row, {
19192
19330
  abortEarly: false,
19193
- convert: true
19331
+ stripUnknown: true
19194
19332
  });
19195
19333
  if (error) {
19196
19334
  invalidRows.push({
@@ -19202,14 +19340,10 @@ function useVehicleController() {
19202
19340
  }
19203
19341
  validRows.push(value);
19204
19342
  });
19205
- const vehicles = validRows.map(mapRowToVehicle);
19206
- let data = {
19207
- matchedCount: 0,
19208
- modifiedCount: 0,
19209
- upsertedCount: 0
19210
- };
19343
+ const vehicles = validRows.map((row) => mapRowToVehicle(row, site, org));
19344
+ let data = {};
19211
19345
  if (vehicles.length > 0) {
19212
- data = await _bulkUpsertVehicles(vehicles);
19346
+ data = await _bulkUpsertVehicles(vehicles, site, org);
19213
19347
  }
19214
19348
  res.status(200).json({
19215
19349
  message: "Excel import completed.",
@@ -19562,7 +19696,7 @@ function useVehicleController() {
19562
19696
  getVehiclesByNRIC,
19563
19697
  reactivateVehicleById,
19564
19698
  getAllVehiclesByUnitId,
19565
- uploadCsvVehicles,
19699
+ // uploadCsvVehicles,
19566
19700
  uploadExcelVehicles
19567
19701
  };
19568
19702
  }
@@ -22416,8 +22550,6 @@ function useVisitorTransactionService() {
22416
22550
  }
22417
22551
  const hourExpiration = site?.dahuaTimeExpiration ? site?.dahuaTimeExpiration : 24 * 60;
22418
22552
  const end = value.checkOut ? new Date(value.checkOut) : new Date(start.getTime() + hourExpiration * 60 * 1e3);
22419
- const startString = start.toISOString();
22420
- const endString = end.toISOString();
22421
22553
  const startDahuaDate = formatDahuaDate(start);
22422
22554
  const endDahuaDate = formatDahuaDate(end);
22423
22555
  if (allowedPersonTypes.includes(value?.type)) {
@@ -22518,8 +22650,8 @@ function useVisitorTransactionService() {
22518
22650
  company,
22519
22651
  remarks,
22520
22652
  contractorType,
22521
- checkIn: startString,
22522
- expiredAt: endString,
22653
+ checkIn: start,
22654
+ expiredAt: end,
22523
22655
  visitorPass: visitorPass ?? [],
22524
22656
  passKeys: passKeys ?? [],
22525
22657
  status: "registered" /* REGISTERED */
@@ -22565,8 +22697,8 @@ function useVisitorTransactionService() {
22565
22697
  }
22566
22698
  const responseData = dahuaResponse?.data?.toString("utf-8") ?? "";
22567
22699
  value.recNo = responseData.split("=")[1]?.trim();
22568
- value.checkIn = startString;
22569
- value.expiredAt = endString;
22700
+ value.checkIn = start;
22701
+ value.expiredAt = end;
22570
22702
  const vehiclePayload = {
22571
22703
  name: value.name ?? "",
22572
22704
  category: value.type,
@@ -22575,8 +22707,8 @@ function useVisitorTransactionService() {
22575
22707
  plateNumber: value.plateNumber,
22576
22708
  type: "whitelist" /* WHITELIST */,
22577
22709
  nric: value.nric,
22578
- start: startString,
22579
- end: endString,
22710
+ start,
22711
+ end,
22580
22712
  recNo: value.recNo
22581
22713
  };
22582
22714
  await addVehicle(vehiclePayload);
@@ -31351,17 +31483,17 @@ function useEventManagementController() {
31351
31483
  import { BadRequestError as BadRequestError138, logger as logger117 } from "@7365admin1/node-server-utils";
31352
31484
  import { ObjectId as ObjectId86 } from "mongodb";
31353
31485
  import Joi83 from "joi";
31354
- var Status = /* @__PURE__ */ ((Status3) => {
31355
- Status3["PENDING"] = "pending";
31356
- Status3["COMPLETED"] = "completed";
31357
- Status3["APPROVED"] = "approved";
31358
- Status3["REJECTED"] = "rejected";
31359
- Status3["CANCELLED"] = "cancelled";
31360
- Status3["RECURRING"] = "recurring";
31361
- Status3["NONRECURRING"] = "non-recurring";
31362
- Status3["ACTIVE"] = "active";
31363
- Status3["INACTIVE"] = "inactive";
31364
- return Status3;
31486
+ var Status = /* @__PURE__ */ ((Status2) => {
31487
+ Status2["PENDING"] = "pending";
31488
+ Status2["COMPLETED"] = "completed";
31489
+ Status2["APPROVED"] = "approved";
31490
+ Status2["REJECTED"] = "rejected";
31491
+ Status2["CANCELLED"] = "cancelled";
31492
+ Status2["RECURRING"] = "recurring";
31493
+ Status2["NONRECURRING"] = "non-recurring";
31494
+ Status2["ACTIVE"] = "active";
31495
+ Status2["INACTIVE"] = "inactive";
31496
+ return Status2;
31365
31497
  })(Status || {});
31366
31498
  var PStatus = /* @__PURE__ */ ((PStatus2) => {
31367
31499
  PStatus2["PROCESSING"] = "processing";
@@ -34813,7 +34945,7 @@ import Joi85 from "joi";
34813
34945
 
34814
34946
  // src/services/access-management.service.ts
34815
34947
  import { parseStringPromise as parseStringPromise3 } from "xml2js";
34816
- import { Readable as Readable2 } from "stream";
34948
+ import { Readable } from "stream";
34817
34949
  import * as xlsx from "xlsx";
34818
34950
  function useAccessManagementSvc() {
34819
34951
  const {
@@ -35019,7 +35151,7 @@ function useAccessManagementSvc() {
35019
35151
  };
35020
35152
  const convertBufferFile = async (bufferFile) => {
35021
35153
  return new Promise((resolve, reject) => {
35022
- const fileStream = Readable2.from(bufferFile);
35154
+ const fileStream = Readable.from(bufferFile);
35023
35155
  let fileBuffer = Buffer.alloc(0);
35024
35156
  fileStream.on("data", (chunk) => {
35025
35157
  fileBuffer = Buffer.concat([fileBuffer, chunk]);
@@ -47721,6 +47853,84 @@ var useRedDotPaymentRepo = () => {
47721
47853
  session?.endSession();
47722
47854
  }
47723
47855
  }
47856
+ async function payMultipleUnitBill(refId, payload) {
47857
+ const session = useAtlas111.getClient()?.startSession();
47858
+ try {
47859
+ session?.startTransaction();
47860
+ const reference = refId?.toString();
47861
+ const checkPayment = await paymentCollection().findOne({
47862
+ referenceNumber: refId
47863
+ });
47864
+ if (!checkPayment)
47865
+ throw new Error("Payment not found");
47866
+ const unitBillsIds = checkPayment.unitBillingItems.map(
47867
+ (unit) => unit._id
47868
+ );
47869
+ const unitBills = await unitBillingCollection().find({ _id: { $in: unitBillsIds } }).toArray();
47870
+ if (!unitBills.length)
47871
+ throw new Error("No unit bills found");
47872
+ unitBills.sort(
47873
+ (a, b) => new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
47874
+ );
47875
+ const paymentInfo = await paymentCollection().findOne(
47876
+ { referenceNumber: reference, status: "pending" },
47877
+ { session }
47878
+ );
47879
+ if (!paymentInfo)
47880
+ throw new Error("Payment info not found");
47881
+ let remaining = Number(payload.amountPaid);
47882
+ if (Number.isNaN(remaining))
47883
+ throw new Error("Invalid amount");
47884
+ const now = /* @__PURE__ */ new Date();
47885
+ for (const bill of unitBills) {
47886
+ if (remaining <= 0)
47887
+ break;
47888
+ const totalAmount = Number(bill.totalAmount);
47889
+ const alreadyPaid = Number(bill.amountPaid || 0);
47890
+ const unpaid = totalAmount - alreadyPaid;
47891
+ if (unpaid <= 0)
47892
+ continue;
47893
+ const toPay = Math.min(unpaid, remaining);
47894
+ const newAmountPaid = alreadyPaid + toPay;
47895
+ const unitUpdate = {
47896
+ amountPaid: newAmountPaid,
47897
+ paymentStatus: newAmountPaid >= totalAmount ? "paid" /* PAID */ : "partial-payment" /* PARTIAL */,
47898
+ datePaid: newAmountPaid >= totalAmount ? now : void 0,
47899
+ updatedAt: now.toISOString(),
47900
+ transaction_id: payload.transaction_id
47901
+ };
47902
+ await unitBillingCollection().updateOne(
47903
+ { _id: bill._id },
47904
+ { $set: unitUpdate },
47905
+ { session }
47906
+ );
47907
+ remaining -= toPay;
47908
+ }
47909
+ const paymentUpdate = {
47910
+ updatedAt: now.toISOString(),
47911
+ transaction_id: payload.transaction_id,
47912
+ message: payload.message,
47913
+ method: payload.method,
47914
+ status: remaining === 0 ? "success" : "partial",
47915
+ datePaid: now
47916
+ };
47917
+ await paymentCollection().updateOne(
47918
+ { _id: paymentInfo._id },
47919
+ { $set: paymentUpdate },
47920
+ { session }
47921
+ );
47922
+ await session?.commitTransaction();
47923
+ return {
47924
+ message: "Bulk payment successful",
47925
+ remainingBalance: remaining
47926
+ };
47927
+ } catch (error) {
47928
+ await session?.abortTransaction();
47929
+ throw new Error(error.message || "Server Internal Error");
47930
+ } finally {
47931
+ session?.endSession();
47932
+ }
47933
+ }
47724
47934
  function formatDateString(today) {
47725
47935
  today = typeof today === "string" ? new Date(today) : today;
47726
47936
  let month = today.getMonth() + 1;
@@ -47729,12 +47939,23 @@ var useRedDotPaymentRepo = () => {
47729
47939
  const formattedDate = `${month.toString().padStart(2, "0")}${day.toString().padStart(2, "0")}${year}`;
47730
47940
  return formattedDate;
47731
47941
  }
47732
- return { paySingleUnitBill, createPayment };
47942
+ return { paySingleUnitBill, createPayment, payMultipleUnitBill };
47733
47943
  };
47734
47944
 
47735
47945
  // src/services/reddot-payment.service.ts
47946
+ import { InternalServerError as InternalServerError68, useAtlas as useAtlas112 } from "@7365admin1/node-server-utils";
47736
47947
  var useRedDotPaymentSvc = () => {
47737
- const { paySingleUnitBill } = useRedDotPaymentRepo();
47948
+ const getDB2 = () => {
47949
+ const db = useAtlas112.getDb();
47950
+ if (!db) {
47951
+ throw new InternalServerError68("Unable to connect to server.");
47952
+ }
47953
+ return db;
47954
+ };
47955
+ const paymentCollection = () => {
47956
+ return getDB2().collection("billing-payments");
47957
+ };
47958
+ const { paySingleUnitBill, payMultipleUnitBill } = useRedDotPaymentRepo();
47738
47959
  const redirectPaymentTransaction = async (payload) => {
47739
47960
  try {
47740
47961
  const SECRET_KEY2 = payload.merchant_key;
@@ -47812,61 +48033,49 @@ var useRedDotPaymentSvc = () => {
47812
48033
  const refId = result.order_id;
47813
48034
  const message = result.response_msg;
47814
48035
  const invoiceDate = /* @__PURE__ */ new Date();
48036
+ const checkPayment = await paymentCollection().findOne({
48037
+ referenceNumber: refId
48038
+ });
48039
+ if (!checkPayment)
48040
+ throw new Error("Payment not found");
48041
+ const isBulk = checkPayment.unitBillingItems.length > 1;
48042
+ const basePayload = {
48043
+ method: payload.method,
48044
+ transaction_id: transactionId,
48045
+ message,
48046
+ updatedAt: invoiceDate
48047
+ };
47815
48048
  if (result.response_code === "0") {
47816
48049
  const success = {
47817
- method: payload.method,
48050
+ ...basePayload,
47818
48051
  paymentStatus: "paid" /* PAID */,
47819
- amountPaid: parseInt(amount),
47820
- updatedAt: invoiceDate,
47821
- transaction_id: transactionId,
47822
- message
48052
+ amountPaid: parseInt(amount)
47823
48053
  };
47824
- await paySingleUnitBill(refId, success);
47825
- } else if (result.response_code !== "0") {
48054
+ if (isBulk) {
48055
+ await payMultipleUnitBill(refId, success);
48056
+ } else {
48057
+ await paySingleUnitBill(refId, success);
48058
+ }
48059
+ } else {
47826
48060
  const fail = {
47827
- method: payload.method,
48061
+ ...basePayload,
47828
48062
  paymentStatus: "failed" /* FAILED */,
47829
- updatedAt: invoiceDate,
47830
- paidBy: "",
47831
- amountPaid: 0,
47832
- transaction_id: transactionId,
47833
- message
48063
+ amountPaid: 0
47834
48064
  };
47835
- await paySingleUnitBill(refId, fail);
48065
+ if (isBulk) {
48066
+ await payMultipleUnitBill(refId, fail);
48067
+ } else {
48068
+ await paySingleUnitBill(refId, fail);
48069
+ }
47836
48070
  }
47837
48071
  return result;
47838
48072
  } catch (error) {
47839
48073
  return Promise.reject(error || error.message || "Server Internal Error!");
47840
48074
  }
47841
48075
  };
47842
- const payInvoice = async (payload) => {
47843
- try {
47844
- const data = {
47845
- cardNumber: payload.cardNumber,
47846
- rdpMid: payload.rdpMid,
47847
- orderId: payload.orderId
47848
- };
47849
- const dataString = JSON.stringify(data);
47850
- const headers = {
47851
- "Content-Type": "application/json",
47852
- "Content-Length": String(dataString.length)
47853
- };
47854
- if (!process.env.MERCHANT_PAYMENT) {
47855
- throw new Error(
47856
- "MERCHANT_PAYMENT environment variable is not defined."
47857
- );
47858
- }
47859
- const url = process.env.MERCHANT_PAYMENT;
47860
- const response = await axios3.post(url, dataString, { headers });
47861
- return response;
47862
- } catch (error) {
47863
- return Promise.reject(error || error.message || "Server Internal Error!");
47864
- }
47865
- };
47866
48076
  return {
47867
48077
  redirectPaymentTransaction,
47868
- enquirePaymentTransaction,
47869
- payInvoice
48078
+ enquirePaymentTransaction
47870
48079
  };
47871
48080
  };
47872
48081
 
@@ -47956,12 +48165,12 @@ function useRedDotPaymentController() {
47956
48165
  import {
47957
48166
  useMailer as useMailer4,
47958
48167
  compileHandlebar as compileHandlebar4,
47959
- logger as logger179,
48168
+ logger as logger178,
47960
48169
  getDirectory as getDirectory4,
47961
48170
  BadRequestError as BadRequestError199,
47962
48171
  NotFoundError as NotFoundError51,
47963
- InternalServerError as InternalServerError68,
47964
- useAtlas as useAtlas112,
48172
+ InternalServerError as InternalServerError69,
48173
+ useAtlas as useAtlas113,
47965
48174
  hashPassword as hashPassword4
47966
48175
  } from "@7365admin1/node-server-utils";
47967
48176
  import crypto4 from "crypto";
@@ -48028,7 +48237,7 @@ function useVerificationServiceV2() {
48028
48237
  email,
48029
48238
  metadata
48030
48239
  }) {
48031
- const session = useAtlas112.getClient()?.startSession();
48240
+ const session = useAtlas113.getClient()?.startSession();
48032
48241
  try {
48033
48242
  session?.startTransaction();
48034
48243
  const user = await _getUserByEmailStatus(email);
@@ -48065,7 +48274,7 @@ function useVerificationServiceV2() {
48065
48274
  html: emailContent,
48066
48275
  sender: "iService365" /* ISERVICE365 */
48067
48276
  }).catch((error) => {
48068
- logger179.log({
48277
+ logger178.log({
48069
48278
  level: "error",
48070
48279
  message: `Error sending user invite email: ${error}`
48071
48280
  });
@@ -48080,7 +48289,7 @@ function useVerificationServiceV2() {
48080
48289
  }
48081
48290
  }
48082
48291
  async function verify(verificationCode) {
48083
- const session = useAtlas112.getClient()?.startSession();
48292
+ const session = useAtlas113.getClient()?.startSession();
48084
48293
  try {
48085
48294
  session?.startTransaction();
48086
48295
  const item = await _getByVerificationCode(verificationCode);
@@ -48110,7 +48319,7 @@ function useVerificationServiceV2() {
48110
48319
  return { _id, type, email, status, expireAt };
48111
48320
  } catch (error) {
48112
48321
  await session?.abortTransaction();
48113
- logger179.log({
48322
+ logger178.log({
48114
48323
  level: "info",
48115
48324
  message: `Error verifying user invitation: ${error}`
48116
48325
  });
@@ -48165,7 +48374,7 @@ function useVerificationServiceV2() {
48165
48374
  html: emailContent,
48166
48375
  sender: "iService365" /* ISERVICE365 */
48167
48376
  }).catch((error) => {
48168
- logger179.log({
48377
+ logger178.log({
48169
48378
  level: "error",
48170
48379
  message: `Error sending user ${type} email: ${error}`
48171
48380
  });
@@ -48195,7 +48404,7 @@ function useVerificationServiceV2() {
48195
48404
  });
48196
48405
  if (error) {
48197
48406
  const messages = error.details.map((d) => d.message).join(", ");
48198
- logger179.log({ level: "error", message: messages });
48407
+ logger178.log({ level: "error", message: messages });
48199
48408
  throw new BadRequestError199(`Invalid input: ${error.message}`);
48200
48409
  }
48201
48410
  let subject = "Service Provider Invite" /* _SERVICE_PROVIDER_INVITE */;
@@ -48277,21 +48486,21 @@ function useVerificationServiceV2() {
48277
48486
  sender: "iService365" /* ISERVICE365 */,
48278
48487
  html: emailContent
48279
48488
  }).catch((error) => {
48280
- logger179.log({
48489
+ logger178.log({
48281
48490
  level: "error",
48282
48491
  message: `Error sending forget password email: ${error}`
48283
48492
  });
48284
48493
  });
48285
48494
  return "Successfully created a link to reset password. Please check your email.";
48286
48495
  } catch (error) {
48287
- throw new InternalServerError68("Failed to create forget password link.");
48496
+ throw new InternalServerError69("Failed to create forget password link.");
48288
48497
  }
48289
48498
  }
48290
48499
  async function cancelUserInvitation(id) {
48291
48500
  try {
48292
48501
  await _updateStatusById(id, "cancelled");
48293
48502
  } catch (error) {
48294
- throw new InternalServerError68(
48503
+ throw new InternalServerError69(
48295
48504
  `Error cancelling user invitation: ${error}`
48296
48505
  );
48297
48506
  }
@@ -48307,7 +48516,7 @@ function useVerificationServiceV2() {
48307
48516
  }
48308
48517
 
48309
48518
  // src/controllers/verification-v2.controller.ts
48310
- import { BadRequestError as BadRequestError200, logger as logger180 } from "@7365admin1/node-server-utils";
48519
+ import { BadRequestError as BadRequestError200, logger as logger179 } from "@7365admin1/node-server-utils";
48311
48520
  import Joi127 from "joi";
48312
48521
  function useVerificationControllerV2() {
48313
48522
  const {
@@ -48329,7 +48538,7 @@ function useVerificationControllerV2() {
48329
48538
  );
48330
48539
  if (error) {
48331
48540
  const messages = error.details.map((d) => d.message).join(", ");
48332
- logger180.log({ level: "error", message: messages });
48541
+ logger179.log({ level: "error", message: messages });
48333
48542
  next(new BadRequestError200(messages));
48334
48543
  return;
48335
48544
  }
@@ -48337,7 +48546,7 @@ function useVerificationControllerV2() {
48337
48546
  res.json(message);
48338
48547
  return;
48339
48548
  } catch (error) {
48340
- logger180.log({ level: "error", message: `${error.message}` });
48549
+ logger179.log({ level: "error", message: `${error.message}` });
48341
48550
  next(error);
48342
48551
  return;
48343
48552
  }
@@ -48355,7 +48564,7 @@ function useVerificationControllerV2() {
48355
48564
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
48356
48565
  if (error) {
48357
48566
  const messages = error.details.map((d) => d.message).join(", ");
48358
- logger180.log({ level: "error", message: messages });
48567
+ logger179.log({ level: "error", message: messages });
48359
48568
  next(new BadRequestError200(messages));
48360
48569
  return;
48361
48570
  }
@@ -48375,7 +48584,7 @@ function useVerificationControllerV2() {
48375
48584
  res.status(201).json({ message: "Successfully invited user." });
48376
48585
  return;
48377
48586
  } catch (error2) {
48378
- logger180.log({ level: "error", message: `${error2.message}` });
48587
+ logger179.log({ level: "error", message: `${error2.message}` });
48379
48588
  next(error2);
48380
48589
  return;
48381
48590
  }
@@ -48390,7 +48599,7 @@ function useVerificationControllerV2() {
48390
48599
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
48391
48600
  if (error) {
48392
48601
  const messages = error.details.map((d) => d.message).join(", ");
48393
- logger180.log({ level: "error", message: messages });
48602
+ logger179.log({ level: "error", message: messages });
48394
48603
  next(new BadRequestError200(messages));
48395
48604
  return;
48396
48605
  }
@@ -48404,7 +48613,7 @@ function useVerificationControllerV2() {
48404
48613
  res.cookie("service-provider-email", value.email, cookieOptions).json({ message: "Successfully invited service provider." });
48405
48614
  return;
48406
48615
  } catch (error2) {
48407
- logger180.log({ level: "error", message: `controller - ${error2.message}` });
48616
+ logger179.log({ level: "error", message: `controller - ${error2.message}` });
48408
48617
  next(error2);
48409
48618
  return;
48410
48619
  }
@@ -48416,7 +48625,7 @@ function useVerificationControllerV2() {
48416
48625
  const { error, value } = schema2.validate(req.body, { abortEarly: false });
48417
48626
  if (error) {
48418
48627
  const messages = error.details.map((d) => d.message).join(", ");
48419
- logger180.log({ level: "error", message: messages });
48628
+ logger179.log({ level: "error", message: messages });
48420
48629
  next(new BadRequestError200(messages));
48421
48630
  return;
48422
48631
  }
@@ -48428,7 +48637,7 @@ function useVerificationControllerV2() {
48428
48637
  });
48429
48638
  return;
48430
48639
  } catch (error2) {
48431
- logger180.log({ level: "error", message: `${error2.message}` });
48640
+ logger179.log({ level: "error", message: `${error2.message}` });
48432
48641
  next(error2);
48433
48642
  return;
48434
48643
  }
@@ -48448,7 +48657,7 @@ function useVerificationControllerV2() {
48448
48657
  const { error, value } = schema2.validate(req.query);
48449
48658
  if (error) {
48450
48659
  const messages = error.details.map((d) => d.message).join(", ");
48451
- logger180.log({ level: "error", message: messages });
48660
+ logger179.log({ level: "error", message: messages });
48452
48661
  next(new BadRequestError200(messages));
48453
48662
  return;
48454
48663
  }
@@ -48465,7 +48674,7 @@ function useVerificationControllerV2() {
48465
48674
  res.json(data);
48466
48675
  return;
48467
48676
  } catch (error2) {
48468
- logger180.log({ level: "error", message: `${error2.message}` });
48677
+ logger179.log({ level: "error", message: `${error2.message}` });
48469
48678
  next(error2);
48470
48679
  return;
48471
48680
  }
@@ -48475,7 +48684,7 @@ function useVerificationControllerV2() {
48475
48684
  const otpId = req.params.id;
48476
48685
  const { error } = validation.validate(otpId);
48477
48686
  if (error) {
48478
- logger180.log({ level: "error", message: `${error.message}` });
48687
+ logger179.log({ level: "error", message: `${error.message}` });
48479
48688
  next(new BadRequestError200(error.message));
48480
48689
  return;
48481
48690
  }
@@ -48486,7 +48695,7 @@ function useVerificationControllerV2() {
48486
48695
  });
48487
48696
  return;
48488
48697
  } catch (error2) {
48489
- logger180.log({ level: "error", message: `${error2.message}` });
48698
+ logger179.log({ level: "error", message: `${error2.message}` });
48490
48699
  next(error2);
48491
48700
  return;
48492
48701
  }
@@ -48503,13 +48712,13 @@ function useVerificationControllerV2() {
48503
48712
 
48504
48713
  // src/controllers/auth-v2.controller.ts
48505
48714
  import Joi128 from "joi";
48506
- import { BadRequestError as BadRequestError204, logger as logger183 } from "@7365admin1/node-server-utils";
48715
+ import { BadRequestError as BadRequestError204, logger as logger182 } from "@7365admin1/node-server-utils";
48507
48716
 
48508
48717
  // src/services/auth-v2.service.ts
48509
48718
  import {
48510
48719
  BadRequestError as BadRequestError202,
48511
48720
  comparePassword as comparePassword3,
48512
- InternalServerError as InternalServerError70,
48721
+ InternalServerError as InternalServerError71,
48513
48722
  NotFoundError as NotFoundError53,
48514
48723
  useCache as useCache68
48515
48724
  } from "@7365admin1/node-server-utils";
@@ -48518,9 +48727,9 @@ import { v4 as uuidv42 } from "uuid";
48518
48727
  // src/repositories/user-v2.repo.ts
48519
48728
  import { ObjectId as ObjectId127 } from "mongodb";
48520
48729
  import {
48521
- useAtlas as useAtlas113,
48522
- InternalServerError as InternalServerError69,
48523
- logger as logger181,
48730
+ useAtlas as useAtlas114,
48731
+ InternalServerError as InternalServerError70,
48732
+ logger as logger180,
48524
48733
  BadRequestError as BadRequestError201,
48525
48734
  paginate as paginate58,
48526
48735
  NotFoundError as NotFoundError52,
@@ -48533,9 +48742,9 @@ function useUserRepoV2() {
48533
48742
  const { updateFeedbackCreatedByName } = useFeedbackRepo();
48534
48743
  const { updateWorkOrderCreatedByName } = useWorkOrderRepo();
48535
48744
  const { updateUserNameBySignatureId } = useOccurrenceEntryRepo();
48536
- const db = useAtlas113.getDb();
48745
+ const db = useAtlas114.getDb();
48537
48746
  if (!db) {
48538
- throw new InternalServerError69("Unable to connect to server.");
48747
+ throw new InternalServerError70("Unable to connect to server.");
48539
48748
  }
48540
48749
  const namespace_collection = "users";
48541
48750
  const collection = db.collection(namespace_collection);
@@ -48544,14 +48753,14 @@ function useUserRepoV2() {
48544
48753
  try {
48545
48754
  await collection.createIndexes([{ key: { email: 1 } }]);
48546
48755
  } catch (error) {
48547
- throw new InternalServerError69("Failed to create text index on user.");
48756
+ throw new InternalServerError70("Failed to create text index on user.");
48548
48757
  }
48549
48758
  }
48550
48759
  async function createTextIndex() {
48551
48760
  try {
48552
48761
  await collection.createIndex({ name: "text", email: "text" });
48553
48762
  } catch (error) {
48554
- throw new InternalServerError69("Failed to create text index on user.");
48763
+ throw new InternalServerError70("Failed to create text index on user.");
48555
48764
  }
48556
48765
  }
48557
48766
  async function createUniqueIndex() {
@@ -48561,7 +48770,7 @@ function useUserRepoV2() {
48561
48770
  { unique: true }
48562
48771
  );
48563
48772
  } catch (error) {
48564
- throw new InternalServerError69("Failed to create unique index on user.");
48773
+ throw new InternalServerError70("Failed to create unique index on user.");
48565
48774
  }
48566
48775
  }
48567
48776
  async function createUser(value, session) {
@@ -48569,16 +48778,16 @@ function useUserRepoV2() {
48569
48778
  value = MUser(value);
48570
48779
  const res = await collection.insertOne(value, { session });
48571
48780
  delNamespace().then(
48572
- () => logger181.info(`Cache cleared for namespace: ${namespace_collection}`)
48781
+ () => logger180.info(`Cache cleared for namespace: ${namespace_collection}`)
48573
48782
  ).catch(
48574
- (err) => logger181.error(
48783
+ (err) => logger180.error(
48575
48784
  `Failed to clear cache for namespace: ${namespace_collection}`,
48576
48785
  err
48577
48786
  )
48578
48787
  );
48579
48788
  return res.insertedId;
48580
48789
  } catch (error) {
48581
- logger181.log({ level: "error", message: `${error}` });
48790
+ logger180.log({ level: "error", message: `${error}` });
48582
48791
  if (error.message.includes("duplicate")) {
48583
48792
  throw new BadRequestError201("User already exists.");
48584
48793
  }
@@ -48590,18 +48799,18 @@ function useUserRepoV2() {
48590
48799
  const cacheKey = makeCacheKey65(namespace_collection, { email });
48591
48800
  const cachedData = await getCache(cacheKey);
48592
48801
  if (cachedData) {
48593
- logger181.info(`Cache hit for key: ${cacheKey}`);
48802
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48594
48803
  return cachedData;
48595
48804
  }
48596
48805
  const data = await collection.findOne({
48597
48806
  email: { $regex: `^${email}$`, $options: "i" }
48598
48807
  });
48599
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48600
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
48808
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
48809
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48601
48810
  );
48602
48811
  return data;
48603
48812
  } catch (error) {
48604
- throw new InternalServerError69("Failed to get user by email.");
48813
+ throw new InternalServerError70("Failed to get user by email.");
48605
48814
  }
48606
48815
  }
48607
48816
  async function getUserByEmailStatus(email) {
@@ -48612,19 +48821,19 @@ function useUserRepoV2() {
48612
48821
  });
48613
48822
  const cachedData = await getCache(cacheKey);
48614
48823
  if (cachedData) {
48615
- logger181.info(`Cache hit for key: ${cacheKey}`);
48824
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48616
48825
  return cachedData;
48617
48826
  }
48618
48827
  const data = await collection.findOne({
48619
48828
  email: { $regex: `^${email}$`, $options: "i" },
48620
48829
  status: "complete" /* COMPLETE */
48621
48830
  });
48622
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48623
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
48831
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
48832
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48624
48833
  );
48625
48834
  return data;
48626
48835
  } catch (error) {
48627
- throw new InternalServerError69("Failed to get user by email.");
48836
+ throw new InternalServerError70("Failed to get user by email.");
48628
48837
  }
48629
48838
  }
48630
48839
  async function getUserById(id) {
@@ -48633,7 +48842,7 @@ function useUserRepoV2() {
48633
48842
  const cacheKey = makeCacheKey65(namespace_collection, { id });
48634
48843
  const cachedData = await getCache(cacheKey);
48635
48844
  if (cachedData) {
48636
- logger181.info(`Cache hit for key: ${cacheKey}`);
48845
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48637
48846
  return cachedData;
48638
48847
  }
48639
48848
  const results = await collection.aggregate([
@@ -48657,14 +48866,14 @@ function useUserRepoV2() {
48657
48866
  const data = results.length > 0 ? results[0] : null;
48658
48867
  if (!data)
48659
48868
  throw new NotFoundError52("User not found.");
48660
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48661
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
48869
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
48870
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48662
48871
  );
48663
48872
  return data;
48664
48873
  } catch (error) {
48665
48874
  if (error instanceof AppError28)
48666
48875
  throw error;
48667
- throw new InternalServerError69("Failed to get user by id.");
48876
+ throw new InternalServerError70("Failed to get user by id.");
48668
48877
  }
48669
48878
  }
48670
48879
  async function getUserByReferralCode(referralCode) {
@@ -48672,16 +48881,16 @@ function useUserRepoV2() {
48672
48881
  const cacheKey = makeCacheKey65(namespace_collection, { referralCode });
48673
48882
  const cachedData = await getCache(cacheKey);
48674
48883
  if (cachedData) {
48675
- logger181.info(`Cache hit for key: ${cacheKey}`);
48884
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48676
48885
  return cachedData;
48677
48886
  }
48678
48887
  const data = await collection.findOne({ referralCode });
48679
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48680
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
48888
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
48889
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48681
48890
  );
48682
48891
  return data;
48683
48892
  } catch (error) {
48684
- throw new InternalServerError69("Failed to get user by referral code.");
48893
+ throw new InternalServerError70("Failed to get user by referral code.");
48685
48894
  }
48686
48895
  }
48687
48896
  async function getByEmailApp(email, app) {
@@ -48689,19 +48898,19 @@ function useUserRepoV2() {
48689
48898
  const cacheKey = makeCacheKey65(namespace_collection, { email, app });
48690
48899
  const cachedData = await getCache(cacheKey);
48691
48900
  if (cachedData) {
48692
- logger181.info(`Cache hit for key: ${cacheKey}`);
48901
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48693
48902
  return cachedData;
48694
48903
  }
48695
48904
  const data = await collection.findOne({
48696
48905
  email,
48697
48906
  "roles.app": app
48698
48907
  });
48699
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48700
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
48908
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
48909
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48701
48910
  );
48702
48911
  return data;
48703
48912
  } catch (error) {
48704
- throw new InternalServerError69("Failed to get user by email and app.");
48913
+ throw new InternalServerError70("Failed to get user by email and app.");
48705
48914
  }
48706
48915
  }
48707
48916
  async function getUsersByOrgId({
@@ -48735,9 +48944,9 @@ function useUserRepoV2() {
48735
48944
  }
48736
48945
  }
48737
48946
  delNamespace().then(() => {
48738
- logger181.info(`Cache cleared for namespace: ${namespace_collection}`);
48947
+ logger180.info(`Cache cleared for namespace: ${namespace_collection}`);
48739
48948
  }).catch((err) => {
48740
- logger181.error(
48949
+ logger180.error(
48741
48950
  `Failed to clear cache for namespace: ${namespace_collection}`,
48742
48951
  err
48743
48952
  );
@@ -48745,7 +48954,7 @@ function useUserRepoV2() {
48745
48954
  const cacheKey = makeCacheKey65(namespace_collection, cacheOptions);
48746
48955
  const cachedData = await getCache(cacheKey);
48747
48956
  if (cachedData) {
48748
- logger181.info(`Cache hit for key: ${cacheKey}`);
48957
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48749
48958
  return cachedData;
48750
48959
  }
48751
48960
  try {
@@ -48767,13 +48976,13 @@ function useUserRepoV2() {
48767
48976
  const length = await collection.countDocuments(query);
48768
48977
  const data = paginate58(items, page, limit, length);
48769
48978
  setCache(cacheKey, data, 15 * 60).then(() => {
48770
- logger181.info(`Cache set for key: ${cacheKey}`);
48979
+ logger180.info(`Cache set for key: ${cacheKey}`);
48771
48980
  }).catch((err) => {
48772
- logger181.error(`Failed to set cache for key: ${cacheKey}`, err);
48981
+ logger180.error(`Failed to set cache for key: ${cacheKey}`, err);
48773
48982
  });
48774
48983
  return data;
48775
48984
  } catch (error) {
48776
- logger181.log({ level: "error", message: `${error}` });
48985
+ logger180.log({ level: "error", message: `${error}` });
48777
48986
  throw error;
48778
48987
  }
48779
48988
  }
@@ -48799,9 +49008,9 @@ function useUserRepoV2() {
48799
49008
  cacheOptions.type = type;
48800
49009
  }
48801
49010
  delNamespace().then(
48802
- () => logger181.info(`Cache cleared for namespace: ${namespace_collection}`)
49011
+ () => logger180.info(`Cache cleared for namespace: ${namespace_collection}`)
48803
49012
  ).catch(
48804
- (err) => logger181.error(
49013
+ (err) => logger180.error(
48805
49014
  `Failed to clear cache for namespace: ${namespace_collection}`,
48806
49015
  err
48807
49016
  )
@@ -48809,7 +49018,7 @@ function useUserRepoV2() {
48809
49018
  const cacheKey = makeCacheKey65(namespace_collection, cacheOptions);
48810
49019
  const cachedData = await getCache(cacheKey);
48811
49020
  if (cachedData) {
48812
- logger181.info(`Cache hit for key: ${cacheKey}`);
49021
+ logger180.info(`Cache hit for key: ${cacheKey}`);
48813
49022
  return cachedData;
48814
49023
  }
48815
49024
  try {
@@ -48822,12 +49031,12 @@ function useUserRepoV2() {
48822
49031
  ]).toArray();
48823
49032
  const length = await collection.countDocuments(query);
48824
49033
  const data = paginate58(items, page, limit, length);
48825
- setCache(cacheKey, data, 15 * 60).then(() => logger181.info(`Cache set for key: ${cacheKey}`)).catch(
48826
- (err) => logger181.error(`Failed to set cache for key: ${cacheKey}`, err)
49034
+ setCache(cacheKey, data, 15 * 60).then(() => logger180.info(`Cache set for key: ${cacheKey}`)).catch(
49035
+ (err) => logger180.error(`Failed to set cache for key: ${cacheKey}`, err)
48827
49036
  );
48828
49037
  return data;
48829
49038
  } catch (error) {
48830
- logger181.log({ level: "error", message: `${error}` });
49039
+ logger180.log({ level: "error", message: `${error}` });
48831
49040
  throw error;
48832
49041
  }
48833
49042
  }
@@ -48841,13 +49050,13 @@ function useUserRepoV2() {
48841
49050
  { session }
48842
49051
  );
48843
49052
  delCache(cacheKey).then(() => {
48844
- logger181.info(`Cache deleted for key: ${cacheKey}`);
49053
+ logger180.info(`Cache deleted for key: ${cacheKey}`);
48845
49054
  }).catch((err) => {
48846
- logger181.error(`Failed to delete cache for key: ${cacheKey}`, err);
49055
+ logger180.error(`Failed to delete cache for key: ${cacheKey}`, err);
48847
49056
  });
48848
49057
  return result;
48849
49058
  } catch (error) {
48850
- throw new InternalServerError69("Failed to update user password.");
49059
+ throw new InternalServerError70("Failed to update user password.");
48851
49060
  }
48852
49061
  }
48853
49062
  async function updateUserFieldById({ _id, field, value } = {}, session) {
@@ -48898,13 +49107,13 @@ function useUserRepoV2() {
48898
49107
  );
48899
49108
  const cacheKey = makeCacheKey65(namespace_collection, { _id });
48900
49109
  delCache(cacheKey).then(() => {
48901
- logger181.info(`Cache deleted for key: ${cacheKey}`);
49110
+ logger180.info(`Cache deleted for key: ${cacheKey}`);
48902
49111
  }).catch((err) => {
48903
- logger181.error(`Failed to delete cache for key: ${cacheKey}`, err);
49112
+ logger180.error(`Failed to delete cache for key: ${cacheKey}`, err);
48904
49113
  });
48905
49114
  return `Successfully updated user ${field}.`;
48906
49115
  } catch (error) {
48907
- throw new InternalServerError69(`Failed to update user ${field}.`);
49116
+ throw new InternalServerError70(`Failed to update user ${field}.`);
48908
49117
  }
48909
49118
  }
48910
49119
  async function updateBirthday({
@@ -48933,13 +49142,13 @@ function useUserRepoV2() {
48933
49142
  );
48934
49143
  const cacheKey = makeCacheKey65(namespace_collection, { _id });
48935
49144
  delCache(cacheKey).then(() => {
48936
- logger181.info(`Cache deleted for key: ${cacheKey}`);
49145
+ logger180.info(`Cache deleted for key: ${cacheKey}`);
48937
49146
  }).catch((err) => {
48938
- logger181.error(`Failed to delete cache for key: ${cacheKey}`, err);
49147
+ logger180.error(`Failed to delete cache for key: ${cacheKey}`, err);
48939
49148
  });
48940
49149
  return "Successfully updated user birthday.";
48941
49150
  } catch (error) {
48942
- throw new InternalServerError69("Failed to update user birthday.");
49151
+ throw new InternalServerError70("Failed to update user birthday.");
48943
49152
  }
48944
49153
  }
48945
49154
  async function updatePassword({ _id, password }, session) {
@@ -48956,13 +49165,13 @@ function useUserRepoV2() {
48956
49165
  );
48957
49166
  const cacheKey = makeCacheKey65(namespace_collection, { _id });
48958
49167
  delCache(cacheKey).then(() => {
48959
- logger181.info(`Cache deleted for key: ${cacheKey}`);
49168
+ logger180.info(`Cache deleted for key: ${cacheKey}`);
48960
49169
  }).catch((err) => {
48961
- logger181.error(`Failed to delete cache for key: ${cacheKey}`, err);
49170
+ logger180.error(`Failed to delete cache for key: ${cacheKey}`, err);
48962
49171
  });
48963
49172
  return result;
48964
49173
  } catch (error) {
48965
- throw new InternalServerError69("Failed to update user password.");
49174
+ throw new InternalServerError70("Failed to update user password.");
48966
49175
  }
48967
49176
  }
48968
49177
  return {
@@ -49002,7 +49211,7 @@ function useAuthServiceV2() {
49002
49211
  );
49003
49212
  }
49004
49213
  if (!user._id) {
49005
- throw new InternalServerError70("Valid user ID.");
49214
+ throw new InternalServerError71("Valid user ID.");
49006
49215
  }
49007
49216
  if (user.status === "suspended") {
49008
49217
  throw new BadRequestError202(
@@ -49036,7 +49245,7 @@ function useAuthServiceV2() {
49036
49245
  await delCache(`sid:${sid}`);
49037
49246
  return "Session deleted successfully";
49038
49247
  } catch (error) {
49039
- throw new InternalServerError70("Error deleting token");
49248
+ throw new InternalServerError71("Error deleting token");
49040
49249
  }
49041
49250
  }
49042
49251
  async function verifyPassword(_id, password) {
@@ -49051,7 +49260,7 @@ function useAuthServiceV2() {
49051
49260
  if (error instanceof BadRequestError202) {
49052
49261
  throw error;
49053
49262
  }
49054
- throw new InternalServerError70("Error during password verification");
49263
+ throw new InternalServerError71("Error during password verification");
49055
49264
  }
49056
49265
  }
49057
49266
  return {
@@ -49066,9 +49275,9 @@ import {
49066
49275
  BadRequestError as BadRequestError203,
49067
49276
  comparePassword as comparePassword4,
49068
49277
  hashPassword as hashPassword5,
49069
- InternalServerError as InternalServerError71,
49278
+ InternalServerError as InternalServerError72,
49070
49279
  NotFoundError as NotFoundError54,
49071
- useAtlas as useAtlas114,
49280
+ useAtlas as useAtlas115,
49072
49281
  useS3 as useS33
49073
49282
  } from "@7365admin1/node-server-utils";
49074
49283
  import "multer";
@@ -49095,7 +49304,7 @@ function useUserServiceV2() {
49095
49304
  id = "",
49096
49305
  name = ""
49097
49306
  }) {
49098
- const session = useAtlas114.getClient()?.startSession();
49307
+ const session = useAtlas115.getClient()?.startSession();
49099
49308
  session?.startTransaction();
49100
49309
  try {
49101
49310
  const signUp = await _getVerificationById(id);
@@ -49161,12 +49370,12 @@ function useUserServiceV2() {
49161
49370
  throw new BadRequestError203("Passwords do not match.");
49162
49371
  }
49163
49372
  let hashedPassword;
49164
- const session = useAtlas114.getClient()?.startSession();
49373
+ const session = useAtlas115.getClient()?.startSession();
49165
49374
  session?.startTransaction();
49166
49375
  try {
49167
49376
  hashedPassword = await hashPassword5(newPassword);
49168
49377
  } catch (error) {
49169
- throw new InternalServerError71(`Error hashing password: ${error}`);
49378
+ throw new InternalServerError72(`Error hashing password: ${error}`);
49170
49379
  }
49171
49380
  try {
49172
49381
  const otpDoc = await _getVerificationById(id);
@@ -49181,7 +49390,7 @@ function useUserServiceV2() {
49181
49390
  throw new NotFoundError54("User not found.");
49182
49391
  }
49183
49392
  if (!user._id) {
49184
- throw new InternalServerError71("Invalid user ID.");
49393
+ throw new InternalServerError72("Invalid user ID.");
49185
49394
  }
49186
49395
  await Promise.all([
49187
49396
  _updateVerificationStatusById(id, "complete" /* COMPLETE */, session),
@@ -49212,7 +49421,7 @@ function useUserServiceV2() {
49212
49421
  user,
49213
49422
  previousProfile
49214
49423
  }) {
49215
- const session = useAtlas114.getClient()?.startSession();
49424
+ const session = useAtlas115.getClient()?.startSession();
49216
49425
  session?.startTransaction();
49217
49426
  const _file = {
49218
49427
  name: file.originalname,
@@ -49256,7 +49465,7 @@ function useUserServiceV2() {
49256
49465
  try {
49257
49466
  hashedPassword = await hashPassword5(newPassword);
49258
49467
  if (!hashedPassword)
49259
- throw new InternalServerError71("Error hashing password.");
49468
+ throw new InternalServerError72("Error hashing password.");
49260
49469
  return await updatePassword({ _id: id, password: hashedPassword });
49261
49470
  } catch (error) {
49262
49471
  throw error;
@@ -49292,7 +49501,7 @@ function useAuthControllerV2() {
49292
49501
  });
49293
49502
  if (error) {
49294
49503
  const messages = error.details.map((d) => d.message);
49295
- logger183.log({ level: "error", message: messages.join(", ") });
49504
+ logger182.log({ level: "error", message: messages.join(", ") });
49296
49505
  next(new BadRequestError204(messages.join(", ")));
49297
49506
  return;
49298
49507
  }
@@ -49309,7 +49518,7 @@ function useAuthControllerV2() {
49309
49518
  return;
49310
49519
  } catch (error) {
49311
49520
  console.log(error);
49312
- logger183.log({ level: "error", message: error.message });
49521
+ logger182.log({ level: "error", message: error.message });
49313
49522
  next(error);
49314
49523
  return;
49315
49524
  }
@@ -49327,7 +49536,7 @@ function useAuthControllerV2() {
49327
49536
  });
49328
49537
  if (error) {
49329
49538
  const messages = error.details.map((d) => d.message);
49330
- logger183.log({ level: "error", message: messages.join(", ") });
49539
+ logger182.log({ level: "error", message: messages.join(", ") });
49331
49540
  next(new BadRequestError204(messages.join(", ")));
49332
49541
  return;
49333
49542
  }
@@ -49340,7 +49549,7 @@ function useAuthControllerV2() {
49340
49549
  res.cookie("sid", session.sid, cookieOptions).cookie("user", session.user, cookieOptions).json(session);
49341
49550
  return;
49342
49551
  } catch (error) {
49343
- logger183.log({ level: "error", message: error.message });
49552
+ logger182.log({ level: "error", message: error.message });
49344
49553
  next(error);
49345
49554
  return;
49346
49555
  }
@@ -49356,7 +49565,7 @@ function useAuthControllerV2() {
49356
49565
  res.json({ message: "Logged out successfully" });
49357
49566
  return;
49358
49567
  } catch (error) {
49359
- logger183.log({ level: "error", message: error.message });
49568
+ logger182.log({ level: "error", message: error.message });
49360
49569
  next(error);
49361
49570
  return;
49362
49571
  }
@@ -49372,7 +49581,7 @@ function useAuthControllerV2() {
49372
49581
  });
49373
49582
  if (error) {
49374
49583
  const messages = error.details.map((d) => d.message);
49375
- logger183.log({ level: "error", message: messages.join(", ") });
49584
+ logger182.log({ level: "error", message: messages.join(", ") });
49376
49585
  next(new BadRequestError204(messages.join(", ")));
49377
49586
  return;
49378
49587
  }
@@ -49386,7 +49595,7 @@ function useAuthControllerV2() {
49386
49595
  res.json({ message });
49387
49596
  return;
49388
49597
  } catch (error2) {
49389
- logger183.log({ level: "error", message: error2.message });
49598
+ logger182.log({ level: "error", message: error2.message });
49390
49599
  next(error2);
49391
49600
  return;
49392
49601
  }
@@ -49402,7 +49611,7 @@ function useAuthControllerV2() {
49402
49611
  );
49403
49612
  if (error) {
49404
49613
  const messages = error.details.map((d) => d.message);
49405
- logger183.log({ level: "error", message: messages.join(", ") });
49614
+ logger182.log({ level: "error", message: messages.join(", ") });
49406
49615
  next(new BadRequestError204(messages.join(", ")));
49407
49616
  return;
49408
49617
  }
@@ -49412,7 +49621,7 @@ function useAuthControllerV2() {
49412
49621
  res.json({ message });
49413
49622
  return;
49414
49623
  } catch (error2) {
49415
- logger183.log({ level: "error", message: error2.message });
49624
+ logger182.log({ level: "error", message: error2.message });
49416
49625
  next(error2);
49417
49626
  return;
49418
49627
  }
@@ -49429,7 +49638,7 @@ function useAuthControllerV2() {
49429
49638
  // src/controllers/user-v2.controller.ts
49430
49639
  import Joi129 from "joi";
49431
49640
  import "multer";
49432
- import { BadRequestError as BadRequestError205, logger as logger184 } from "@7365admin1/node-server-utils";
49641
+ import { BadRequestError as BadRequestError205, logger as logger183 } from "@7365admin1/node-server-utils";
49433
49642
  function useUserControllerV2() {
49434
49643
  const {
49435
49644
  updateBirthday: _updateBirthday,
@@ -49443,7 +49652,7 @@ function useUserControllerV2() {
49443
49652
  const { createUserBySignUp, updateUserProfile: _updateUserProfile, updatePasswordById: _updatePasswordById } = useUserServiceV2();
49444
49653
  function rejectValidation(error, next) {
49445
49654
  const message = error.details.map((d) => d.message).join(", ");
49446
- logger184.log({ level: "error", message });
49655
+ logger183.log({ level: "error", message });
49447
49656
  next(new BadRequestError205(message));
49448
49657
  }
49449
49658
  async function getById(req, res, next) {
@@ -49451,7 +49660,7 @@ function useUserControllerV2() {
49451
49660
  const _id = req.params.id;
49452
49661
  const { error, value } = validation.validate(_id);
49453
49662
  if (error) {
49454
- logger184.log({ level: "error", message: `${error.message}` });
49663
+ logger183.log({ level: "error", message: `${error.message}` });
49455
49664
  next(new BadRequestError205(error.message));
49456
49665
  return;
49457
49666
  }
@@ -49460,7 +49669,7 @@ function useUserControllerV2() {
49460
49669
  res.json(user);
49461
49670
  return;
49462
49671
  } catch (error2) {
49463
- logger184.log({ level: "error", message: `${error2.message}` });
49672
+ logger183.log({ level: "error", message: `${error2.message}` });
49464
49673
  next(error2);
49465
49674
  return;
49466
49675
  }
@@ -49474,7 +49683,7 @@ function useUserControllerV2() {
49474
49683
  res.json(user);
49475
49684
  return;
49476
49685
  } catch (err) {
49477
- logger184.log({ level: "error", message: `${err.message}` });
49686
+ logger183.log({ level: "error", message: `${err.message}` });
49478
49687
  next(err);
49479
49688
  return;
49480
49689
  }
@@ -49541,7 +49750,7 @@ function useUserControllerV2() {
49541
49750
  const payload = { ...req.body };
49542
49751
  const { error, value } = validation.validate({ id, ...payload });
49543
49752
  if (error) {
49544
- logger184.log({ level: "error", message: `${error.message}` });
49753
+ logger183.log({ level: "error", message: `${error.message}` });
49545
49754
  next(new BadRequestError205(error.message));
49546
49755
  return;
49547
49756
  }
@@ -49550,7 +49759,7 @@ function useUserControllerV2() {
49550
49759
  res.status(201).json({ message: "Successfully created account." });
49551
49760
  return;
49552
49761
  } catch (error2) {
49553
- logger184.log({ level: "error", message: `${error2.message}` });
49762
+ logger183.log({ level: "error", message: `${error2.message}` });
49554
49763
  next(error2);
49555
49764
  return;
49556
49765
  }
@@ -49566,7 +49775,7 @@ function useUserControllerV2() {
49566
49775
  const payload = { ...req.body };
49567
49776
  const { error, value } = validation.validate(payload);
49568
49777
  if (error) {
49569
- logger184.log({ level: "error", message: `${error.message}` });
49778
+ logger183.log({ level: "error", message: `${error.message}` });
49570
49779
  next(new BadRequestError205(error.message));
49571
49780
  return;
49572
49781
  }
@@ -49580,7 +49789,7 @@ function useUserControllerV2() {
49580
49789
  res.json({ message: "Successfully updated profile picture." });
49581
49790
  return;
49582
49791
  } catch (error2) {
49583
- logger184.log({ level: "error", message: `${error2.message}` });
49792
+ logger183.log({ level: "error", message: `${error2.message}` });
49584
49793
  next(error2);
49585
49794
  return;
49586
49795
  }
@@ -49610,7 +49819,7 @@ function useUserControllerV2() {
49610
49819
  const payload = { ...req.body };
49611
49820
  const { error } = validation.validate({ _id, ...payload });
49612
49821
  if (error) {
49613
- logger184.log({ level: "error", message: `${error.message}` });
49822
+ logger183.log({ level: "error", message: `${error.message}` });
49614
49823
  next(new BadRequestError205(error.message));
49615
49824
  return;
49616
49825
  }
@@ -49619,7 +49828,7 @@ function useUserControllerV2() {
49619
49828
  res.json({ message });
49620
49829
  return;
49621
49830
  } catch (error2) {
49622
- logger184.log({ level: "error", message: `${error2.message}` });
49831
+ logger183.log({ level: "error", message: `${error2.message}` });
49623
49832
  next(error2);
49624
49833
  return;
49625
49834
  }
@@ -49641,7 +49850,7 @@ function useUserControllerV2() {
49641
49850
  const payload = { ...req.body };
49642
49851
  const { error } = validation.validate({ _id, ...payload });
49643
49852
  if (error) {
49644
- logger184.log({ level: "error", message: `${error.message}` });
49853
+ logger183.log({ level: "error", message: `${error.message}` });
49645
49854
  next(new BadRequestError205(error.message));
49646
49855
  return;
49647
49856
  }
@@ -49650,7 +49859,7 @@ function useUserControllerV2() {
49650
49859
  res.json({ message });
49651
49860
  return;
49652
49861
  } catch (error2) {
49653
- logger184.log({ level: "error", message: `${error2.message}` });
49862
+ logger183.log({ level: "error", message: `${error2.message}` });
49654
49863
  next(error2);
49655
49864
  return;
49656
49865
  }
@@ -49751,15 +49960,15 @@ var MRoleV2 = class {
49751
49960
  // src/repositories/role-v2.repo.ts
49752
49961
  import {
49753
49962
  BadRequestError as BadRequestError207,
49754
- InternalServerError as InternalServerError72,
49755
- useAtlas as useAtlas115,
49756
- logger as logger185,
49963
+ InternalServerError as InternalServerError73,
49964
+ useAtlas as useAtlas116,
49965
+ logger as logger184,
49757
49966
  useCache as useCache69
49758
49967
  } from "@7365admin1/node-server-utils";
49759
49968
  function useRoleRepoV2() {
49760
- const db = useAtlas115.getDb();
49969
+ const db = useAtlas116.getDb();
49761
49970
  if (!db) {
49762
- throw new InternalServerError72("Unable to connect to server.");
49971
+ throw new InternalServerError73("Unable to connect to server.");
49763
49972
  }
49764
49973
  const namespace_collection = "roles.v2";
49765
49974
  const collection = db.collection(namespace_collection);
@@ -49771,14 +49980,14 @@ function useRoleRepoV2() {
49771
49980
  { key: { status: 1 } }
49772
49981
  ]);
49773
49982
  } catch (error) {
49774
- throw new InternalServerError72("Failed to create index on role.");
49983
+ throw new InternalServerError73("Failed to create index on role.");
49775
49984
  }
49776
49985
  }
49777
49986
  async function createTextIndex() {
49778
49987
  try {
49779
49988
  await collection.createIndex({ name: "text" });
49780
49989
  } catch (error) {
49781
- throw new InternalServerError72("Failed to create text index on role.");
49990
+ throw new InternalServerError73("Failed to create text index on role.");
49782
49991
  }
49783
49992
  }
49784
49993
  async function createUniqueIndex() {
@@ -49788,7 +49997,7 @@ function useRoleRepoV2() {
49788
49997
  { unique: true }
49789
49998
  );
49790
49999
  } catch (error) {
49791
- throw new InternalServerError72("Failed to create unique index on role.");
50000
+ throw new InternalServerError73("Failed to create unique index on role.");
49792
50001
  }
49793
50002
  }
49794
50003
  const { delNamespace } = useCache69(namespace_collection);
@@ -49797,21 +50006,21 @@ function useRoleRepoV2() {
49797
50006
  try {
49798
50007
  const res = await collection.insertOne(value, { session });
49799
50008
  delNamespace().then(() => {
49800
- logger185.info(`Cache cleared for namespace: ${namespace_collection}`);
50009
+ logger184.info(`Cache cleared for namespace: ${namespace_collection}`);
49801
50010
  }).catch((err) => {
49802
- logger185.error(
50011
+ logger184.error(
49803
50012
  `Failed to clear cache for namespace: ${namespace_collection}`,
49804
50013
  err
49805
50014
  );
49806
50015
  });
49807
50016
  return res.insertedId;
49808
50017
  } catch (error) {
49809
- logger185.log({ level: "error", message: `${error}` });
50018
+ logger184.log({ level: "error", message: `${error}` });
49810
50019
  const isDuplicated = error.message.includes("duplicate");
49811
50020
  if (isDuplicated) {
49812
50021
  throw new BadRequestError207("Role already exists.");
49813
50022
  }
49814
- throw new InternalServerError72("Failed to create role.");
50023
+ throw new InternalServerError73("Failed to create role.");
49815
50024
  }
49816
50025
  }
49817
50026
  return {
@@ -49837,7 +50046,7 @@ function useRoleServiceV2() {
49837
50046
 
49838
50047
  // src/controllers/role-v2.controller.ts
49839
50048
  import Joi130 from "joi";
49840
- import { BadRequestError as BadRequestError208, logger as logger186 } from "@7365admin1/node-server-utils";
50049
+ import { BadRequestError as BadRequestError208, logger as logger185 } from "@7365admin1/node-server-utils";
49841
50050
  function useRoleControllerV2() {
49842
50051
  const { createRole: _createRole } = useRoleServiceV2();
49843
50052
  async function createRole(req, res, next) {
@@ -49853,7 +50062,7 @@ function useRoleControllerV2() {
49853
50062
  const { error, value } = validation.validate(payload, { abortEarly: false });
49854
50063
  if (error) {
49855
50064
  const message = error.details.map((item) => item.message).join(", ");
49856
- logger186.log({ level: "error", message });
50065
+ logger185.log({ level: "error", message });
49857
50066
  next(new BadRequestError208(message));
49858
50067
  return;
49859
50068
  }
@@ -49862,7 +50071,7 @@ function useRoleControllerV2() {
49862
50071
  res.status(201).json({ message: "Successfully created role.", data: { role } });
49863
50072
  return;
49864
50073
  } catch (error2) {
49865
- logger186.log({ level: "error", message: error2.message });
50074
+ logger185.log({ level: "error", message: error2.message });
49866
50075
  next(error2);
49867
50076
  return;
49868
50077
  }