@7365admin1/core 3.8.0 → 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,
@@ -6062,6 +6068,7 @@ __export(src_exports, {
6062
6068
  schema: () => schema,
6063
6069
  schemaApprovedBy: () => schemaApprovedBy,
6064
6070
  schemaApprover: () => schemaApprover,
6071
+ schemaBidPreloved: () => schemaBidPreloved,
6065
6072
  schemaBilling: () => schemaBilling,
6066
6073
  schemaBillingConfiguration: () => schemaBillingConfiguration,
6067
6074
  schemaBillingItem: () => schemaBillingItem,
@@ -6074,6 +6081,7 @@ __export(src_exports, {
6074
6081
  schemaCategoryPreloved: () => schemaCategoryPreloved,
6075
6082
  schemaChannelPreloved: () => schemaChannelPreloved,
6076
6083
  schemaChatPreloved: () => schemaChatPreloved,
6084
+ schemaCreateHidAmicoIdentity: () => schemaCreateHidAmicoIdentity,
6077
6085
  schemaCustomerSite: () => schemaCustomerSite,
6078
6086
  schemaDocumentManagement: () => schemaDocumentManagement,
6079
6087
  schemaEntryPassSettings: () => schemaEntryPassSettings,
@@ -6081,6 +6089,21 @@ __export(src_exports, {
6081
6089
  schemaFiles: () => schemaFiles,
6082
6090
  schemaFormEntry: () => schemaFormEntry,
6083
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,
6084
6107
  schemaIncidentReport: () => schemaIncidentReport,
6085
6108
  schemaMultipleDocumentManagement: () => schemaMultipleDocumentManagement,
6086
6109
  schemaNfcPatrolLog: () => schemaNfcPatrolLog,
@@ -6108,6 +6131,7 @@ __export(src_exports, {
6108
6131
  schemaStatementOfAccount: () => schemaStatementOfAccount,
6109
6132
  schemaSubcategoryPreloved: () => schemaSubcategoryPreloved,
6110
6133
  schemaUnitBilling: () => schemaUnitBilling,
6134
+ schemaUpdateBidPreloved: () => schemaUpdateBidPreloved,
6111
6135
  schemaUpdateBuildingLevel: () => schemaUpdateBuildingLevel,
6112
6136
  schemaUpdateBulletinBoard: () => schemaUpdateBulletinBoard,
6113
6137
  schemaUpdateBulletinVideo: () => schemaUpdateBulletinVideo,
@@ -6118,6 +6142,8 @@ __export(src_exports, {
6118
6142
  schemaUpdateEventManagement: () => schemaUpdateEventManagement,
6119
6143
  schemaUpdateFormEntry: () => schemaUpdateFormEntry,
6120
6144
  schemaUpdateGuestManagement: () => schemaUpdateGuestManagement,
6145
+ schemaUpdateHidAmicoIdentity: () => schemaUpdateHidAmicoIdentity,
6146
+ schemaUpdateHidAmicoReader: () => schemaUpdateHidAmicoReader,
6121
6147
  schemaUpdateIncidentReport: () => schemaUpdateIncidentReport,
6122
6148
  schemaUpdateOccurrenceBook: () => schemaUpdateOccurrenceBook,
6123
6149
  schemaUpdateOccurrenceEntry: () => schemaUpdateOccurrenceEntry,
@@ -6163,6 +6189,8 @@ __export(src_exports, {
6163
6189
  useAuthControllerV2: () => useAuthControllerV2,
6164
6190
  useAuthService: () => useAuthService,
6165
6191
  useAuthServiceV2: () => useAuthServiceV2,
6192
+ useBidPrelovedController: () => useBidPrelovedController,
6193
+ useBidPrelovedRepo: () => useBidPrelovedRepo,
6166
6194
  useBuildingController: () => useBuildingController,
6167
6195
  useBuildingLevelController: () => useBuildingLevelController,
6168
6196
  useBuildingLevelRepo: () => useBuildingLevelRepo,
@@ -6185,6 +6213,7 @@ __export(src_exports, {
6185
6213
  useChatController: () => useChatController,
6186
6214
  useChatPrelovedController: () => useChatPrelovedController,
6187
6215
  useChatPrelovedRepo: () => useChatPrelovedRepo,
6216
+ useChatPrelovedService: () => useChatPrelovedService,
6188
6217
  useChatRepo: () => useChatRepo,
6189
6218
  useCounterModel: () => useCounterModel,
6190
6219
  useCounterRepo: () => useCounterRepo,
@@ -6215,6 +6244,9 @@ __export(src_exports, {
6215
6244
  useGuestManagementController: () => useGuestManagementController,
6216
6245
  useGuestManagementRepo: () => useGuestManagementRepo,
6217
6246
  useGuestManagementService: () => useGuestManagementService,
6247
+ useHidAmicoController: () => useHidAmicoController,
6248
+ useHidAmicoRepo: () => useHidAmicoRepo,
6249
+ useHidAmicoService: () => useHidAmicoService,
6218
6250
  useHrmLabsAttendanceCtrl: () => useHrmLabsAttendanceCtrl,
6219
6251
  useHrmLabsAttendanceSrvc: () => useHrmLabsAttendanceSrvc,
6220
6252
  useIncidentReportController: () => useIncidentReportController,
@@ -11204,7 +11236,8 @@ var metadataSchema3 = import_joi9.default.object({
11204
11236
  guardPosts: import_joi9.default.number().optional(),
11205
11237
  gracePeriod: import_joi9.default.number().optional(),
11206
11238
  incidentCounter: import_joi9.default.number().optional(),
11207
- 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()
11208
11241
  });
11209
11242
  var updateAddressSchema = import_joi9.default.object({
11210
11243
  line1: import_joi9.default.string().min(3).allow("", null),
@@ -11234,7 +11267,8 @@ var allowedFieldsSite = [
11234
11267
  "metadata.guardPosts",
11235
11268
  "metadata.gracePeriod",
11236
11269
  "metadata.incidentCounter",
11237
- "metadata.incidentLogo"
11270
+ "metadata.incidentLogo",
11271
+ "metadata.services"
11238
11272
  ];
11239
11273
  var siteSchema = import_joi9.default.object({
11240
11274
  name: import_joi9.default.string().required(),
@@ -12108,9 +12142,7 @@ function useVerificationRepoV2() {
12108
12142
  }
12109
12143
  );
12110
12144
  } catch (error) {
12111
- throw new import_node_server_utils20.InternalServerError(
12112
- "Failed to retrieve verification."
12113
- );
12145
+ throw new import_node_server_utils20.InternalServerError("Failed to retrieve verification.");
12114
12146
  }
12115
12147
  }
12116
12148
  async function updateVerificationCodeById(_id, verificationCode, expireAt, session) {
@@ -12128,9 +12160,7 @@ function useVerificationRepoV2() {
12128
12160
  { session }
12129
12161
  );
12130
12162
  } catch (error) {
12131
- throw new import_node_server_utils20.InternalServerError(
12132
- "Failed to update verification code."
12133
- );
12163
+ throw new import_node_server_utils20.InternalServerError("Failed to update verification code.");
12134
12164
  }
12135
12165
  }
12136
12166
  return {
@@ -21014,12 +21044,20 @@ var schemaVisitorTransaction = import_joi37.default.object({
21014
21044
  nric: import_joi37.default.string().optional().allow(null, ""),
21015
21045
  visitorPass: import_joi37.default.array().items(
21016
21046
  import_joi37.default.object({
21017
- 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, "")
21018
21052
  })
21019
21053
  ).optional().allow(null),
21020
21054
  passKeys: import_joi37.default.array().items(
21021
21055
  import_joi37.default.object({
21022
- 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, "")
21023
21061
  })
21024
21062
  ).optional().allow(null),
21025
21063
  contact: import_joi37.default.string().optional().allow(null, "")
@@ -21036,19 +21074,28 @@ var schemaVisitorTransaction = import_joi37.default.object({
21036
21074
  numberOfPassengers: import_joi37.default.number().integer().optional().allow(null, ""),
21037
21075
  visitorPass: import_joi37.default.array().items(
21038
21076
  import_joi37.default.object({
21039
- 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, "")
21040
21082
  })
21041
21083
  ).optional().allow(null),
21042
21084
  passKeys: import_joi37.default.array().items(
21043
21085
  import_joi37.default.object({
21044
- 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, "")
21045
21091
  })
21046
21092
  ).optional().allow(null),
21047
21093
  checkInRemarks: import_joi37.default.string().optional().allow("", null),
21048
21094
  checkOutRemarks: import_joi37.default.string().optional().allow("", null),
21049
21095
  expectedCheckIn: import_joi37.default.string().isoDate().optional(),
21050
21096
  purpose: import_joi37.default.string().optional().allow(null, ""),
21051
- 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, "")
21052
21099
  });
21053
21100
  var schemaUpdateVisTrans = import_joi37.default.object({
21054
21101
  _id: import_joi37.default.string().hex().length(24).required(),
@@ -21168,22 +21215,22 @@ function MVisitorTransaction(value) {
21168
21215
  throw new Error("Invalid type for manualCheckout key.");
21169
21216
  }
21170
21217
  }
21171
- if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
21218
+ if (Array.isArray(value.visitorPass)) {
21172
21219
  value.visitorPass = value.visitorPass.map((v) => {
21173
- if (typeof v === "string")
21174
- return { keyId: new import_mongodb39.ObjectId(v) };
21175
- if (v?.keyId && typeof v.keyId === "string") {
21176
- 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.");
21177
21224
  }
21178
21225
  return v;
21179
21226
  });
21180
21227
  }
21181
- if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
21228
+ if (Array.isArray(value.passKeys)) {
21182
21229
  value.passKeys = value.passKeys.map((p) => {
21183
- if (typeof p === "string")
21184
- return { keyId: new import_mongodb39.ObjectId(p) };
21185
- if (p?.keyId && typeof p.keyId === "string") {
21186
- 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.");
21187
21234
  }
21188
21235
  return p;
21189
21236
  });
@@ -21878,9 +21925,57 @@ function useVisitorTransactionRepo() {
21878
21925
  }
21879
21926
  }
21880
21927
  async function resendEmailInvitedResident(visitorId, updatedBy) {
21881
- const updatedDocument = await collection.findOne({
21882
- _id: await convertObjectIdUtil(visitorId)
21883
- });
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;
21884
21979
  if (!updatedDocument?.email)
21885
21980
  return;
21886
21981
  if (!updatedDocument?._id)
@@ -21895,7 +21990,7 @@ function useVisitorTransactionRepo() {
21895
21990
  name: `${updatedDocument?.name}`,
21896
21991
  plateNumber: updatedDocument?.plateNumber,
21897
21992
  nric: updatedDocument?.nric,
21898
- address: `${updatedDocument?.block} ${updatedDocument?.level} ${updatedDocument?.unitName}`,
21993
+ address: `${updatedDocument?.blockName} ${updatedDocument?.levelName} ${updatedDocument?.unitName}`,
21899
21994
  contactNumber: updatedDocument?.contact ? updatedDocument?.contact : "N/A",
21900
21995
  email: updatedDocument?.email ? updatedDocument?.email : "N/A",
21901
21996
  duration: updatedDocument?.duration ? updatedDocument?.duration : "N/A",
@@ -27795,7 +27890,7 @@ function useBuildingRepo() {
27795
27890
  try {
27796
27891
  await collection.createIndexes([
27797
27892
  { key: { name: "text" }, name: "text-index" },
27798
- { key: { name: 1 }, unique: true, name: "unique-name-index" },
27893
+ // { key: { name: 1 }, unique: true, name: "unique-name-index" },
27799
27894
  { key: { site: 1 } },
27800
27895
  { key: { createdAt: 1 } },
27801
27896
  {
@@ -28472,11 +28567,6 @@ function useBuildingLevelRepo() {
28472
28567
  try {
28473
28568
  await collection.createIndexes([
28474
28569
  // Ensure name is unique per blockId
28475
- {
28476
- key: { blockId: 1, name: 1 },
28477
- unique: true,
28478
- name: "unique_name_per_blockId"
28479
- },
28480
28570
  // Other useful indexes
28481
28571
  { key: { site: 1 }, name: "idx_site" },
28482
28572
  { key: { blockId: 1 }, name: "idx_blockId" },
@@ -28737,7 +28827,11 @@ function useBuildingLevelRepo() {
28737
28827
  const res = await collection.bulkWrite(operations, { session });
28738
28828
  delCachedData();
28739
28829
  return {
28740
- insertedIds: res.insertedIds
28830
+ insertedIds: res.insertedIds,
28831
+ levels: levels.map((l, i) => ({
28832
+ _id: res.insertedIds[i],
28833
+ name: l.name
28834
+ }))
28741
28835
  };
28742
28836
  } catch (error) {
28743
28837
  import_node_server_utils86.logger.log({
@@ -29021,8 +29115,8 @@ function useBuildingService() {
29021
29115
  const name = row.name;
29022
29116
  const rawLevel = row.level?.toString().trim();
29023
29117
  const rawUnit = row.unit?.toString().trim();
29024
- const normalizedLevel = /^(na|n\/a)$/i.test(rawLevel) ? null : `Lvl${rawLevel}`;
29025
- 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;
29026
29120
  if (!blockMap.has(block)) {
29027
29121
  blockMap.set(block, { name, levels: [], unitsByLevel: /* @__PURE__ */ new Map() });
29028
29122
  }
@@ -29043,57 +29137,76 @@ function useBuildingService() {
29043
29137
  }
29044
29138
  }
29045
29139
  }
29046
- const buildingPayloads = Array.from(blockMap.entries()).map(
29047
- ([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,
29048
29168
  site,
29049
29169
  block,
29050
29170
  name,
29051
- levels
29052
- })
29053
- );
29054
- const blockToBuildingId = /* @__PURE__ */ new Map();
29055
- for (const buildingPayload of buildingPayloads) {
29056
- const result = await _add(buildingPayload);
29057
- blockToBuildingId.set(buildingPayload.block, result);
29058
- }
29059
- const buildingUnitPayloads = [];
29060
- Array.from(blockMap.entries()).forEach(
29061
- ([block, { name, unitsByLevel }]) => {
29062
- const buildingId = blockToBuildingId.get(block);
29063
- Array.from(unitsByLevel.entries()).forEach(([level, units]) => {
29064
- units.forEach((unit) => {
29065
- buildingUnitPayloads.push({
29066
- site,
29067
- name: unit,
29068
- building: buildingId.toString(),
29069
- buildingName: name,
29070
- block,
29071
- level,
29072
- category: "",
29073
- status: "active" /* ACTIVE */,
29074
- buildingUnitFiles: [],
29075
- owner: "",
29076
- ownerName: "",
29077
- companyName: "",
29078
- companyRegistrationNumber: "",
29079
- billing: [],
29080
- unitNumber: parseInt(unit.replace("Unit ", ""), 10) || null,
29081
- createdAt: /* @__PURE__ */ new Date(),
29082
- updatedAt: "",
29083
- deletedAt: ""
29084
- });
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: ""
29085
29198
  });
29086
29199
  });
29087
- }
29088
- );
29200
+ });
29201
+ }
29089
29202
  await _bulkAddBuildingUnits(buildingUnitPayloads);
29090
- await session?.commitTransaction();
29203
+ await session.commitTransaction();
29091
29204
  return { buildingPayloads, buildingUnitPayloads };
29092
29205
  } catch (error) {
29093
- await session?.abortTransaction();
29206
+ await session.abortTransaction();
29094
29207
  throw error;
29095
29208
  } finally {
29096
- session?.endSession();
29209
+ session.endSession();
29097
29210
  }
29098
29211
  }
29099
29212
  return {
@@ -29364,9 +29477,9 @@ function useBuildingController() {
29364
29477
  const lowerName = originalname.toLowerCase();
29365
29478
  const rowSchema = import_joi46.default.object({
29366
29479
  block: import_joi46.default.number().integer().min(0).required(),
29367
- level: import_joi46.default.string().optional().allow(null, ""),
29368
- unit: import_joi46.default.string().optional().allow(null, ""),
29369
- 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, ""),
29370
29483
  name: import_joi46.default.string().trim().optional().allow(null, ""),
29371
29484
  email: import_joi46.default.string().email().lowercase().optional().allow(null, ""),
29372
29485
  phoneNumber: import_joi46.default.string().trim().optional().allow(null, "")
@@ -29380,11 +29493,9 @@ function useBuildingController() {
29380
29493
  { abortEarly: false, convert: true }
29381
29494
  );
29382
29495
  if (queryError) {
29383
- next(
29384
- new import_node_server_utils88.BadRequestError(
29385
- queryError.details.map((d) => d.message).join(", ")
29386
- )
29387
- );
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));
29388
29499
  return;
29389
29500
  }
29390
29501
  const { site, org } = queryValue;
@@ -29419,11 +29530,11 @@ function useBuildingController() {
29419
29530
  } else if (lowerName.endsWith(".csv")) {
29420
29531
  rows = await new Promise((resolve, reject) => {
29421
29532
  const parsed = [];
29422
- import_fs3.default.createReadStream(path5).pipe((0, import_csv_parser.default)()).on("headers", (headers) => {
29423
- headers = headers.map(
29424
- (h) => h.trim().replace(/\(.*\)/, "").trim()
29425
- );
29426
- }).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);
29427
29538
  });
29428
29539
  } else {
29429
29540
  next(
@@ -29441,6 +29552,7 @@ function useBuildingController() {
29441
29552
  if (error) {
29442
29553
  invalidRows.push({
29443
29554
  row: index + 2,
29555
+ // +2 because header is row 1
29444
29556
  data: row,
29445
29557
  errors: error.details.map((d) => d.message)
29446
29558
  });
@@ -29462,6 +29574,7 @@ function useBuildingController() {
29462
29574
  import_fs3.default.unlink(path5, () => {
29463
29575
  });
29464
29576
  } catch (error) {
29577
+ console.log(error);
29465
29578
  import_node_server_utils88.logger.log({ level: "error", message: error.message });
29466
29579
  next(error);
29467
29580
  }
@@ -33390,17 +33503,13 @@ var KeyRepo = class {
33390
33503
  }
33391
33504
  }
33392
33505
  static async updateKeyById(keyId, key, site, session, isChild) {
33393
- try {
33394
- keyId = new import_mongodb61.ObjectId(keyId);
33395
- if (site)
33396
- site = new import_mongodb61.ObjectId(site);
33397
- if (key.updatedBy)
33398
- key.updatedBy = await convertObjectIdUtil(key.updatedBy);
33399
- if (!key.status)
33400
- delete key.status;
33401
- } catch (error) {
33402
- return Promise.reject("Invalid key id");
33403
- }
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;
33404
33513
  try {
33405
33514
  key.updatedAt = /* @__PURE__ */ new Date();
33406
33515
  const query = { _id: keyId, ...site && { site } };
@@ -33413,6 +33522,7 @@ var KeyRepo = class {
33413
33522
  { session }
33414
33523
  );
33415
33524
  let setKeys = [];
33525
+ console.log("updateKeyById result", result);
33416
33526
  if (result.modifiedCount > 0) {
33417
33527
  const updatedDocs = await this.collection().find(find).toArray();
33418
33528
  if (Array.isArray(updatedDocs) && updatedDocs.length > 0) {
@@ -33427,10 +33537,12 @@ var KeyRepo = class {
33427
33537
  await this.collectionDynamic("keys-histories").insertMany(setKeys, {
33428
33538
  session
33429
33539
  });
33540
+ } else {
33541
+ throw new Error("Failed Updating Keys");
33430
33542
  }
33431
33543
  return result;
33432
33544
  } catch (error) {
33433
- console.log(error);
33545
+ throw new Error(error);
33434
33546
  }
33435
33547
  }
33436
33548
  static async deleteKeyById(_id, session) {
@@ -33870,51 +33982,51 @@ function useVisitorTransactionService() {
33870
33982
  for (let i = 0; i < value.members.length; i += chunkSize) {
33871
33983
  const chunk = value.members.slice(i, i + chunkSize);
33872
33984
  for (const member of chunk) {
33873
- await KeyRepo.checkPassKeyAvailability(
33874
- member.visitorPass,
33875
- member.passKeys
33876
- );
33877
- if (member.visitorPass && Array.isArray(member.visitorPass) && member.visitorPass.length > 0) {
33878
- for (const vp of member.visitorPass) {
33879
- try {
33880
- const updatePayload = { status: "In Use" /* IN_USE */ };
33881
- const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
33882
- if (!visitorPassId)
33883
- value.visitorPass = [];
33884
- await KeyRepo.updateKeyById(
33885
- visitorPassId,
33886
- updatePayload,
33887
- value.site
33888
- );
33889
- } catch (error) {
33890
- throw error;
33891
- }
33985
+ await KeyRepo.checkPassKeyAvailability(member.visitorPass, member.passKeys);
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 = "";
33892
34003
  }
33893
34004
  }
33894
- if (member.passKeys && Array.isArray(member.passKeys) && member.passKeys.length > 0) {
33895
- for (const pk of member.passKeys) {
33896
- try {
33897
- const updatePayload = { status: "In Use" /* IN_USE */ };
33898
- const passKeyId = typeof pk === "string" || pk instanceof import_mongodb62.ObjectId ? pk : pk.keyId;
33899
- if (!passKeyId)
33900
- value.passKeys = [];
33901
- await KeyRepo.updateKeyById(
33902
- passKeyId,
33903
- updatePayload,
33904
- value.site
33905
- );
33906
- } catch (error) {
33907
- throw error;
33908
- }
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 = "";
33909
34020
  }
33910
34021
  }
33911
34022
  }
33912
34023
  await Promise.all(
33913
34024
  chunk.map((member) => {
33914
- const { visitorPass, passKeys } = member;
34025
+ const clonedMember = structuredClone(member);
34026
+ const { visitorPass, passKeys } = clonedMember;
33915
34027
  return _add(
33916
34028
  {
33917
- ...member,
34029
+ ...clonedMember,
33918
34030
  block,
33919
34031
  level,
33920
34032
  unit,
@@ -33961,184 +34073,184 @@ function useVisitorTransactionService() {
33961
34073
  throw new import_node_server_utils106.BadRequestError("This plate number is blocklisted");
33962
34074
  }
33963
34075
  await KeyRepo.checkPassKeyAvailability(value.visitorPass, value.passKeys);
33964
- if (value.visitorPass && Array.isArray(value.visitorPass) && value.visitorPass.length > 0 && value.visitorPass) {
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 = "";
34091
+ }
34092
+ }
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 = "";
34108
+ }
34109
+ }
34110
+ const result = await _add(value, session);
34111
+ await session?.commitTransaction();
34112
+ let openBarrier = null;
34113
+ const isOpenBarrier = allowedPersonTypes.includes(value?.type) || camera?.ANPRSwitches?.openBarrierPickUpDropOff == true;
34114
+ if (isOpenBarrier && value.plateNumber && host && username && password) {
34115
+ try {
34116
+ import_node_server_utils106.logger.info(`Attempting to open barrier at host: ${host}`);
34117
+ openBarrier = await _openBarrier({
34118
+ host,
34119
+ username,
34120
+ password,
34121
+ plateNumber: value?.plateNumber
34122
+ });
34123
+ import_node_server_utils106.logger.info(`Barrier command sent successfully to ${host}`, {
34124
+ response: openBarrier
34125
+ });
34126
+ } catch (error) {
34127
+ import_node_server_utils106.logger.error(
34128
+ `Failed to open barrier at host ${host}. Critical system error:`,
34129
+ error
34130
+ );
34131
+ openBarrier = { success: false, error: error?.message };
34132
+ }
34133
+ }
34134
+ console.log("Open barrier response:", openBarrier);
34135
+ return result;
34136
+ } catch (error) {
34137
+ await session?.abortTransaction();
34138
+ throw error;
34139
+ } finally {
34140
+ session?.endSession();
34141
+ }
34142
+ }
34143
+ async function updateVisitorTransactionById(id, value) {
34144
+ const session = import_node_server_utils106.useAtlas.getClient()?.startSession();
34145
+ session?.startTransaction();
34146
+ try {
34147
+ let camera;
34148
+ let host;
34149
+ let username;
34150
+ let password;
34151
+ if (value.site && value.plateNumber) {
34152
+ try {
34153
+ camera = await _getVisitorsInBySite(value.site);
34154
+ if (!camera) {
34155
+ import_node_server_utils106.logger.warn(`No camera document found for site: ${value.site}`);
34156
+ }
34157
+ } catch (error) {
34158
+ import_node_server_utils106.logger.error(
34159
+ `Error _getVisitorsInBySite camera for site ${value.site}:`,
34160
+ error
34161
+ );
34162
+ }
34163
+ }
34164
+ if (camera && value.plateNumber && camera.host && camera.username && camera.password) {
34165
+ host = camera.host;
34166
+ username = camera.username;
34167
+ password = camera.password;
34168
+ const blacklist = "TrafficBlackList" /* TRAFFIC_BLACKLIST */;
34169
+ const _plateNumber = value.plateNumber;
34170
+ const dahuaBlocklistQuery = {
34171
+ host,
34172
+ username,
34173
+ password,
34174
+ plateNumber: _plateNumber,
34175
+ mode: blacklist
34176
+ };
34177
+ const isBlocklistedRaw = await _getPlateNumber(dahuaBlocklistQuery);
34178
+ const rawString = isBlocklistedRaw?.toString?.("utf-8") ?? String(isBlocklistedRaw);
34179
+ const foundMatch = rawString.match(/found=(\d+)/);
34180
+ const found = foundMatch ? Number(foundMatch[1]) : 0;
34181
+ if (found === 1)
34182
+ throw new import_node_server_utils106.BadRequestError("This plate number is blocklisted");
34183
+ }
34184
+ if (Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
34185
+ const keptVisitorPass = [];
33965
34186
  for (const vp of value.visitorPass) {
33966
- try {
33967
- const updatePayload = { status: "In Use" /* IN_USE */ };
33968
- const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
33969
- if (!visitorPassId)
33970
- value.visitorPass = [];
33971
- await KeyRepo.updateKeyById(
33972
- visitorPassId,
33973
- updatePayload,
33974
- value.site
33975
- );
33976
- } catch (error) {
33977
- throw error;
34187
+ const updatePayload = {
34188
+ ...vp.status && { status: vp.status },
34189
+ ...vp.remarks && { remarks: vp.remarks }
34190
+ };
34191
+ const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
34192
+ await KeyRepo.updateKeyById(
34193
+ visitorPassId,
34194
+ updatePayload,
34195
+ value.site
34196
+ );
34197
+ if (typeof vp !== "string" && !(vp instanceof import_mongodb62.ObjectId)) {
34198
+ keptVisitorPass.push({
34199
+ keyId: new import_mongodb62.ObjectId(visitorPassId)
34200
+ });
33978
34201
  }
33979
34202
  }
34203
+ value.visitorPass = keptVisitorPass;
33980
34204
  }
33981
34205
  if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
34206
+ const keptPassKeys = [];
33982
34207
  for (const pk of value.passKeys) {
33983
34208
  try {
33984
- const updatePayload = { status: "In Use" /* IN_USE */ };
34209
+ const updatePayload = {
34210
+ ...pk.status && { status: pk.status },
34211
+ ...pk.remarks && { remarks: pk.remarks }
34212
+ };
33985
34213
  const passKeyId = typeof pk === "string" || pk instanceof import_mongodb62.ObjectId ? pk : pk.keyId;
33986
- if (!passKeyId)
33987
- value.passKeys = [];
33988
34214
  await KeyRepo.updateKeyById(
33989
34215
  passKeyId,
33990
34216
  updatePayload,
33991
34217
  value.site
33992
34218
  );
34219
+ if (typeof pk !== "string" && !(pk instanceof import_mongodb62.ObjectId)) {
34220
+ keptPassKeys.push({
34221
+ keyId: new import_mongodb62.ObjectId(passKeyId)
34222
+ });
34223
+ }
33993
34224
  } catch (error) {
33994
34225
  throw error;
33995
34226
  }
33996
34227
  }
34228
+ value.passKeys = keptPassKeys;
33997
34229
  }
33998
- const result = await _add(value, session);
33999
- await session?.commitTransaction();
34000
- let openBarrier = null;
34001
- const isOpenBarrier = allowedPersonTypes.includes(value?.type) || camera?.ANPRSwitches?.openBarrierPickUpDropOff == true;
34002
- if (isOpenBarrier && value.plateNumber && host && username && password) {
34003
- try {
34004
- import_node_server_utils106.logger.info(`Attempting to open barrier at host: ${host}`);
34005
- openBarrier = await _openBarrier({
34006
- host,
34007
- username,
34008
- password,
34009
- plateNumber: value?.plateNumber
34010
- });
34011
- import_node_server_utils106.logger.info(`Barrier command sent successfully to ${host}`, {
34012
- response: openBarrier
34013
- });
34014
- } catch (error) {
34015
- import_node_server_utils106.logger.error(
34016
- `Failed to open barrier at host ${host}. Critical system error:`,
34017
- error
34018
- );
34019
- openBarrier = { success: false, error: error?.message };
34020
- }
34021
- }
34022
- console.log("Open barrier response:", openBarrier);
34023
- return result;
34024
- } catch (error) {
34025
- await session?.abortTransaction();
34026
- throw error;
34027
- } finally {
34028
- session?.endSession();
34029
- }
34030
- }
34031
- async function updateVisitorTransactionById(id, value) {
34032
- const session = import_node_server_utils106.useAtlas.getClient()?.startSession();
34033
- session?.startTransaction();
34034
- try {
34035
- let camera;
34036
- let host;
34037
- let username;
34038
- let password;
34039
- if (value.site && value.plateNumber) {
34040
- try {
34041
- camera = await _getVisitorsInBySite(value.site);
34042
- if (!camera) {
34043
- import_node_server_utils106.logger.warn(`No camera document found for site: ${value.site}`);
34044
- }
34045
- } catch (error) {
34046
- import_node_server_utils106.logger.error(
34047
- `Error _getVisitorsInBySite camera for site ${value.site}:`,
34048
- error
34049
- );
34050
- }
34051
- }
34052
- if (camera && value.plateNumber && camera.host && camera.username && camera.password) {
34053
- host = camera.host;
34054
- username = camera.username;
34055
- password = camera.password;
34056
- const blacklist = "TrafficBlackList" /* TRAFFIC_BLACKLIST */;
34057
- const _plateNumber = value.plateNumber;
34058
- const dahuaBlocklistQuery = {
34059
- host,
34060
- username,
34061
- password,
34062
- plateNumber: _plateNumber,
34063
- mode: blacklist
34064
- };
34065
- const isBlocklistedRaw = await _getPlateNumber(dahuaBlocklistQuery);
34066
- const rawString = isBlocklistedRaw?.toString?.("utf-8") ?? String(isBlocklistedRaw);
34067
- const foundMatch = rawString.match(/found=(\d+)/);
34068
- const found = foundMatch ? Number(foundMatch[1]) : 0;
34069
- if (found === 1)
34070
- throw new import_node_server_utils106.BadRequestError("This plate number is blocklisted");
34071
- }
34072
- if (Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
34073
- const keptVisitorPass = [];
34074
- for (const vp of value.visitorPass) {
34075
- const updatePayload = {
34076
- ...vp.status && { status: vp.status },
34077
- ...vp.remarks && { remarks: vp.remarks }
34078
- };
34079
- const visitorPassId = typeof vp === "string" || vp instanceof import_mongodb62.ObjectId ? vp : vp.keyId;
34080
- await KeyRepo.updateKeyById(
34081
- visitorPassId,
34082
- updatePayload,
34083
- value.site
34084
- );
34085
- if (typeof vp !== "string" && !(vp instanceof import_mongodb62.ObjectId)) {
34086
- keptVisitorPass.push({
34087
- keyId: new import_mongodb62.ObjectId(visitorPassId)
34088
- });
34089
- }
34090
- }
34091
- value.visitorPass = keptVisitorPass;
34092
- }
34093
- if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
34094
- const keptPassKeys = [];
34095
- for (const pk of value.passKeys) {
34096
- try {
34097
- const updatePayload = {
34098
- ...pk.status && { status: pk.status },
34099
- ...pk.remarks && { remarks: pk.remarks }
34100
- };
34101
- const passKeyId = typeof pk === "string" || pk instanceof import_mongodb62.ObjectId ? pk : pk.keyId;
34102
- await KeyRepo.updateKeyById(
34103
- passKeyId,
34104
- updatePayload,
34105
- value.site
34106
- );
34107
- if (typeof pk !== "string" && !(pk instanceof import_mongodb62.ObjectId)) {
34108
- keptPassKeys.push({
34109
- keyId: new import_mongodb62.ObjectId(passKeyId)
34110
- });
34111
- }
34112
- } catch (error) {
34113
- throw error;
34114
- }
34115
- }
34116
- value.passKeys = keptPassKeys;
34117
- }
34118
- if (value.checkIn) {
34119
- const parsed = new Date(value.checkIn);
34120
- value.checkIn = isNaN(parsed.getTime()) ? null : parsed;
34121
- }
34122
- if (value.checkOut) {
34123
- const parsed = new Date(value.checkOut);
34124
- value.checkOut = isNaN(parsed.getTime()) ? null : parsed;
34125
- }
34126
- if (value.site) {
34127
- value.site = typeof value.site === "string" ? new import_mongodb62.ObjectId(value.site) : value.site;
34128
- }
34129
- if (value.unit) {
34130
- value.unit = typeof value.unit === "string" ? new import_mongodb62.ObjectId(value.unit) : value.unit;
34131
- const unit = await _getUnitById(value.unit);
34132
- value.unitName = unit?.name;
34133
- }
34134
- await _updateVisitorTansactionById(id, value, session);
34135
- const allowedPersonTypes = [
34136
- "contractor" /* CONTRACTOR */,
34137
- "walk-in" /* WALK_IN */,
34138
- "guest" /* GUEST */,
34139
- "delivery" /* DELIVERY */
34140
- // PersonTypes.PICK_UP,
34141
- ];
34230
+ if (value.checkIn) {
34231
+ const parsed = new Date(value.checkIn);
34232
+ value.checkIn = isNaN(parsed.getTime()) ? null : parsed;
34233
+ }
34234
+ if (value.checkOut) {
34235
+ const parsed = new Date(value.checkOut);
34236
+ value.checkOut = isNaN(parsed.getTime()) ? null : parsed;
34237
+ }
34238
+ if (value.site) {
34239
+ value.site = typeof value.site === "string" ? new import_mongodb62.ObjectId(value.site) : value.site;
34240
+ }
34241
+ if (value.unit) {
34242
+ value.unit = typeof value.unit === "string" ? new import_mongodb62.ObjectId(value.unit) : value.unit;
34243
+ const unit = await _getUnitById(value.unit);
34244
+ value.unitName = unit?.name;
34245
+ }
34246
+ await _updateVisitorTansactionById(id, value, session);
34247
+ const allowedPersonTypes = [
34248
+ "contractor" /* CONTRACTOR */,
34249
+ "walk-in" /* WALK_IN */,
34250
+ "guest" /* GUEST */,
34251
+ "delivery" /* DELIVERY */
34252
+ // PersonTypes.PICK_UP,
34253
+ ];
34142
34254
  let openBarrier = null;
34143
34255
  const isOpenBarrier = allowedPersonTypes.includes(value?.type) || camera?.ANPRSwitches?.openBarrierPickUpDropOff == true;
34144
34256
  if (isOpenBarrier && value.plateNumber && host && username && password) {
@@ -34275,9 +34387,9 @@ function useVisitorTransactionService() {
34275
34387
  value.checkIn = null;
34276
34388
  const payload = {
34277
34389
  ...value,
34278
- block: inviter?.block,
34279
- level: inviter?.level,
34280
- unit: inviter?.unit,
34390
+ block: inviter?.block?.toString(),
34391
+ level: inviter?.level?.toString(),
34392
+ unit: inviter?.unit?.toString(),
34281
34393
  unitName: unit?.name,
34282
34394
  org: inviter?.org.toString(),
34283
34395
  site: inviter?.site.toString(),
@@ -34373,7 +34485,8 @@ function useVisitorTransactionController() {
34373
34485
  } = useVisitorTransactionRepo();
34374
34486
  async function add(req, res, next) {
34375
34487
  try {
34376
- const { error, value } = schemaVisitorTransaction.validate(req.body, {
34488
+ const { companyName, firstName, lastName, ...restData } = req.body;
34489
+ const { error, value } = schemaVisitorTransaction.validate(restData, {
34377
34490
  abortEarly: false
34378
34491
  });
34379
34492
  if (error) {
@@ -34605,8 +34718,11 @@ function useVisitorTransactionController() {
34605
34718
  return;
34606
34719
  } catch (error2) {
34607
34720
  import_node_server_utils107.logger.log({ level: "error", message: error2.message });
34608
- next(error2);
34609
- return;
34721
+ if (error2?.message) {
34722
+ next(new import_node_server_utils107.BadRequestError(error2?.message));
34723
+ } else {
34724
+ next(error2);
34725
+ }
34610
34726
  }
34611
34727
  }
34612
34728
  async function changeVisitorTransactionKeysById(req, res, next) {
@@ -66094,10 +66210,6 @@ function useChatPrelovedRepo() {
66094
66210
  return { add, updateById, deleteById };
66095
66211
  }
66096
66212
 
66097
- // src/controllers/chat-preloved.controller.ts
66098
- var import_node_server_utils248 = require("@7365admin1/node-server-utils");
66099
- var import_joi143 = __toESM(require("joi"));
66100
-
66101
66213
  // src/services/chat-preloved.service.ts
66102
66214
  var import_node_server_utils247 = require("@7365admin1/node-server-utils");
66103
66215
 
@@ -66424,6 +66536,8 @@ function useChatPrelovedService() {
66424
66536
  }
66425
66537
 
66426
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"));
66427
66541
  function useChatPrelovedController() {
66428
66542
  const { add: _add } = useChatPrelovedService();
66429
66543
  const { updateById: _updateById, deleteById: _deleteById } = useChatPrelovedRepo();
@@ -66603,58 +66717,196 @@ function useChannelPrelovedController() {
66603
66717
  return { add, getChannel, getChatLists, getChannelMessages };
66604
66718
  }
66605
66719
 
66606
- // src/models/online-forms-v2.model.ts
66720
+ // src/models/bid-preloved.model.ts
66607
66721
  var import_joi145 = __toESM(require("joi"));
66608
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");
66609
66861
  var FormEntryStatus = /* @__PURE__ */ ((FormEntryStatus2) => {
66610
66862
  FormEntryStatus2["ACTIVE"] = "active";
66611
66863
  FormEntryStatus2["INACTIVE"] = "inactive";
66612
66864
  FormEntryStatus2["DELETED"] = "deleted";
66613
66865
  return FormEntryStatus2;
66614
66866
  })(FormEntryStatus || {});
66615
- var schemaFormEntry = import_joi145.default.object({
66616
- _id: import_joi145.default.string().hex().optional().allow("", null),
66617
- formType: import_joi145.default.string().required(),
66618
- block: import_joi145.default.string().optional().allow(null, ""),
66619
- level: import_joi145.default.string().optional().allow(null, ""),
66620
- unit: import_joi145.default.string().optional().allow(null, ""),
66621
- name: import_joi145.default.string().optional().allow(null, ""),
66622
- phoneNumber: import_joi145.default.string().optional().allow(null, ""),
66623
- createdBy: import_joi145.default.string().required(),
66624
- fields: import_joi145.default.object().pattern(
66625
- import_joi145.default.string(),
66626
- import_joi145.default.alternatives().try(
66627
- import_joi145.default.string(),
66628
- import_joi145.default.number(),
66629
- import_joi145.default.boolean(),
66630
- 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)
66631
66883
  )
66632
66884
  ).required(),
66633
- status: import_joi145.default.string().optional().allow("", null),
66634
- org: import_joi145.default.string().hex().optional().allow("", null),
66635
- site: import_joi145.default.string().hex().optional().allow("", null),
66636
- createdAt: import_joi145.default.date().optional().allow("", null),
66637
- updatedAt: import_joi145.default.date().optional().allow("", null),
66638
- 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)
66639
66891
  });
66640
- var schemaUpdateFormEntry = import_joi145.default.object({
66641
- _id: import_joi145.default.string().hex().required(),
66642
- formType: import_joi145.default.string().optional().allow("", null),
66643
- block: import_joi145.default.string().optional().allow(null, ""),
66644
- level: import_joi145.default.string().optional().allow(null, ""),
66645
- unit: import_joi145.default.string().optional().allow(null, ""),
66646
- fields: import_joi145.default.object().pattern(
66647
- import_joi145.default.string(),
66648
- import_joi145.default.alternatives().try(
66649
- import_joi145.default.string(),
66650
- import_joi145.default.number(),
66651
- import_joi145.default.boolean(),
66652
- 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)
66653
66905
  )
66654
66906
  ).optional(),
66655
- status: import_joi145.default.string().optional().allow("", null),
66656
- updatedAt: import_joi145.default.date().optional().allow("", null),
66657
- 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)
66658
66910
  });
66659
66911
  function MFormEntry(value) {
66660
66912
  const { error } = schemaFormEntry.validate(value);
@@ -66663,21 +66915,21 @@ function MFormEntry(value) {
66663
66915
  }
66664
66916
  if (value._id && typeof value._id === "string") {
66665
66917
  try {
66666
- value._id = new import_mongodb149.ObjectId(value._id);
66918
+ value._id = new import_mongodb151.ObjectId(value._id);
66667
66919
  } catch {
66668
66920
  throw new Error("Invalid ID.");
66669
66921
  }
66670
66922
  }
66671
66923
  if (value.org && typeof value.org === "string") {
66672
66924
  try {
66673
- value.org = new import_mongodb149.ObjectId(value.org);
66925
+ value.org = new import_mongodb151.ObjectId(value.org);
66674
66926
  } catch {
66675
66927
  throw new Error("Invalid org ID.");
66676
66928
  }
66677
66929
  }
66678
66930
  if (value.site && typeof value.site === "string") {
66679
66931
  try {
66680
- value.site = new import_mongodb149.ObjectId(value.site);
66932
+ value.site = new import_mongodb151.ObjectId(value.site);
66681
66933
  } catch {
66682
66934
  throw new Error("Invalid site ID.");
66683
66935
  }
@@ -66699,49 +66951,49 @@ function MFormEntry(value) {
66699
66951
  deletedAt: value.deletedAt ?? null
66700
66952
  };
66701
66953
  }
66702
- var residentFormEntry = import_joi145.default.object({
66703
- _id: import_joi145.default.string().hex().optional().allow("", null),
66704
- typeOfForm: import_joi145.default.string().optional().allow("", null),
66705
- unitNumber: import_joi145.default.string().optional().allow(null, ""),
66706
- fields: import_joi145.default.object().pattern(
66707
- import_joi145.default.string(),
66708
- import_joi145.default.alternatives().try(
66709
- import_joi145.default.string(),
66710
- import_joi145.default.number(),
66711
- import_joi145.default.boolean(),
66712
- 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)
66713
66965
  )
66714
66966
  ).optional().allow(null, ""),
66715
- status: import_joi145.default.string().optional().allow("", null),
66716
- org: import_joi145.default.string().hex().optional().allow("", null),
66717
- site: import_joi145.default.string().hex().optional().allow("", null),
66718
- userId: import_joi145.default.string().hex().optional().allow("", null),
66719
- createdAt: import_joi145.default.date().optional().allow("", null),
66720
- updatedAt: import_joi145.default.date().optional().allow("", null),
66721
- deletedAt: import_joi145.default.date().optional().allow("", null),
66722
- remarks: import_joi145.default.string().optional().allow("", null),
66723
- managementValues: import_joi145.default.object().pattern(
66724
- import_joi145.default.string(),
66725
- import_joi145.default.alternatives().try(
66726
- import_joi145.default.string(),
66727
- import_joi145.default.number(),
66728
- import_joi145.default.boolean(),
66729
- 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)
66730
66982
  )
66731
66983
  ).optional().allow(null, "")
66732
66984
  });
66733
66985
 
66734
66986
  // src/repositories/online-forms-v2.repository.ts
66735
- var import_node_server_utils250 = require("@7365admin1/node-server-utils");
66736
- var import_mongodb150 = require("mongodb");
66987
+ var import_node_server_utils252 = require("@7365admin1/node-server-utils");
66988
+ var import_mongodb152 = require("mongodb");
66737
66989
  var online_forms_namespace_collection = "online-forms";
66738
66990
  function useFormEntryRepo() {
66739
- const db = import_node_server_utils250.useAtlas.getDb();
66991
+ const db = import_node_server_utils252.useAtlas.getDb();
66740
66992
  if (!db) {
66741
- 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.");
66742
66994
  }
66743
66995
  const collection = db.collection(online_forms_namespace_collection);
66744
- const { delNamespace, getCache, setCache } = (0, import_node_server_utils250.useCache)(
66996
+ const { delNamespace, getCache, setCache } = (0, import_node_server_utils252.useCache)(
66745
66997
  online_forms_namespace_collection
66746
66998
  );
66747
66999
  async function createTextIndex() {
@@ -66750,7 +67002,7 @@ function useFormEntryRepo() {
66750
67002
  name: "text"
66751
67003
  });
66752
67004
  } catch (error) {
66753
- throw new import_node_server_utils250.InternalServerError(
67005
+ throw new import_node_server_utils252.InternalServerError(
66754
67006
  "Failed to create text index on online form."
66755
67007
  );
66756
67008
  }
@@ -66760,11 +67012,11 @@ function useFormEntryRepo() {
66760
67012
  value = MFormEntry(value);
66761
67013
  const res = await collection.insertOne(value, { session });
66762
67014
  delNamespace().then(() => {
66763
- import_node_server_utils250.logger.info(
67015
+ import_node_server_utils252.logger.info(
66764
67016
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66765
67017
  );
66766
67018
  }).catch((err) => {
66767
- import_node_server_utils250.logger.error(
67019
+ import_node_server_utils252.logger.error(
66768
67020
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66769
67021
  err
66770
67022
  );
@@ -66773,7 +67025,7 @@ function useFormEntryRepo() {
66773
67025
  } catch (error) {
66774
67026
  const isDuplicated = error.message.includes("duplicate");
66775
67027
  if (isDuplicated) {
66776
- throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
67028
+ throw new import_node_server_utils252.BadRequestError("Online Form already exists.");
66777
67029
  }
66778
67030
  throw error;
66779
67031
  }
@@ -66789,8 +67041,8 @@ function useFormEntryRepo() {
66789
67041
  }) {
66790
67042
  page = page > 0 ? page - 1 : 0;
66791
67043
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
66792
- site = new import_mongodb150.ObjectId(site);
66793
- org = new import_mongodb150.ObjectId(org);
67044
+ site = new import_mongodb152.ObjectId(site);
67045
+ org = new import_mongodb152.ObjectId(org);
66794
67046
  const cacheOptions = {
66795
67047
  page,
66796
67048
  limit,
@@ -66810,13 +67062,13 @@ function useFormEntryRepo() {
66810
67062
  { unitNumber: { $regex: search, $options: "i" } }
66811
67063
  ];
66812
67064
  }
66813
- const cacheKey = (0, import_node_server_utils250.makeCacheKey)(
67065
+ const cacheKey = (0, import_node_server_utils252.makeCacheKey)(
66814
67066
  online_forms_namespace_collection,
66815
67067
  cacheOptions
66816
67068
  );
66817
67069
  const cachedData = await getCache(cacheKey);
66818
67070
  if (cachedData) {
66819
- import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
67071
+ import_node_server_utils252.logger.info(`Cache hit for key: ${cacheKey}`);
66820
67072
  return cachedData;
66821
67073
  }
66822
67074
  try {
@@ -66843,11 +67095,11 @@ function useFormEntryRepo() {
66843
67095
  { $project: { user: 0 } }
66844
67096
  ]).toArray();
66845
67097
  const length = await collection.countDocuments(query);
66846
- 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);
66847
67099
  setCache(cacheKey, data, 15 * 60).then(() => {
66848
- import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
67100
+ import_node_server_utils252.logger.info(`Cache set for key: ${cacheKey}`);
66849
67101
  }).catch((err) => {
66850
- 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);
66851
67103
  });
66852
67104
  return data;
66853
67105
  } catch (error) {
@@ -66855,27 +67107,27 @@ function useFormEntryRepo() {
66855
67107
  }
66856
67108
  }
66857
67109
  async function getFormEntryById(_id) {
66858
- 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 });
66859
67111
  const cachedData = await getCache(cacheKey);
66860
67112
  if (cachedData) {
66861
- import_node_server_utils250.logger.info(`Cache hit for key: ${cacheKey}`);
67113
+ import_node_server_utils252.logger.info(`Cache hit for key: ${cacheKey}`);
66862
67114
  return cachedData;
66863
67115
  }
66864
67116
  try {
66865
- _id = new import_mongodb150.ObjectId(_id);
67117
+ _id = new import_mongodb152.ObjectId(_id);
66866
67118
  } catch (error) {
66867
- 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.");
66868
67120
  }
66869
67121
  const query = { _id, status: { $ne: "deleted" } };
66870
67122
  try {
66871
67123
  const [data] = await collection.aggregate([{ $match: query }]).toArray();
66872
67124
  if (!data) {
66873
- throw new import_node_server_utils250.NotFoundError("Document not found.");
67125
+ throw new import_node_server_utils252.NotFoundError("Document not found.");
66874
67126
  }
66875
67127
  setCache(cacheKey, data, 15 * 60).then(() => {
66876
- import_node_server_utils250.logger.info(`Cache set for key: ${cacheKey}`);
67128
+ import_node_server_utils252.logger.info(`Cache set for key: ${cacheKey}`);
66877
67129
  }).catch((err) => {
66878
- 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);
66879
67131
  });
66880
67132
  return data;
66881
67133
  } catch (error) {
@@ -66884,9 +67136,9 @@ function useFormEntryRepo() {
66884
67136
  }
66885
67137
  async function updateFormEntryById(_id, value) {
66886
67138
  try {
66887
- _id = new import_mongodb150.ObjectId(_id);
67139
+ _id = new import_mongodb152.ObjectId(_id);
66888
67140
  } catch (error) {
66889
- 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.");
66890
67142
  }
66891
67143
  try {
66892
67144
  const updateValue = {
@@ -66895,14 +67147,14 @@ function useFormEntryRepo() {
66895
67147
  };
66896
67148
  const res = await collection.updateOne({ _id }, { $set: updateValue });
66897
67149
  if (res.modifiedCount === 0) {
66898
- 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.");
66899
67151
  }
66900
67152
  delNamespace().then(() => {
66901
- import_node_server_utils250.logger.info(
67153
+ import_node_server_utils252.logger.info(
66902
67154
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66903
67155
  );
66904
67156
  }).catch((err) => {
66905
- import_node_server_utils250.logger.error(
67157
+ import_node_server_utils252.logger.error(
66906
67158
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66907
67159
  err
66908
67160
  );
@@ -66914,9 +67166,9 @@ function useFormEntryRepo() {
66914
67166
  }
66915
67167
  async function deleteOnlineFormById(_id, session) {
66916
67168
  try {
66917
- _id = new import_mongodb150.ObjectId(_id);
67169
+ _id = new import_mongodb152.ObjectId(_id);
66918
67170
  } catch (error) {
66919
- 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.");
66920
67172
  }
66921
67173
  try {
66922
67174
  const updateValue = {
@@ -66930,12 +67182,12 @@ function useFormEntryRepo() {
66930
67182
  { session }
66931
67183
  );
66932
67184
  if (res.modifiedCount === 0) {
66933
- 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.");
66934
67186
  }
66935
67187
  delNamespace().then(() => {
66936
- 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}`);
66937
67189
  }).catch((err) => {
66938
- import_node_server_utils250.logger.error(
67190
+ import_node_server_utils252.logger.error(
66939
67191
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66940
67192
  err
66941
67193
  );
@@ -66947,16 +67199,16 @@ function useFormEntryRepo() {
66947
67199
  }
66948
67200
  async function addResidentForm(value, session) {
66949
67201
  try {
66950
- value.site = new import_mongodb150.ObjectId(value.site);
66951
- value.org = new import_mongodb150.ObjectId(value.org);
66952
- 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);
66953
67205
  const res = await collection.insertOne(value, { session });
66954
67206
  delNamespace().then(() => {
66955
- import_node_server_utils250.logger.info(
67207
+ import_node_server_utils252.logger.info(
66956
67208
  `Cache cleared for namespace: ${online_forms_namespace_collection}`
66957
67209
  );
66958
67210
  }).catch((err) => {
66959
- import_node_server_utils250.logger.error(
67211
+ import_node_server_utils252.logger.error(
66960
67212
  `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
66961
67213
  err
66962
67214
  );
@@ -66965,16 +67217,16 @@ function useFormEntryRepo() {
66965
67217
  } catch (error) {
66966
67218
  const isDuplicated = error.message.includes("duplicate");
66967
67219
  if (isDuplicated) {
66968
- throw new import_node_server_utils250.BadRequestError("Online Form already exists.");
67220
+ throw new import_node_server_utils252.BadRequestError("Online Form already exists.");
66969
67221
  }
66970
67222
  throw error;
66971
67223
  }
66972
67224
  }
66973
67225
  async function residentForm({ userId, site, org }) {
66974
67226
  try {
66975
- const user = new import_mongodb150.ObjectId(userId);
66976
- const siteId = new import_mongodb150.ObjectId(site);
66977
- 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);
66978
67230
  const res = await collection.aggregate([
66979
67231
  {
66980
67232
  $match: {
@@ -67002,8 +67254,8 @@ function useFormEntryRepo() {
67002
67254
  }
67003
67255
 
67004
67256
  // src/controllers/online-forms-v2.controller.ts
67005
- var import_node_server_utils251 = require("@7365admin1/node-server-utils");
67006
- var import_joi146 = __toESM(require("joi"));
67257
+ var import_node_server_utils253 = require("@7365admin1/node-server-utils");
67258
+ var import_joi148 = __toESM(require("joi"));
67007
67259
  var import_exceljs3 = __toESM(require("exceljs"));
67008
67260
  var import_fs7 = __toESM(require("fs"));
67009
67261
  function useFormEntryController() {
@@ -67029,14 +67281,14 @@ function useFormEntryController() {
67029
67281
  async function uploadFormEntrys(req, res, next) {
67030
67282
  try {
67031
67283
  if (!req.file) {
67032
- next(new import_node_server_utils251.BadRequestError("Excel file is required."));
67284
+ next(new import_node_server_utils253.BadRequestError("Excel file is required."));
67033
67285
  return;
67034
67286
  }
67035
67287
  const workbook = new import_exceljs3.default.Workbook();
67036
67288
  await workbook.xlsx.readFile(req.file.path);
67037
67289
  const worksheet = workbook.worksheets[0];
67038
67290
  if (!worksheet) {
67039
- 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."));
67040
67292
  return;
67041
67293
  }
67042
67294
  const headerRow = worksheet.getRow(1);
@@ -67064,8 +67316,8 @@ function useFormEntryController() {
67064
67316
  });
67065
67317
  if (error) {
67066
67318
  const messages = error.details.map((d) => d.message).join(", ");
67067
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67068
- 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));
67069
67321
  return;
67070
67322
  }
67071
67323
  const result = await _add(value);
@@ -67073,25 +67325,25 @@ function useFormEntryController() {
67073
67325
  import_fs7.default.unlink(req.file.path, () => {
67074
67326
  });
67075
67327
  } catch (error) {
67076
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67328
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67077
67329
  next(error);
67078
67330
  }
67079
67331
  }
67080
67332
  async function getAll(req, res, next) {
67081
67333
  try {
67082
- const schema2 = import_joi146.default.object({
67083
- search: import_joi146.default.string().optional().allow("", null),
67084
- page: import_joi146.default.number().integer().min(1).allow("", null).default(1),
67085
- limit: import_joi146.default.number().integer().min(1).max(100).allow("", null).default(10),
67086
- status: import_joi146.default.string().optional().allow(null, ""),
67087
- org: import_joi146.default.string().hex().optional().allow("", null),
67088
- 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)
67089
67341
  });
67090
67342
  const { error, value } = schema2.validate(req.query);
67091
67343
  if (error) {
67092
67344
  const messages = error.details.map((d) => d.message).join(", ");
67093
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67094
- 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));
67095
67347
  return;
67096
67348
  }
67097
67349
  const { search, page, limit, status, org, site } = value;
@@ -67099,21 +67351,21 @@ function useFormEntryController() {
67099
67351
  res.json(data);
67100
67352
  return;
67101
67353
  } catch (error) {
67102
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67354
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67103
67355
  next(error);
67104
67356
  return;
67105
67357
  }
67106
67358
  }
67107
67359
  async function getFormEntryById(req, res, next) {
67108
67360
  try {
67109
- const schema2 = import_joi146.default.object({
67110
- _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()
67111
67363
  });
67112
67364
  const { error, value } = schema2.validate({ _id: req.params.id });
67113
67365
  if (error) {
67114
67366
  const messages = error.details.map((d) => d.message).join(", ");
67115
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67116
- 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));
67117
67369
  return;
67118
67370
  }
67119
67371
  const { _id } = value;
@@ -67121,7 +67373,7 @@ function useFormEntryController() {
67121
67373
  res.json(data);
67122
67374
  return;
67123
67375
  } catch (error) {
67124
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67376
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67125
67377
  next(error);
67126
67378
  return;
67127
67379
  }
@@ -67134,8 +67386,8 @@ function useFormEntryController() {
67134
67386
  });
67135
67387
  if (error) {
67136
67388
  const messages = error.details.map((d) => d.message).join(", ");
67137
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67138
- 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));
67139
67391
  return;
67140
67392
  }
67141
67393
  const { _id, ...rest } = value;
@@ -67143,26 +67395,26 @@ function useFormEntryController() {
67143
67395
  res.json({ message: "Successfully updated online form." });
67144
67396
  return;
67145
67397
  } catch (error) {
67146
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67398
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67147
67399
  next(error);
67148
67400
  return;
67149
67401
  }
67150
67402
  }
67151
67403
  async function deleteFormEntryById(req, res, next) {
67152
67404
  try {
67153
- const validation = import_joi146.default.string().hex().required();
67405
+ const validation = import_joi148.default.string().hex().required();
67154
67406
  const _id = req.params.id;
67155
67407
  const { error } = validation.validate(_id);
67156
67408
  if (error) {
67157
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67158
- 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));
67159
67411
  return;
67160
67412
  }
67161
67413
  await _deleteOnlineFormById(_id);
67162
67414
  res.json({ message: "Successfully deleted online form." });
67163
67415
  return;
67164
67416
  } catch (error) {
67165
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67417
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67166
67418
  next(error);
67167
67419
  return;
67168
67420
  }
@@ -67179,8 +67431,8 @@ function useFormEntryController() {
67179
67431
  });
67180
67432
  if (error) {
67181
67433
  const messages = error.details.map((d) => d.message).join(", ");
67182
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67183
- 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));
67184
67436
  return;
67185
67437
  }
67186
67438
  try {
@@ -67188,7 +67440,7 @@ function useFormEntryController() {
67188
67440
  res.status(201).json({ message: data });
67189
67441
  return;
67190
67442
  } catch (error2) {
67191
- import_node_server_utils251.logger.log({ level: "error", message: error2.message });
67443
+ import_node_server_utils253.logger.log({ level: "error", message: error2.message });
67192
67444
  next(error2);
67193
67445
  return;
67194
67446
  }
@@ -67200,8 +67452,8 @@ function useFormEntryController() {
67200
67452
  });
67201
67453
  if (error) {
67202
67454
  const messages = error.details.map((d) => d.message).join(", ");
67203
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67204
- 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));
67205
67457
  return;
67206
67458
  }
67207
67459
  try {
@@ -67209,7 +67461,7 @@ function useFormEntryController() {
67209
67461
  res.status(201).json({ message: data });
67210
67462
  return;
67211
67463
  } catch (error2) {
67212
- import_node_server_utils251.logger.log({ level: "error", message: error2.message });
67464
+ import_node_server_utils253.logger.log({ level: "error", message: error2.message });
67213
67465
  next(error2);
67214
67466
  return;
67215
67467
  }
@@ -67217,22 +67469,22 @@ function useFormEntryController() {
67217
67469
  async function residentForm(req, res, next) {
67218
67470
  try {
67219
67471
  const { site, userId, org } = req.query;
67220
- const residentFormPayload = import_joi146.default.object({
67221
- org: import_joi146.default.string().hex().required(),
67222
- site: import_joi146.default.string().hex().required(),
67223
- 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()
67224
67476
  });
67225
67477
  const { error } = residentFormPayload.validate({ site, userId, org }, { abortEarly: true });
67226
67478
  if (error) {
67227
67479
  const messages = error.details.map((d) => d.message).join(", ");
67228
- import_node_server_utils251.logger.log({ level: "error", message: messages });
67229
- 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));
67230
67482
  return;
67231
67483
  }
67232
67484
  const result = await _residentForm({ userId, site, org });
67233
67485
  res.json(result);
67234
67486
  } catch (error) {
67235
- import_node_server_utils251.logger.log({ level: "error", message: error.message });
67487
+ import_node_server_utils253.logger.log({ level: "error", message: error.message });
67236
67488
  next(error);
67237
67489
  return;
67238
67490
  }
@@ -67250,11 +67502,11 @@ function useFormEntryController() {
67250
67502
  }
67251
67503
 
67252
67504
  // src/services/building-level.service.ts
67253
- var import_node_server_utils252 = require("@7365admin1/node-server-utils");
67505
+ var import_node_server_utils254 = require("@7365admin1/node-server-utils");
67254
67506
  function useBuildingLevelService() {
67255
67507
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelRepo();
67256
67508
  async function add(value) {
67257
- const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
67509
+ const session = import_node_server_utils254.useAtlas.getClient()?.startSession();
67258
67510
  try {
67259
67511
  session?.startTransaction();
67260
67512
  await _add(value, session);
@@ -67268,7 +67520,7 @@ function useBuildingLevelService() {
67268
67520
  }
67269
67521
  }
67270
67522
  async function updateLevelById(_id, value) {
67271
- const session = import_node_server_utils252.useAtlas.getClient()?.startSession();
67523
+ const session = import_node_server_utils254.useAtlas.getClient()?.startSession();
67272
67524
  try {
67273
67525
  session?.startTransaction();
67274
67526
  await _updateLevelById(_id, value, session);
@@ -67288,8 +67540,8 @@ function useBuildingLevelService() {
67288
67540
  }
67289
67541
 
67290
67542
  // src/controllers/building-level.controller.ts
67291
- var import_node_server_utils253 = require("@7365admin1/node-server-utils");
67292
- var import_joi147 = __toESM(require("joi"));
67543
+ var import_node_server_utils255 = require("@7365admin1/node-server-utils");
67544
+ var import_joi149 = __toESM(require("joi"));
67293
67545
  function useBuildingLevelController() {
67294
67546
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelService();
67295
67547
  const {
@@ -67306,8 +67558,8 @@ function useBuildingLevelController() {
67306
67558
  });
67307
67559
  if (error) {
67308
67560
  const messages = error.details.map((d) => d.message).join(", ");
67309
- import_node_server_utils253.logger.log({ level: "error", message: messages });
67310
- 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));
67311
67563
  return;
67312
67564
  }
67313
67565
  const result = await _add(value);
@@ -67318,20 +67570,20 @@ function useBuildingLevelController() {
67318
67570
  }
67319
67571
  async function getAll(req, res, next) {
67320
67572
  try {
67321
- const validation = import_joi147.default.object({
67322
- page: import_joi147.default.number().min(1).optional().default(1),
67323
- limit: import_joi147.default.number().min(1).optional().default(20),
67324
- search: import_joi147.default.string().optional().allow("", null),
67325
- site: import_joi147.default.string().hex().length(24).optional().allow("", null),
67326
- 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 */)
67327
67579
  });
67328
67580
  const { error, value } = validation.validate(req.query, {
67329
67581
  abortEarly: false
67330
67582
  });
67331
67583
  if (error) {
67332
67584
  const messages = error.details.map((d) => d.message);
67333
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67334
- 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(", ")));
67335
67587
  return;
67336
67588
  }
67337
67589
  const { page, limit, status, site, search } = value;
@@ -67350,14 +67602,14 @@ function useBuildingLevelController() {
67350
67602
  }
67351
67603
  async function getById(req, res, next) {
67352
67604
  try {
67353
- const schema2 = import_joi147.default.object({
67354
- 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()
67355
67607
  });
67356
67608
  const { error, value } = schema2.validate({ id: req.params.id });
67357
67609
  if (error) {
67358
67610
  const messages = error.details.map((d) => d.message);
67359
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67360
- 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(", ")));
67361
67613
  return;
67362
67614
  }
67363
67615
  const { id } = value;
@@ -67376,8 +67628,8 @@ function useBuildingLevelController() {
67376
67628
  });
67377
67629
  if (error) {
67378
67630
  const messages = error.details.map((d) => d.message);
67379
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67380
- 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(", ")));
67381
67633
  return;
67382
67634
  }
67383
67635
  const { _id, ...rest } = value;
@@ -67389,14 +67641,14 @@ function useBuildingLevelController() {
67389
67641
  }
67390
67642
  async function deleteById(req, res, next) {
67391
67643
  try {
67392
- const schema2 = import_joi147.default.object({
67393
- id: import_joi147.default.string().hex().required()
67644
+ const schema2 = import_joi149.default.object({
67645
+ id: import_joi149.default.string().hex().required()
67394
67646
  });
67395
67647
  const { error, value } = schema2.validate({ id: req.params.id });
67396
67648
  if (error) {
67397
67649
  const messages = error.details.map((d) => d.message);
67398
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67399
- 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(", ")));
67400
67652
  return;
67401
67653
  }
67402
67654
  const { id } = value;
@@ -67409,19 +67661,19 @@ function useBuildingLevelController() {
67409
67661
  }
67410
67662
  async function batchUpdateByIds(req, res, next) {
67411
67663
  try {
67412
- const schema2 = import_joi147.default.array().items(
67413
- import_joi147.default.object({
67414
- _id: import_joi147.default.string().hex().length(24).required(),
67415
- value: import_joi147.default.object({
67416
- 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)
67417
67669
  }).required()
67418
67670
  })
67419
67671
  );
67420
67672
  const { error, value } = schema2.validate(req.body);
67421
67673
  if (error) {
67422
67674
  const messages = error.details.map((d) => d.message);
67423
- import_node_server_utils253.logger.log({ level: "error", message: messages.join(", ") });
67424
- 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(", ")));
67425
67677
  return;
67426
67678
  }
67427
67679
  const updates = value.map((item) => ({
@@ -67436,9 +67688,9 @@ function useBuildingLevelController() {
67436
67688
  }
67437
67689
  async function getBuildingLevelList(req, res, next) {
67438
67690
  try {
67439
- const schema2 = import_joi147.default.object({
67440
- site: import_joi147.default.string().hex().length(24).required(),
67441
- 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()
67442
67694
  });
67443
67695
  const { error, value } = schema2.validate({
67444
67696
  site: req.params.siteId,
@@ -67446,8 +67698,8 @@ function useBuildingLevelController() {
67446
67698
  });
67447
67699
  if (error) {
67448
67700
  const messages = error.details.map((d) => d.message).join(", ");
67449
- import_node_server_utils253.logger.log({ level: "error", message: messages });
67450
- 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));
67451
67703
  return;
67452
67704
  }
67453
67705
  const { site, block } = value;
@@ -67468,11 +67720,1358 @@ function useBuildingLevelController() {
67468
67720
  getBuildingLevelList
67469
67721
  };
67470
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
+ }
67471
69068
  // Annotate the CommonJS export names for ESM import in node:
67472
69069
  0 && (module.exports = {
67473
69070
  ANPRMode,
67474
69071
  AccessTypeProps,
67475
69072
  AppServiceType,
69073
+ BidStatus,
69074
+ BidType,
67476
69075
  BuildingLevelStatus,
67477
69076
  BuildingStatus,
67478
69077
  BulletinOrder,
@@ -67504,6 +69103,7 @@ function useBuildingLevelController() {
67504
69103
  MAddress,
67505
69104
  MAttendance,
67506
69105
  MAttendanceSettings,
69106
+ MBidPreloved,
67507
69107
  MBillingConfiguration,
67508
69108
  MBillingItem,
67509
69109
  MBuilding,
@@ -67524,6 +69124,9 @@ function useBuildingLevelController() {
67524
69124
  MFile,
67525
69125
  MFormEntry,
67526
69126
  MGuestManagement,
69127
+ MHidAmicoEvent,
69128
+ MHidAmicoIdentity,
69129
+ MHidAmicoReader,
67527
69130
  MIncidentReport,
67528
69131
  MManpowerDesignations,
67529
69132
  MManpowerMonitoring,
@@ -67643,6 +69246,7 @@ function useBuildingLevelController() {
67643
69246
  schema,
67644
69247
  schemaApprovedBy,
67645
69248
  schemaApprover,
69249
+ schemaBidPreloved,
67646
69250
  schemaBilling,
67647
69251
  schemaBillingConfiguration,
67648
69252
  schemaBillingItem,
@@ -67655,6 +69259,7 @@ function useBuildingLevelController() {
67655
69259
  schemaCategoryPreloved,
67656
69260
  schemaChannelPreloved,
67657
69261
  schemaChatPreloved,
69262
+ schemaCreateHidAmicoIdentity,
67658
69263
  schemaCustomerSite,
67659
69264
  schemaDocumentManagement,
67660
69265
  schemaEntryPassSettings,
@@ -67662,6 +69267,21 @@ function useBuildingLevelController() {
67662
69267
  schemaFiles,
67663
69268
  schemaFormEntry,
67664
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,
67665
69285
  schemaIncidentReport,
67666
69286
  schemaMultipleDocumentManagement,
67667
69287
  schemaNfcPatrolLog,
@@ -67689,6 +69309,7 @@ function useBuildingLevelController() {
67689
69309
  schemaStatementOfAccount,
67690
69310
  schemaSubcategoryPreloved,
67691
69311
  schemaUnitBilling,
69312
+ schemaUpdateBidPreloved,
67692
69313
  schemaUpdateBuildingLevel,
67693
69314
  schemaUpdateBulletinBoard,
67694
69315
  schemaUpdateBulletinVideo,
@@ -67699,6 +69320,8 @@ function useBuildingLevelController() {
67699
69320
  schemaUpdateEventManagement,
67700
69321
  schemaUpdateFormEntry,
67701
69322
  schemaUpdateGuestManagement,
69323
+ schemaUpdateHidAmicoIdentity,
69324
+ schemaUpdateHidAmicoReader,
67702
69325
  schemaUpdateIncidentReport,
67703
69326
  schemaUpdateOccurrenceBook,
67704
69327
  schemaUpdateOccurrenceEntry,
@@ -67744,6 +69367,8 @@ function useBuildingLevelController() {
67744
69367
  useAuthControllerV2,
67745
69368
  useAuthService,
67746
69369
  useAuthServiceV2,
69370
+ useBidPrelovedController,
69371
+ useBidPrelovedRepo,
67747
69372
  useBuildingController,
67748
69373
  useBuildingLevelController,
67749
69374
  useBuildingLevelRepo,
@@ -67766,6 +69391,7 @@ function useBuildingLevelController() {
67766
69391
  useChatController,
67767
69392
  useChatPrelovedController,
67768
69393
  useChatPrelovedRepo,
69394
+ useChatPrelovedService,
67769
69395
  useChatRepo,
67770
69396
  useCounterModel,
67771
69397
  useCounterRepo,
@@ -67796,6 +69422,9 @@ function useBuildingLevelController() {
67796
69422
  useGuestManagementController,
67797
69423
  useGuestManagementRepo,
67798
69424
  useGuestManagementService,
69425
+ useHidAmicoController,
69426
+ useHidAmicoRepo,
69427
+ useHidAmicoService,
67799
69428
  useHrmLabsAttendanceCtrl,
67800
69429
  useHrmLabsAttendanceSrvc,
67801
69430
  useIncidentReportController,