@7365admin1/core 3.7.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -536,13 +536,13 @@ var require_logger = __commonJS({
536
536
  "use strict";
537
537
  exports.__esModule = true;
538
538
  var _utils = require_utils();
539
- var logger197 = {
539
+ var logger200 = {
540
540
  methodMap: ["debug", "info", "warn", "error"],
541
541
  level: "info",
542
542
  // Maps a given level value to the `methodMap` indexes above.
543
543
  lookupLevel: function lookupLevel(level) {
544
544
  if (typeof level === "string") {
545
- var levelMap = _utils.indexOf(logger197.methodMap, level.toLowerCase());
545
+ var levelMap = _utils.indexOf(logger200.methodMap, level.toLowerCase());
546
546
  if (levelMap >= 0) {
547
547
  level = levelMap;
548
548
  } else {
@@ -553,9 +553,9 @@ var require_logger = __commonJS({
553
553
  },
554
554
  // Can be overridden in the host environment
555
555
  log: function log(level) {
556
- level = logger197.lookupLevel(level);
557
- if (typeof console !== "undefined" && logger197.lookupLevel(logger197.level) <= level) {
558
- var method = logger197.methodMap[level];
556
+ level = logger200.lookupLevel(level);
557
+ if (typeof console !== "undefined" && logger200.lookupLevel(logger200.level) <= level) {
558
+ var method = logger200.methodMap[level];
559
559
  if (!console[method]) {
560
560
  method = "log";
561
561
  }
@@ -566,7 +566,7 @@ var require_logger = __commonJS({
566
566
  }
567
567
  }
568
568
  };
569
- exports["default"] = logger197;
569
+ exports["default"] = logger200;
570
570
  module2.exports = exports["default"];
571
571
  }
572
572
  });
@@ -5892,6 +5892,8 @@ __export(src_exports, {
5892
5892
  ANPRMode: () => ANPRMode,
5893
5893
  AccessTypeProps: () => AccessTypeProps,
5894
5894
  AppServiceType: () => AppServiceType,
5895
+ BidStatus: () => BidStatus,
5896
+ BidType: () => BidType,
5895
5897
  BuildingLevelStatus: () => BuildingLevelStatus,
5896
5898
  BuildingStatus: () => BuildingStatus,
5897
5899
  BulletinOrder: () => BulletinOrder,
@@ -5923,6 +5925,7 @@ __export(src_exports, {
5923
5925
  MAddress: () => MAddress,
5924
5926
  MAttendance: () => MAttendance,
5925
5927
  MAttendanceSettings: () => MAttendanceSettings,
5928
+ MBidPreloved: () => MBidPreloved,
5926
5929
  MBillingConfiguration: () => MBillingConfiguration,
5927
5930
  MBillingItem: () => MBillingItem,
5928
5931
  MBuilding: () => MBuilding,
@@ -5943,6 +5946,9 @@ __export(src_exports, {
5943
5946
  MFile: () => MFile,
5944
5947
  MFormEntry: () => MFormEntry,
5945
5948
  MGuestManagement: () => MGuestManagement,
5949
+ MHidAmicoEvent: () => MHidAmicoEvent,
5950
+ MHidAmicoIdentity: () => MHidAmicoIdentity,
5951
+ MHidAmicoReader: () => MHidAmicoReader,
5946
5952
  MIncidentReport: () => MIncidentReport,
5947
5953
  MManpowerDesignations: () => MManpowerDesignations,
5948
5954
  MManpowerMonitoring: () => MManpowerMonitoring,
@@ -6030,7 +6036,6 @@ __export(src_exports, {
6030
6036
  building_units_namespace_collection: () => building_units_namespace_collection,
6031
6037
  buildings_namespace_collection: () => buildings_namespace_collection,
6032
6038
  bulletin_boards_namespace_collection: () => bulletin_boards_namespace_collection,
6033
- calculatePercentage: () => calculatePercentage,
6034
6039
  chatSchema: () => chatSchema,
6035
6040
  createManpowerRemarksDaily: () => createManpowerRemarksDaily,
6036
6041
  customerSchema: () => customerSchema,
@@ -6041,7 +6046,6 @@ __export(src_exports, {
6041
6046
  feedbacks2_namespace_collection: () => feedbacks2_namespace_collection,
6042
6047
  feedbacks_namespace_collection: () => feedbacks_namespace_collection,
6043
6048
  formatDahuaDate: () => formatDahuaDate,
6044
- getPeriodRangeWithPrevious: () => getPeriodRangeWithPrevious,
6045
6049
  guests_namespace_collection: () => guests_namespace_collection,
6046
6050
  incidentReportLog: () => incidentReportLog,
6047
6051
  incidents_namespace_collection: () => incidents_namespace_collection,
@@ -6064,6 +6068,7 @@ __export(src_exports, {
6064
6068
  schema: () => schema,
6065
6069
  schemaApprovedBy: () => schemaApprovedBy,
6066
6070
  schemaApprover: () => schemaApprover,
6071
+ schemaBidPreloved: () => schemaBidPreloved,
6067
6072
  schemaBilling: () => schemaBilling,
6068
6073
  schemaBillingConfiguration: () => schemaBillingConfiguration,
6069
6074
  schemaBillingItem: () => schemaBillingItem,
@@ -6076,6 +6081,7 @@ __export(src_exports, {
6076
6081
  schemaCategoryPreloved: () => schemaCategoryPreloved,
6077
6082
  schemaChannelPreloved: () => schemaChannelPreloved,
6078
6083
  schemaChatPreloved: () => schemaChatPreloved,
6084
+ schemaCreateHidAmicoIdentity: () => schemaCreateHidAmicoIdentity,
6079
6085
  schemaCustomerSite: () => schemaCustomerSite,
6080
6086
  schemaDocumentManagement: () => schemaDocumentManagement,
6081
6087
  schemaEntryPassSettings: () => schemaEntryPassSettings,
@@ -6083,6 +6089,21 @@ __export(src_exports, {
6083
6089
  schemaFiles: () => schemaFiles,
6084
6090
  schemaFormEntry: () => schemaFormEntry,
6085
6091
  schemaGuestManagement: () => schemaGuestManagement,
6092
+ schemaHidAmicoConfiguration: () => schemaHidAmicoConfiguration,
6093
+ schemaHidAmicoEvent: () => schemaHidAmicoEvent,
6094
+ schemaHidAmicoExecuteActions: () => schemaHidAmicoExecuteActions,
6095
+ schemaHidAmicoIdentity: () => schemaHidAmicoIdentity,
6096
+ schemaHidAmicoIdentityIdParams: () => schemaHidAmicoIdentityIdParams,
6097
+ schemaHidAmicoIdentityQuery: () => schemaHidAmicoIdentityQuery,
6098
+ schemaHidAmicoLogQuery: () => schemaHidAmicoLogQuery,
6099
+ schemaHidAmicoNotificationParams: () => schemaHidAmicoNotificationParams,
6100
+ schemaHidAmicoObjectOperation: () => schemaHidAmicoObjectOperation,
6101
+ schemaHidAmicoReader: () => schemaHidAmicoReader,
6102
+ schemaHidAmicoReaderIdParams: () => schemaHidAmicoReaderIdParams,
6103
+ schemaHidAmicoReaderListQuery: () => schemaHidAmicoReaderListQuery,
6104
+ schemaHidAmicoSetConfiguration: () => schemaHidAmicoSetConfiguration,
6105
+ schemaHidAmicoSync: () => schemaHidAmicoSync,
6106
+ schemaHidAmicoUserImageParams: () => schemaHidAmicoUserImageParams,
6086
6107
  schemaIncidentReport: () => schemaIncidentReport,
6087
6108
  schemaMultipleDocumentManagement: () => schemaMultipleDocumentManagement,
6088
6109
  schemaNfcPatrolLog: () => schemaNfcPatrolLog,
@@ -6110,6 +6131,7 @@ __export(src_exports, {
6110
6131
  schemaStatementOfAccount: () => schemaStatementOfAccount,
6111
6132
  schemaSubcategoryPreloved: () => schemaSubcategoryPreloved,
6112
6133
  schemaUnitBilling: () => schemaUnitBilling,
6134
+ schemaUpdateBidPreloved: () => schemaUpdateBidPreloved,
6113
6135
  schemaUpdateBuildingLevel: () => schemaUpdateBuildingLevel,
6114
6136
  schemaUpdateBulletinBoard: () => schemaUpdateBulletinBoard,
6115
6137
  schemaUpdateBulletinVideo: () => schemaUpdateBulletinVideo,
@@ -6120,6 +6142,8 @@ __export(src_exports, {
6120
6142
  schemaUpdateEventManagement: () => schemaUpdateEventManagement,
6121
6143
  schemaUpdateFormEntry: () => schemaUpdateFormEntry,
6122
6144
  schemaUpdateGuestManagement: () => schemaUpdateGuestManagement,
6145
+ schemaUpdateHidAmicoIdentity: () => schemaUpdateHidAmicoIdentity,
6146
+ schemaUpdateHidAmicoReader: () => schemaUpdateHidAmicoReader,
6123
6147
  schemaUpdateIncidentReport: () => schemaUpdateIncidentReport,
6124
6148
  schemaUpdateOccurrenceBook: () => schemaUpdateOccurrenceBook,
6125
6149
  schemaUpdateOccurrenceEntry: () => schemaUpdateOccurrenceEntry,
@@ -6165,6 +6189,8 @@ __export(src_exports, {
6165
6189
  useAuthControllerV2: () => useAuthControllerV2,
6166
6190
  useAuthService: () => useAuthService,
6167
6191
  useAuthServiceV2: () => useAuthServiceV2,
6192
+ useBidPrelovedController: () => useBidPrelovedController,
6193
+ useBidPrelovedRepo: () => useBidPrelovedRepo,
6168
6194
  useBuildingController: () => useBuildingController,
6169
6195
  useBuildingLevelController: () => useBuildingLevelController,
6170
6196
  useBuildingLevelRepo: () => useBuildingLevelRepo,
@@ -6187,6 +6213,7 @@ __export(src_exports, {
6187
6213
  useChatController: () => useChatController,
6188
6214
  useChatPrelovedController: () => useChatPrelovedController,
6189
6215
  useChatPrelovedRepo: () => useChatPrelovedRepo,
6216
+ useChatPrelovedService: () => useChatPrelovedService,
6190
6217
  useChatRepo: () => useChatRepo,
6191
6218
  useCounterModel: () => useCounterModel,
6192
6219
  useCounterRepo: () => useCounterRepo,
@@ -6217,6 +6244,9 @@ __export(src_exports, {
6217
6244
  useGuestManagementController: () => useGuestManagementController,
6218
6245
  useGuestManagementRepo: () => useGuestManagementRepo,
6219
6246
  useGuestManagementService: () => useGuestManagementService,
6247
+ useHidAmicoController: () => useHidAmicoController,
6248
+ useHidAmicoRepo: () => useHidAmicoRepo,
6249
+ useHidAmicoService: () => useHidAmicoService,
6220
6250
  useHrmLabsAttendanceCtrl: () => useHrmLabsAttendanceCtrl,
6221
6251
  useHrmLabsAttendanceSrvc: () => useHrmLabsAttendanceSrvc,
6222
6252
  useIncidentReportController: () => useIncidentReportController,
@@ -11206,7 +11236,8 @@ var metadataSchema3 = import_joi9.default.object({
11206
11236
  guardPosts: import_joi9.default.number().optional(),
11207
11237
  gracePeriod: import_joi9.default.number().optional(),
11208
11238
  incidentCounter: import_joi9.default.number().optional(),
11209
- incidentLogo: import_joi9.default.string().optional().allow("", null)
11239
+ incidentLogo: import_joi9.default.string().optional().allow("", null),
11240
+ services: import_joi9.default.array().items(import_joi9.default.object().unknown(true)).optional()
11210
11241
  });
11211
11242
  var updateAddressSchema = import_joi9.default.object({
11212
11243
  line1: import_joi9.default.string().min(3).allow("", null),
@@ -11236,7 +11267,8 @@ var allowedFieldsSite = [
11236
11267
  "metadata.guardPosts",
11237
11268
  "metadata.gracePeriod",
11238
11269
  "metadata.incidentCounter",
11239
- "metadata.incidentLogo"
11270
+ "metadata.incidentLogo",
11271
+ "metadata.services"
11240
11272
  ];
11241
11273
  var siteSchema = import_joi9.default.object({
11242
11274
  name: import_joi9.default.string().required(),
@@ -12110,9 +12142,7 @@ function useVerificationRepoV2() {
12110
12142
  }
12111
12143
  );
12112
12144
  } catch (error) {
12113
- throw new import_node_server_utils20.InternalServerError(
12114
- "Failed to retrieve verification."
12115
- );
12145
+ throw new import_node_server_utils20.InternalServerError("Failed to retrieve verification.");
12116
12146
  }
12117
12147
  }
12118
12148
  async function updateVerificationCodeById(_id, verificationCode, expireAt, session) {
@@ -12130,9 +12160,7 @@ function useVerificationRepoV2() {
12130
12160
  { session }
12131
12161
  );
12132
12162
  } catch (error) {
12133
- throw new import_node_server_utils20.InternalServerError(
12134
- "Failed to update verification code."
12135
- );
12163
+ throw new import_node_server_utils20.InternalServerError("Failed to update verification code.");
12136
12164
  }
12137
12165
  }
12138
12166
  return {
@@ -21016,12 +21044,20 @@ var schemaVisitorTransaction = import_joi37.default.object({
21016
21044
  nric: import_joi37.default.string().optional().allow(null, ""),
21017
21045
  visitorPass: import_joi37.default.array().items(
21018
21046
  import_joi37.default.object({
21019
- keyId: import_joi37.default.string().hex().length(24).required()
21047
+ keyId: import_joi37.default.string().hex().length(24).required(),
21048
+ receivedDate: import_joi37.default.date().optional().allow(null),
21049
+ status: import_joi37.default.string().optional().allow(null, ""),
21050
+ lastUpdate: import_joi37.default.date().optional().allow(null),
21051
+ remarks: import_joi37.default.string().optional().allow(null, "")
21020
21052
  })
21021
21053
  ).optional().allow(null),
21022
21054
  passKeys: import_joi37.default.array().items(
21023
21055
  import_joi37.default.object({
21024
- keyId: import_joi37.default.string().hex().length(24).required()
21056
+ keyId: import_joi37.default.string().hex().length(24).required(),
21057
+ receivedDate: import_joi37.default.date().optional().allow(null),
21058
+ status: import_joi37.default.string().optional().allow(null, ""),
21059
+ lastUpdate: import_joi37.default.date().optional().allow(null),
21060
+ remarks: import_joi37.default.string().optional().allow(null, "")
21025
21061
  })
21026
21062
  ).optional().allow(null),
21027
21063
  contact: import_joi37.default.string().optional().allow(null, "")
@@ -21038,19 +21074,28 @@ var schemaVisitorTransaction = import_joi37.default.object({
21038
21074
  numberOfPassengers: import_joi37.default.number().integer().optional().allow(null, ""),
21039
21075
  visitorPass: import_joi37.default.array().items(
21040
21076
  import_joi37.default.object({
21041
- keyId: import_joi37.default.string().hex().length(24).allow(null, "")
21077
+ keyId: import_joi37.default.string().hex().length(24).allow(null, ""),
21078
+ receivedDate: import_joi37.default.date().optional().allow(null),
21079
+ status: import_joi37.default.string().optional().allow(null, ""),
21080
+ lastUpdate: import_joi37.default.date().optional().allow(null),
21081
+ remarks: import_joi37.default.string().optional().allow(null, "")
21042
21082
  })
21043
21083
  ).optional().allow(null),
21044
21084
  passKeys: import_joi37.default.array().items(
21045
21085
  import_joi37.default.object({
21046
- keyId: import_joi37.default.string().hex().length(24).allow(null, "")
21086
+ keyId: import_joi37.default.string().hex().length(24).allow(null, ""),
21087
+ receivedDate: import_joi37.default.date().optional().allow(null),
21088
+ status: import_joi37.default.string().optional().allow(null, ""),
21089
+ lastUpdate: import_joi37.default.date().optional().allow(null),
21090
+ remarks: import_joi37.default.string().optional().allow(null, "")
21047
21091
  })
21048
21092
  ).optional().allow(null),
21049
21093
  checkInRemarks: import_joi37.default.string().optional().allow("", null),
21050
21094
  checkOutRemarks: import_joi37.default.string().optional().allow("", null),
21051
21095
  expectedCheckIn: import_joi37.default.string().isoDate().optional(),
21052
21096
  purpose: import_joi37.default.string().optional().allow(null, ""),
21053
- inviterId: import_joi37.default.any().optional().allow(null, "")
21097
+ inviterId: import_joi37.default.any().optional().allow(null, ""),
21098
+ createdBy: import_joi37.default.string().hex().length(24).optional().allow(null, "")
21054
21099
  });
21055
21100
  var schemaUpdateVisTrans = import_joi37.default.object({
21056
21101
  _id: import_joi37.default.string().hex().length(24).required(),
@@ -21170,22 +21215,22 @@ function MVisitorTransaction(value) {
21170
21215
  throw new Error("Invalid type for manualCheckout key.");
21171
21216
  }
21172
21217
  }
21173
- if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
21218
+ if (Array.isArray(value.visitorPass)) {
21174
21219
  value.visitorPass = value.visitorPass.map((v) => {
21175
- if (typeof v === "string")
21176
- return { keyId: new import_mongodb39.ObjectId(v) };
21177
- if (v?.keyId && typeof v.keyId === "string") {
21178
- return { keyId: new import_mongodb39.ObjectId(v.keyId) };
21220
+ try {
21221
+ v.keyId = new import_mongodb39.ObjectId(v.keyId);
21222
+ } catch (error2) {
21223
+ throw new Error("Invalid VisitorPass ID.");
21179
21224
  }
21180
21225
  return v;
21181
21226
  });
21182
21227
  }
21183
- if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
21228
+ if (Array.isArray(value.passKeys)) {
21184
21229
  value.passKeys = value.passKeys.map((p) => {
21185
- if (typeof p === "string")
21186
- return { keyId: new import_mongodb39.ObjectId(p) };
21187
- if (p?.keyId && typeof p.keyId === "string") {
21188
- return { keyId: new import_mongodb39.ObjectId(p.keyId) };
21230
+ try {
21231
+ p.keyId = new import_mongodb39.ObjectId(p.keyId);
21232
+ } catch (error2) {
21233
+ throw new Error("Invalid PassKey ID.");
21189
21234
  }
21190
21235
  return p;
21191
21236
  });
@@ -21880,9 +21925,57 @@ function useVisitorTransactionRepo() {
21880
21925
  }
21881
21926
  }
21882
21927
  async function resendEmailInvitedResident(visitorId, updatedBy) {
21883
- const updatedDocument = await collection.findOne({
21884
- _id: await convertObjectIdUtil(visitorId)
21885
- });
21928
+ const pipeline = [
21929
+ { $match: { _id: await convertObjectIdUtil(visitorId) } },
21930
+ {
21931
+ $lookup: {
21932
+ from: "buildings",
21933
+ localField: "block",
21934
+ foreignField: "_id",
21935
+ as: "blockDetails"
21936
+ }
21937
+ },
21938
+ {
21939
+ $addFields: {
21940
+ blockName: {
21941
+ $ifNull: [
21942
+ { $arrayElemAt: ["$blockDetails.name", 0] },
21943
+ "Unknown"
21944
+ ]
21945
+ }
21946
+ }
21947
+ },
21948
+ {
21949
+ $project: {
21950
+ blockDetails: 0
21951
+ }
21952
+ },
21953
+ {
21954
+ $lookup: {
21955
+ from: "building-levels",
21956
+ localField: "level",
21957
+ foreignField: "_id",
21958
+ as: "levelDetails"
21959
+ }
21960
+ },
21961
+ {
21962
+ $addFields: {
21963
+ levelName: {
21964
+ $ifNull: [
21965
+ { $arrayElemAt: ["$levelDetails.name", 0] },
21966
+ "Unknown"
21967
+ ]
21968
+ }
21969
+ }
21970
+ },
21971
+ {
21972
+ $project: {
21973
+ levelDetails: 0
21974
+ }
21975
+ }
21976
+ ];
21977
+ const results = await collection.aggregate(pipeline).toArray();
21978
+ const updatedDocument = results[0] || null;
21886
21979
  if (!updatedDocument?.email)
21887
21980
  return;
21888
21981
  if (!updatedDocument?._id)
@@ -21897,7 +21990,7 @@ function useVisitorTransactionRepo() {
21897
21990
  name: `${updatedDocument?.name}`,
21898
21991
  plateNumber: updatedDocument?.plateNumber,
21899
21992
  nric: updatedDocument?.nric,
21900
- address: `${updatedDocument?.block} ${updatedDocument?.level} ${updatedDocument?.unitName}`,
21993
+ address: `${updatedDocument?.blockName} ${updatedDocument?.levelName} ${updatedDocument?.unitName}`,
21901
21994
  contactNumber: updatedDocument?.contact ? updatedDocument?.contact : "N/A",
21902
21995
  email: updatedDocument?.email ? updatedDocument?.email : "N/A",
21903
21996
  duration: updatedDocument?.duration ? updatedDocument?.duration : "N/A",
@@ -27797,7 +27890,7 @@ function useBuildingRepo() {
27797
27890
  try {
27798
27891
  await collection.createIndexes([
27799
27892
  { key: { name: "text" }, name: "text-index" },
27800
- { key: { name: 1 }, unique: true, name: "unique-name-index" },
27893
+ // { key: { name: 1 }, unique: true, name: "unique-name-index" },
27801
27894
  { key: { site: 1 } },
27802
27895
  { key: { createdAt: 1 } },
27803
27896
  {
@@ -28474,11 +28567,6 @@ function useBuildingLevelRepo() {
28474
28567
  try {
28475
28568
  await collection.createIndexes([
28476
28569
  // Ensure name is unique per blockId
28477
- {
28478
- key: { blockId: 1, name: 1 },
28479
- unique: true,
28480
- name: "unique_name_per_blockId"
28481
- },
28482
28570
  // Other useful indexes
28483
28571
  { key: { site: 1 }, name: "idx_site" },
28484
28572
  { key: { blockId: 1 }, name: "idx_blockId" },
@@ -28739,7 +28827,11 @@ function useBuildingLevelRepo() {
28739
28827
  const res = await collection.bulkWrite(operations, { session });
28740
28828
  delCachedData();
28741
28829
  return {
28742
- insertedIds: res.insertedIds
28830
+ insertedIds: res.insertedIds,
28831
+ levels: levels.map((l, i) => ({
28832
+ _id: res.insertedIds[i],
28833
+ name: l.name
28834
+ }))
28743
28835
  };
28744
28836
  } catch (error) {
28745
28837
  import_node_server_utils86.logger.log({
@@ -29023,8 +29115,8 @@ function useBuildingService() {
29023
29115
  const name = row.name;
29024
29116
  const rawLevel = row.level?.toString().trim();
29025
29117
  const rawUnit = row.unit?.toString().trim();
29026
- const normalizedLevel = /^(na|n\/a)$/i.test(rawLevel) ? null : `Lvl${rawLevel}`;
29027
- const normalizedUnit = /^(na|n\/a)$/i.test(rawUnit) ? null : `Unit ${rawUnit}`;
29118
+ const normalizedLevel = /^(na|n\/a)$/i.test(rawLevel) ? null : rawLevel;
29119
+ const normalizedUnit = /^(na|n\/a)$/i.test(rawUnit) ? null : rawUnit;
29028
29120
  if (!blockMap.has(block)) {
29029
29121
  blockMap.set(block, { name, levels: [], unitsByLevel: /* @__PURE__ */ new Map() });
29030
29122
  }
@@ -29045,57 +29137,76 @@ function useBuildingService() {
29045
29137
  }
29046
29138
  }
29047
29139
  }
29048
- const buildingPayloads = Array.from(blockMap.entries()).map(
29049
- ([block, { name, levels }]) => ({
29140
+ const buildingPayloads = [];
29141
+ const buildingUnitPayloads = [];
29142
+ for (const [
29143
+ block,
29144
+ { name, levels, unitsByLevel }
29145
+ ] of blockMap.entries()) {
29146
+ const buildingId = new import_mongodb53.ObjectId();
29147
+ const levelsPayload = (levels ?? []).map((levelName) => ({
29148
+ blockId: buildingId.toString(),
29149
+ site: site.toString(),
29150
+ name: levelName,
29151
+ status: "active" /* ACTIVE */,
29152
+ createdAt: /* @__PURE__ */ new Date(),
29153
+ updatedAt: null,
29154
+ deletedAt: null
29155
+ }));
29156
+ let insertedLevels;
29157
+ if (levelsPayload.length > 0) {
29158
+ insertedLevels = await _bulkWriteLevels(levelsPayload, session);
29159
+ }
29160
+ const levelNameToId = /* @__PURE__ */ new Map();
29161
+ if (insertedLevels) {
29162
+ insertedLevels.levels.forEach((lvl) => {
29163
+ levelNameToId.set(lvl.name, lvl._id);
29164
+ });
29165
+ }
29166
+ const buildingPayload = {
29167
+ _id: buildingId,
29050
29168
  site,
29051
29169
  block,
29052
29170
  name,
29053
- levels
29054
- })
29055
- );
29056
- const blockToBuildingId = /* @__PURE__ */ new Map();
29057
- for (const buildingPayload of buildingPayloads) {
29058
- const result = await _add(buildingPayload);
29059
- blockToBuildingId.set(buildingPayload.block, result);
29060
- }
29061
- const buildingUnitPayloads = [];
29062
- Array.from(blockMap.entries()).forEach(
29063
- ([block, { name, unitsByLevel }]) => {
29064
- const buildingId = blockToBuildingId.get(block);
29065
- Array.from(unitsByLevel.entries()).forEach(([level, units]) => {
29066
- units.forEach((unit) => {
29067
- buildingUnitPayloads.push({
29068
- site,
29069
- name: unit,
29070
- building: buildingId.toString(),
29071
- buildingName: name,
29072
- block,
29073
- level,
29074
- category: "",
29075
- status: "active" /* ACTIVE */,
29076
- buildingUnitFiles: [],
29077
- owner: "",
29078
- ownerName: "",
29079
- companyName: "",
29080
- companyRegistrationNumber: "",
29081
- billing: [],
29082
- unitNumber: parseInt(unit.replace("Unit ", ""), 10) || null,
29083
- createdAt: /* @__PURE__ */ new Date(),
29084
- updatedAt: "",
29085
- deletedAt: ""
29086
- });
29171
+ levels: insertedLevels ? Object.values(insertedLevels.insertedIds) : []
29172
+ };
29173
+ const buildingResult = await _add(buildingPayload, session);
29174
+ Array.from(unitsByLevel.entries()).forEach(([levelName, units]) => {
29175
+ const levelId = levelNameToId.get(levelName);
29176
+ units.forEach((unit) => {
29177
+ buildingUnitPayloads.push({
29178
+ site: new import_mongodb53.ObjectId(site),
29179
+ name: unit,
29180
+ building: buildingId,
29181
+ // already an ObjectId
29182
+ buildingName: name,
29183
+ block,
29184
+ level: levelId,
29185
+ // ✅ use ObjectId instead of string
29186
+ category: "",
29187
+ status: "active" /* ACTIVE */,
29188
+ buildingUnitFiles: [],
29189
+ owner: "",
29190
+ ownerName: "",
29191
+ companyName: "",
29192
+ companyRegistrationNumber: "",
29193
+ billing: [],
29194
+ unitNumber: parseInt(unit.replace("Unit ", ""), 10) || null,
29195
+ createdAt: /* @__PURE__ */ new Date(),
29196
+ updatedAt: "",
29197
+ deletedAt: ""
29087
29198
  });
29088
29199
  });
29089
- }
29090
- );
29200
+ });
29201
+ }
29091
29202
  await _bulkAddBuildingUnits(buildingUnitPayloads);
29092
- await session?.commitTransaction();
29203
+ await session.commitTransaction();
29093
29204
  return { buildingPayloads, buildingUnitPayloads };
29094
29205
  } catch (error) {
29095
- await session?.abortTransaction();
29206
+ await session.abortTransaction();
29096
29207
  throw error;
29097
29208
  } finally {
29098
- session?.endSession();
29209
+ session.endSession();
29099
29210
  }
29100
29211
  }
29101
29212
  return {
@@ -29366,9 +29477,9 @@ function useBuildingController() {
29366
29477
  const lowerName = originalname.toLowerCase();
29367
29478
  const rowSchema = import_joi46.default.object({
29368
29479
  block: import_joi46.default.number().integer().min(0).required(),
29369
- level: import_joi46.default.string().optional().allow(null, ""),
29370
- unit: import_joi46.default.string().optional().allow(null, ""),
29371
- category: import_joi46.default.string().trim().required(),
29480
+ level: import_joi46.default.alternatives().try(import_joi46.default.string(), import_joi46.default.number()).custom((value) => String(value)).optional().allow(null, ""),
29481
+ unit: import_joi46.default.alternatives().try(import_joi46.default.string(), import_joi46.default.number()).custom((value) => String(value)).optional().allow(null, ""),
29482
+ category: import_joi46.default.string().trim().optional().allow(null, ""),
29372
29483
  name: import_joi46.default.string().trim().optional().allow(null, ""),
29373
29484
  email: import_joi46.default.string().email().lowercase().optional().allow(null, ""),
29374
29485
  phoneNumber: import_joi46.default.string().trim().optional().allow(null, "")
@@ -29382,11 +29493,9 @@ function useBuildingController() {
29382
29493
  { abortEarly: false, convert: true }
29383
29494
  );
29384
29495
  if (queryError) {
29385
- next(
29386
- new import_node_server_utils88.BadRequestError(
29387
- queryError.details.map((d) => d.message).join(", ")
29388
- )
29389
- );
29496
+ const messages = queryError.details.map((d) => d.message).join(", ");
29497
+ import_node_server_utils88.logger.log({ level: "error", message: messages });
29498
+ next(new import_node_server_utils88.BadRequestError(messages));
29390
29499
  return;
29391
29500
  }
29392
29501
  const { site, org } = queryValue;
@@ -29421,11 +29530,11 @@ function useBuildingController() {
29421
29530
  } else if (lowerName.endsWith(".csv")) {
29422
29531
  rows = await new Promise((resolve, reject) => {
29423
29532
  const parsed = [];
29424
- import_fs3.default.createReadStream(path5).pipe((0, import_csv_parser.default)()).on("headers", (headers) => {
29425
- headers = headers.map(
29426
- (h) => h.trim().replace(/\(.*\)/, "").trim()
29427
- );
29428
- }).on("data", (row) => parsed.push(row)).on("end", () => resolve(parsed)).on("error", reject);
29533
+ import_fs3.default.createReadStream(path5).pipe(
29534
+ (0, import_csv_parser.default)({
29535
+ mapHeaders: ({ header }) => header.trim().replace(/\(.*\)/, "").trim()
29536
+ })
29537
+ ).on("data", (row) => parsed.push(row)).on("end", () => resolve(parsed)).on("error", reject);
29429
29538
  });
29430
29539
  } else {
29431
29540
  next(
@@ -29443,6 +29552,7 @@ function useBuildingController() {
29443
29552
  if (error) {
29444
29553
  invalidRows.push({
29445
29554
  row: index + 2,
29555
+ // +2 because header is row 1
29446
29556
  data: row,
29447
29557
  errors: error.details.map((d) => d.message)
29448
29558
  });
@@ -29464,6 +29574,7 @@ function useBuildingController() {
29464
29574
  import_fs3.default.unlink(path5, () => {
29465
29575
  });
29466
29576
  } catch (error) {
29577
+ console.log(error);
29467
29578
  import_node_server_utils88.logger.log({ level: "error", message: error.message });
29468
29579
  next(error);
29469
29580
  }
@@ -33392,17 +33503,13 @@ var KeyRepo = class {
33392
33503
  }
33393
33504
  }
33394
33505
  static async updateKeyById(keyId, key, site, session, isChild) {
33395
- try {
33396
- keyId = new import_mongodb61.ObjectId(keyId);
33397
- if (site)
33398
- site = new import_mongodb61.ObjectId(site);
33399
- if (key.updatedBy)
33400
- key.updatedBy = await convertObjectIdUtil(key.updatedBy);
33401
- if (!key.status)
33402
- delete key.status;
33403
- } catch (error) {
33404
- return Promise.reject("Invalid key id");
33405
- }
33506
+ keyId = await convertObjectIdUtil2(keyId, "keyId");
33507
+ if (site)
33508
+ site = await convertObjectIdUtil2(site, "Site");
33509
+ if (key.updatedBy)
33510
+ key.updatedBy = await convertObjectIdUtil2(key.updatedBy, "Updated By");
33511
+ if (!key.status)
33512
+ delete key.status;
33406
33513
  try {
33407
33514
  key.updatedAt = /* @__PURE__ */ new Date();
33408
33515
  const query = { _id: keyId, ...site && { site } };
@@ -33415,6 +33522,7 @@ var KeyRepo = class {
33415
33522
  { session }
33416
33523
  );
33417
33524
  let setKeys = [];
33525
+ console.log("updateKeyById result", result);
33418
33526
  if (result.modifiedCount > 0) {
33419
33527
  const updatedDocs = await this.collection().find(find).toArray();
33420
33528
  if (Array.isArray(updatedDocs) && updatedDocs.length > 0) {
@@ -33429,10 +33537,12 @@ var KeyRepo = class {
33429
33537
  await this.collectionDynamic("keys-histories").insertMany(setKeys, {
33430
33538
  session
33431
33539
  });
33540
+ } else {
33541
+ throw new Error("Failed Updating Keys");
33432
33542
  }
33433
33543
  return result;
33434
33544
  } catch (error) {
33435
- console.log(error);
33545
+ throw new Error(error);
33436
33546
  }
33437
33547
  }
33438
33548
  static async deleteKeyById(_id, session) {
@@ -33515,6 +33625,176 @@ var KeyRepo = class {
33515
33625
  }
33516
33626
  };
33517
33627
 
33628
+ // src/services/notification.service.ts
33629
+ var import_iservice365_expo_notifications = require("iservice365-expo-notifications");
33630
+
33631
+ // src/repositories/push-token.repository.ts
33632
+ var PushTokenRepo = class {
33633
+ static collection() {
33634
+ return getDB().collection("push_tokens");
33635
+ }
33636
+ static async createIndexes() {
33637
+ await Promise.all([
33638
+ this.collection().createIndex({ token: 1 }, { unique: true }),
33639
+ this.collection().createIndex({ userId: 1, platform: 1 }),
33640
+ this.collection().createIndex({ siteId: 1 })
33641
+ ]);
33642
+ }
33643
+ static async upsert(userId, token, platform, siteId, projectId, appSlug) {
33644
+ const now = /* @__PURE__ */ new Date();
33645
+ const p = platform;
33646
+ const existing = await this.collection().findOne({ token });
33647
+ if (existing) {
33648
+ await this.collection().updateOne(
33649
+ { token },
33650
+ {
33651
+ $set: {
33652
+ userId,
33653
+ platform: p,
33654
+ siteId,
33655
+ projectId,
33656
+ appSlug,
33657
+ updatedAt: now
33658
+ }
33659
+ }
33660
+ );
33661
+ return;
33662
+ }
33663
+ await this.collection().deleteMany({ userId, platform: p });
33664
+ await this.collection().insertOne({
33665
+ userId,
33666
+ siteId,
33667
+ token,
33668
+ platform: p,
33669
+ projectId,
33670
+ appSlug,
33671
+ createdAt: now,
33672
+ updatedAt: now
33673
+ });
33674
+ }
33675
+ static async remove(token) {
33676
+ await this.collection().deleteMany({ token });
33677
+ }
33678
+ static async findTokensByUserIds(userIds, appSlug) {
33679
+ const docs = await this.collection().find({ userId: { $in: userIds }, appSlug: { $eq: appSlug } }).toArray();
33680
+ return docs.map((d) => d.token);
33681
+ }
33682
+ };
33683
+
33684
+ // src/services/notification.service.ts
33685
+ function toStringArray(recipient) {
33686
+ const arr = Array.isArray(recipient) ? recipient : [recipient];
33687
+ return arr.map((r) => r.toString());
33688
+ }
33689
+ async function send(userIds, title, body, data, isForMAMobileApp = false, appSlug) {
33690
+ try {
33691
+ let tokens = [];
33692
+ if (isForMAMobileApp) {
33693
+ tokens = await PushTokenRepo.findTokensByUserIds(userIds, appSlug);
33694
+ } else {
33695
+ tokens = await PushTokenRepo.findTokensByUserIds(userIds);
33696
+ }
33697
+ if (!tokens.length)
33698
+ return;
33699
+ for (const token of tokens) {
33700
+ await (0, import_iservice365_expo_notifications.sendExpoPushNotifications)([token], { title, body, data });
33701
+ }
33702
+ } catch (error) {
33703
+ console.warn("[NotificationService]", error);
33704
+ }
33705
+ }
33706
+ var NotificationService = class {
33707
+ static async bulletinBoardCreated(payload) {
33708
+ await send(
33709
+ toStringArray(payload.to),
33710
+ "Bulletin Board",
33711
+ `There is new ${payload.status} bulletin board.`,
33712
+ {
33713
+ bulletinId: payload.bulletinId.toString(),
33714
+ status: payload.status,
33715
+ module: "feedback",
33716
+ screen: "/(user)/bulletinInfo",
33717
+ params: {
33718
+ id: payload.bulletinId.toString()
33719
+ }
33720
+ },
33721
+ false,
33722
+ "iservice365-resident-mobile-app"
33723
+ );
33724
+ }
33725
+ static async prelovedMarketplacePostCreation(payload) {
33726
+ await send(
33727
+ toStringArray(payload.to),
33728
+ "Preloved Marketplace",
33729
+ `New preloved marketplace post added.`,
33730
+ {
33731
+ prelovedId: payload.prelovedId.toString(),
33732
+ status: payload.status,
33733
+ module: "prelovedMarketplace",
33734
+ screen: "/(user)/(marketplace)/prelovedPostInfo",
33735
+ params: {
33736
+ id: payload.prelovedId.toString()
33737
+ }
33738
+ },
33739
+ false,
33740
+ "iservice365-resident-mobile-app"
33741
+ );
33742
+ }
33743
+ static async bulletinBoardCreatedForMA(payload) {
33744
+ await send(
33745
+ toStringArray(payload.to),
33746
+ "Bulletin Board",
33747
+ `There is new ${payload.status} bulletin board.`,
33748
+ {
33749
+ bulletinId: payload.bulletinId.toString(),
33750
+ status: payload.status,
33751
+ module: "feedback",
33752
+ screen: "/(user)/(bulletin-board)",
33753
+ params: {
33754
+ id: payload.bulletinId.toString()
33755
+ }
33756
+ },
33757
+ true,
33758
+ "iservice365-ma-mobile-app"
33759
+ );
33760
+ }
33761
+ static async eventCreatedForMA(payload) {
33762
+ await send(
33763
+ toStringArray(payload.to),
33764
+ "Event",
33765
+ `There is new ${payload.status} event.`,
33766
+ {
33767
+ eventId: payload.eventId.toString(),
33768
+ status: payload.status,
33769
+ module: "event",
33770
+ screen: "/(user)/(events)",
33771
+ params: {
33772
+ id: payload.eventId.toString()
33773
+ }
33774
+ },
33775
+ true,
33776
+ "iservice365-ma-mobile-app"
33777
+ );
33778
+ }
33779
+ static async invitedVisitorCheckOutForMa(payload) {
33780
+ await send(
33781
+ toStringArray(payload.to),
33782
+ "Invited Visitor Check Out",
33783
+ `The invited visitor ${payload.name}, has been checked out.`,
33784
+ {
33785
+ visitorTransactionId: payload._id.toString(),
33786
+ module: "visitors",
33787
+ screen: "/(user)/visitor-management",
33788
+ params: {
33789
+ id: payload._id.toString()
33790
+ }
33791
+ },
33792
+ true,
33793
+ "iservice365-ma-mobile-app"
33794
+ );
33795
+ }
33796
+ };
33797
+
33518
33798
  // src/services/visitor-transaction.service.ts
33519
33799
  function useVisitorTransactionService() {
33520
33800
  const MailerConfig = {
@@ -33553,6 +33833,7 @@ function useVisitorTransactionService() {
33553
33833
  getBlocklistedVehicleByPlateNumber: _getBlocklistedVehicleByPlateNumber
33554
33834
  } = useVehicleRepo();
33555
33835
  const { getById: _getUnitById } = useBuildingUnitRepo();
33836
+ const { getUsersBySiteId } = useMemberRepo();
33556
33837
  function extractKeyId(item) {
33557
33838
  if (!item)
33558
33839
  return null;
@@ -33702,47 +33983,50 @@ function useVisitorTransactionService() {
33702
33983
  const chunk = value.members.slice(i, i + chunkSize);
33703
33984
  for (const member of chunk) {
33704
33985
  await KeyRepo.checkPassKeyAvailability(member.visitorPass, member.passKeys);
33705
- if (member.visitorPass && Array.isArray(member.visitorPass) && member.visitorPass.length > 0) {
33706
- for (const vp of member.visitorPass) {
33707
- try {
33708
- const updatePayload = { status: "In Use" /* IN_USE */ };
33709
- const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
33710
- if (!visitorPassId)
33711
- value.visitorPass = [];
33712
- await KeyRepo.updateKeyById(
33713
- visitorPassId,
33714
- updatePayload,
33715
- value.site
33716
- );
33717
- } catch (error) {
33718
- throw error;
33719
- }
33986
+ if (Array.isArray(member.visitorPass)) {
33987
+ for (const item of member.visitorPass) {
33988
+ console.log("Type of keyId:", typeof item.keyId);
33989
+ console.log("item visitorPass", item);
33990
+ await KeyRepo.updateKeyById(
33991
+ item.keyId,
33992
+ {
33993
+ status: "In Use" /* IN_USE */,
33994
+ updatedBy: value.createdBy
33995
+ },
33996
+ value.site,
33997
+ session
33998
+ );
33999
+ item.receivedDate = /* @__PURE__ */ new Date();
34000
+ item.status = "Not Returned" /* NOT_RETURNED */;
34001
+ item.lastUpdate = null;
34002
+ item.remarks = "";
33720
34003
  }
33721
34004
  }
33722
- if (member.passKeys && Array.isArray(member.passKeys) && member.passKeys.length > 0) {
33723
- for (const pk of member.passKeys) {
33724
- try {
33725
- const updatePayload = { status: "In Use" /* IN_USE */ };
33726
- const passKeyId = typeof pk === "string" || pk instanceof import_mongodb62.ObjectId ? pk : pk.keyId;
33727
- if (!passKeyId)
33728
- value.passKeys = [];
33729
- await KeyRepo.updateKeyById(
33730
- passKeyId,
33731
- updatePayload,
33732
- value.site
33733
- );
33734
- } catch (error) {
33735
- throw error;
33736
- }
34005
+ if (Array.isArray(member.passKeys)) {
34006
+ for (const item of member.passKeys) {
34007
+ await KeyRepo.updateKeyById(
34008
+ item.keyId,
34009
+ {
34010
+ status: "In Use" /* IN_USE */,
34011
+ updatedBy: value.createdBy
34012
+ },
34013
+ value.site,
34014
+ session
34015
+ );
34016
+ item.receivedDate = /* @__PURE__ */ new Date();
34017
+ item.status = "Not Returned" /* NOT_RETURNED */;
34018
+ item.lastUpdate = null;
34019
+ item.remarks = "";
33737
34020
  }
33738
34021
  }
33739
34022
  }
33740
34023
  await Promise.all(
33741
34024
  chunk.map((member) => {
33742
- const { visitorPass, passKeys } = member;
34025
+ const clonedMember = structuredClone(member);
34026
+ const { visitorPass, passKeys } = clonedMember;
33743
34027
  return _add(
33744
34028
  {
33745
- ...member,
34029
+ ...clonedMember,
33746
34030
  block,
33747
34031
  level,
33748
34032
  unit,
@@ -33789,38 +34073,38 @@ function useVisitorTransactionService() {
33789
34073
  throw new import_node_server_utils106.BadRequestError("This plate number is blocklisted");
33790
34074
  }
33791
34075
  await KeyRepo.checkPassKeyAvailability(value.visitorPass, value.passKeys);
33792
- if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0 && value.visitorPass) {
33793
- for (const vp of value.visitorPass) {
33794
- try {
33795
- const updatePayload = { status: "In Use" /* IN_USE */ };
33796
- const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
33797
- if (!visitorPassId)
33798
- value.visitorPass = [];
33799
- await KeyRepo.updateKeyById(
33800
- visitorPassId,
33801
- updatePayload,
33802
- value.site
33803
- );
33804
- } catch (error) {
33805
- throw error;
33806
- }
34076
+ if (Array.isArray(value.visitorPass)) {
34077
+ for (const item of value.visitorPass) {
34078
+ await KeyRepo.updateKeyById(
34079
+ item.keyId,
34080
+ {
34081
+ status: "In Use" /* IN_USE */,
34082
+ updatedBy: value.createdBy
34083
+ },
34084
+ value.site,
34085
+ session
34086
+ );
34087
+ item.receivedDate = /* @__PURE__ */ new Date();
34088
+ item.status = "Not Returned" /* NOT_RETURNED */;
34089
+ item.lastUpdate = null;
34090
+ item.remarks = "";
33807
34091
  }
33808
34092
  }
33809
- if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
33810
- for (const pk of value.passKeys) {
33811
- try {
33812
- const updatePayload = { status: "In Use" /* IN_USE */ };
33813
- const passKeyId = typeof pk === "string" || pk instanceof import_mongodb62.ObjectId ? pk : pk.keyId;
33814
- if (!passKeyId)
33815
- value.passKeys = [];
33816
- await KeyRepo.updateKeyById(
33817
- passKeyId,
33818
- updatePayload,
33819
- value.site
33820
- );
33821
- } catch (error) {
33822
- throw error;
33823
- }
34093
+ if (Array.isArray(value.passKeys)) {
34094
+ for (const item of value.passKeys) {
34095
+ await KeyRepo.updateKeyById(
34096
+ item.keyId,
34097
+ {
34098
+ status: "In Use" /* IN_USE */,
34099
+ updatedBy: value.createdBy
34100
+ },
34101
+ value.site,
34102
+ session
34103
+ );
34104
+ item.receivedDate = /* @__PURE__ */ new Date();
34105
+ item.status = "Not Returned" /* NOT_RETURNED */;
34106
+ item.lastUpdate = null;
34107
+ item.remarks = "";
33824
34108
  }
33825
34109
  }
33826
34110
  const result = await _add(value, session);
@@ -33990,6 +34274,28 @@ function useVisitorTransactionService() {
33990
34274
  }
33991
34275
  }
33992
34276
  console.log("Open barrier response:", openBarrier);
34277
+ const visitorTransaction = await _getVisitorTransactionById(
34278
+ id.toString()
34279
+ );
34280
+ if (!visitorTransaction) {
34281
+ throw new Error("Visitor transaction not found.");
34282
+ }
34283
+ if (value.checkOut && visitorTransaction.type === "guest" /* GUEST */) {
34284
+ const users = await getUsersBySiteId({
34285
+ status: "active",
34286
+ siteId: visitorTransaction.site.toString()
34287
+ });
34288
+ if (users?.length > 0) {
34289
+ const userIds = Array.from(
34290
+ new Set(users.map((item) => item.user.toString()))
34291
+ );
34292
+ NotificationService.invitedVisitorCheckOutForMa({
34293
+ to: userIds,
34294
+ name: visitorTransaction.name,
34295
+ _id: id.toString()
34296
+ });
34297
+ }
34298
+ }
33993
34299
  await session?.commitTransaction();
33994
34300
  return "Successfully updated visitor transaction.";
33995
34301
  } catch (error) {
@@ -34081,9 +34387,9 @@ function useVisitorTransactionService() {
34081
34387
  value.checkIn = null;
34082
34388
  const payload = {
34083
34389
  ...value,
34084
- block: inviter?.block,
34085
- level: inviter?.level,
34086
- unit: inviter?.unit,
34390
+ block: inviter?.block?.toString(),
34391
+ level: inviter?.level?.toString(),
34392
+ unit: inviter?.unit?.toString(),
34087
34393
  unitName: unit?.name,
34088
34394
  org: inviter?.org.toString(),
34089
34395
  site: inviter?.site.toString(),
@@ -34179,7 +34485,8 @@ function useVisitorTransactionController() {
34179
34485
  } = useVisitorTransactionRepo();
34180
34486
  async function add(req, res, next) {
34181
34487
  try {
34182
- const { error, value } = schemaVisitorTransaction.validate(req.body, {
34488
+ const { companyName, firstName, lastName, ...restData } = req.body;
34489
+ const { error, value } = schemaVisitorTransaction.validate(restData, {
34183
34490
  abortEarly: false
34184
34491
  });
34185
34492
  if (error) {
@@ -34411,8 +34718,11 @@ function useVisitorTransactionController() {
34411
34718
  return;
34412
34719
  } catch (error2) {
34413
34720
  import_node_server_utils107.logger.log({ level: "error", message: error2.message });
34414
- next(error2);
34415
- return;
34721
+ if (error2?.message) {
34722
+ next(new import_node_server_utils107.BadRequestError(error2?.message));
34723
+ } else {
34724
+ next(error2);
34725
+ }
34416
34726
  }
34417
34727
  }
34418
34728
  async function changeVisitorTransactionKeysById(req, res, next) {
@@ -41047,120 +41357,6 @@ function useBulletinBoardRepo() {
41047
41357
  // src/services/bulletin-board.service.ts
41048
41358
  var import_node_server_utils140 = require("@7365admin1/node-server-utils");
41049
41359
  var import_mongodb85 = require("mongodb");
41050
-
41051
- // src/services/notification.service.ts
41052
- var import_iservice365_expo_notifications = require("iservice365-expo-notifications");
41053
-
41054
- // src/repositories/push-token.repository.ts
41055
- var PushTokenRepo = class {
41056
- static collection() {
41057
- return getDB().collection("push_tokens");
41058
- }
41059
- static async createIndexes() {
41060
- await Promise.all([
41061
- this.collection().createIndex({ token: 1 }, { unique: true }),
41062
- this.collection().createIndex({ userId: 1, platform: 1 }),
41063
- this.collection().createIndex({ siteId: 1 })
41064
- ]);
41065
- }
41066
- static async upsert(userId, token, platform, siteId, projectId, appSlug) {
41067
- const now = /* @__PURE__ */ new Date();
41068
- const p = platform;
41069
- const existing = await this.collection().findOne({ token });
41070
- if (existing) {
41071
- await this.collection().updateOne(
41072
- { token },
41073
- {
41074
- $set: {
41075
- userId,
41076
- platform: p,
41077
- siteId,
41078
- projectId,
41079
- appSlug,
41080
- updatedAt: now
41081
- }
41082
- }
41083
- );
41084
- return;
41085
- }
41086
- await this.collection().deleteMany({ userId, platform: p });
41087
- await this.collection().insertOne({
41088
- userId,
41089
- siteId,
41090
- token,
41091
- platform: p,
41092
- projectId,
41093
- appSlug,
41094
- createdAt: now,
41095
- updatedAt: now
41096
- });
41097
- }
41098
- static async remove(token) {
41099
- await this.collection().deleteMany({ token });
41100
- }
41101
- static async findTokensByUserIds(userIds, appSlug) {
41102
- const docs = await this.collection().find({ userId: { $in: userIds }, appSlug: { $eq: appSlug } }).toArray();
41103
- return docs.map((d) => d.token);
41104
- }
41105
- };
41106
-
41107
- // src/services/notification.service.ts
41108
- function toStringArray(recipient) {
41109
- const arr = Array.isArray(recipient) ? recipient : [recipient];
41110
- return arr.map((r) => r.toString());
41111
- }
41112
- async function send(userIds, title, body, data, appSlug) {
41113
- try {
41114
- const tokens = Array.from(
41115
- new Set(await PushTokenRepo.findTokensByUserIds(userIds, appSlug))
41116
- );
41117
- if (!tokens.length)
41118
- return;
41119
- for (const token of tokens) {
41120
- await (0, import_iservice365_expo_notifications.sendExpoPushNotifications)([token], { title, body, data });
41121
- }
41122
- } catch (error) {
41123
- console.warn("[NotificationService]", error);
41124
- }
41125
- }
41126
- var NotificationService = class {
41127
- static async bulletinBoardCreated(payload) {
41128
- await send(
41129
- toStringArray(payload.to),
41130
- "Bulletin Board",
41131
- `There is new ${payload.status} bulletin board.`,
41132
- {
41133
- bulletinId: payload.bulletinId.toString(),
41134
- status: payload.status,
41135
- module: "feedback",
41136
- screen: "/(user)/bulletinInfo",
41137
- params: {
41138
- id: payload.bulletinId.toString()
41139
- }
41140
- },
41141
- "iservice365-resident-mobile-app"
41142
- );
41143
- }
41144
- static async prelovedMarketplacePostCreation(payload) {
41145
- await send(
41146
- toStringArray(payload.to),
41147
- "Preloved Marketplace",
41148
- `New preloved marketplace post added.`,
41149
- {
41150
- prelovedId: payload.prelovedId.toString(),
41151
- status: payload.status,
41152
- module: "prelovedMarketplace",
41153
- screen: "/(user)/(marketplace)/prelovedPostInfo",
41154
- params: {
41155
- id: payload.prelovedId.toString()
41156
- }
41157
- },
41158
- "iservice365-resident-mobile-app"
41159
- );
41160
- }
41161
- };
41162
-
41163
- // src/services/bulletin-board.service.ts
41164
41360
  function useBulletinBoardService() {
41165
41361
  const {
41166
41362
  add: _add,
@@ -41227,6 +41423,12 @@ function useBulletinBoardService() {
41227
41423
  status: bulletinBoardStatus
41228
41424
  });
41229
41425
  }
41426
+ NotificationService.bulletinBoardCreatedForMA({
41427
+ to: userIds,
41428
+ bulletinId: bulletinBoardId,
41429
+ subject: "Bulletin Board",
41430
+ status: bulletinBoardStatus
41431
+ });
41230
41432
  }
41231
41433
  await session?.commitTransaction();
41232
41434
  return "Successfully added bulletin board.";
@@ -43154,11 +43356,27 @@ function useEventManagementService() {
43154
43356
  updateEventManagementById: _updateEventManagementById,
43155
43357
  processCompletedEvents: _processCompletedEvents
43156
43358
  } = useEventManagementRepo();
43359
+ const { getUsersBySiteId } = useMemberRepo();
43157
43360
  async function add(value) {
43158
43361
  const session = import_node_server_utils151.useAtlas.getClient()?.startSession();
43159
43362
  try {
43160
43363
  session?.startTransaction();
43161
- await _add(value, session);
43364
+ const response = await _add(value, session);
43365
+ console.log("response", response);
43366
+ const users = await getUsersBySiteId({
43367
+ status: "active",
43368
+ siteId: value.site
43369
+ });
43370
+ if (users?.length > 0) {
43371
+ const userIds = Array.from(
43372
+ new Set(users.map((item) => item.user.toString()))
43373
+ );
43374
+ NotificationService.eventCreatedForMA({
43375
+ to: userIds,
43376
+ eventId: response,
43377
+ status: value.status
43378
+ });
43379
+ }
43162
43380
  await session?.commitTransaction();
43163
43381
  return "Successfully added event.";
43164
43382
  } catch (error) {
@@ -56514,73 +56732,6 @@ var Period = /* @__PURE__ */ ((Period2) => {
56514
56732
  Period2["THIS_MONTH"] = "thisMonth";
56515
56733
  return Period2;
56516
56734
  })(Period || {});
56517
- function getPeriodRangeWithPrevious(period) {
56518
- const now = /* @__PURE__ */ new Date();
56519
- let currentStart = /* @__PURE__ */ new Date();
56520
- let currentEnd = /* @__PURE__ */ new Date();
56521
- let previousStart = /* @__PURE__ */ new Date();
56522
- let previousEnd = /* @__PURE__ */ new Date();
56523
- if (period === "today" /* TODAY */) {
56524
- currentStart.setHours(0, 0, 0, 0);
56525
- currentEnd.setHours(23, 59, 59, 999);
56526
- previousStart = new Date(currentStart);
56527
- previousStart.setDate(previousStart.getDate() - 1);
56528
- previousEnd = new Date(currentEnd);
56529
- previousEnd.setDate(previousEnd.getDate() - 1);
56530
- } else if (period === "thisWeek" /* THIS_WEEK */) {
56531
- const day = now.getDay();
56532
- const diffToMonday = day === 0 ? -6 : 1 - day;
56533
- currentStart = new Date(now);
56534
- currentStart.setDate(now.getDate() + diffToMonday);
56535
- currentStart.setHours(0, 0, 0, 0);
56536
- currentEnd = new Date(currentStart);
56537
- currentEnd.setDate(currentStart.getDate() + 6);
56538
- currentEnd.setHours(23, 59, 59, 999);
56539
- previousStart = new Date(currentStart);
56540
- previousStart.setDate(previousStart.getDate() - 7);
56541
- previousEnd = new Date(currentEnd);
56542
- previousEnd.setDate(previousEnd.getDate() - 7);
56543
- } else if (period === "thisMonth" /* THIS_MONTH */) {
56544
- currentStart = new Date(now.getFullYear(), now.getMonth(), 1);
56545
- currentEnd = new Date(
56546
- now.getFullYear(),
56547
- now.getMonth() + 1,
56548
- 0,
56549
- 23,
56550
- 59,
56551
- 59,
56552
- 999
56553
- );
56554
- previousStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
56555
- previousEnd = new Date(
56556
- now.getFullYear(),
56557
- now.getMonth(),
56558
- 0,
56559
- 23,
56560
- 59,
56561
- 59,
56562
- 999
56563
- );
56564
- } else {
56565
- throw new import_node_server_utils199.BadRequestError("Invalid period.");
56566
- }
56567
- return {
56568
- current: {
56569
- start: currentStart.toISOString(),
56570
- end: currentEnd.toISOString()
56571
- },
56572
- previous: {
56573
- start: previousStart.toISOString(),
56574
- end: previousEnd.toISOString()
56575
- }
56576
- };
56577
- }
56578
- function calculatePercentage(current, previous) {
56579
- if (previous === 0) {
56580
- return current === 0 ? 0 : 100;
56581
- }
56582
- return Number(((current - previous) / previous * 100).toFixed(2));
56583
- }
56584
56735
  function useNewDashboardRepo() {
56585
56736
  const db = import_node_server_utils199.useAtlas.getDb();
56586
56737
  if (!db) {
@@ -57089,7 +57240,8 @@ function useNewDashboardRepo() {
57089
57240
  currentlyOnSiteCount,
57090
57241
  facilityReport,
57091
57242
  yesterdayFacilityReport,
57092
- todayFacilityReport
57243
+ todayFacilityReport,
57244
+ workOrderStatusReport
57093
57245
  ] = await Promise.all([
57094
57246
  workOrderCollection.aggregate([
57095
57247
  {
@@ -57279,6 +57431,20 @@ function useNewDashboardRepo() {
57279
57431
  }
57280
57432
  },
57281
57433
  { $count: "count" }
57434
+ ]).toArray(),
57435
+ workOrderCollection.aggregate([
57436
+ {
57437
+ $match: {
57438
+ site: { $in: [siteIdObj, siteId] },
57439
+ createdAt: periodRange
57440
+ }
57441
+ },
57442
+ {
57443
+ $group: {
57444
+ _id: "$status",
57445
+ count: { $sum: 1 }
57446
+ }
57447
+ }
57282
57448
  ]).toArray()
57283
57449
  ]);
57284
57450
  const wFacet = workOrderReport[0] ?? { total: [], inProgress: [] };
@@ -57287,6 +57453,23 @@ function useNewDashboardRepo() {
57287
57453
  ongoing: [],
57288
57454
  waitingApproval: []
57289
57455
  };
57456
+ const workOrderStatus = {
57457
+ pending: 0,
57458
+ inProgress: 0,
57459
+ completed: 0
57460
+ };
57461
+ for (const item of workOrderStatusReport || []) {
57462
+ const rawStatus = String(item._id || "").toLowerCase().trim();
57463
+ if (rawStatus === "to-do" || rawStatus === "for-review") {
57464
+ workOrderStatus.pending += item.count || 0;
57465
+ } else if (rawStatus === "in-progress") {
57466
+ workOrderStatus.inProgress += item.count || 0;
57467
+ } else if (rawStatus === "completed") {
57468
+ workOrderStatus.completed += item.count || 0;
57469
+ } else {
57470
+ workOrderStatus.pending += item.count || 0;
57471
+ }
57472
+ }
57290
57473
  const data = {
57291
57474
  openWorkOrder: {
57292
57475
  count: wFacet.total[0]?.count ?? 0,
@@ -57321,6 +57504,7 @@ function useNewDashboardRepo() {
57321
57504
  yesterdayFacilityReport[0]?.count ?? 0
57322
57505
  )
57323
57506
  },
57507
+ workOrderStatus,
57324
57508
  upcomingEvents,
57325
57509
  todayReminders,
57326
57510
  todayAttentions
@@ -65901,7 +66085,8 @@ var schemaUpdateChatPreloved = import_joi141.default.object({
65901
66085
  reactions: import_joi141.default.string().optional().allow("", null)
65902
66086
  });
65903
66087
  var schemaChatPreloved = import_joi141.default.object({
65904
- channelId: import_joi141.default.string().hex().length(24).required(),
66088
+ channelId: import_joi141.default.string().hex().length(24).optional().allow("", null),
66089
+ receiverId: import_joi141.default.string().hex().length(24).optional().allow("", null),
65905
66090
  senderId: import_joi141.default.string().hex().length(24).required(),
65906
66091
  postId: import_joi141.default.string().hex().length(24).optional().allow("", null),
65907
66092
  message: schemaMessage.required(),
@@ -65948,7 +66133,7 @@ function MChatPreloved(value) {
65948
66133
  }
65949
66134
  return {
65950
66135
  _id: new import_mongodb145.ObjectId(),
65951
- channelId: value.channelId ?? "",
66136
+ channelId: value.channelId ?? null,
65952
66137
  senderId: value.senderId ?? "",
65953
66138
  postId: value.postId ?? null,
65954
66139
  message: {
@@ -66025,10 +66210,6 @@ function useChatPrelovedRepo() {
66025
66210
  return { add, updateById, deleteById };
66026
66211
  }
66027
66212
 
66028
- // src/controllers/chat-preloved.controller.ts
66029
- var import_node_server_utils248 = require("@7365admin1/node-server-utils");
66030
- var import_joi143 = __toESM(require("joi"));
66031
-
66032
66213
  // src/services/chat-preloved.service.ts
66033
66214
  var import_node_server_utils247 = require("@7365admin1/node-server-utils");
66034
66215
 
@@ -66178,7 +66359,130 @@ function useChannelPrelovedRepo() {
66178
66359
  throw error;
66179
66360
  }
66180
66361
  }
66181
- return { add, getByParticipants, getChannelMessages };
66362
+ async function getChatLists(currentUserId, page = 1, limit = 10, search) {
66363
+ const normalizedPage = page > 0 ? page - 1 : 0;
66364
+ const normalizedLimit = limit || 10;
66365
+ const _currentUserId = new import_mongodb148.ObjectId(currentUserId);
66366
+ const escapedSearch = search ? search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : null;
66367
+ const pipeline = [
66368
+ {
66369
+ $match: {
66370
+ $or: [{ receiverId: _currentUserId }, { senderId: _currentUserId }]
66371
+ }
66372
+ },
66373
+ {
66374
+ $lookup: {
66375
+ from: "users",
66376
+ localField: "senderId",
66377
+ foreignField: "_id",
66378
+ pipeline: [
66379
+ {
66380
+ $project: {
66381
+ name: 1,
66382
+ profile: 1,
66383
+ type: 1
66384
+ }
66385
+ }
66386
+ ],
66387
+ as: "senderId"
66388
+ }
66389
+ },
66390
+ { $unwind: { path: "$senderId", preserveNullAndEmptyArrays: true } },
66391
+ {
66392
+ $lookup: {
66393
+ from: "post-preloved",
66394
+ localField: "postId",
66395
+ foreignField: "_id",
66396
+ pipeline: [
66397
+ {
66398
+ $project: {
66399
+ title: 1,
66400
+ description: 1,
66401
+ attachments: 1,
66402
+ price: 1,
66403
+ status: 1,
66404
+ createdBy: 1,
66405
+ reserverId: 1
66406
+ }
66407
+ }
66408
+ ],
66409
+ as: "postDetails"
66410
+ }
66411
+ },
66412
+ { $unwind: { path: "$postDetails", preserveNullAndEmptyArrays: true } },
66413
+ ...escapedSearch ? [
66414
+ {
66415
+ $match: {
66416
+ $or: [
66417
+ {
66418
+ "senderId.name": {
66419
+ $regex: new RegExp(escapedSearch, "i")
66420
+ }
66421
+ },
66422
+ {
66423
+ "postDetails.title": {
66424
+ $regex: new RegExp(escapedSearch, "i")
66425
+ }
66426
+ }
66427
+ ]
66428
+ }
66429
+ }
66430
+ ] : [],
66431
+ {
66432
+ $lookup: {
66433
+ from: "chat-preloved",
66434
+ localField: "_id",
66435
+ foreignField: "channelId",
66436
+ pipeline: [
66437
+ { $match: { deletedAt: null } },
66438
+ { $sort: { createdAt: -1 } },
66439
+ { $limit: 1 }
66440
+ ],
66441
+ as: "latestChat"
66442
+ }
66443
+ },
66444
+ { $unwind: { path: "$latestChat", preserveNullAndEmptyArrays: true } },
66445
+ { $addFields: { lastMessageDate: "$latestChat.createdAt" } },
66446
+ {
66447
+ $lookup: {
66448
+ from: "bid-preloved",
66449
+ localField: "postId",
66450
+ foreignField: "postId",
66451
+ pipeline: [
66452
+ { $sort: { createdAt: -1 } },
66453
+ { $limit: 1 },
66454
+ { $project: { price: 1, message: 1, status: 1, type: 1 } }
66455
+ ],
66456
+ as: "latestBidDetails"
66457
+ }
66458
+ },
66459
+ {
66460
+ $unwind: {
66461
+ path: "$latestBidDetails",
66462
+ preserveNullAndEmptyArrays: true
66463
+ }
66464
+ },
66465
+ { $sort: { lastMessageDate: -1 } },
66466
+ {
66467
+ $facet: {
66468
+ totalCount: [{ $count: "count" }],
66469
+ items: [
66470
+ { $skip: normalizedPage * normalizedLimit },
66471
+ { $limit: normalizedLimit }
66472
+ ]
66473
+ }
66474
+ }
66475
+ ];
66476
+ try {
66477
+ const result = await collection.aggregate(pipeline).toArray();
66478
+ const totalCount = result[0].totalCount[0]?.count ?? 0;
66479
+ const items = result[0].items;
66480
+ return (0, import_node_server_utils246.paginate)(items, normalizedPage, normalizedLimit, totalCount);
66481
+ } catch (error) {
66482
+ throw error;
66483
+ }
66484
+ }
66485
+ return { add, getByParticipants, getChatLists, getChannelMessages };
66182
66486
  }
66183
66487
 
66184
66488
  // src/services/chat-preloved.service.ts
@@ -66232,6 +66536,8 @@ function useChatPrelovedService() {
66232
66536
  }
66233
66537
 
66234
66538
  // src/controllers/chat-preloved.controller.ts
66539
+ var import_node_server_utils248 = require("@7365admin1/node-server-utils");
66540
+ var import_joi143 = __toESM(require("joi"));
66235
66541
  function useChatPrelovedController() {
66236
66542
  const { add: _add } = useChatPrelovedService();
66237
66543
  const { updateById: _updateById, deleteById: _deleteById } = useChatPrelovedRepo();
@@ -66296,7 +66602,12 @@ function useChatPrelovedController() {
66296
66602
  var import_node_server_utils249 = require("@7365admin1/node-server-utils");
66297
66603
  var import_joi144 = __toESM(require("joi"));
66298
66604
  function useChannelPrelovedController() {
66299
- const { add: _add, getChannelMessages: _getChannelMessages } = useChannelPrelovedRepo();
66605
+ const {
66606
+ add: _add,
66607
+ getByParticipants: _getByParticipants,
66608
+ getChatLists: _getChatLists,
66609
+ getChannelMessages: _getChannelMessages
66610
+ } = useChannelPrelovedRepo();
66300
66611
  async function add(req, res, next) {
66301
66612
  const { error, value } = schemaChannelPreloved.validate(req.body, {
66302
66613
  abortEarly: false
@@ -66333,9 +66644,7 @@ function useChannelPrelovedController() {
66333
66644
  next(new import_node_server_utils249.BadRequestError(paramError.message));
66334
66645
  return;
66335
66646
  }
66336
- const { error: queryError, value: query } = querySchema.validate(
66337
- req.query
66338
- );
66647
+ const { error: queryError, value: query } = querySchema.validate(req.query);
66339
66648
  if (queryError) {
66340
66649
  import_node_server_utils249.logger.log({ level: "error", message: queryError.message });
66341
66650
  next(new import_node_server_utils249.BadRequestError(queryError.message));
@@ -66355,61 +66664,249 @@ function useChannelPrelovedController() {
66355
66664
  next(error);
66356
66665
  }
66357
66666
  }
66358
- return { add, getChannelMessages };
66667
+ async function getChannel(req, res, next) {
66668
+ const querySchema = import_joi144.default.object({
66669
+ postId: import_joi144.default.string().hex().length(24).required(),
66670
+ receiverId: import_joi144.default.string().hex().length(24).required(),
66671
+ senderId: import_joi144.default.string().hex().length(24).required()
66672
+ });
66673
+ const { error, value } = querySchema.validate(req.query);
66674
+ if (error) {
66675
+ import_node_server_utils249.logger.log({ level: "error", message: error.message });
66676
+ next(new import_node_server_utils249.BadRequestError(error.message));
66677
+ return;
66678
+ }
66679
+ try {
66680
+ const data = await _getByParticipants(
66681
+ value.senderId,
66682
+ value.receiverId,
66683
+ value.postId
66684
+ );
66685
+ res.status(200).json(data);
66686
+ } catch (error2) {
66687
+ import_node_server_utils249.logger.log({ level: "error", message: error2.message });
66688
+ next(error2);
66689
+ }
66690
+ }
66691
+ async function getChatLists(req, res, next) {
66692
+ const querySchema = import_joi144.default.object({
66693
+ currentUserId: import_joi144.default.string().hex().length(24).required(),
66694
+ page: import_joi144.default.number().integer().min(1).default(1),
66695
+ limit: import_joi144.default.number().integer().min(1).max(100).default(10),
66696
+ search: import_joi144.default.string().optional().allow("", null)
66697
+ });
66698
+ const { error, value } = querySchema.validate(req.query);
66699
+ if (error) {
66700
+ import_node_server_utils249.logger.log({ level: "error", message: error.message });
66701
+ next(new import_node_server_utils249.BadRequestError(error.message));
66702
+ return;
66703
+ }
66704
+ try {
66705
+ const data = await _getChatLists(
66706
+ value.currentUserId,
66707
+ value.page,
66708
+ value.limit,
66709
+ value.search || void 0
66710
+ );
66711
+ res.status(200).json(data);
66712
+ } catch (error2) {
66713
+ import_node_server_utils249.logger.log({ level: "error", message: error2.message });
66714
+ next(error2);
66715
+ }
66716
+ }
66717
+ return { add, getChannel, getChatLists, getChannelMessages };
66359
66718
  }
66360
66719
 
66361
- // src/models/online-forms-v2.model.ts
66720
+ // src/models/bid-preloved.model.ts
66362
66721
  var import_joi145 = __toESM(require("joi"));
66363
66722
  var import_mongodb149 = require("mongodb");
66723
+ var BidType = /* @__PURE__ */ ((BidType2) => {
66724
+ BidType2["BID"] = "bid";
66725
+ BidType2["RESERVE"] = "reserve";
66726
+ return BidType2;
66727
+ })(BidType || {});
66728
+ var BidStatus = /* @__PURE__ */ ((BidStatus3) => {
66729
+ BidStatus3["PENDING"] = "pending";
66730
+ BidStatus3["ACCEPTED"] = "accepted";
66731
+ BidStatus3["RESERVED"] = "reserved";
66732
+ BidStatus3["CANCELLED"] = "cancelled";
66733
+ return BidStatus3;
66734
+ })(BidStatus || {});
66735
+ var schemaBidPreloved = import_joi145.default.object({
66736
+ type: import_joi145.default.string().valid(...Object.values(BidType)).required(),
66737
+ postId: import_joi145.default.string().hex().length(24).required(),
66738
+ price: import_joi145.default.when("type", {
66739
+ is: "bid" /* BID */,
66740
+ then: import_joi145.default.number().required(),
66741
+ otherwise: import_joi145.default.number().optional().allow(null)
66742
+ }),
66743
+ message: import_joi145.default.string().optional().allow("", null),
66744
+ buyerId: import_joi145.default.string().hex().length(24).optional().allow("", null),
66745
+ status: import_joi145.default.string().valid(...Object.values(BidStatus)).optional().default("pending" /* PENDING */)
66746
+ });
66747
+ var schemaUpdateBidPreloved = import_joi145.default.object({
66748
+ status: import_joi145.default.string().valid(...Object.values(BidStatus)).required()
66749
+ });
66750
+ function MBidPreloved(value) {
66751
+ const { error } = schemaBidPreloved.validate(value);
66752
+ if (error)
66753
+ throw new Error(error.details[0].message);
66754
+ if (value.postId && typeof value.postId === "string")
66755
+ value.postId = new import_mongodb149.ObjectId(value.postId);
66756
+ if (value.buyerId && typeof value.buyerId === "string")
66757
+ value.buyerId = new import_mongodb149.ObjectId(value.buyerId);
66758
+ return {
66759
+ _id: new import_mongodb149.ObjectId(),
66760
+ price: value.price ?? null,
66761
+ message: value.message ?? "",
66762
+ status: value.status ?? "pending" /* PENDING */,
66763
+ type: value.type,
66764
+ postId: value.postId,
66765
+ buyerId: value.buyerId ?? null,
66766
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
66767
+ updatedAt: null
66768
+ };
66769
+ }
66770
+
66771
+ // src/repositories/bid-preloved.repo.ts
66772
+ var import_node_server_utils250 = require("@7365admin1/node-server-utils");
66773
+ var import_mongodb150 = require("mongodb");
66774
+ function useBidPrelovedRepo() {
66775
+ const db = import_node_server_utils250.useAtlas.getDb();
66776
+ if (!db)
66777
+ throw new import_node_server_utils250.InternalServerError("Unable to connect to server.");
66778
+ const collection = db.collection("bid-preloved");
66779
+ async function add(value, session) {
66780
+ try {
66781
+ const doc = MBidPreloved(value);
66782
+ const res = await collection.insertOne(doc, { session });
66783
+ return res.insertedId;
66784
+ } catch (error) {
66785
+ throw error;
66786
+ }
66787
+ }
66788
+ async function updateStatus(_id, status) {
66789
+ const objectId2 = typeof _id === "string" ? new import_mongodb150.ObjectId(_id) : _id;
66790
+ const existing = await collection.findOne({ _id: objectId2 });
66791
+ if (!existing)
66792
+ throw new import_node_server_utils250.NotFoundError("Bid not found.");
66793
+ const res = await collection.updateOne(
66794
+ { _id: objectId2 },
66795
+ { $set: { status, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } }
66796
+ );
66797
+ if (res.modifiedCount === 0)
66798
+ throw new import_node_server_utils250.InternalServerError("Unable to update bid.");
66799
+ return "Bid updated successfully.";
66800
+ }
66801
+ return { add, updateStatus };
66802
+ }
66803
+
66804
+ // src/controllers/bid-preloved.controller.ts
66805
+ var import_node_server_utils251 = require("@7365admin1/node-server-utils");
66806
+ var import_joi146 = __toESM(require("joi"));
66807
+ function useBidPrelovedController() {
66808
+ const { add: _add, updateStatus: _updateStatus } = useBidPrelovedRepo();
66809
+ async function add(req, res, next) {
66810
+ const { error, value } = schemaBidPreloved.validate(req.body, {
66811
+ abortEarly: false
66812
+ });
66813
+ if (error) {
66814
+ const messages = error.details.map((d) => d.message).join(", ");
66815
+ import_node_server_utils251.logger.log({ level: "error", message: messages });
66816
+ next(new import_node_server_utils251.BadRequestError(messages));
66817
+ return;
66818
+ }
66819
+ try {
66820
+ const data = await _add(value);
66821
+ res.status(201).json(data);
66822
+ } catch (error2) {
66823
+ import_node_server_utils251.logger.log({ level: "error", message: error2.message });
66824
+ next(error2);
66825
+ }
66826
+ }
66827
+ async function updateStatus(req, res, next) {
66828
+ const paramsSchema = import_joi146.default.object({
66829
+ id: import_joi146.default.string().hex().length(24).required()
66830
+ });
66831
+ const { error: paramError, value: params } = paramsSchema.validate(
66832
+ req.params
66833
+ );
66834
+ if (paramError) {
66835
+ import_node_server_utils251.logger.log({ level: "error", message: paramError.message });
66836
+ next(new import_node_server_utils251.BadRequestError(paramError.message));
66837
+ return;
66838
+ }
66839
+ const { error: bodyError, value: body } = schemaUpdateBidPreloved.validate(
66840
+ req.body
66841
+ );
66842
+ if (bodyError) {
66843
+ import_node_server_utils251.logger.log({ level: "error", message: bodyError.message });
66844
+ next(new import_node_server_utils251.BadRequestError(bodyError.message));
66845
+ return;
66846
+ }
66847
+ try {
66848
+ const data = await _updateStatus(params.id, body.status);
66849
+ res.status(200).json(data);
66850
+ } catch (error) {
66851
+ import_node_server_utils251.logger.log({ level: "error", message: error.message });
66852
+ next(error);
66853
+ }
66854
+ }
66855
+ return { add, updateStatus };
66856
+ }
66857
+
66858
+ // src/models/online-forms-v2.model.ts
66859
+ var import_joi147 = __toESM(require("joi"));
66860
+ var import_mongodb151 = require("mongodb");
66364
66861
  var FormEntryStatus = /* @__PURE__ */ ((FormEntryStatus2) => {
66365
66862
  FormEntryStatus2["ACTIVE"] = "active";
66366
66863
  FormEntryStatus2["INACTIVE"] = "inactive";
66367
66864
  FormEntryStatus2["DELETED"] = "deleted";
66368
66865
  return FormEntryStatus2;
66369
66866
  })(FormEntryStatus || {});
66370
- var schemaFormEntry = import_joi145.default.object({
66371
- _id: import_joi145.default.string().hex().optional().allow("", null),
66372
- formType: import_joi145.default.string().required(),
66373
- block: import_joi145.default.string().optional().allow(null, ""),
66374
- level: import_joi145.default.string().optional().allow(null, ""),
66375
- unit: import_joi145.default.string().optional().allow(null, ""),
66376
- name: import_joi145.default.string().optional().allow(null, ""),
66377
- phoneNumber: import_joi145.default.string().optional().allow(null, ""),
66378
- createdBy: import_joi145.default.string().required(),
66379
- fields: import_joi145.default.object().pattern(
66380
- import_joi145.default.string(),
66381
- import_joi145.default.alternatives().try(
66382
- import_joi145.default.string(),
66383
- import_joi145.default.number(),
66384
- import_joi145.default.boolean(),
66385
- import_joi145.default.valid(null)
66867
+ var schemaFormEntry = import_joi147.default.object({
66868
+ _id: import_joi147.default.string().hex().optional().allow("", null),
66869
+ formType: import_joi147.default.string().required(),
66870
+ block: import_joi147.default.string().optional().allow(null, ""),
66871
+ level: import_joi147.default.string().optional().allow(null, ""),
66872
+ unit: import_joi147.default.string().optional().allow(null, ""),
66873
+ name: import_joi147.default.string().optional().allow(null, ""),
66874
+ phoneNumber: import_joi147.default.string().optional().allow(null, ""),
66875
+ createdBy: import_joi147.default.string().required(),
66876
+ fields: import_joi147.default.object().pattern(
66877
+ import_joi147.default.string(),
66878
+ import_joi147.default.alternatives().try(
66879
+ import_joi147.default.string(),
66880
+ import_joi147.default.number(),
66881
+ import_joi147.default.boolean(),
66882
+ import_joi147.default.valid(null)
66386
66883
  )
66387
66884
  ).required(),
66388
- status: import_joi145.default.string().optional().allow("", null),
66389
- org: import_joi145.default.string().hex().optional().allow("", null),
66390
- site: import_joi145.default.string().hex().optional().allow("", null),
66391
- createdAt: import_joi145.default.date().optional().allow("", null),
66392
- updatedAt: import_joi145.default.date().optional().allow("", null),
66393
- deletedAt: import_joi145.default.date().optional().allow("", null)
66885
+ status: import_joi147.default.string().optional().allow("", null),
66886
+ org: import_joi147.default.string().hex().optional().allow("", null),
66887
+ site: import_joi147.default.string().hex().optional().allow("", null),
66888
+ createdAt: import_joi147.default.date().optional().allow("", null),
66889
+ updatedAt: import_joi147.default.date().optional().allow("", null),
66890
+ deletedAt: import_joi147.default.date().optional().allow("", null)
66394
66891
  });
66395
- var schemaUpdateFormEntry = import_joi145.default.object({
66396
- _id: import_joi145.default.string().hex().required(),
66397
- formType: import_joi145.default.string().optional().allow("", null),
66398
- block: import_joi145.default.string().optional().allow(null, ""),
66399
- level: import_joi145.default.string().optional().allow(null, ""),
66400
- unit: import_joi145.default.string().optional().allow(null, ""),
66401
- fields: import_joi145.default.object().pattern(
66402
- import_joi145.default.string(),
66403
- import_joi145.default.alternatives().try(
66404
- import_joi145.default.string(),
66405
- import_joi145.default.number(),
66406
- import_joi145.default.boolean(),
66407
- import_joi145.default.valid(null)
66892
+ var schemaUpdateFormEntry = import_joi147.default.object({
66893
+ _id: import_joi147.default.string().hex().required(),
66894
+ formType: import_joi147.default.string().optional().allow("", null),
66895
+ block: import_joi147.default.string().optional().allow(null, ""),
66896
+ level: import_joi147.default.string().optional().allow(null, ""),
66897
+ unit: import_joi147.default.string().optional().allow(null, ""),
66898
+ fields: import_joi147.default.object().pattern(
66899
+ import_joi147.default.string(),
66900
+ import_joi147.default.alternatives().try(
66901
+ import_joi147.default.string(),
66902
+ import_joi147.default.number(),
66903
+ import_joi147.default.boolean(),
66904
+ import_joi147.default.valid(null)
66408
66905
  )
66409
66906
  ).optional(),
66410
- status: import_joi145.default.string().optional().allow("", null),
66411
- updatedAt: import_joi145.default.date().optional().allow("", null),
66412
- deletedAt: import_joi145.default.date().optional().allow("", null)
66907
+ status: import_joi147.default.string().optional().allow("", null),
66908
+ updatedAt: import_joi147.default.date().optional().allow("", null),
66909
+ deletedAt: import_joi147.default.date().optional().allow("", null)
66413
66910
  });
66414
66911
  function MFormEntry(value) {
66415
66912
  const { error } = schemaFormEntry.validate(value);
@@ -66418,21 +66915,21 @@ function MFormEntry(value) {
66418
66915
  }
66419
66916
  if (value._id && typeof value._id === "string") {
66420
66917
  try {
66421
- value._id = new import_mongodb149.ObjectId(value._id);
66918
+ value._id = new import_mongodb151.ObjectId(value._id);
66422
66919
  } catch {
66423
66920
  throw new Error("Invalid ID.");
66424
66921
  }
66425
66922
  }
66426
66923
  if (value.org && typeof value.org === "string") {
66427
66924
  try {
66428
- value.org = new import_mongodb149.ObjectId(value.org);
66925
+ value.org = new import_mongodb151.ObjectId(value.org);
66429
66926
  } catch {
66430
66927
  throw new Error("Invalid org ID.");
66431
66928
  }
66432
66929
  }
66433
66930
  if (value.site && typeof value.site === "string") {
66434
66931
  try {
66435
- value.site = new import_mongodb149.ObjectId(value.site);
66932
+ value.site = new import_mongodb151.ObjectId(value.site);
66436
66933
  } catch {
66437
66934
  throw new Error("Invalid site ID.");
66438
66935
  }
@@ -66454,49 +66951,49 @@ function MFormEntry(value) {
66454
66951
  deletedAt: value.deletedAt ?? null
66455
66952
  };
66456
66953
  }
66457
- var residentFormEntry = import_joi145.default.object({
66458
- _id: import_joi145.default.string().hex().optional().allow("", null),
66459
- typeOfForm: import_joi145.default.string().optional().allow("", null),
66460
- unitNumber: import_joi145.default.string().optional().allow(null, ""),
66461
- fields: import_joi145.default.object().pattern(
66462
- import_joi145.default.string(),
66463
- import_joi145.default.alternatives().try(
66464
- import_joi145.default.string(),
66465
- import_joi145.default.number(),
66466
- import_joi145.default.boolean(),
66467
- import_joi145.default.valid(null)
66954
+ var residentFormEntry = import_joi147.default.object({
66955
+ _id: import_joi147.default.string().hex().optional().allow("", null),
66956
+ typeOfForm: import_joi147.default.string().optional().allow("", null),
66957
+ unitNumber: import_joi147.default.string().optional().allow(null, ""),
66958
+ fields: import_joi147.default.object().pattern(
66959
+ import_joi147.default.string(),
66960
+ import_joi147.default.alternatives().try(
66961
+ import_joi147.default.string(),
66962
+ import_joi147.default.number(),
66963
+ import_joi147.default.boolean(),
66964
+ import_joi147.default.valid(null)
66468
66965
  )
66469
66966
  ).optional().allow(null, ""),
66470
- status: import_joi145.default.string().optional().allow("", null),
66471
- org: import_joi145.default.string().hex().optional().allow("", null),
66472
- site: import_joi145.default.string().hex().optional().allow("", null),
66473
- userId: import_joi145.default.string().hex().optional().allow("", null),
66474
- createdAt: import_joi145.default.date().optional().allow("", null),
66475
- updatedAt: import_joi145.default.date().optional().allow("", null),
66476
- deletedAt: import_joi145.default.date().optional().allow("", null),
66477
- remarks: import_joi145.default.string().optional().allow("", null),
66478
- managementValues: import_joi145.default.object().pattern(
66479
- import_joi145.default.string(),
66480
- import_joi145.default.alternatives().try(
66481
- import_joi145.default.string(),
66482
- import_joi145.default.number(),
66483
- import_joi145.default.boolean(),
66484
- import_joi145.default.valid(null)
66967
+ status: import_joi147.default.string().optional().allow("", null),
66968
+ org: import_joi147.default.string().hex().optional().allow("", null),
66969
+ site: import_joi147.default.string().hex().optional().allow("", null),
66970
+ userId: import_joi147.default.string().hex().optional().allow("", null),
66971
+ createdAt: import_joi147.default.date().optional().allow("", null),
66972
+ updatedAt: import_joi147.default.date().optional().allow("", null),
66973
+ deletedAt: import_joi147.default.date().optional().allow("", null),
66974
+ remarks: import_joi147.default.string().optional().allow("", null),
66975
+ managementValues: import_joi147.default.object().pattern(
66976
+ import_joi147.default.string(),
66977
+ import_joi147.default.alternatives().try(
66978
+ import_joi147.default.string(),
66979
+ import_joi147.default.number(),
66980
+ import_joi147.default.boolean(),
66981
+ import_joi147.default.valid(null)
66485
66982
  )
66486
66983
  ).optional().allow(null, "")
66487
66984
  });
66488
66985
 
66489
66986
  // src/repositories/online-forms-v2.repository.ts
66490
- var import_node_server_utils250 = require("@7365admin1/node-server-utils");
66491
- var import_mongodb150 = require("mongodb");
66987
+ var import_node_server_utils252 = require("@7365admin1/node-server-utils");
66988
+ var import_mongodb152 = require("mongodb");
66492
66989
  var online_forms_namespace_collection = "online-forms";
66493
66990
  function useFormEntryRepo() {
66494
- const db = import_node_server_utils250.useAtlas.getDb();
66991
+ const db = import_node_server_utils252.useAtlas.getDb();
66495
66992
  if (!db) {
66496
- throw new import_node_server_utils250.InternalServerError("Unable to connect to server.");
66993
+ throw new import_node_server_utils252.InternalServerError("Unable to connect to server.");
66497
66994
  }
66498
66995
  const collection = db.collection(online_forms_namespace_collection);
66499
- const { delNamespace, getCache, setCache } = (0, import_node_server_utils250.useCache)(
66996
+ const { delNamespace, getCache, setCache } = (0, import_node_server_utils252.useCache)(
66500
66997
  online_forms_namespace_collection
66501
66998
  );
66502
66999
  async function createTextIndex() {
@@ -66505,7 +67002,7 @@ function useFormEntryRepo() {
66505
67002
  name: "text"
66506
67003
  });
66507
67004
  } catch (error) {
66508
- throw new import_node_server_utils250.InternalServerError(
67005
+ throw new import_node_server_utils252.InternalServerError(
66509
67006
  "Failed to create text index on online form."
66510
67007
  );
66511
67008
  }
@@ -66515,11 +67012,11 @@ function useFormEntryRepo() {
66515
67012
  value = MFormEntry(value);
66516
67013
  const res = await collection.insertOne(value, { session });
66517
67014
  delNamespace().then(() => {
66518
- import_node_server_utils250.logger.info(
67015
+ import_node_server_utils252.logger.info(
66519
67016
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66520
67017
  );
66521
67018
  }).catch((err) => {
66522
- import_node_server_utils250.logger.error(
67019
+ import_node_server_utils252.logger.error(
66523
67020
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66524
67021
  err
66525
67022
  );
@@ -66528,7 +67025,7 @@ function useFormEntryRepo() {
66528
67025
  } catch (error) {
66529
67026
  const isDuplicated = error.message.includes("duplicate");
66530
67027
  if (isDuplicated) {
66531
- throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
67028
+ throw new import_node_server_utils252.BadRequestError("Online Form already exists.");
66532
67029
  }
66533
67030
  throw error;
66534
67031
  }
@@ -66544,8 +67041,8 @@ function useFormEntryRepo() {
66544
67041
  }) {
66545
67042
  page = page > 0 ? page - 1 : 0;
66546
67043
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
66547
- site = new import_mongodb150.ObjectId(site);
66548
- org = new import_mongodb150.ObjectId(org);
67044
+ site = new import_mongodb152.ObjectId(site);
67045
+ org = new import_mongodb152.ObjectId(org);
66549
67046
  const cacheOptions = {
66550
67047
  page,
66551
67048
  limit,
@@ -66565,13 +67062,13 @@ function useFormEntryRepo() {
66565
67062
  { unitNumber: { $regex: search, $options: "i" } }
66566
67063
  ];
66567
67064
  }
66568
- const cacheKey = (0, import_node_server_utils250.makeCacheKey)(
67065
+ const cacheKey = (0, import_node_server_utils252.makeCacheKey)(
66569
67066
  online_forms_namespace_collection,
66570
67067
  cacheOptions
66571
67068
  );
66572
67069
  const cachedData = await getCache(cacheKey);
66573
67070
  if (cachedData) {
66574
- import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
67071
+ import_node_server_utils252.logger.info(`Cache hit for key: ${cacheKey}`);
66575
67072
  return cachedData;
66576
67073
  }
66577
67074
  try {
@@ -66579,14 +67076,30 @@ function useFormEntryRepo() {
66579
67076
  { $match: query },
66580
67077
  { $sort: sort },
66581
67078
  { $skip: page * limit },
66582
- { $limit: limit }
67079
+ { $limit: limit },
67080
+ {
67081
+ $lookup: {
67082
+ from: "users",
67083
+ localField: "userId",
67084
+ foreignField: "_id",
67085
+ as: "user",
67086
+ pipeline: [{ $project: { name: 1 } }]
67087
+ }
67088
+ },
67089
+ { $unwind: { path: "$user", preserveNullAndEmptyArrays: true } },
67090
+ {
67091
+ $addFields: {
67092
+ name: { $ifNull: ["$user.name", "$name"] }
67093
+ }
67094
+ },
67095
+ { $project: { user: 0 } }
66583
67096
  ]).toArray();
66584
67097
  const length = await collection.countDocuments(query);
66585
- const data = (0, import_node_server_utils250.paginate)(items, page, limit, length);
67098
+ const data = (0, import_node_server_utils252.paginate)(items, page, limit, length);
66586
67099
  setCache(cacheKey, data, 15 * 60).then(() => {
66587
- import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
67100
+ import_node_server_utils252.logger.info(`Cache set for key: ${cacheKey}`);
66588
67101
  }).catch((err) => {
66589
- import_node_server_utils250.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
67102
+ import_node_server_utils252.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
66590
67103
  });
66591
67104
  return data;
66592
67105
  } catch (error) {
@@ -66594,27 +67107,27 @@ function useFormEntryRepo() {
66594
67107
  }
66595
67108
  }
66596
67109
  async function getFormEntryById(_id) {
66597
- const cacheKey = (0, import_node_server_utils250.makeCacheKey)(online_forms_namespace_collection, { _id });
67110
+ const cacheKey = (0, import_node_server_utils252.makeCacheKey)(online_forms_namespace_collection, { _id });
66598
67111
  const cachedData = await getCache(cacheKey);
66599
67112
  if (cachedData) {
66600
- import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
67113
+ import_node_server_utils252.logger.info(`Cache hit for key: ${cacheKey}`);
66601
67114
  return cachedData;
66602
67115
  }
66603
67116
  try {
66604
- _id = new import_mongodb150.ObjectId(_id);
67117
+ _id = new import_mongodb152.ObjectId(_id);
66605
67118
  } catch (error) {
66606
- throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
67119
+ throw new import_node_server_utils252.BadRequestError("Invalid online form ID format.");
66607
67120
  }
66608
67121
  const query = { _id, status: { $ne: "deleted" } };
66609
67122
  try {
66610
67123
  const [data] = await collection.aggregate([{ $match: query }]).toArray();
66611
67124
  if (!data) {
66612
- throw new import_node_server_utils250.NotFoundError("Document not found.");
67125
+ throw new import_node_server_utils252.NotFoundError("Document not found.");
66613
67126
  }
66614
67127
  setCache(cacheKey, data, 15 * 60).then(() => {
66615
- import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
67128
+ import_node_server_utils252.logger.info(`Cache set for key: ${cacheKey}`);
66616
67129
  }).catch((err) => {
66617
- import_node_server_utils250.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
67130
+ import_node_server_utils252.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
66618
67131
  });
66619
67132
  return data;
66620
67133
  } catch (error) {
@@ -66623,9 +67136,9 @@ function useFormEntryRepo() {
66623
67136
  }
66624
67137
  async function updateFormEntryById(_id, value) {
66625
67138
  try {
66626
- _id = new import_mongodb150.ObjectId(_id);
67139
+ _id = new import_mongodb152.ObjectId(_id);
66627
67140
  } catch (error) {
66628
- throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
67141
+ throw new import_node_server_utils252.BadRequestError("Invalid online form ID format.");
66629
67142
  }
66630
67143
  try {
66631
67144
  const updateValue = {
@@ -66634,14 +67147,14 @@ function useFormEntryRepo() {
66634
67147
  };
66635
67148
  const res = await collection.updateOne({ _id }, { $set: updateValue });
66636
67149
  if (res.modifiedCount === 0) {
66637
- throw new import_node_server_utils250.InternalServerError("Unable to update online form.");
67150
+ throw new import_node_server_utils252.InternalServerError("Unable to update online form.");
66638
67151
  }
66639
67152
  delNamespace().then(() => {
66640
- import_node_server_utils250.logger.info(
67153
+ import_node_server_utils252.logger.info(
66641
67154
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66642
67155
  );
66643
67156
  }).catch((err) => {
66644
- import_node_server_utils250.logger.error(
67157
+ import_node_server_utils252.logger.error(
66645
67158
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66646
67159
  err
66647
67160
  );
@@ -66653,9 +67166,9 @@ function useFormEntryRepo() {
66653
67166
  }
66654
67167
  async function deleteOnlineFormById(_id, session) {
66655
67168
  try {
66656
- _id = new import_mongodb150.ObjectId(_id);
67169
+ _id = new import_mongodb152.ObjectId(_id);
66657
67170
  } catch (error) {
66658
- throw new import_node_server_utils250.BadRequestError("Invalid online form ID format.");
67171
+ throw new import_node_server_utils252.BadRequestError("Invalid online form ID format.");
66659
67172
  }
66660
67173
  try {
66661
67174
  const updateValue = {
@@ -66669,12 +67182,12 @@ function useFormEntryRepo() {
66669
67182
  { session }
66670
67183
  );
66671
67184
  if (res.modifiedCount === 0) {
66672
- throw new import_node_server_utils250.InternalServerError("Unable to delete online form.");
67185
+ throw new import_node_server_utils252.InternalServerError("Unable to delete online form.");
66673
67186
  }
66674
67187
  delNamespace().then(() => {
66675
- import_node_server_utils250.logger.info(`Cache cleared for namespace: ${online_forms_namespace_collection}`);
67188
+ import_node_server_utils252.logger.info(`Cache cleared for namespace: ${online_forms_namespace_collection}`);
66676
67189
  }).catch((err) => {
66677
- import_node_server_utils250.logger.error(
67190
+ import_node_server_utils252.logger.error(
66678
67191
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66679
67192
  err
66680
67193
  );
@@ -66686,16 +67199,16 @@ function useFormEntryRepo() {
66686
67199
  }
66687
67200
  async function addResidentForm(value, session) {
66688
67201
  try {
66689
- value.site = new import_mongodb150.ObjectId(value.site);
66690
- value.org = new import_mongodb150.ObjectId(value.org);
66691
- value.userId = new import_mongodb150.ObjectId(value.userId);
67202
+ value.site = new import_mongodb152.ObjectId(value.site);
67203
+ value.org = new import_mongodb152.ObjectId(value.org);
67204
+ value.userId = new import_mongodb152.ObjectId(value.userId);
66692
67205
  const res = await collection.insertOne(value, { session });
66693
67206
  delNamespace().then(() => {
66694
- import_node_server_utils250.logger.info(
67207
+ import_node_server_utils252.logger.info(
66695
67208
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66696
67209
  );
66697
67210
  }).catch((err) => {
66698
- import_node_server_utils250.logger.error(
67211
+ import_node_server_utils252.logger.error(
66699
67212
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66700
67213
  err
66701
67214
  );
@@ -66704,16 +67217,16 @@ function useFormEntryRepo() {
66704
67217
  } catch (error) {
66705
67218
  const isDuplicated = error.message.includes("duplicate");
66706
67219
  if (isDuplicated) {
66707
- throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
67220
+ throw new import_node_server_utils252.BadRequestError("Online Form already exists.");
66708
67221
  }
66709
67222
  throw error;
66710
67223
  }
66711
67224
  }
66712
67225
  async function residentForm({ userId, site, org }) {
66713
67226
  try {
66714
- const user = new import_mongodb150.ObjectId(userId);
66715
- const siteId = new import_mongodb150.ObjectId(site);
66716
- const orgId = new import_mongodb150.ObjectId(org);
67227
+ const user = new import_mongodb152.ObjectId(userId);
67228
+ const siteId = new import_mongodb152.ObjectId(site);
67229
+ const orgId = new import_mongodb152.ObjectId(org);
66717
67230
  const res = await collection.aggregate([
66718
67231
  {
66719
67232
  $match: {
@@ -66741,8 +67254,8 @@ function useFormEntryRepo() {
66741
67254
  }
66742
67255
 
66743
67256
  // src/controllers/online-forms-v2.controller.ts
66744
- var import_node_server_utils251 = require("@7365admin1/node-server-utils");
66745
- var import_joi146 = __toESM(require("joi"));
67257
+ var import_node_server_utils253 = require("@7365admin1/node-server-utils");
67258
+ var import_joi148 = __toESM(require("joi"));
66746
67259
  var import_exceljs3 = __toESM(require("exceljs"));
66747
67260
  var import_fs7 = __toESM(require("fs"));
66748
67261
  function useFormEntryController() {
@@ -66768,14 +67281,14 @@ function useFormEntryController() {
66768
67281
  async function uploadFormEntrys(req, res, next) {
66769
67282
  try {
66770
67283
  if (!req.file) {
66771
- next(new import_node_server_utils251.BadRequestError("Excel file is required."));
67284
+ next(new import_node_server_utils253.BadRequestError("Excel file is required."));
66772
67285
  return;
66773
67286
  }
66774
67287
  const workbook = new import_exceljs3.default.Workbook();
66775
67288
  await workbook.xlsx.readFile(req.file.path);
66776
67289
  const worksheet = workbook.worksheets[0];
66777
67290
  if (!worksheet) {
66778
- next(new import_node_server_utils251.BadRequestError("No worksheet found in uploaded Excel file."));
67291
+ next(new import_node_server_utils253.BadRequestError("No worksheet found in uploaded Excel file."));
66779
67292
  return;
66780
67293
  }
66781
67294
  const headerRow = worksheet.getRow(1);
@@ -66803,8 +67316,8 @@ function useFormEntryController() {
66803
67316
  });
66804
67317
  if (error) {
66805
67318
  const messages = error.details.map((d) => d.message).join(", ");
66806
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66807
- next(new import_node_server_utils251.BadRequestError(messages));
67319
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67320
+ next(new import_node_server_utils253.BadRequestError(messages));
66808
67321
  return;
66809
67322
  }
66810
67323
  const result = await _add(value);
@@ -66812,25 +67325,25 @@ function useFormEntryController() {
66812
67325
  import_fs7.default.unlink(req.file.path, () => {
66813
67326
  });
66814
67327
  } catch (error) {
66815
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67328
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66816
67329
  next(error);
66817
67330
  }
66818
67331
  }
66819
67332
  async function getAll(req, res, next) {
66820
67333
  try {
66821
- const schema2 = import_joi146.default.object({
66822
- search: import_joi146.default.string().optional().allow("", null),
66823
- page: import_joi146.default.number().integer().min(1).allow("", null).default(1),
66824
- limit: import_joi146.default.number().integer().min(1).max(100).allow("", null).default(10),
66825
- status: import_joi146.default.string().optional().allow(null, ""),
66826
- org: import_joi146.default.string().hex().optional().allow("", null),
66827
- site: import_joi146.default.string().hex().optional().allow("", null)
67334
+ const schema2 = import_joi148.default.object({
67335
+ search: import_joi148.default.string().optional().allow("", null),
67336
+ page: import_joi148.default.number().integer().min(1).allow("", null).default(1),
67337
+ limit: import_joi148.default.number().integer().min(1).max(100).allow("", null).default(10),
67338
+ status: import_joi148.default.string().optional().allow(null, ""),
67339
+ org: import_joi148.default.string().hex().optional().allow("", null),
67340
+ site: import_joi148.default.string().hex().optional().allow("", null)
66828
67341
  });
66829
67342
  const { error, value } = schema2.validate(req.query);
66830
67343
  if (error) {
66831
67344
  const messages = error.details.map((d) => d.message).join(", ");
66832
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66833
- next(new import_node_server_utils251.BadRequestError(messages));
67345
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67346
+ next(new import_node_server_utils253.BadRequestError(messages));
66834
67347
  return;
66835
67348
  }
66836
67349
  const { search, page, limit, status, org, site } = value;
@@ -66838,21 +67351,21 @@ function useFormEntryController() {
66838
67351
  res.json(data);
66839
67352
  return;
66840
67353
  } catch (error) {
66841
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67354
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66842
67355
  next(error);
66843
67356
  return;
66844
67357
  }
66845
67358
  }
66846
67359
  async function getFormEntryById(req, res, next) {
66847
67360
  try {
66848
- const schema2 = import_joi146.default.object({
66849
- _id: import_joi146.default.string().hex().length(24).required()
67361
+ const schema2 = import_joi148.default.object({
67362
+ _id: import_joi148.default.string().hex().length(24).required()
66850
67363
  });
66851
67364
  const { error, value } = schema2.validate({ _id: req.params.id });
66852
67365
  if (error) {
66853
67366
  const messages = error.details.map((d) => d.message).join(", ");
66854
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66855
- next(new import_node_server_utils251.BadRequestError(messages));
67367
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67368
+ next(new import_node_server_utils253.BadRequestError(messages));
66856
67369
  return;
66857
67370
  }
66858
67371
  const { _id } = value;
@@ -66860,7 +67373,7 @@ function useFormEntryController() {
66860
67373
  res.json(data);
66861
67374
  return;
66862
67375
  } catch (error) {
66863
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67376
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66864
67377
  next(error);
66865
67378
  return;
66866
67379
  }
@@ -66873,8 +67386,8 @@ function useFormEntryController() {
66873
67386
  });
66874
67387
  if (error) {
66875
67388
  const messages = error.details.map((d) => d.message).join(", ");
66876
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66877
- next(new import_node_server_utils251.BadRequestError(messages));
67389
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67390
+ next(new import_node_server_utils253.BadRequestError(messages));
66878
67391
  return;
66879
67392
  }
66880
67393
  const { _id, ...rest } = value;
@@ -66882,26 +67395,26 @@ function useFormEntryController() {
66882
67395
  res.json({ message: "Successfully updated online form." });
66883
67396
  return;
66884
67397
  } catch (error) {
66885
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67398
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66886
67399
  next(error);
66887
67400
  return;
66888
67401
  }
66889
67402
  }
66890
67403
  async function deleteFormEntryById(req, res, next) {
66891
67404
  try {
66892
- const validation = import_joi146.default.string().hex().required();
67405
+ const validation = import_joi148.default.string().hex().required();
66893
67406
  const _id = req.params.id;
66894
67407
  const { error } = validation.validate(_id);
66895
67408
  if (error) {
66896
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
66897
- next(new import_node_server_utils251.BadRequestError(error.message));
67409
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67410
+ next(new import_node_server_utils253.BadRequestError(error.message));
66898
67411
  return;
66899
67412
  }
66900
67413
  await _deleteOnlineFormById(_id);
66901
67414
  res.json({ message: "Successfully deleted online form." });
66902
67415
  return;
66903
67416
  } catch (error) {
66904
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67417
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66905
67418
  next(error);
66906
67419
  return;
66907
67420
  }
@@ -66918,8 +67431,8 @@ function useFormEntryController() {
66918
67431
  });
66919
67432
  if (error) {
66920
67433
  const messages = error.details.map((d) => d.message).join(", ");
66921
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66922
- next(new import_node_server_utils251.BadRequestError(messages));
67434
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67435
+ next(new import_node_server_utils253.BadRequestError(messages));
66923
67436
  return;
66924
67437
  }
66925
67438
  try {
@@ -66927,7 +67440,7 @@ function useFormEntryController() {
66927
67440
  res.status(201).json({ message: data });
66928
67441
  return;
66929
67442
  } catch (error2) {
66930
- import_node_server_utils251.logger.log({ level: "error", message: error2.message });
67443
+ import_node_server_utils253.logger.log({ level: "error", message: error2.message });
66931
67444
  next(error2);
66932
67445
  return;
66933
67446
  }
@@ -66939,8 +67452,8 @@ function useFormEntryController() {
66939
67452
  });
66940
67453
  if (error) {
66941
67454
  const messages = error.details.map((d) => d.message).join(", ");
66942
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66943
- next(new import_node_server_utils251.BadRequestError(messages));
67455
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67456
+ next(new import_node_server_utils253.BadRequestError(messages));
66944
67457
  return;
66945
67458
  }
66946
67459
  try {
@@ -66948,7 +67461,7 @@ function useFormEntryController() {
66948
67461
  res.status(201).json({ message: data });
66949
67462
  return;
66950
67463
  } catch (error2) {
66951
- import_node_server_utils251.logger.log({ level: "error", message: error2.message });
67464
+ import_node_server_utils253.logger.log({ level: "error", message: error2.message });
66952
67465
  next(error2);
66953
67466
  return;
66954
67467
  }
@@ -66956,22 +67469,22 @@ function useFormEntryController() {
66956
67469
  async function residentForm(req, res, next) {
66957
67470
  try {
66958
67471
  const { site, userId, org } = req.query;
66959
- const residentFormPayload = import_joi146.default.object({
66960
- org: import_joi146.default.string().hex().required(),
66961
- site: import_joi146.default.string().hex().required(),
66962
- userId: import_joi146.default.string().hex().required()
67472
+ const residentFormPayload = import_joi148.default.object({
67473
+ org: import_joi148.default.string().hex().required(),
67474
+ site: import_joi148.default.string().hex().required(),
67475
+ userId: import_joi148.default.string().hex().required()
66963
67476
  });
66964
67477
  const { error } = residentFormPayload.validate({ site, userId, org }, { abortEarly: true });
66965
67478
  if (error) {
66966
67479
  const messages = error.details.map((d) => d.message).join(", ");
66967
- import_node_server_utils251.logger.log({ level: "error", message: messages });
66968
- next(new import_node_server_utils251.BadRequestError(messages));
67480
+ import_node_server_utils253.logger.log({ level: "error", message: messages });
67481
+ next(new import_node_server_utils253.BadRequestError(messages));
66969
67482
  return;
66970
67483
  }
66971
67484
  const result = await _residentForm({ userId, site, org });
66972
67485
  res.json(result);
66973
67486
  } catch (error) {
66974
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67487
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
66975
67488
  next(error);
66976
67489
  return;
66977
67490
  }
@@ -66989,11 +67502,11 @@ function useFormEntryController() {
66989
67502
  }
66990
67503
 
66991
67504
  // src/services/building-level.service.ts
66992
- var import_node_server_utils252 = require("@7365admin1/node-server-utils");
67505
+ var import_node_server_utils254 = require("@7365admin1/node-server-utils");
66993
67506
  function useBuildingLevelService() {
66994
67507
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelRepo();
66995
67508
  async function add(value) {
66996
- const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
67509
+ const session = import_node_server_utils254.useAtlas.getClient()?.startSession();
66997
67510
  try {
66998
67511
  session?.startTransaction();
66999
67512
  await _add(value, session);
@@ -67007,7 +67520,7 @@ function useBuildingLevelService() {
67007
67520
  }
67008
67521
  }
67009
67522
  async function updateLevelById(_id, value) {
67010
- const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
67523
+ const session = import_node_server_utils254.useAtlas.getClient()?.startSession();
67011
67524
  try {
67012
67525
  session?.startTransaction();
67013
67526
  await _updateLevelById(_id, value, session);
@@ -67027,8 +67540,8 @@ function useBuildingLevelService() {
67027
67540
  }
67028
67541
 
67029
67542
  // src/controllers/building-level.controller.ts
67030
- var import_node_server_utils253 = require("@7365admin1/node-server-utils");
67031
- var import_joi147 = __toESM(require("joi"));
67543
+ var import_node_server_utils255 = require("@7365admin1/node-server-utils");
67544
+ var import_joi149 = __toESM(require("joi"));
67032
67545
  function useBuildingLevelController() {
67033
67546
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelService();
67034
67547
  const {
@@ -67045,8 +67558,8 @@ function useBuildingLevelController() {
67045
67558
  });
67046
67559
  if (error) {
67047
67560
  const messages = error.details.map((d) => d.message).join(", ");
67048
- import_node_server_utils253.logger.log({ level: "error", message: messages });
67049
- next(new import_node_server_utils253.BadRequestError(messages));
67561
+ import_node_server_utils255.logger.log({ level: "error", message: messages });
67562
+ next(new import_node_server_utils255.BadRequestError(messages));
67050
67563
  return;
67051
67564
  }
67052
67565
  const result = await _add(value);
@@ -67057,20 +67570,20 @@ function useBuildingLevelController() {
67057
67570
  }
67058
67571
  async function getAll(req, res, next) {
67059
67572
  try {
67060
- const validation = import_joi147.default.object({
67061
- page: import_joi147.default.number().min(1).optional().default(1),
67062
- limit: import_joi147.default.number().min(1).optional().default(20),
67063
- search: import_joi147.default.string().optional().allow("", null),
67064
- site: import_joi147.default.string().hex().length(24).optional().allow("", null),
67065
- status: import_joi147.default.string().valid(...Object.values(BuildingLevelStatus)).default("active" /* ACTIVE */)
67573
+ const validation = import_joi149.default.object({
67574
+ page: import_joi149.default.number().min(1).optional().default(1),
67575
+ limit: import_joi149.default.number().min(1).optional().default(20),
67576
+ search: import_joi149.default.string().optional().allow("", null),
67577
+ site: import_joi149.default.string().hex().length(24).optional().allow("", null),
67578
+ status: import_joi149.default.string().valid(...Object.values(BuildingLevelStatus)).default("active" /* ACTIVE */)
67066
67579
  });
67067
67580
  const { error, value } = validation.validate(req.query, {
67068
67581
  abortEarly: false
67069
67582
  });
67070
67583
  if (error) {
67071
67584
  const messages = error.details.map((d) => d.message);
67072
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67073
- next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
67585
+ import_node_server_utils255.logger.log({ level: "error", message: messages.join(", ") });
67586
+ next(new import_node_server_utils255.BadRequestError(messages.join(", ")));
67074
67587
  return;
67075
67588
  }
67076
67589
  const { page, limit, status, site, search } = value;
@@ -67089,14 +67602,14 @@ function useBuildingLevelController() {
67089
67602
  }
67090
67603
  async function getById(req, res, next) {
67091
67604
  try {
67092
- const schema2 = import_joi147.default.object({
67093
- id: import_joi147.default.string().hex().length(24).required()
67605
+ const schema2 = import_joi149.default.object({
67606
+ id: import_joi149.default.string().hex().length(24).required()
67094
67607
  });
67095
67608
  const { error, value } = schema2.validate({ id: req.params.id });
67096
67609
  if (error) {
67097
67610
  const messages = error.details.map((d) => d.message);
67098
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67099
- next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
67611
+ import_node_server_utils255.logger.log({ level: "error", message: messages.join(", ") });
67612
+ next(new import_node_server_utils255.BadRequestError(messages.join(", ")));
67100
67613
  return;
67101
67614
  }
67102
67615
  const { id } = value;
@@ -67115,8 +67628,8 @@ function useBuildingLevelController() {
67115
67628
  });
67116
67629
  if (error) {
67117
67630
  const messages = error.details.map((d) => d.message);
67118
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67119
- next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
67631
+ import_node_server_utils255.logger.log({ level: "error", message: messages.join(", ") });
67632
+ next(new import_node_server_utils255.BadRequestError(messages.join(", ")));
67120
67633
  return;
67121
67634
  }
67122
67635
  const { _id, ...rest } = value;
@@ -67128,14 +67641,14 @@ function useBuildingLevelController() {
67128
67641
  }
67129
67642
  async function deleteById(req, res, next) {
67130
67643
  try {
67131
- const schema2 = import_joi147.default.object({
67132
- id: import_joi147.default.string().hex().required()
67644
+ const schema2 = import_joi149.default.object({
67645
+ id: import_joi149.default.string().hex().required()
67133
67646
  });
67134
67647
  const { error, value } = schema2.validate({ id: req.params.id });
67135
67648
  if (error) {
67136
67649
  const messages = error.details.map((d) => d.message);
67137
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67138
- next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
67650
+ import_node_server_utils255.logger.log({ level: "error", message: messages.join(", ") });
67651
+ next(new import_node_server_utils255.BadRequestError(messages.join(", ")));
67139
67652
  return;
67140
67653
  }
67141
67654
  const { id } = value;
@@ -67148,19 +67661,19 @@ function useBuildingLevelController() {
67148
67661
  }
67149
67662
  async function batchUpdateByIds(req, res, next) {
67150
67663
  try {
67151
- const schema2 = import_joi147.default.array().items(
67152
- import_joi147.default.object({
67153
- _id: import_joi147.default.string().hex().length(24).required(),
67154
- value: import_joi147.default.object({
67155
- name: import_joi147.default.string().optional().allow("", null)
67664
+ const schema2 = import_joi149.default.array().items(
67665
+ import_joi149.default.object({
67666
+ _id: import_joi149.default.string().hex().length(24).required(),
67667
+ value: import_joi149.default.object({
67668
+ name: import_joi149.default.string().optional().allow("", null)
67156
67669
  }).required()
67157
67670
  })
67158
67671
  );
67159
67672
  const { error, value } = schema2.validate(req.body);
67160
67673
  if (error) {
67161
67674
  const messages = error.details.map((d) => d.message);
67162
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67163
- next(new import_node_server_utils253.BadRequestError(messages.join(", ")));
67675
+ import_node_server_utils255.logger.log({ level: "error", message: messages.join(", ") });
67676
+ next(new import_node_server_utils255.BadRequestError(messages.join(", ")));
67164
67677
  return;
67165
67678
  }
67166
67679
  const updates = value.map((item) => ({
@@ -67175,9 +67688,9 @@ function useBuildingLevelController() {
67175
67688
  }
67176
67689
  async function getBuildingLevelList(req, res, next) {
67177
67690
  try {
67178
- const schema2 = import_joi147.default.object({
67179
- site: import_joi147.default.string().hex().length(24).required(),
67180
- block: import_joi147.default.string().hex().length(24).required()
67691
+ const schema2 = import_joi149.default.object({
67692
+ site: import_joi149.default.string().hex().length(24).required(),
67693
+ block: import_joi149.default.string().hex().length(24).required()
67181
67694
  });
67182
67695
  const { error, value } = schema2.validate({
67183
67696
  site: req.params.siteId,
@@ -67185,8 +67698,8 @@ function useBuildingLevelController() {
67185
67698
  });
67186
67699
  if (error) {
67187
67700
  const messages = error.details.map((d) => d.message).join(", ");
67188
- import_node_server_utils253.logger.log({ level: "error", message: messages });
67189
- next(new import_node_server_utils253.BadRequestError(messages));
67701
+ import_node_server_utils255.logger.log({ level: "error", message: messages });
67702
+ next(new import_node_server_utils255.BadRequestError(messages));
67190
67703
  return;
67191
67704
  }
67192
67705
  const { site, block } = value;
@@ -67207,11 +67720,1358 @@ function useBuildingLevelController() {
67207
67720
  getBuildingLevelList
67208
67721
  };
67209
67722
  }
67723
+
67724
+ // src/models/hid-amico.model.ts
67725
+ var import_node_server_utils256 = require("@7365admin1/node-server-utils");
67726
+ var import_mongodb153 = require("mongodb");
67727
+ var import_joi150 = __toESM(require("joi"));
67728
+ function canReadObjectId(value) {
67729
+ if (value instanceof import_mongodb153.ObjectId)
67730
+ return true;
67731
+ if (typeof value === "string")
67732
+ return import_mongodb153.ObjectId.isValid(value);
67733
+ if (value && typeof value === "object") {
67734
+ const candidate = value;
67735
+ if (canReadObjectId(candidate._id) || canReadObjectId(candidate.$oid))
67736
+ return true;
67737
+ if (typeof candidate.toHexString === "function" && import_mongodb153.ObjectId.isValid(candidate.toHexString()))
67738
+ return true;
67739
+ if (typeof candidate.toString === "function") {
67740
+ const text = candidate.toString();
67741
+ return text !== "[object Object]" && import_mongodb153.ObjectId.isValid(text);
67742
+ }
67743
+ }
67744
+ return false;
67745
+ }
67746
+ function toObjectId23(value, label = "ID") {
67747
+ if (value instanceof import_mongodb153.ObjectId)
67748
+ return value;
67749
+ if (typeof value === "string" && import_mongodb153.ObjectId.isValid(value))
67750
+ return new import_mongodb153.ObjectId(value);
67751
+ if (value && typeof value === "object") {
67752
+ const candidate = value;
67753
+ if (candidate._id)
67754
+ return toObjectId23(candidate._id, label);
67755
+ if (candidate.$oid)
67756
+ return toObjectId23(candidate.$oid, label);
67757
+ if (typeof candidate.toHexString === "function")
67758
+ return toObjectId23(candidate.toHexString(), label);
67759
+ if (typeof candidate.toString === "function") {
67760
+ const text = candidate.toString();
67761
+ if (text !== "[object Object]")
67762
+ return toObjectId23(text, label);
67763
+ }
67764
+ }
67765
+ throw new import_node_server_utils256.BadRequestError(`Invalid ${label} format`);
67766
+ }
67767
+ var objectIdSchema2 = import_joi150.default.custom((value, helpers) => canReadObjectId(value) ? value : helpers.error("any.invalid"), "ObjectId").messages({
67768
+ "any.invalid": "{{#label}} must be a valid ObjectId"
67769
+ });
67770
+ var schemaHidAmicoReader = import_joi150.default.object({
67771
+ _id: objectIdSchema2.optional(),
67772
+ site: objectIdSchema2.required(),
67773
+ name: import_joi150.default.string().trim().required(),
67774
+ baseUrl: import_joi150.default.string().uri({ scheme: ["http", "https"] }).required(),
67775
+ username: import_joi150.default.string().trim().required(),
67776
+ password: import_joi150.default.string().required(),
67777
+ location: import_joi150.default.string().allow(null, "").optional(),
67778
+ deviceId: import_joi150.default.string().allow(null, "").optional(),
67779
+ monitorPath: import_joi150.default.string().allow(null, "").optional(),
67780
+ enabled: import_joi150.default.boolean().optional(),
67781
+ status: import_joi150.default.string().valid("active", "inactive", "deleted", "offline").optional(),
67782
+ lastSeenAt: import_joi150.default.date().optional(),
67783
+ lastSyncAt: import_joi150.default.date().optional(),
67784
+ lastSyncStatus: import_joi150.default.string().valid("idle", "running", "completed", "failed").optional(),
67785
+ lastSyncMessage: import_joi150.default.string().allow(null, "").optional(),
67786
+ createdAt: import_joi150.default.date().optional(),
67787
+ updatedAt: import_joi150.default.date().optional(),
67788
+ deletedAt: import_joi150.default.date().optional()
67789
+ });
67790
+ var schemaUpdateHidAmicoReader = import_joi150.default.object({
67791
+ site: objectIdSchema2.optional(),
67792
+ name: import_joi150.default.string().trim().optional(),
67793
+ baseUrl: import_joi150.default.string().uri({ scheme: ["http", "https"] }).optional(),
67794
+ username: import_joi150.default.string().trim().optional(),
67795
+ password: import_joi150.default.string().allow(null, "").optional(),
67796
+ location: import_joi150.default.string().allow(null, "").optional(),
67797
+ deviceId: import_joi150.default.string().allow(null, "").optional(),
67798
+ monitorPath: import_joi150.default.string().allow(null, "").optional(),
67799
+ enabled: import_joi150.default.boolean().optional(),
67800
+ status: import_joi150.default.string().valid("active", "inactive", "deleted", "offline").optional(),
67801
+ lastSeenAt: import_joi150.default.date().optional(),
67802
+ lastSyncAt: import_joi150.default.date().optional(),
67803
+ lastSyncStatus: import_joi150.default.string().valid("idle", "running", "completed", "failed").optional(),
67804
+ lastSyncMessage: import_joi150.default.string().allow(null, "").optional(),
67805
+ deletedAt: import_joi150.default.date().optional()
67806
+ });
67807
+ var schemaHidAmicoEvent = import_joi150.default.object({
67808
+ _id: objectIdSchema2.optional(),
67809
+ reader: objectIdSchema2.required(),
67810
+ site: objectIdSchema2.optional(),
67811
+ type: import_joi150.default.string().required(),
67812
+ payload: import_joi150.default.object().unknown(true).required(),
67813
+ status: import_joi150.default.string().valid("received", "processed", "failed").optional(),
67814
+ createdAt: import_joi150.default.date().optional()
67815
+ });
67816
+ var schemaHidAmicoIdentity = import_joi150.default.object({
67817
+ _id: objectIdSchema2.optional(),
67818
+ reader: objectIdSchema2.required(),
67819
+ site: objectIdSchema2.required(),
67820
+ hidUserId: import_joi150.default.alternatives(import_joi150.default.string(), import_joi150.default.number()).optional().allow(null, ""),
67821
+ registration: import_joi150.default.string().optional().allow(null, ""),
67822
+ cardNo: import_joi150.default.string().optional().allow(null, ""),
67823
+ person: objectIdSchema2.optional().allow(null, ""),
67824
+ user: objectIdSchema2.optional().allow(null, ""),
67825
+ member: objectIdSchema2.optional().allow(null, ""),
67826
+ visitor: objectIdSchema2.optional().allow(null, ""),
67827
+ type: import_joi150.default.string().valid("resident", "staff", "contractor", "visitor", "admin", "unknown").required(),
67828
+ status: import_joi150.default.string().valid("active", "inactive", "deleted").optional(),
67829
+ metadata: import_joi150.default.object().unknown(true).optional(),
67830
+ createdAt: import_joi150.default.date().optional(),
67831
+ updatedAt: import_joi150.default.date().optional(),
67832
+ deletedAt: import_joi150.default.date().optional()
67833
+ }).or("hidUserId", "registration", "cardNo");
67834
+ var schemaCreateHidAmicoIdentity = import_joi150.default.object({
67835
+ site: objectIdSchema2.optional(),
67836
+ hidUserId: import_joi150.default.alternatives(import_joi150.default.string(), import_joi150.default.number()).optional().allow(null, ""),
67837
+ registration: import_joi150.default.string().optional().allow(null, ""),
67838
+ cardNo: import_joi150.default.string().optional().allow(null, ""),
67839
+ person: objectIdSchema2.optional().allow(null, ""),
67840
+ user: objectIdSchema2.optional().allow(null, ""),
67841
+ member: objectIdSchema2.optional().allow(null, ""),
67842
+ visitor: objectIdSchema2.optional().allow(null, ""),
67843
+ type: import_joi150.default.string().valid("resident", "staff", "contractor", "visitor", "admin", "unknown").required(),
67844
+ status: import_joi150.default.string().valid("active", "inactive", "deleted").optional(),
67845
+ metadata: import_joi150.default.object().unknown(true).optional()
67846
+ }).or("hidUserId", "registration", "cardNo");
67847
+ var schemaUpdateHidAmicoIdentity = import_joi150.default.object({
67848
+ hidUserId: import_joi150.default.alternatives(import_joi150.default.string(), import_joi150.default.number()).optional().allow(null, ""),
67849
+ registration: import_joi150.default.string().optional().allow(null, ""),
67850
+ cardNo: import_joi150.default.string().optional().allow(null, ""),
67851
+ person: objectIdSchema2.optional().allow(null, ""),
67852
+ user: objectIdSchema2.optional().allow(null, ""),
67853
+ member: objectIdSchema2.optional().allow(null, ""),
67854
+ visitor: objectIdSchema2.optional().allow(null, ""),
67855
+ type: import_joi150.default.string().valid("resident", "staff", "contractor", "visitor", "admin", "unknown").optional(),
67856
+ status: import_joi150.default.string().valid("active", "inactive", "deleted").optional(),
67857
+ metadata: import_joi150.default.object().unknown(true).optional(),
67858
+ deletedAt: import_joi150.default.date().optional()
67859
+ });
67860
+ var schemaHidAmicoReaderIdParams = import_joi150.default.object({
67861
+ readerId: import_joi150.default.string().hex().length(24).required()
67862
+ });
67863
+ var schemaHidAmicoUserImageParams = import_joi150.default.object({
67864
+ readerId: import_joi150.default.string().hex().length(24).required(),
67865
+ hidUserId: import_joi150.default.alternatives().try(import_joi150.default.string(), import_joi150.default.number()).required()
67866
+ });
67867
+ var schemaHidAmicoIdentityIdParams = import_joi150.default.object({
67868
+ identityId: import_joi150.default.string().hex().length(24).required()
67869
+ });
67870
+ var schemaHidAmicoReaderListQuery = import_joi150.default.object({
67871
+ site: import_joi150.default.string().hex().length(24).optional(),
67872
+ page: import_joi150.default.number().min(1).optional(),
67873
+ limit: import_joi150.default.number().min(1).optional()
67874
+ });
67875
+ var schemaHidAmicoLogQuery = import_joi150.default.object({
67876
+ page: import_joi150.default.number().min(1).optional(),
67877
+ limit: import_joi150.default.number().min(1).optional(),
67878
+ type: import_joi150.default.string().optional()
67879
+ });
67880
+ var schemaHidAmicoIdentityQuery = import_joi150.default.object({
67881
+ page: import_joi150.default.number().min(1).optional(),
67882
+ limit: import_joi150.default.number().min(1).optional(),
67883
+ type: import_joi150.default.string().valid("resident", "staff", "contractor", "visitor", "admin", "unknown").optional(),
67884
+ status: import_joi150.default.string().valid("active", "inactive", "deleted").optional(),
67885
+ search: import_joi150.default.string().allow("").optional()
67886
+ });
67887
+ var schemaHidAmicoSync = import_joi150.default.object({
67888
+ objects: import_joi150.default.array().items(
67889
+ import_joi150.default.object({
67890
+ object: import_joi150.default.string().required(),
67891
+ values: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).required()
67892
+ }).unknown(true)
67893
+ ).optional(),
67894
+ users: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).optional(),
67895
+ cards: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).optional(),
67896
+ qrcodes: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).optional(),
67897
+ pins: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).optional()
67898
+ }).unknown(true);
67899
+ var schemaHidAmicoExecuteActions = import_joi150.default.object({
67900
+ actions: import_joi150.default.array().items(import_joi150.default.object().unknown(true)).min(1).required()
67901
+ }).unknown(true);
67902
+ var schemaHidAmicoConfiguration = import_joi150.default.object().pattern(import_joi150.default.string(), import_joi150.default.array().items(import_joi150.default.string())).min(1).unknown(true);
67903
+ var schemaHidAmicoSetConfiguration = import_joi150.default.object().unknown(true);
67904
+ var schemaHidAmicoObjectOperation = import_joi150.default.object({
67905
+ operation: import_joi150.default.string().valid("load", "create", "modify", "destroy").required(),
67906
+ object: import_joi150.default.string().required(),
67907
+ values: import_joi150.default.alternatives().try(
67908
+ import_joi150.default.array().items(import_joi150.default.object().unknown(true)),
67909
+ import_joi150.default.object().unknown(true)
67910
+ ).optional(),
67911
+ where: import_joi150.default.object().unknown(true).optional(),
67912
+ fields: import_joi150.default.array().items(import_joi150.default.string()).optional(),
67913
+ order: import_joi150.default.array().items(import_joi150.default.string()).optional(),
67914
+ limit: import_joi150.default.number().integer().min(1).optional(),
67915
+ offset: import_joi150.default.number().integer().min(0).optional()
67916
+ }).unknown(true);
67917
+ var schemaHidAmicoNotificationParams = import_joi150.default.object({
67918
+ readerId: import_joi150.default.string().hex().length(24).required(),
67919
+ type: import_joi150.default.string().valid(
67920
+ "dao",
67921
+ "template",
67922
+ "user_image",
67923
+ "card",
67924
+ "pin",
67925
+ "password",
67926
+ "operation_mode",
67927
+ "door",
67928
+ "secbox",
67929
+ "access_photo",
67930
+ "new_user_identified",
67931
+ "push_result"
67932
+ ).required()
67933
+ });
67934
+ function MHidAmicoReader(value) {
67935
+ const { error } = schemaHidAmicoReader.validate(value);
67936
+ if (error) {
67937
+ import_node_server_utils256.logger.info(`HID Amico reader: ${error.message}`);
67938
+ throw new import_node_server_utils256.BadRequestError(error.message);
67939
+ }
67940
+ return {
67941
+ _id: value._id ? toObjectId23(value._id, "reader ID") : new import_mongodb153.ObjectId(),
67942
+ site: toObjectId23(value.site, "site ID"),
67943
+ name: value.name,
67944
+ baseUrl: value.baseUrl.replace(/\/+$/, ""),
67945
+ username: value.username,
67946
+ password: value.password,
67947
+ location: value.location ?? "",
67948
+ deviceId: value.deviceId ?? "",
67949
+ monitorPath: value.monitorPath ?? "api/notifications",
67950
+ enabled: value.enabled ?? true,
67951
+ status: value.status ?? "active",
67952
+ lastSeenAt: value.lastSeenAt ?? "",
67953
+ lastSyncAt: value.lastSyncAt ?? "",
67954
+ lastSyncStatus: value.lastSyncStatus ?? "idle",
67955
+ lastSyncMessage: value.lastSyncMessage ?? "",
67956
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
67957
+ updatedAt: value.updatedAt ?? /* @__PURE__ */ new Date(),
67958
+ deletedAt: value.deletedAt ?? ""
67959
+ };
67960
+ }
67961
+ function MHidAmicoEvent(value) {
67962
+ const { error } = schemaHidAmicoEvent.validate(value);
67963
+ if (error) {
67964
+ import_node_server_utils256.logger.info(`HID Amico event: ${error.message}`);
67965
+ throw new import_node_server_utils256.BadRequestError(error.message);
67966
+ }
67967
+ return {
67968
+ _id: value._id ? toObjectId23(value._id, "event ID") : new import_mongodb153.ObjectId(),
67969
+ reader: toObjectId23(value.reader, "reader ID"),
67970
+ site: value.site ? toObjectId23(value.site, "site ID") : void 0,
67971
+ type: value.type,
67972
+ payload: value.payload,
67973
+ status: value.status ?? "received",
67974
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date()
67975
+ };
67976
+ }
67977
+ function optionalObjectId(value) {
67978
+ return value ? toObjectId23(value) : void 0;
67979
+ }
67980
+ function MHidAmicoIdentity(value) {
67981
+ const { error } = schemaHidAmicoIdentity.validate(value);
67982
+ if (error) {
67983
+ import_node_server_utils256.logger.info(`HID Amico identity: ${error.message}`);
67984
+ throw new import_node_server_utils256.BadRequestError(error.message);
67985
+ }
67986
+ return {
67987
+ _id: value._id ? toObjectId23(value._id, "identity ID") : new import_mongodb153.ObjectId(),
67988
+ reader: toObjectId23(value.reader, "reader ID"),
67989
+ site: toObjectId23(value.site, "site ID"),
67990
+ hidUserId: value.hidUserId === void 0 || value.hidUserId === null ? "" : String(value.hidUserId),
67991
+ registration: value.registration ?? "",
67992
+ cardNo: value.cardNo ?? "",
67993
+ person: optionalObjectId(value.person),
67994
+ user: optionalObjectId(value.user),
67995
+ member: optionalObjectId(value.member),
67996
+ visitor: optionalObjectId(value.visitor),
67997
+ type: value.type,
67998
+ status: value.status ?? "active",
67999
+ metadata: value.metadata ?? {},
68000
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
68001
+ updatedAt: value.updatedAt ?? /* @__PURE__ */ new Date(),
68002
+ deletedAt: value.deletedAt ?? ""
68003
+ };
68004
+ }
68005
+
68006
+ // src/repositories/hid-amico.repo.ts
68007
+ var import_node_server_utils257 = require("@7365admin1/node-server-utils");
68008
+ var import_mongodb154 = require("mongodb");
68009
+ function useHidAmicoRepo() {
68010
+ function db() {
68011
+ const instance = import_node_server_utils257.useAtlas.getDb();
68012
+ if (!instance) {
68013
+ throw new import_node_server_utils257.InternalServerError("Unable to connect to server.");
68014
+ }
68015
+ return instance;
68016
+ }
68017
+ function readers() {
68018
+ return db().collection("hid-amico-readers");
68019
+ }
68020
+ function events() {
68021
+ return db().collection("hid-amico-events");
68022
+ }
68023
+ function identities() {
68024
+ return db().collection("hid-amico-identities");
68025
+ }
68026
+ function toId(id, label = "ID") {
68027
+ try {
68028
+ return new import_mongodb154.ObjectId(id);
68029
+ } catch {
68030
+ throw new import_node_server_utils257.BadRequestError(`Invalid ${label} format`);
68031
+ }
68032
+ }
68033
+ function hideSecret(reader) {
68034
+ if (!reader) {
68035
+ return reader;
68036
+ }
68037
+ const { password, ...safeReader } = reader;
68038
+ const status = safeReader.lastSyncStatus === "failed" && safeReader.status === "active" ? "offline" : safeReader.status;
68039
+ return {
68040
+ ...safeReader,
68041
+ status,
68042
+ passwordSet: Boolean(password)
68043
+ };
68044
+ }
68045
+ function escapeRegex(value) {
68046
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
68047
+ }
68048
+ function buildIdentityKeyQuery(value) {
68049
+ const or = [];
68050
+ if (value.hidUserId !== void 0 && value.hidUserId !== null && String(value.hidUserId) !== "") {
68051
+ or.push({ hidUserId: String(value.hidUserId) });
68052
+ }
68053
+ if (value.registration) {
68054
+ or.push({ registration: value.registration });
68055
+ }
68056
+ if (value.cardNo) {
68057
+ or.push({ cardNo: value.cardNo });
68058
+ }
68059
+ return or;
68060
+ }
68061
+ async function createIndexes() {
68062
+ try {
68063
+ await Promise.all([
68064
+ readers().createIndex({ site: 1, status: 1 }),
68065
+ readers().createIndex(
68066
+ { site: 1, baseUrl: 1 },
68067
+ { unique: true, partialFilterExpression: { status: "active" } }
68068
+ ),
68069
+ readers().createIndex({ deviceId: 1 }),
68070
+ events().createIndex({ reader: 1, createdAt: -1 }),
68071
+ events().createIndex({ site: 1, createdAt: -1 }),
68072
+ events().createIndex({ type: 1, createdAt: -1 }),
68073
+ identities().createIndex({ reader: 1, status: 1 }),
68074
+ identities().createIndex({ site: 1, status: 1 }),
68075
+ identities().createIndex({ reader: 1, hidUserId: 1 }),
68076
+ identities().createIndex({ reader: 1, registration: 1 }),
68077
+ identities().createIndex({ reader: 1, cardNo: 1 })
68078
+ ]);
68079
+ return "HID Amico indexes created.";
68080
+ } catch (error) {
68081
+ import_node_server_utils257.logger.error(error.message);
68082
+ throw new Error("Failed to create HID Amico indexes.");
68083
+ }
68084
+ }
68085
+ async function add(value, session) {
68086
+ try {
68087
+ const doc = MHidAmicoReader(value);
68088
+ await readers().insertOne(doc, { session });
68089
+ return hideSecret(doc);
68090
+ } catch (error) {
68091
+ if (error.message?.includes("duplicate")) {
68092
+ throw new import_node_server_utils257.BadRequestError("HID Amico reader already exists for this site and URL.");
68093
+ }
68094
+ throw error;
68095
+ }
68096
+ }
68097
+ async function list(value) {
68098
+ const page = value.page ? value.page - 1 : 0;
68099
+ const limit = value.limit || 10;
68100
+ const query = { status: { $ne: "deleted" } };
68101
+ if (value.site) {
68102
+ query.site = toId(value.site, "site ID");
68103
+ }
68104
+ const items = await readers().find(query).sort({ createdAt: -1 }).skip(page * limit).limit(limit).toArray();
68105
+ const total = await readers().countDocuments(query);
68106
+ return (0, import_node_server_utils257.paginate)(items.map(hideSecret), page, limit, total);
68107
+ }
68108
+ async function getById(id, options = {}) {
68109
+ const _id = toId(id, "reader ID");
68110
+ const reader = await readers().findOne(
68111
+ { _id, status: { $ne: "deleted" } }
68112
+ );
68113
+ if (!reader) {
68114
+ throw new import_node_server_utils257.BadRequestError("HID Amico reader not found.");
68115
+ }
68116
+ return options.includePassword ? reader : hideSecret(reader);
68117
+ }
68118
+ async function updateById(id, value, session) {
68119
+ const { error } = schemaUpdateHidAmicoReader.validate(value);
68120
+ if (error) {
68121
+ throw new import_node_server_utils257.BadRequestError(error.message);
68122
+ }
68123
+ const _id = toId(id, "reader ID");
68124
+ const payload = {
68125
+ ...value,
68126
+ updatedAt: /* @__PURE__ */ new Date()
68127
+ };
68128
+ if (payload.site) {
68129
+ payload.site = toId(payload.site, "site ID");
68130
+ }
68131
+ if (payload.baseUrl) {
68132
+ payload.baseUrl = payload.baseUrl.replace(/\/+$/, "");
68133
+ }
68134
+ const updated = await readers().findOneAndUpdate(
68135
+ { _id, status: { $ne: "deleted" } },
68136
+ { $set: payload },
68137
+ { returnDocument: "after", session }
68138
+ );
68139
+ if (!updated) {
68140
+ throw new import_node_server_utils257.BadRequestError("HID Amico reader not found.");
68141
+ }
68142
+ return hideSecret(updated);
68143
+ }
68144
+ async function markDeleted(id, session) {
68145
+ return updateById(
68146
+ id,
68147
+ {
68148
+ status: "deleted",
68149
+ enabled: false,
68150
+ deletedAt: /* @__PURE__ */ new Date()
68151
+ },
68152
+ session
68153
+ );
68154
+ }
68155
+ async function addEvent(value, session) {
68156
+ const event = MHidAmicoEvent(value);
68157
+ await events().insertOne(event, { session });
68158
+ return event;
68159
+ }
68160
+ async function listEvents(value) {
68161
+ const page = value.page ? value.page - 1 : 0;
68162
+ const limit = value.limit || 20;
68163
+ const query = { reader: toId(value.reader, "reader ID") };
68164
+ if (value.type) {
68165
+ query.type = value.type;
68166
+ }
68167
+ const items = await events().find(query).sort({ createdAt: -1 }).skip(page * limit).limit(limit).toArray();
68168
+ const total = await events().countDocuments(query);
68169
+ return (0, import_node_server_utils257.paginate)(items, page, limit, total);
68170
+ }
68171
+ async function addIdentity(value, session) {
68172
+ try {
68173
+ const identity = MHidAmicoIdentity(value);
68174
+ const existing = await findExistingIdentity({
68175
+ reader: identity.reader,
68176
+ hidUserId: identity.hidUserId,
68177
+ registration: identity.registration,
68178
+ cardNo: identity.cardNo
68179
+ });
68180
+ if (existing) {
68181
+ throw new import_node_server_utils257.BadRequestError("HID Amico identity already exists for this reader.");
68182
+ }
68183
+ await identities().insertOne(identity, { session });
68184
+ return identity;
68185
+ } catch (error) {
68186
+ if (error instanceof import_node_server_utils257.BadRequestError) {
68187
+ throw error;
68188
+ }
68189
+ if (error.message?.includes("duplicate")) {
68190
+ throw new import_node_server_utils257.BadRequestError("HID Amico identity already exists for this reader.");
68191
+ }
68192
+ throw error;
68193
+ }
68194
+ }
68195
+ async function listIdentities(value) {
68196
+ const page = value.page ? value.page - 1 : 0;
68197
+ const limit = value.limit || 20;
68198
+ const query = {
68199
+ reader: toId(value.reader, "reader ID"),
68200
+ status: value.status || { $ne: "deleted" }
68201
+ };
68202
+ if (value.type) {
68203
+ query.type = value.type;
68204
+ }
68205
+ if (value.search) {
68206
+ const search = escapeRegex(value.search);
68207
+ query.$or = [
68208
+ { hidUserId: { $regex: search, $options: "i" } },
68209
+ { registration: { $regex: search, $options: "i" } },
68210
+ { cardNo: { $regex: search, $options: "i" } }
68211
+ ];
68212
+ }
68213
+ const items = await identities().find(query).sort({ createdAt: -1 }).skip(page * limit).limit(limit).toArray();
68214
+ const total = await identities().countDocuments(query);
68215
+ return (0, import_node_server_utils257.paginate)(items, page, limit, total);
68216
+ }
68217
+ async function updateIdentity(id, value, session) {
68218
+ const { error } = schemaUpdateHidAmicoIdentity.validate(value);
68219
+ if (error) {
68220
+ throw new import_node_server_utils257.BadRequestError(error.message);
68221
+ }
68222
+ const payload = {
68223
+ ...value,
68224
+ updatedAt: /* @__PURE__ */ new Date()
68225
+ };
68226
+ const unsetPayload = {};
68227
+ ["person", "user", "member", "visitor"].forEach((field) => {
68228
+ if (payload[field]) {
68229
+ payload[field] = toId(payload[field], `${field} ID`);
68230
+ }
68231
+ if (payload[field] === "" || payload[field] === null) {
68232
+ delete payload[field];
68233
+ unsetPayload[field] = "";
68234
+ }
68235
+ });
68236
+ if (payload.hidUserId !== void 0 && payload.hidUserId !== null) {
68237
+ payload.hidUserId = String(payload.hidUserId);
68238
+ }
68239
+ const updated = await identities().findOneAndUpdate(
68240
+ { _id: toId(id, "identity ID"), status: { $ne: "deleted" } },
68241
+ {
68242
+ $set: payload,
68243
+ ...Object.keys(unsetPayload).length ? { $unset: unsetPayload } : {}
68244
+ },
68245
+ { returnDocument: "after", session }
68246
+ );
68247
+ if (!updated) {
68248
+ throw new import_node_server_utils257.BadRequestError("HID Amico identity not found.");
68249
+ }
68250
+ return updated;
68251
+ }
68252
+ async function deleteIdentity(id, session) {
68253
+ return updateIdentity(
68254
+ id,
68255
+ {
68256
+ status: "deleted",
68257
+ deletedAt: /* @__PURE__ */ new Date()
68258
+ },
68259
+ session
68260
+ );
68261
+ }
68262
+ async function findIdentity(value) {
68263
+ const or = buildIdentityKeyQuery(value);
68264
+ if (!or.length) {
68265
+ return null;
68266
+ }
68267
+ return identities().findOne({
68268
+ reader: toId(value.reader, "reader ID"),
68269
+ status: "active",
68270
+ $or: or
68271
+ });
68272
+ }
68273
+ async function findExistingIdentity(value) {
68274
+ const or = buildIdentityKeyQuery(value);
68275
+ if (!or.length) {
68276
+ return null;
68277
+ }
68278
+ return identities().findOne({
68279
+ reader: toId(value.reader, "reader ID"),
68280
+ status: { $ne: "deleted" },
68281
+ $or: or
68282
+ });
68283
+ }
68284
+ return {
68285
+ createIndexes,
68286
+ add,
68287
+ list,
68288
+ getById,
68289
+ updateById,
68290
+ markDeleted,
68291
+ addEvent,
68292
+ listEvents,
68293
+ addIdentity,
68294
+ listIdentities,
68295
+ updateIdentity,
68296
+ deleteIdentity,
68297
+ findIdentity,
68298
+ findExistingIdentity
68299
+ };
68300
+ }
68301
+
68302
+ // src/services/hid-amico.service.ts
68303
+ var import_crypto3 = __toESM(require("crypto"));
68304
+ var import_axios4 = __toESM(require("axios"));
68305
+ var import_node_server_utils258 = require("@7365admin1/node-server-utils");
68306
+ var PASSWORD_PREFIX = "v1";
68307
+ function getSecretKey() {
68308
+ const secret = process.env.HID_AMICO_SECRET || process.env.ACCESS_TOKEN_SECRET || "iservice365-hid-amico";
68309
+ return import_crypto3.default.createHash("sha256").update(secret).digest();
68310
+ }
68311
+ function encryptSecret(value) {
68312
+ const iv = import_crypto3.default.randomBytes(12);
68313
+ const cipher = import_crypto3.default.createCipheriv("aes-256-gcm", getSecretKey(), iv);
68314
+ const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
68315
+ const tag = cipher.getAuthTag();
68316
+ return [PASSWORD_PREFIX, iv.toString("hex"), tag.toString("hex"), encrypted.toString("hex")].join(":");
68317
+ }
68318
+ function decryptSecret(value) {
68319
+ if (!value?.startsWith(`${PASSWORD_PREFIX}:`)) {
68320
+ return value;
68321
+ }
68322
+ const [, ivHex, tagHex, encryptedHex] = value.split(":");
68323
+ const decipher = import_crypto3.default.createDecipheriv("aes-256-gcm", getSecretKey(), Buffer.from(ivHex, "hex"));
68324
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
68325
+ return Buffer.concat([
68326
+ decipher.update(Buffer.from(encryptedHex, "hex")),
68327
+ decipher.final()
68328
+ ]).toString("utf8");
68329
+ }
68330
+ function formatHidResponse(data) {
68331
+ if (data === void 0 || data === null) {
68332
+ return "";
68333
+ }
68334
+ const text = typeof data === "string" ? data : JSON.stringify(data);
68335
+ return text.length > 300 ? `${text.slice(0, 300)}...` : text;
68336
+ }
68337
+ function sanitizeHidPath(path5) {
68338
+ return path5.replace(/([?&]session=)[^&]+/i, "$1<redacted>");
68339
+ }
68340
+ function toHidRequestError(error, path5) {
68341
+ if (import_axios4.default.isAxiosError(error)) {
68342
+ const status = error.response?.status;
68343
+ const payload = formatHidResponse(error.response?.data);
68344
+ const detail = [
68345
+ `HID Amico request failed: ${sanitizeHidPath(path5)}`,
68346
+ status ? `status ${status}` : "",
68347
+ payload ? `response ${payload}` : error.message
68348
+ ].filter(Boolean).join(" - ");
68349
+ return new import_node_server_utils258.BadRequestError(detail);
68350
+ }
68351
+ return error;
68352
+ }
68353
+ var HidAmicoClient = class {
68354
+ constructor(reader) {
68355
+ this.reader = reader;
68356
+ this.session = "";
68357
+ this.http = import_axios4.default.create({
68358
+ baseURL: reader.baseUrl.replace(/\/+$/, ""),
68359
+ timeout: 15e3,
68360
+ headers: { "Content-Type": "application/json" }
68361
+ });
68362
+ }
68363
+ async post(path5, body) {
68364
+ try {
68365
+ return await this.http.post(path5, body);
68366
+ } catch (error) {
68367
+ throw toHidRequestError(error, path5);
68368
+ }
68369
+ }
68370
+ async get(path5, responseType = "json") {
68371
+ try {
68372
+ return await this.http.get(path5, { responseType });
68373
+ } catch (error) {
68374
+ throw toHidRequestError(error, path5);
68375
+ }
68376
+ }
68377
+ url(path5) {
68378
+ const normalizedPath = path5.startsWith("/") ? path5 : `/${path5}`;
68379
+ if (!this.session) {
68380
+ return normalizedPath;
68381
+ }
68382
+ const separator = normalizedPath.includes("?") ? "&" : "?";
68383
+ return `${normalizedPath}${separator}session=${encodeURIComponent(this.session)}`;
68384
+ }
68385
+ async login() {
68386
+ const res = await this.post("/hidlogin.fcgi", {
68387
+ login: this.reader.username,
68388
+ password: decryptSecret(this.reader.password)
68389
+ });
68390
+ if (!res.data?.session) {
68391
+ throw new import_node_server_utils258.BadRequestError("HID Amico login failed: missing session.");
68392
+ }
68393
+ this.session = res.data.session;
68394
+ return this.session;
68395
+ }
68396
+ async sessionIsValid() {
68397
+ if (!this.session) {
68398
+ await this.login();
68399
+ }
68400
+ const res = await this.post(this.url("/session_is_valid.fcgi"), {});
68401
+ return Boolean(res.data?.session_is_valid ?? res.data?.valid ?? true);
68402
+ }
68403
+ async getUserImage(hidUserId) {
68404
+ if (!this.session) {
68405
+ await this.login();
68406
+ }
68407
+ const path5 = this.url(`/user_get_image.fcgi?user_id=${encodeURIComponent(String(hidUserId))}`);
68408
+ const res = await this.get(path5, "arraybuffer");
68409
+ const contentType = String(res.headers?.["content-type"] || "");
68410
+ const buffer = Buffer.from(res.data);
68411
+ if (contentType.includes("application/json")) {
68412
+ const payload = JSON.parse(buffer.toString("utf8"));
68413
+ const image = payload.image || payload.photo || payload.data?.image || payload.data?.photo;
68414
+ if (!image) {
68415
+ throw new import_node_server_utils258.BadRequestError("HID Amico user image response did not include an image.");
68416
+ }
68417
+ return {
68418
+ contentType: payload.contentType || payload.mimeType || "image/jpeg",
68419
+ base64: String(image).replace(/^data:image\/[a-zA-Z0-9.+-]+;base64,/, "")
68420
+ };
68421
+ }
68422
+ return {
68423
+ contentType: contentType || "image/jpeg",
68424
+ base64: buffer.toString("base64")
68425
+ };
68426
+ }
68427
+ async logout() {
68428
+ if (!this.session) {
68429
+ return;
68430
+ }
68431
+ const logoutUrl = this.url("/logout.fcgi");
68432
+ try {
68433
+ this.session = "";
68434
+ await this.post(logoutUrl, {});
68435
+ } catch {
68436
+ this.session = "";
68437
+ }
68438
+ }
68439
+ async createObjects(batch) {
68440
+ if (!this.session) {
68441
+ await this.login();
68442
+ }
68443
+ const res = await this.post(this.url("/create_objects.fcgi"), {
68444
+ object: batch.object,
68445
+ values: batch.values
68446
+ });
68447
+ return res.data;
68448
+ }
68449
+ async loadObjects(query) {
68450
+ if (!this.session) {
68451
+ await this.login();
68452
+ }
68453
+ const res = await this.post(this.url("/load_objects.fcgi"), query);
68454
+ return res.data;
68455
+ }
68456
+ async modifyObjects(payload) {
68457
+ if (!this.session) {
68458
+ await this.login();
68459
+ }
68460
+ const res = await this.post(this.url("/modify_objects.fcgi"), payload);
68461
+ return res.data;
68462
+ }
68463
+ async destroyObjects(payload) {
68464
+ if (!this.session) {
68465
+ await this.login();
68466
+ }
68467
+ const res = await this.post(this.url("/destroy_objects.fcgi"), payload);
68468
+ return res.data;
68469
+ }
68470
+ async doorState() {
68471
+ if (!this.session) {
68472
+ await this.login();
68473
+ }
68474
+ const res = await this.post(this.url("/door_state.fcgi"), {});
68475
+ return res.data;
68476
+ }
68477
+ async executeActions(actions) {
68478
+ if (!this.session) {
68479
+ await this.login();
68480
+ }
68481
+ const res = await this.post(this.url("/execute_actions.fcgi"), { actions });
68482
+ return res.data;
68483
+ }
68484
+ async getConfiguration(payload) {
68485
+ if (!this.session) {
68486
+ await this.login();
68487
+ }
68488
+ const res = await this.post(this.url("/get_configuration.fcgi"), payload);
68489
+ return res.data;
68490
+ }
68491
+ async setConfiguration(payload) {
68492
+ if (!this.session) {
68493
+ await this.login();
68494
+ }
68495
+ const res = await this.post(this.url("/set_configuration.fcgi"), payload);
68496
+ return res.data;
68497
+ }
68498
+ };
68499
+ function normalizeBatches(payload) {
68500
+ if (Array.isArray(payload?.objects)) {
68501
+ return payload.objects.filter((batch) => batch?.object && Array.isArray(batch?.values));
68502
+ }
68503
+ const batches = [];
68504
+ const mappings = [
68505
+ ["users", "users"],
68506
+ ["cards", "cards"],
68507
+ ["qrcodes", "qrcodes"],
68508
+ ["pins", "pins"]
68509
+ ];
68510
+ mappings.forEach(([key, object]) => {
68511
+ if (Array.isArray(payload?.[key]) && payload[key].length) {
68512
+ batches.push({ object, values: payload[key] });
68513
+ }
68514
+ });
68515
+ return batches;
68516
+ }
68517
+ function firstValue(payload, keys) {
68518
+ for (const key of keys) {
68519
+ const value = payload?.[key];
68520
+ if (value !== void 0 && value !== null && value !== "") {
68521
+ return value;
68522
+ }
68523
+ }
68524
+ return void 0;
68525
+ }
68526
+ function extractIdentityKeys(payload) {
68527
+ const nested = payload?.user || payload?.person || payload?.data || {};
68528
+ const merged = { ...payload, ...nested };
68529
+ return {
68530
+ hidUserId: firstValue(merged, ["hidUserId", "hid_user_id", "user_id", "userId", "id", "user"]),
68531
+ registration: firstValue(merged, ["registration", "register", "employeeNo", "staffNo", "memberNo"]),
68532
+ cardNo: firstValue(merged, ["cardNo", "card_no", "card", "cardNumber", "value"])
68533
+ };
68534
+ }
68535
+ function useHidAmicoService() {
68536
+ const repo = useHidAmicoRepo();
68537
+ async function getActiveReader(id) {
68538
+ const reader = await repo.getById(id, { includePassword: true });
68539
+ if (reader.enabled === false || reader.status === "inactive" || reader.status === "deleted") {
68540
+ throw new import_node_server_utils258.BadRequestError("HID Amico reader is not active.");
68541
+ }
68542
+ return reader;
68543
+ }
68544
+ async function createReader(value) {
68545
+ return repo.add({
68546
+ ...value,
68547
+ baseUrl: value.baseUrl.replace(/\/+$/, ""),
68548
+ password: encryptSecret(value.password)
68549
+ });
68550
+ }
68551
+ async function updateReader(id, value) {
68552
+ const payload = { ...value };
68553
+ if (payload.password) {
68554
+ payload.password = encryptSecret(payload.password);
68555
+ } else {
68556
+ delete payload.password;
68557
+ }
68558
+ return repo.updateById(id, payload);
68559
+ }
68560
+ async function listReaders(value) {
68561
+ return repo.list(value);
68562
+ }
68563
+ async function deleteReader(id) {
68564
+ return repo.markDeleted(id);
68565
+ }
68566
+ async function testReader(id) {
68567
+ const reader = await repo.getById(id, { includePassword: true });
68568
+ const client = new HidAmicoClient(reader);
68569
+ try {
68570
+ await client.login();
68571
+ const valid = await client.sessionIsValid();
68572
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date(), lastSyncMessage: "Connection test succeeded." });
68573
+ await repo.addEvent({ reader: id, site: reader.site, type: "test", payload: { valid } });
68574
+ return { valid, message: "HID Amico connection test succeeded." };
68575
+ } catch (error) {
68576
+ await repo.updateById(id, {
68577
+ status: "offline",
68578
+ lastSyncAt: /* @__PURE__ */ new Date(),
68579
+ lastSyncStatus: "failed",
68580
+ lastSyncMessage: error.message
68581
+ });
68582
+ await repo.addEvent({ reader: id, site: reader.site, type: "test_failed", payload: { message: error.message } });
68583
+ throw error;
68584
+ } finally {
68585
+ await client.logout();
68586
+ }
68587
+ }
68588
+ async function syncReader(id, payload) {
68589
+ const reader = await getActiveReader(id);
68590
+ const batches = normalizeBatches(payload);
68591
+ const client = new HidAmicoClient(reader);
68592
+ const results = [];
68593
+ await repo.updateById(id, { lastSyncStatus: "running", lastSyncMessage: "Sync started." });
68594
+ try {
68595
+ await client.login();
68596
+ for (const batch of batches) {
68597
+ const result = await client.createObjects(batch);
68598
+ results.push({ object: batch.object, count: batch.values.length, result });
68599
+ }
68600
+ const message = batches.length ? `Synced ${batches.length} HID object batch(es).` : "HID reader session verified. No sync payload was supplied.";
68601
+ await repo.updateById(id, {
68602
+ lastSeenAt: /* @__PURE__ */ new Date(),
68603
+ lastSyncAt: /* @__PURE__ */ new Date(),
68604
+ lastSyncStatus: "completed",
68605
+ lastSyncMessage: message
68606
+ });
68607
+ await repo.addEvent({ reader: id, site: reader.site, type: "sync", payload: { message, results } });
68608
+ return { message, results };
68609
+ } catch (error) {
68610
+ await repo.updateById(id, {
68611
+ status: "offline",
68612
+ lastSyncAt: /* @__PURE__ */ new Date(),
68613
+ lastSyncStatus: "failed",
68614
+ lastSyncMessage: error.message
68615
+ });
68616
+ await repo.addEvent({ reader: id, site: reader.site, type: "sync_failed", payload: { message: error.message } });
68617
+ throw error;
68618
+ } finally {
68619
+ await client.logout();
68620
+ }
68621
+ }
68622
+ async function receiveNotification(readerId, type, payload) {
68623
+ const reader = await repo.getById(readerId);
68624
+ const identityKeys = extractIdentityKeys(payload);
68625
+ const identity = await repo.findIdentity({
68626
+ reader: readerId,
68627
+ ...identityKeys
68628
+ });
68629
+ const enrichedPayload = identity ? {
68630
+ ...payload,
68631
+ identity: {
68632
+ _id: identity._id,
68633
+ type: identity.type,
68634
+ hidUserId: identity.hidUserId,
68635
+ registration: identity.registration,
68636
+ cardNo: identity.cardNo,
68637
+ person: identity.person,
68638
+ user: identity.user,
68639
+ member: identity.member,
68640
+ visitor: identity.visitor
68641
+ }
68642
+ } : {
68643
+ ...payload,
68644
+ identity: null,
68645
+ identityLookup: identityKeys
68646
+ };
68647
+ await repo.updateById(readerId, { lastSeenAt: /* @__PURE__ */ new Date() });
68648
+ return repo.addEvent({
68649
+ reader: readerId,
68650
+ site: reader.site,
68651
+ type,
68652
+ payload: enrichedPayload,
68653
+ status: identity ? "processed" : "received"
68654
+ });
68655
+ }
68656
+ async function listLogs(value) {
68657
+ return repo.listEvents(value);
68658
+ }
68659
+ async function listIdentities(value) {
68660
+ return repo.listIdentities(value);
68661
+ }
68662
+ async function createIdentity(readerId, value) {
68663
+ const reader = await repo.getById(readerId);
68664
+ return repo.addIdentity({
68665
+ ...value,
68666
+ reader: readerId,
68667
+ site: value.site || reader?.site?.toString()
68668
+ });
68669
+ }
68670
+ async function updateIdentity(identityId, value) {
68671
+ return repo.updateIdentity(identityId, value);
68672
+ }
68673
+ async function deleteIdentity(identityId) {
68674
+ return repo.deleteIdentity(identityId);
68675
+ }
68676
+ async function runObjectOperation(id, operation, payload) {
68677
+ const reader = await getActiveReader(id);
68678
+ const client = new HidAmicoClient(reader);
68679
+ try {
68680
+ await client.login();
68681
+ let result;
68682
+ if (operation === "load") {
68683
+ result = await client.loadObjects(payload);
68684
+ } else if (operation === "create") {
68685
+ result = await client.createObjects(payload);
68686
+ } else if (operation === "modify") {
68687
+ result = await client.modifyObjects(payload);
68688
+ } else {
68689
+ result = await client.destroyObjects(payload);
68690
+ }
68691
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date() });
68692
+ await repo.addEvent({ reader: id, site: reader.site, type: `objects_${operation}`, payload: { request: payload, result } });
68693
+ return result;
68694
+ } catch (error) {
68695
+ await repo.addEvent({ reader: id, site: reader.site, type: `objects_${operation}_failed`, payload: { request: payload, message: error.message } });
68696
+ throw error;
68697
+ } finally {
68698
+ await client.logout();
68699
+ }
68700
+ }
68701
+ async function getUserImage(readerId, hidUserId) {
68702
+ const reader = await getActiveReader(readerId);
68703
+ const client = new HidAmicoClient(reader);
68704
+ try {
68705
+ await client.login();
68706
+ return await client.getUserImage(hidUserId);
68707
+ } finally {
68708
+ await client.logout();
68709
+ }
68710
+ }
68711
+ async function getDoorState(id) {
68712
+ const reader = await getActiveReader(id);
68713
+ const client = new HidAmicoClient(reader);
68714
+ try {
68715
+ await client.login();
68716
+ const state = await client.doorState();
68717
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date() });
68718
+ await repo.addEvent({ reader: id, site: reader.site, type: "door_state", payload: state });
68719
+ return state;
68720
+ } finally {
68721
+ await client.logout();
68722
+ }
68723
+ }
68724
+ async function executeActions(id, actions) {
68725
+ const reader = await getActiveReader(id);
68726
+ const client = new HidAmicoClient(reader);
68727
+ try {
68728
+ await client.login();
68729
+ const result = await client.executeActions(actions);
68730
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date() });
68731
+ await repo.addEvent({ reader: id, site: reader.site, type: "execute_actions", payload: { actions, result } });
68732
+ return result;
68733
+ } catch (error) {
68734
+ await repo.addEvent({ reader: id, site: reader.site, type: "execute_actions_failed", payload: { actions, message: error.message } });
68735
+ throw error;
68736
+ } finally {
68737
+ await client.logout();
68738
+ }
68739
+ }
68740
+ async function getConfiguration(id, payload) {
68741
+ const reader = await getActiveReader(id);
68742
+ const client = new HidAmicoClient(reader);
68743
+ try {
68744
+ await client.login();
68745
+ const result = await client.getConfiguration(payload);
68746
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date() });
68747
+ await repo.addEvent({ reader: id, site: reader.site, type: "configuration", payload: { request: payload, result } });
68748
+ return result;
68749
+ } catch (error) {
68750
+ await repo.addEvent({ reader: id, site: reader.site, type: "configuration_failed", payload: { request: payload, message: error.message } });
68751
+ throw error;
68752
+ } finally {
68753
+ await client.logout();
68754
+ }
68755
+ }
68756
+ async function setConfiguration(id, payload) {
68757
+ const reader = await getActiveReader(id);
68758
+ const client = new HidAmicoClient(reader);
68759
+ try {
68760
+ await client.login();
68761
+ const result = await client.setConfiguration(payload);
68762
+ await repo.updateById(id, { lastSeenAt: /* @__PURE__ */ new Date() });
68763
+ await repo.addEvent({ reader: id, site: reader.site, type: "set_configuration", payload: { request: payload, result } });
68764
+ return result;
68765
+ } catch (error) {
68766
+ await repo.addEvent({ reader: id, site: reader.site, type: "set_configuration_failed", payload: { request: payload, message: error.message } });
68767
+ throw error;
68768
+ } finally {
68769
+ await client.logout();
68770
+ }
68771
+ }
68772
+ return {
68773
+ listReaders,
68774
+ createReader,
68775
+ updateReader,
68776
+ deleteReader,
68777
+ testReader,
68778
+ syncReader,
68779
+ receiveNotification,
68780
+ listLogs,
68781
+ listIdentities,
68782
+ createIdentity,
68783
+ updateIdentity,
68784
+ deleteIdentity,
68785
+ runObjectOperation,
68786
+ getUserImage,
68787
+ getDoorState,
68788
+ executeActions,
68789
+ getConfiguration,
68790
+ setConfiguration
68791
+ };
68792
+ }
68793
+
68794
+ // src/controllers/hid-amico.controller.ts
68795
+ var import_node_server_utils259 = require("@7365admin1/node-server-utils");
68796
+ function useHidAmicoController() {
68797
+ const service = useHidAmicoService();
68798
+ async function listReaders(req, res, next) {
68799
+ const { error, value } = schemaHidAmicoReaderListQuery.validate(req.query);
68800
+ if (error) {
68801
+ next(new import_node_server_utils259.BadRequestError(error.message));
68802
+ return;
68803
+ }
68804
+ try {
68805
+ res.json(await service.listReaders(value));
68806
+ } catch (error2) {
68807
+ next(error2);
68808
+ }
68809
+ }
68810
+ async function createReader(req, res, next) {
68811
+ const { error, value } = schemaHidAmicoReader.validate(req.body);
68812
+ if (error) {
68813
+ next(new import_node_server_utils259.BadRequestError(error.message));
68814
+ return;
68815
+ }
68816
+ try {
68817
+ res.status(201).json({ data: await service.createReader(value) });
68818
+ } catch (error2) {
68819
+ next(error2);
68820
+ }
68821
+ }
68822
+ async function updateReader(req, res, next) {
68823
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68824
+ const body = schemaUpdateHidAmicoReader.validate(req.body);
68825
+ if (params.error || body.error) {
68826
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
68827
+ return;
68828
+ }
68829
+ try {
68830
+ res.json({ data: await service.updateReader(params.value.readerId, body.value) });
68831
+ } catch (error) {
68832
+ next(error);
68833
+ }
68834
+ }
68835
+ async function deleteReader(req, res, next) {
68836
+ const { error, value } = schemaHidAmicoReaderIdParams.validate(req.params);
68837
+ if (error) {
68838
+ next(new import_node_server_utils259.BadRequestError(error.message));
68839
+ return;
68840
+ }
68841
+ try {
68842
+ res.json({ data: await service.deleteReader(value.readerId), message: "HID Amico reader deleted." });
68843
+ } catch (error2) {
68844
+ next(error2);
68845
+ }
68846
+ }
68847
+ async function testReader(req, res, next) {
68848
+ const { error, value } = schemaHidAmicoReaderIdParams.validate(req.params);
68849
+ if (error) {
68850
+ next(new import_node_server_utils259.BadRequestError(error.message));
68851
+ return;
68852
+ }
68853
+ try {
68854
+ res.json({ data: await service.testReader(value.readerId) });
68855
+ } catch (error2) {
68856
+ next(error2);
68857
+ }
68858
+ }
68859
+ async function syncReader(req, res, next) {
68860
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68861
+ const body = schemaHidAmicoSync.validate(req.body ?? {});
68862
+ if (params.error || body.error) {
68863
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
68864
+ return;
68865
+ }
68866
+ try {
68867
+ res.json({ data: await service.syncReader(params.value.readerId, body.value) });
68868
+ } catch (error) {
68869
+ next(error);
68870
+ }
68871
+ }
68872
+ async function listLogs(req, res, next) {
68873
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68874
+ const query = schemaHidAmicoLogQuery.validate(req.query);
68875
+ if (params.error || query.error) {
68876
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || query.error?.message));
68877
+ return;
68878
+ }
68879
+ try {
68880
+ res.json(await service.listLogs({ reader: params.value.readerId, ...query.value }));
68881
+ } catch (error) {
68882
+ next(error);
68883
+ }
68884
+ }
68885
+ async function listIdentities(req, res, next) {
68886
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68887
+ const query = schemaHidAmicoIdentityQuery.validate(req.query);
68888
+ if (params.error || query.error) {
68889
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || query.error?.message));
68890
+ return;
68891
+ }
68892
+ try {
68893
+ res.json(await service.listIdentities({ reader: params.value.readerId, ...query.value }));
68894
+ } catch (error) {
68895
+ next(error);
68896
+ }
68897
+ }
68898
+ async function createIdentity(req, res, next) {
68899
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68900
+ if (params.error) {
68901
+ next(new import_node_server_utils259.BadRequestError(params.error.message));
68902
+ return;
68903
+ }
68904
+ try {
68905
+ const body = schemaCreateHidAmicoIdentity.validate(req.body);
68906
+ if (body.error) {
68907
+ next(new import_node_server_utils259.BadRequestError(body.error.message));
68908
+ return;
68909
+ }
68910
+ res.status(201).json({ data: await service.createIdentity(params.value.readerId, body.value) });
68911
+ } catch (error) {
68912
+ next(error);
68913
+ }
68914
+ }
68915
+ async function updateIdentity(req, res, next) {
68916
+ const params = schemaHidAmicoIdentityIdParams.validate(req.params);
68917
+ const body = schemaUpdateHidAmicoIdentity.validate(req.body ?? {});
68918
+ if (params.error || body.error) {
68919
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
68920
+ return;
68921
+ }
68922
+ try {
68923
+ res.json({ data: await service.updateIdentity(params.value.identityId, body.value) });
68924
+ } catch (error) {
68925
+ next(error);
68926
+ }
68927
+ }
68928
+ async function deleteIdentity(req, res, next) {
68929
+ const { error, value } = schemaHidAmicoIdentityIdParams.validate(req.params);
68930
+ if (error) {
68931
+ next(new import_node_server_utils259.BadRequestError(error.message));
68932
+ return;
68933
+ }
68934
+ try {
68935
+ res.json({ data: await service.deleteIdentity(value.identityId), message: "HID Amico identity deleted." });
68936
+ } catch (error2) {
68937
+ next(error2);
68938
+ }
68939
+ }
68940
+ async function receiveNotification(req, res, next) {
68941
+ const validation = schemaHidAmicoNotificationParams.validate(req.params);
68942
+ if (validation.error) {
68943
+ next(new import_node_server_utils259.BadRequestError(validation.error.message));
68944
+ return;
68945
+ }
68946
+ try {
68947
+ const event = await service.receiveNotification(
68948
+ validation.value.readerId,
68949
+ validation.value.type,
68950
+ req.body ?? {}
68951
+ );
68952
+ res.status(202).json({ data: event });
68953
+ } catch (error) {
68954
+ next(error);
68955
+ }
68956
+ }
68957
+ async function getDoorState(req, res, next) {
68958
+ const { error, value } = schemaHidAmicoReaderIdParams.validate(req.params);
68959
+ if (error) {
68960
+ next(new import_node_server_utils259.BadRequestError(error.message));
68961
+ return;
68962
+ }
68963
+ try {
68964
+ res.json({ data: await service.getDoorState(value.readerId) });
68965
+ } catch (error2) {
68966
+ next(error2);
68967
+ }
68968
+ }
68969
+ async function getUserImage(req, res, next) {
68970
+ const { error, value } = schemaHidAmicoUserImageParams.validate(req.params);
68971
+ if (error) {
68972
+ next(new import_node_server_utils259.BadRequestError(error.message));
68973
+ return;
68974
+ }
68975
+ try {
68976
+ const image = await service.getUserImage(value.readerId, value.hidUserId);
68977
+ res.json({ data: image });
68978
+ } catch (error2) {
68979
+ next(error2);
68980
+ }
68981
+ }
68982
+ async function executeActions(req, res, next) {
68983
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68984
+ const body = schemaHidAmicoExecuteActions.validate(req.body ?? {});
68985
+ if (params.error || body.error) {
68986
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
68987
+ return;
68988
+ }
68989
+ try {
68990
+ res.json({ data: await service.executeActions(params.value.readerId, body.value.actions) });
68991
+ } catch (error) {
68992
+ next(error);
68993
+ }
68994
+ }
68995
+ async function getConfiguration(req, res, next) {
68996
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
68997
+ const body = schemaHidAmicoConfiguration.validate(req.body ?? {});
68998
+ if (params.error || body.error) {
68999
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
69000
+ return;
69001
+ }
69002
+ try {
69003
+ res.json({ data: await service.getConfiguration(params.value.readerId, body.value) });
69004
+ } catch (error) {
69005
+ next(error);
69006
+ }
69007
+ }
69008
+ async function setConfiguration(req, res, next) {
69009
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
69010
+ const body = schemaHidAmicoSetConfiguration.validate(req.body ?? {});
69011
+ if (params.error || body.error) {
69012
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
69013
+ return;
69014
+ }
69015
+ try {
69016
+ res.json({ data: await service.setConfiguration(params.value.readerId, body.value) });
69017
+ } catch (error) {
69018
+ next(error);
69019
+ }
69020
+ }
69021
+ async function runObjectOperation(req, res, next) {
69022
+ const params = schemaHidAmicoReaderIdParams.validate(req.params);
69023
+ const body = schemaHidAmicoObjectOperation.validate(req.body ?? {});
69024
+ if (params.error || body.error) {
69025
+ next(new import_node_server_utils259.BadRequestError(params.error?.message || body.error?.message));
69026
+ return;
69027
+ }
69028
+ const { operation, ...payload } = body.value;
69029
+ if (operation === "create" && !Array.isArray(payload.values)) {
69030
+ next(new import_node_server_utils259.BadRequestError("values array is required for HID object create operations."));
69031
+ return;
69032
+ }
69033
+ if (operation === "modify" && (!payload.values || Array.isArray(payload.values) || !payload.where)) {
69034
+ next(new import_node_server_utils259.BadRequestError("values object and where are required for HID object modify operations."));
69035
+ return;
69036
+ }
69037
+ if (operation === "destroy" && !payload.where) {
69038
+ next(new import_node_server_utils259.BadRequestError("where is required for HID object destroy operations."));
69039
+ return;
69040
+ }
69041
+ try {
69042
+ res.json({ data: await service.runObjectOperation(params.value.readerId, operation, payload) });
69043
+ } catch (error) {
69044
+ next(error);
69045
+ }
69046
+ }
69047
+ return {
69048
+ listReaders,
69049
+ createReader,
69050
+ updateReader,
69051
+ deleteReader,
69052
+ testReader,
69053
+ syncReader,
69054
+ listLogs,
69055
+ listIdentities,
69056
+ createIdentity,
69057
+ updateIdentity,
69058
+ deleteIdentity,
69059
+ receiveNotification,
69060
+ getUserImage,
69061
+ getDoorState,
69062
+ executeActions,
69063
+ getConfiguration,
69064
+ setConfiguration,
69065
+ runObjectOperation
69066
+ };
69067
+ }
67210
69068
  // Annotate the CommonJS export names for ESM import in node:
67211
69069
  0 && (module.exports = {
67212
69070
  ANPRMode,
67213
69071
  AccessTypeProps,
67214
69072
  AppServiceType,
69073
+ BidStatus,
69074
+ BidType,
67215
69075
  BuildingLevelStatus,
67216
69076
  BuildingStatus,
67217
69077
  BulletinOrder,
@@ -67243,6 +69103,7 @@ function useBuildingLevelController() {
67243
69103
  MAddress,
67244
69104
  MAttendance,
67245
69105
  MAttendanceSettings,
69106
+ MBidPreloved,
67246
69107
  MBillingConfiguration,
67247
69108
  MBillingItem,
67248
69109
  MBuilding,
@@ -67263,6 +69124,9 @@ function useBuildingLevelController() {
67263
69124
  MFile,
67264
69125
  MFormEntry,
67265
69126
  MGuestManagement,
69127
+ MHidAmicoEvent,
69128
+ MHidAmicoIdentity,
69129
+ MHidAmicoReader,
67266
69130
  MIncidentReport,
67267
69131
  MManpowerDesignations,
67268
69132
  MManpowerMonitoring,
@@ -67350,7 +69214,6 @@ function useBuildingLevelController() {
67350
69214
  building_units_namespace_collection,
67351
69215
  buildings_namespace_collection,
67352
69216
  bulletin_boards_namespace_collection,
67353
- calculatePercentage,
67354
69217
  chatSchema,
67355
69218
  createManpowerRemarksDaily,
67356
69219
  customerSchema,
@@ -67361,7 +69224,6 @@ function useBuildingLevelController() {
67361
69224
  feedbacks2_namespace_collection,
67362
69225
  feedbacks_namespace_collection,
67363
69226
  formatDahuaDate,
67364
- getPeriodRangeWithPrevious,
67365
69227
  guests_namespace_collection,
67366
69228
  incidentReportLog,
67367
69229
  incidents_namespace_collection,
@@ -67384,6 +69246,7 @@ function useBuildingLevelController() {
67384
69246
  schema,
67385
69247
  schemaApprovedBy,
67386
69248
  schemaApprover,
69249
+ schemaBidPreloved,
67387
69250
  schemaBilling,
67388
69251
  schemaBillingConfiguration,
67389
69252
  schemaBillingItem,
@@ -67396,6 +69259,7 @@ function useBuildingLevelController() {
67396
69259
  schemaCategoryPreloved,
67397
69260
  schemaChannelPreloved,
67398
69261
  schemaChatPreloved,
69262
+ schemaCreateHidAmicoIdentity,
67399
69263
  schemaCustomerSite,
67400
69264
  schemaDocumentManagement,
67401
69265
  schemaEntryPassSettings,
@@ -67403,6 +69267,21 @@ function useBuildingLevelController() {
67403
69267
  schemaFiles,
67404
69268
  schemaFormEntry,
67405
69269
  schemaGuestManagement,
69270
+ schemaHidAmicoConfiguration,
69271
+ schemaHidAmicoEvent,
69272
+ schemaHidAmicoExecuteActions,
69273
+ schemaHidAmicoIdentity,
69274
+ schemaHidAmicoIdentityIdParams,
69275
+ schemaHidAmicoIdentityQuery,
69276
+ schemaHidAmicoLogQuery,
69277
+ schemaHidAmicoNotificationParams,
69278
+ schemaHidAmicoObjectOperation,
69279
+ schemaHidAmicoReader,
69280
+ schemaHidAmicoReaderIdParams,
69281
+ schemaHidAmicoReaderListQuery,
69282
+ schemaHidAmicoSetConfiguration,
69283
+ schemaHidAmicoSync,
69284
+ schemaHidAmicoUserImageParams,
67406
69285
  schemaIncidentReport,
67407
69286
  schemaMultipleDocumentManagement,
67408
69287
  schemaNfcPatrolLog,
@@ -67430,6 +69309,7 @@ function useBuildingLevelController() {
67430
69309
  schemaStatementOfAccount,
67431
69310
  schemaSubcategoryPreloved,
67432
69311
  schemaUnitBilling,
69312
+ schemaUpdateBidPreloved,
67433
69313
  schemaUpdateBuildingLevel,
67434
69314
  schemaUpdateBulletinBoard,
67435
69315
  schemaUpdateBulletinVideo,
@@ -67440,6 +69320,8 @@ function useBuildingLevelController() {
67440
69320
  schemaUpdateEventManagement,
67441
69321
  schemaUpdateFormEntry,
67442
69322
  schemaUpdateGuestManagement,
69323
+ schemaUpdateHidAmicoIdentity,
69324
+ schemaUpdateHidAmicoReader,
67443
69325
  schemaUpdateIncidentReport,
67444
69326
  schemaUpdateOccurrenceBook,
67445
69327
  schemaUpdateOccurrenceEntry,
@@ -67485,6 +69367,8 @@ function useBuildingLevelController() {
67485
69367
  useAuthControllerV2,
67486
69368
  useAuthService,
67487
69369
  useAuthServiceV2,
69370
+ useBidPrelovedController,
69371
+ useBidPrelovedRepo,
67488
69372
  useBuildingController,
67489
69373
  useBuildingLevelController,
67490
69374
  useBuildingLevelRepo,
@@ -67507,6 +69391,7 @@ function useBuildingLevelController() {
67507
69391
  useChatController,
67508
69392
  useChatPrelovedController,
67509
69393
  useChatPrelovedRepo,
69394
+ useChatPrelovedService,
67510
69395
  useChatRepo,
67511
69396
  useCounterModel,
67512
69397
  useCounterRepo,
@@ -67537,6 +69422,9 @@ function useBuildingLevelController() {
67537
69422
  useGuestManagementController,
67538
69423
  useGuestManagementRepo,
67539
69424
  useGuestManagementService,
69425
+ useHidAmicoController,
69426
+ useHidAmicoRepo,
69427
+ useHidAmicoService,
67540
69428
  useHrmLabsAttendanceCtrl,
67541
69429
  useHrmLabsAttendanceSrvc,
67542
69430
  useIncidentReportController,