@7365admin1/core 2.65.0 → 2.67.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
@@ -33,6 +33,7 @@ __export(src_exports, {
33
33
  ANPRMode: () => ANPRMode,
34
34
  AccessTypeProps: () => AccessTypeProps,
35
35
  AppServiceType: () => AppServiceType,
36
+ BuildingLevelStatus: () => BuildingLevelStatus,
36
37
  BuildingStatus: () => BuildingStatus,
37
38
  BulletinOrder: () => BulletinOrder,
38
39
  BulletinRecipient: () => BulletinRecipient,
@@ -55,6 +56,7 @@ __export(src_exports, {
55
56
  EventType: () => EventType,
56
57
  FacilitySort: () => FacilitySort,
57
58
  FacilityStatus: () => FacilityStatus,
59
+ FormEntryStatus: () => FormEntryStatus,
58
60
  GuestSort: () => GuestSort,
59
61
  GuestStatus: () => GuestStatus,
60
62
  MAccessCard: () => MAccessCard,
@@ -65,9 +67,11 @@ __export(src_exports, {
65
67
  MBillingConfiguration: () => MBillingConfiguration,
66
68
  MBillingItem: () => MBillingItem,
67
69
  MBuilding: () => MBuilding,
70
+ MBuildingLevel: () => MBuildingLevel,
68
71
  MBuildingUnit: () => MBuildingUnit,
69
72
  MBulletinBoard: () => MBulletinBoard,
70
73
  MBulletinVideo: () => MBulletinVideo,
74
+ MCategoryPreloved: () => MCategoryPreloved,
71
75
  MChat: () => MChat,
72
76
  MCustomer: () => MCustomer,
73
77
  MCustomerSite: () => MCustomerSite,
@@ -76,6 +80,7 @@ __export(src_exports, {
76
80
  MEventManagement: () => MEventManagement,
77
81
  MFeedback: () => MFeedback,
78
82
  MFile: () => MFile,
83
+ MFormEntry: () => MFormEntry,
79
84
  MGuestManagement: () => MGuestManagement,
80
85
  MIncidentReport: () => MIncidentReport,
81
86
  MManpowerDesignations: () => MManpowerDesignations,
@@ -112,6 +117,7 @@ __export(src_exports, {
112
117
  MSiteFacility: () => MSiteFacility,
113
118
  MSiteFacilityBooking: () => MSiteFacilityBooking,
114
119
  MStatementOfAccount: () => MStatementOfAccount,
120
+ MSubcategoryPreloved: () => MSubcategoryPreloved,
115
121
  MSubscription: () => MSubscription,
116
122
  MUnitBilling: () => MUnitBilling,
117
123
  MUser: () => MUser,
@@ -159,6 +165,7 @@ __export(src_exports, {
159
165
  allowedNatures: () => allowedNatures,
160
166
  attendanceSchema: () => attendanceSchema,
161
167
  attendanceSettingsSchema: () => attendanceSettingsSchema,
168
+ building_level_namespace_collection: () => building_level_namespace_collection,
162
169
  building_units_namespace_collection: () => building_units_namespace_collection,
163
170
  buildings_namespace_collection: () => buildings_namespace_collection,
164
171
  bulletin_boards_namespace_collection: () => bulletin_boards_namespace_collection,
@@ -187,6 +194,7 @@ __export(src_exports, {
187
194
  nfcPatrolSettingsSchema: () => nfcPatrolSettingsSchema,
188
195
  nfcPatrolSettingsSchemaUpdate: () => nfcPatrolSettingsSchemaUpdate,
189
196
  occurrence_book_namespace_collection: () => occurrence_book_namespace_collection,
197
+ online_forms_namespace_collection: () => online_forms_namespace_collection,
190
198
  orgSchema: () => orgSchema,
191
199
  overnight_parking_requests_namespace_collection: () => overnight_parking_requests_namespace_collection,
192
200
  parseDahuaFind: () => parseDahuaFind,
@@ -202,15 +210,18 @@ __export(src_exports, {
202
210
  schemaBillingConfiguration: () => schemaBillingConfiguration,
203
211
  schemaBillingItem: () => schemaBillingItem,
204
212
  schemaBuilding: () => schemaBuilding,
213
+ schemaBuildingLevel: () => schemaBuildingLevel,
205
214
  schemaBuildingUnit: () => schemaBuildingUnit,
206
215
  schemaBuildingUpdateOptions: () => schemaBuildingUpdateOptions,
207
216
  schemaBulletinBoard: () => schemaBulletinBoard,
208
217
  schemaBulletinVideo: () => schemaBulletinVideo,
218
+ schemaCategoryPreloved: () => schemaCategoryPreloved,
209
219
  schemaCustomerSite: () => schemaCustomerSite,
210
220
  schemaDocumentManagement: () => schemaDocumentManagement,
211
221
  schemaEntryPassSettings: () => schemaEntryPassSettings,
212
222
  schemaEventManagement: () => schemaEventManagement,
213
223
  schemaFiles: () => schemaFiles,
224
+ schemaFormEntry: () => schemaFormEntry,
214
225
  schemaGuestManagement: () => schemaGuestManagement,
215
226
  schemaIncidentReport: () => schemaIncidentReport,
216
227
  schemaNfcPatrolLog: () => schemaNfcPatrolLog,
@@ -235,12 +246,15 @@ __export(src_exports, {
235
246
  schemaSiteFacility: () => schemaSiteFacility,
236
247
  schemaSiteFacilityBooking: () => schemaSiteFacilityBooking,
237
248
  schemaStatementOfAccount: () => schemaStatementOfAccount,
249
+ schemaSubcategoryPreloved: () => schemaSubcategoryPreloved,
238
250
  schemaUnitBilling: () => schemaUnitBilling,
239
251
  schemaUpdateBulletinBoard: () => schemaUpdateBulletinBoard,
240
252
  schemaUpdateBulletinVideo: () => schemaUpdateBulletinVideo,
253
+ schemaUpdateCategoryPreloved: () => schemaUpdateCategoryPreloved,
241
254
  schemaUpdateDocumentManagement: () => schemaUpdateDocumentManagement,
242
255
  schemaUpdateEntryPassSettings: () => schemaUpdateEntryPassSettings,
243
256
  schemaUpdateEventManagement: () => schemaUpdateEventManagement,
257
+ schemaUpdateFormEntry: () => schemaUpdateFormEntry,
244
258
  schemaUpdateGuestManagement: () => schemaUpdateGuestManagement,
245
259
  schemaUpdateIncidentReport: () => schemaUpdateIncidentReport,
246
260
  schemaUpdateOccurrenceBook: () => schemaUpdateOccurrenceBook,
@@ -262,6 +276,7 @@ __export(src_exports, {
262
276
  schemaUpdateSiteFacilityBooking: () => schemaUpdateSiteFacilityBooking,
263
277
  schemaUpdateSiteUnitBilling: () => schemaUpdateSiteUnitBilling,
264
278
  schemaUpdateStatementOfAccount: () => schemaUpdateStatementOfAccount,
279
+ schemaUpdateSubcategoryPreloved: () => schemaUpdateSubcategoryPreloved,
265
280
  schemaUpdateVisTrans: () => schemaUpdateVisTrans,
266
281
  schemaVehicleTransaction: () => schemaVehicleTransaction,
267
282
  schemaVisitorTransaction: () => schemaVisitorTransaction,
@@ -287,6 +302,9 @@ __export(src_exports, {
287
302
  useAuthService: () => useAuthService,
288
303
  useAuthServiceV2: () => useAuthServiceV2,
289
304
  useBuildingController: () => useBuildingController,
305
+ useBuildingLevelController: () => useBuildingLevelController,
306
+ useBuildingLevelRepo: () => useBuildingLevelRepo,
307
+ useBuildingLevelService: () => useBuildingLevelService,
290
308
  useBuildingRepo: () => useBuildingRepo,
291
309
  useBuildingService: () => useBuildingService,
292
310
  useBuildingUnitController: () => useBuildingUnitController,
@@ -298,6 +316,8 @@ __export(src_exports, {
298
316
  useBulletinVideoController: () => useBulletinVideoController,
299
317
  useBulletinVideoRepo: () => useBulletinVideoRepo,
300
318
  useBulletinVideoService: () => useBulletinVideoService,
319
+ useCategoryPrelovedController: () => useCategoryPrelovedController,
320
+ useCategoryPrelovedRepo: () => useCategoryPrelovedRepo,
301
321
  useChatController: () => useChatController,
302
322
  useChatRepo: () => useChatRepo,
303
323
  useCounterModel: () => useCounterModel,
@@ -324,6 +344,8 @@ __export(src_exports, {
324
344
  useFileController: () => useFileController,
325
345
  useFileRepo: () => useFileRepo,
326
346
  useFileService: () => useFileService,
347
+ useFormEntryController: () => useFormEntryController,
348
+ useFormEntryRepo: () => useFormEntryRepo,
327
349
  useGuestManagementController: () => useGuestManagementController,
328
350
  useGuestManagementRepo: () => useGuestManagementRepo,
329
351
  useGuestManagementService: () => useGuestManagementService,
@@ -433,6 +455,8 @@ __export(src_exports, {
433
455
  useSiteUnitBillingService: () => useSiteUnitBillingService,
434
456
  useStatementOfAccountController: () => useStatementOfAccountController,
435
457
  useStatementOfAccountRepo: () => useStatementOfAccountRepo,
458
+ useSubcategoryPrelovedController: () => useSubcategoryPrelovedController,
459
+ useSubcategoryPrelovedRepo: () => useSubcategoryPrelovedRepo,
436
460
  useSubscriptionController: () => useSubscriptionController,
437
461
  useSubscriptionRepo: () => useSubscriptionRepo,
438
462
  useSubscriptionService: () => useSubscriptionService,
@@ -588,7 +612,15 @@ var userSchema = import_joi2.default.object({
588
612
  email: import_joi2.default.string().email().required(),
589
613
  password: import_joi2.default.string().min(8).required(),
590
614
  name: import_joi2.default.string().required(),
591
- defaultOrg: import_joi2.default.string().hex().optional().allow("", null)
615
+ defaultOrg: import_joi2.default.string().hex().optional().allow("", null),
616
+ status: import_joi2.default.string().optional().allow("", null),
617
+ block: import_joi2.default.number().optional().allow(null),
618
+ level: import_joi2.default.string().optional().allow("", null),
619
+ type: import_joi2.default.string().optional().allow("", null),
620
+ unitName: import_joi2.default.string().optional().allow("", null),
621
+ contact: import_joi2.default.string().optional().allow("", null),
622
+ site: import_joi2.default.string().hex().optional().allow("", null),
623
+ unitId: import_joi2.default.string().hex().optional().allow("", null)
592
624
  });
593
625
  function MUser(value) {
594
626
  const { error } = userSchema.validate(value);
@@ -602,12 +634,33 @@ function MUser(value) {
602
634
  throw new import_node_server_utils3.BadRequestError("Invalid default org ID format.");
603
635
  }
604
636
  }
637
+ if (value.site && typeof value.site === "string") {
638
+ try {
639
+ value.site = new import_mongodb.ObjectId(value.site);
640
+ } catch {
641
+ throw new import_node_server_utils3.BadRequestError("Invalid site ID format.");
642
+ }
643
+ }
644
+ if (value.unitId && typeof value.unitId === "string") {
645
+ try {
646
+ value.unitId = new import_mongodb.ObjectId(value.unitId);
647
+ } catch {
648
+ throw new import_node_server_utils3.BadRequestError("Invalid unit ID format.");
649
+ }
650
+ }
605
651
  return {
606
652
  email: value.email,
607
653
  password: value.password,
608
654
  name: value.name ?? "",
609
655
  defaultOrg: value.defaultOrg ?? "",
610
- status: "active" /* ACTIVE */,
656
+ status: value.status ?? "active" /* ACTIVE */,
657
+ block: value.block ?? null,
658
+ level: value.level ?? "",
659
+ type: value.type ?? "",
660
+ unitName: value.unitName ?? "",
661
+ contact: value.contact ?? "",
662
+ site: value.site ?? "",
663
+ unitId: value.unitId ?? "",
611
664
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
612
665
  updatedAt: value.updatedAt ?? "",
613
666
  deletedAt: value.deletedAt ?? ""
@@ -4563,7 +4616,7 @@ function useOrgRepo() {
4563
4616
  }
4564
4617
  async function createUniqueIndex() {
4565
4618
  try {
4566
- await collection.createIndex({ email: 1 }, { unique: true });
4619
+ await collection.createIndex({ email: 1 });
4567
4620
  } catch (error) {
4568
4621
  throw new import_node_server_utils17.InternalServerError("Failed to create unique index on name.");
4569
4622
  }
@@ -4753,6 +4806,29 @@ function useOrgRepo() {
4753
4806
  throw error;
4754
4807
  }
4755
4808
  }
4809
+ async function getOrgsByEmail(email) {
4810
+ const cacheKey = (0, import_node_server_utils17.makeCacheKey)(namespace_collection, {
4811
+ email
4812
+ });
4813
+ const cachedData = await getCache(cacheKey);
4814
+ if (cachedData) {
4815
+ import_node_server_utils17.logger.info(`Cache hit for key: ${cacheKey}`);
4816
+ return cachedData;
4817
+ }
4818
+ try {
4819
+ const data = await collection.find({
4820
+ email
4821
+ }).toArray();
4822
+ setCache(cacheKey, data, 15 * 60).then(() => {
4823
+ import_node_server_utils17.logger.info(`Cache set for key: ${cacheKey}`);
4824
+ }).catch((err) => {
4825
+ import_node_server_utils17.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
4826
+ });
4827
+ return data;
4828
+ } catch (error) {
4829
+ throw error;
4830
+ }
4831
+ }
4756
4832
  async function updateFieldById({
4757
4833
  _id,
4758
4834
  field,
@@ -4855,7 +4931,8 @@ function useOrgRepo() {
4855
4931
  getByEmail,
4856
4932
  updateFieldById,
4857
4933
  updateStatusById,
4858
- deleteById
4934
+ deleteById,
4935
+ getOrgsByEmail
4859
4936
  };
4860
4937
  }
4861
4938
 
@@ -5855,7 +5932,6 @@ function useVerificationService() {
5855
5932
  await getSiteById(metadata.siteId);
5856
5933
  }
5857
5934
  const verificationIds = [];
5858
- const invitedApps = [];
5859
5935
  for (const app of apps) {
5860
5936
  await useVerificationRepo().findOne({
5861
5937
  type,
@@ -5878,34 +5954,32 @@ function useVerificationService() {
5878
5954
  };
5879
5955
  const createdId = await add(value);
5880
5956
  verificationIds.push(createdId.toString());
5881
- invitedApps.push(app);
5957
+ const link = `${APP_MAIN}/verify/invitation/${createdId}`;
5958
+ const emailContent = (0, import_node_server_utils21.compileHandlebar)({
5959
+ context: {
5960
+ email,
5961
+ validity: VERIFICATION_USER_INVITE_DURATION,
5962
+ link,
5963
+ hasPropertyManagement: app === "property_management_agency",
5964
+ hasSecurity: app === "security_agency",
5965
+ hasCleaning: app === "cleaning_services",
5966
+ hasMechanical: app === "mechanical_electrical_services",
5967
+ hasLandscape: app === "landscaping_services",
5968
+ hasPestControl: app === "pest_control_services",
5969
+ hasPoolMaintenance: app === "pool_maintenance_services"
5970
+ },
5971
+ filePath: (0, import_node_server_utils21.getDirectory)(
5972
+ __dirname,
5973
+ "./public/handlebars/user-invite"
5974
+ )
5975
+ });
5976
+ await mailer.sendMail({
5977
+ to: email,
5978
+ subject: "User Invite",
5979
+ html: emailContent,
5980
+ sender: "iService365"
5981
+ });
5882
5982
  }
5883
- const link = `${APP_MAIN}/verify/invitation/${verificationIds[0]}`;
5884
- const appsSet = new Set(invitedApps);
5885
- const emailContent = (0, import_node_server_utils21.compileHandlebar)({
5886
- context: {
5887
- email,
5888
- validity: VERIFICATION_USER_INVITE_DURATION,
5889
- link,
5890
- hasPropertyManagement: appsSet.has("property_management_agency"),
5891
- hasSecurity: appsSet.has("security_agency"),
5892
- hasCleaning: appsSet.has("cleaning_services"),
5893
- hasMechanical: appsSet.has("mechanical_electrical_services"),
5894
- hasLandscape: appsSet.has("landscaping_services"),
5895
- hasPestControl: appsSet.has("pest_control_services"),
5896
- hasPoolMaintenance: appsSet.has("pool_maintenance_services")
5897
- },
5898
- filePath: (0, import_node_server_utils21.getDirectory)(
5899
- __dirname,
5900
- "./public/handlebars/user-invite"
5901
- )
5902
- });
5903
- await mailer.sendMail({
5904
- to: email,
5905
- subject: "User Invite",
5906
- html: emailContent,
5907
- sender: "iService365"
5908
- });
5909
5983
  return verificationIds;
5910
5984
  }
5911
5985
  async function createSimpleMemberInvite({
@@ -8375,7 +8449,7 @@ function useVerificationController() {
8375
8449
  siteId: import_joi16.default.string().hex().optional().allow("", null),
8376
8450
  siteName: import_joi16.default.string().optional().allow("", null)
8377
8451
  });
8378
- const { error } = validation.validate(payload);
8452
+ const { error, value } = validation.validate(payload);
8379
8453
  if (error) {
8380
8454
  import_node_server_utils32.logger.log({
8381
8455
  level: "error",
@@ -8384,15 +8458,17 @@ function useVerificationController() {
8384
8458
  next(new import_node_server_utils32.BadRequestError(error.message));
8385
8459
  return;
8386
8460
  }
8387
- const email = req.body.email ?? "";
8388
- const app = req.body.app ?? [];
8389
- const role = req.body.role ?? "";
8390
- const name = req.body.name ?? "";
8391
- const org = req.body.org ?? "";
8392
- const siteId = req.body.siteId ?? "";
8393
- const siteName = req.body.siteName ?? "";
8394
8461
  try {
8395
- await _createSimpleUserInvite({
8462
+ const {
8463
+ email,
8464
+ app,
8465
+ role,
8466
+ name,
8467
+ org,
8468
+ siteId,
8469
+ siteName
8470
+ } = value;
8471
+ const verificationIds = await _createSimpleUserInvite({
8396
8472
  email,
8397
8473
  metadata: {
8398
8474
  app,
@@ -8404,7 +8480,9 @@ function useVerificationController() {
8404
8480
  }
8405
8481
  });
8406
8482
  res.status(201).json({
8407
- message: "Successfully invited user."
8483
+ message: "Successfully invited user.",
8484
+ totalInvites: verificationIds.length,
8485
+ verificationIds
8408
8486
  });
8409
8487
  return;
8410
8488
  } catch (error2) {
@@ -8860,7 +8938,8 @@ function useOrgController() {
8860
8938
  getByEmail: _getByEmail,
8861
8939
  getAll: _getAll,
8862
8940
  add: _add,
8863
- update: _update
8941
+ update: _update,
8942
+ getOrgsByEmail: _getOrgsByEmail
8864
8943
  } = useOrgRepo();
8865
8944
  async function add(req, res, next) {
8866
8945
  const validation = import_joi18.default.object({
@@ -9044,6 +9123,30 @@ function useOrgController() {
9044
9123
  return;
9045
9124
  }
9046
9125
  }
9126
+ async function getOrgsByEmail(req, res, next) {
9127
+ const validation = import_joi18.default.object({
9128
+ email: import_joi18.default.string().email().required()
9129
+ });
9130
+ const query = {
9131
+ email: req.params.email
9132
+ };
9133
+ const { error } = validation.validate(query);
9134
+ if (error) {
9135
+ import_node_server_utils35.logger.log({ level: "error", message: error.message });
9136
+ next(new import_node_server_utils35.BadRequestError(error.message));
9137
+ return;
9138
+ }
9139
+ const email = req.params.email;
9140
+ try {
9141
+ const data = await _getOrgsByEmail(email);
9142
+ res.json(data);
9143
+ return;
9144
+ } catch (error2) {
9145
+ import_node_server_utils35.logger.log({ level: "error", message: error2.message });
9146
+ next(error2);
9147
+ return;
9148
+ }
9149
+ }
9047
9150
  async function update(req, res, next) {
9048
9151
  const validation = import_joi18.default.object({
9049
9152
  name: import_joi18.default.string().optional(),
@@ -9077,7 +9180,8 @@ function useOrgController() {
9077
9180
  getByName,
9078
9181
  getById,
9079
9182
  getByEmail,
9080
- update
9183
+ update,
9184
+ getOrgsByEmail
9081
9185
  };
9082
9186
  }
9083
9187
 
@@ -26659,7 +26763,14 @@ function usePersonService() {
26659
26763
  password: hashedPassword,
26660
26764
  name: value.name,
26661
26765
  status: value.platform == "mobile" ? "pending" : "active",
26662
- defaultOrg: value.org?.toString() || ""
26766
+ defaultOrg: value.org?.toString() || "",
26767
+ block: value.block,
26768
+ level: value.level,
26769
+ type: value.type,
26770
+ unitName: value.unitName,
26771
+ contact: value.contact,
26772
+ site: value.site?.toString() || "",
26773
+ unitId: value.unit?.toString() || ""
26663
26774
  };
26664
26775
  const userId = await addUser(user, session);
26665
26776
  value.user = userId.toString();
@@ -31322,26 +31433,31 @@ var schemaDocumentManagement = import_joi74.default.object({
31322
31433
  _id: import_joi74.default.string().hex().optional().allow("", null),
31323
31434
  name: import_joi74.default.string().required(),
31324
31435
  type: import_joi74.default.string().optional().allow("", null),
31325
- attachment: import_joi74.default.string().required(),
31326
- status: import_joi74.default.string().required(),
31327
- createdBy: import_joi74.default.string().hex().required(),
31436
+ attachment: import_joi74.default.when("isFolder", { is: true, then: import_joi74.default.forbidden(), otherwise: import_joi74.default.string().optional().allow("", null) }),
31437
+ remarks: import_joi74.default.string().optional().allow("", null),
31438
+ isFolder: import_joi74.default.boolean().optional().default(false),
31328
31439
  org: import_joi74.default.string().hex().optional().allow("", null),
31329
31440
  site: import_joi74.default.string().hex().optional().allow("", null),
31441
+ parentId: import_joi74.default.string().hex().optional().allow("", null),
31442
+ createdBy: import_joi74.default.string().hex().required(),
31330
31443
  updatedBy: import_joi74.default.string().hex().optional().allow("", null),
31331
31444
  createdAt: import_joi74.default.date().optional().allow("", null),
31332
- updatedAt: import_joi74.default.date().optional().allow("", null)
31445
+ updatedAt: import_joi74.default.date().optional().allow("", null),
31446
+ status: import_joi74.default.string().optional().allow("", null).default("active")
31333
31447
  });
31334
31448
  var schemaUpdateDocumentManagement = import_joi74.default.object({
31335
31449
  _id: import_joi74.default.string().hex().required(),
31336
31450
  name: import_joi74.default.string().optional().allow("", null),
31337
31451
  type: import_joi74.default.string().optional().allow("", null),
31338
- attachment: import_joi74.default.string().optional(),
31339
- status: import_joi74.default.string().optional().allow("", null),
31452
+ attachment: import_joi74.default.when("isFolder", { is: true, then: import_joi74.default.forbidden(), otherwise: import_joi74.default.string().optional().allow("", null) }),
31453
+ remarks: import_joi74.default.string().optional().allow("", null),
31454
+ isFolder: import_joi74.default.boolean().optional(),
31340
31455
  org: import_joi74.default.string().hex().optional().allow("", null),
31341
31456
  site: import_joi74.default.string().hex().optional().allow("", null),
31457
+ parentId: import_joi74.default.string().hex().optional().allow("", null),
31342
31458
  updatedBy: import_joi74.default.string().hex().optional().allow("", null),
31343
- createdAt: import_joi74.default.date().optional().allow("", null),
31344
- updatedAt: import_joi74.default.date().optional().allow("", null)
31459
+ updatedAt: import_joi74.default.date().optional().allow("", null),
31460
+ status: import_joi74.default.string().optional().allow("", null)
31345
31461
  });
31346
31462
  function MDocumentManagement(value) {
31347
31463
  const { error } = schemaDocumentManagement.validate(value);
@@ -31369,18 +31485,31 @@ function MDocumentManagement(value) {
31369
31485
  throw new Error("Invalid site ID.");
31370
31486
  }
31371
31487
  }
31488
+ if (value.parentId && typeof value.parentId === "string") {
31489
+ try {
31490
+ value.parentId = new import_mongodb76.ObjectId(value.parentId);
31491
+ } catch (error2) {
31492
+ throw new Error("Invalid parentId.");
31493
+ }
31494
+ }
31495
+ if (value.isFolder) {
31496
+ value.attachment = void 0;
31497
+ }
31372
31498
  return {
31373
31499
  _id: value._id,
31374
31500
  name: value.name,
31375
31501
  type: value.type,
31376
31502
  attachment: value.attachment,
31377
- status: value.status,
31503
+ remarks: value.remarks ?? "",
31504
+ isFolder: value.isFolder ?? false,
31378
31505
  org: value.org,
31379
31506
  site: value.site,
31507
+ ...value.parentId ? { parentId: value.parentId } : {},
31380
31508
  createdBy: value.createdBy,
31381
31509
  updatedBy: value.updatedBy,
31382
31510
  createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
31383
- updatedAt: value.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
31511
+ updatedAt: value.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
31512
+ status: value.status ?? "active"
31384
31513
  };
31385
31514
  }
31386
31515
 
@@ -31395,11 +31524,22 @@ function useDocumentManagementRepo() {
31395
31524
  const namespace_collection = "documents";
31396
31525
  const collection = db.collection(namespace_collection);
31397
31526
  const { delNamespace, getCache, setCache } = (0, import_node_server_utils133.useCache)(namespace_collection);
31527
+ async function createIndex() {
31528
+ try {
31529
+ await collection.createIndexes([
31530
+ { key: { site: 1 } },
31531
+ { key: { isFolder: 1 } },
31532
+ { key: { parentId: 1 } }
31533
+ ]);
31534
+ } catch (error) {
31535
+ throw new import_node_server_utils133.InternalServerError("Failed to create index on document.");
31536
+ }
31537
+ }
31398
31538
  async function createTextIndex() {
31399
31539
  try {
31400
31540
  await collection.createIndex({
31401
31541
  name: "text",
31402
- type: "text"
31542
+ remarks: "text"
31403
31543
  });
31404
31544
  } catch (error) {
31405
31545
  throw new import_node_server_utils133.InternalServerError("Failed to create text index on document.");
@@ -31433,7 +31573,8 @@ function useDocumentManagementRepo() {
31433
31573
  sort = {},
31434
31574
  status = "active",
31435
31575
  org = "",
31436
- site = ""
31576
+ site = "",
31577
+ parentId = ""
31437
31578
  }) {
31438
31579
  page = page > 0 ? page - 1 : 0;
31439
31580
  try {
@@ -31452,14 +31593,24 @@ function useDocumentManagementRepo() {
31452
31593
  const query = {
31453
31594
  ...status ? { $and: [{ status }, { status: { $ne: "deleted" } }] } : { status: { $ne: "deleted" } }
31454
31595
  };
31455
- if (site) {
31456
- query.site = site;
31457
- cacheOptions.site = site;
31596
+ if (org) {
31597
+ query.org = new import_mongodb77.ObjectId(org);
31598
+ cacheOptions.org = org.toString();
31599
+ }
31600
+ if (parentId) {
31601
+ try {
31602
+ query.parentId = new import_mongodb77.ObjectId(parentId);
31603
+ cacheOptions.parentId = parentId.toString();
31604
+ } catch (error) {
31605
+ throw new import_node_server_utils133.BadRequestError("Invalid parentId format.");
31606
+ }
31607
+ } else {
31608
+ query.parentId = { $in: [null, ""] };
31458
31609
  }
31459
31610
  if (search) {
31460
31611
  query.$or = [
31461
31612
  { name: { $regex: search, $options: "i" } },
31462
- { type: { $regex: search, $options: "i" } }
31613
+ { remarks: { $regex: search, $options: "i" } }
31463
31614
  ];
31464
31615
  cacheOptions.search = search;
31465
31616
  }
@@ -31481,6 +31632,9 @@ function useDocumentManagementRepo() {
31481
31632
  type: 1,
31482
31633
  status: 1,
31483
31634
  attachment: 1,
31635
+ parentId: 1,
31636
+ isFolder: 1,
31637
+ remarks: 1,
31484
31638
  createdAt: 1,
31485
31639
  updatedAt: 1
31486
31640
  }
@@ -31652,6 +31806,7 @@ function useDocumentManagementRepo() {
31652
31806
  }
31653
31807
  }
31654
31808
  return {
31809
+ createIndex,
31655
31810
  createTextIndex,
31656
31811
  add,
31657
31812
  getAll,
@@ -31665,7 +31820,7 @@ function useDocumentManagementRepo() {
31665
31820
  // src/services/document-management.service.ts
31666
31821
  var import_node_server_utils134 = require("@7365admin1/node-server-utils");
31667
31822
  function useDocumentManagementService() {
31668
- const { add: _add, getAll: _getAll } = useDocumentManagementRepo();
31823
+ const { add: _add } = useDocumentManagementRepo();
31669
31824
  const { updateStatusById } = useFileRepo();
31670
31825
  async function createDocument(value) {
31671
31826
  const session = import_node_server_utils134.useAtlas.getClient()?.startSession();
@@ -31695,32 +31850,8 @@ function useDocumentManagementService() {
31695
31850
  session?.endSession();
31696
31851
  }
31697
31852
  }
31698
- async function getDocuments({
31699
- search,
31700
- page,
31701
- limit,
31702
- sort,
31703
- status,
31704
- org,
31705
- site
31706
- }) {
31707
- try {
31708
- return await _getAll({
31709
- search,
31710
- page,
31711
- limit,
31712
- sort,
31713
- status,
31714
- org,
31715
- site
31716
- });
31717
- } catch (error) {
31718
- throw error;
31719
- }
31720
- }
31721
31853
  return {
31722
- createDocument,
31723
- getDocuments
31854
+ createDocument
31724
31855
  };
31725
31856
  }
31726
31857
 
@@ -31728,8 +31859,9 @@ function useDocumentManagementService() {
31728
31859
  var import_node_server_utils135 = require("@7365admin1/node-server-utils");
31729
31860
  var import_joi75 = __toESM(require("joi"));
31730
31861
  function useDocumentManagementController() {
31731
- const { createDocument: _add, getDocuments: _getDocuments } = useDocumentManagementService();
31862
+ const { createDocument: _add } = useDocumentManagementService();
31732
31863
  const {
31864
+ getAll: _getDocuments,
31733
31865
  getDocumentById: _getDocumentById,
31734
31866
  updateDocumentById: _updateDocumentById,
31735
31867
  deleteDocumentById: _deleteDocumentById,
@@ -31747,8 +31879,12 @@ function useDocumentManagementController() {
31747
31879
  createdBy = req.body.createdBy;
31748
31880
  }
31749
31881
  const payload = { ...req.body, createdBy };
31750
- if (payload.attachment.length > 0) {
31882
+ if (payload.isFolder) {
31883
+ delete payload.attachment;
31884
+ } else if (Array.isArray(payload.attachment)) {
31751
31885
  payload.attachment = payload.attachment[0];
31886
+ } else if (!payload.attachment) {
31887
+ payload.attachment = "";
31752
31888
  }
31753
31889
  const { error } = schemaDocumentManagement.validate(payload, {
31754
31890
  abortEarly: false
@@ -31776,7 +31912,8 @@ function useDocumentManagementController() {
31776
31912
  limit: import_joi75.default.number().integer().min(1).max(100).allow("", null).default(10),
31777
31913
  status: import_joi75.default.string().required(),
31778
31914
  org: import_joi75.default.string().hex().optional().allow("", null),
31779
- site: import_joi75.default.string().hex().optional().allow("", null)
31915
+ site: import_joi75.default.string().hex().optional().allow("", null),
31916
+ parentId: import_joi75.default.string().hex().optional().allow("", null)
31780
31917
  });
31781
31918
  const query = { ...req.query };
31782
31919
  query.status = req.query.status;
@@ -31792,6 +31929,7 @@ function useDocumentManagementController() {
31792
31929
  const status = req.query.status ?? "active";
31793
31930
  const org = req.query.org ?? "";
31794
31931
  const site = req.query.site ?? "";
31932
+ const parentId = req.query.parentId ?? "";
31795
31933
  try {
31796
31934
  const data = await _getDocuments({
31797
31935
  search,
@@ -31799,7 +31937,8 @@ function useDocumentManagementController() {
31799
31937
  limit,
31800
31938
  status,
31801
31939
  org,
31802
- site
31940
+ site,
31941
+ parentId
31803
31942
  });
31804
31943
  res.json(data);
31805
31944
  return;
@@ -31855,8 +31994,12 @@ function useDocumentManagementController() {
31855
31994
  }
31856
31995
  const _id = req.params.id;
31857
31996
  const payload = { ...req.body, updatedBy };
31858
- if (payload.attachment.length > 0) {
31997
+ if (payload.isFolder) {
31998
+ delete payload.attachment;
31999
+ } else if (Array.isArray(payload.attachment)) {
31859
32000
  payload.attachment = payload.attachment[0];
32001
+ } else if (!payload.attachment) {
32002
+ payload.attachment = "";
31860
32003
  }
31861
32004
  const { error } = validation.validate({ _id, ...payload });
31862
32005
  if (error) {
@@ -36305,10 +36448,42 @@ function UseAccessManagementRepo() {
36305
36448
  },
36306
36449
  {
36307
36450
  $facet: {
36308
- available_physical: [{ $match: { assignedUnit: { $eq: null }, type: "NFC" /* NFC */ } }, { $count: "count" }],
36309
- available_non_physical: [{ $match: { assignedUnit: { $eq: null }, type: "QRCODE" /* QR */ } }, { $count: "count" }],
36310
- assigned_physical: [{ $match: { assignedUnit: { $ne: null }, type: "NFC" /* NFC */ } }, { $count: "count" }],
36311
- assigned_non_physical: [{ $match: { assignedUnit: { $ne: null }, type: "QRCODE" /* QR */ } }, { $count: "count" }]
36451
+ available_physical: [
36452
+ {
36453
+ $match: {
36454
+ assignedUnit: { $eq: null },
36455
+ type: "NFC" /* NFC */
36456
+ }
36457
+ },
36458
+ { $count: "count" }
36459
+ ],
36460
+ available_non_physical: [
36461
+ {
36462
+ $match: {
36463
+ assignedUnit: { $eq: null },
36464
+ type: "QRCODE" /* QR */
36465
+ }
36466
+ },
36467
+ { $count: "count" }
36468
+ ],
36469
+ assigned_physical: [
36470
+ {
36471
+ $match: {
36472
+ assignedUnit: { $ne: null },
36473
+ type: "NFC" /* NFC */
36474
+ }
36475
+ },
36476
+ { $count: "count" }
36477
+ ],
36478
+ assigned_non_physical: [
36479
+ {
36480
+ $match: {
36481
+ assignedUnit: { $ne: null },
36482
+ type: "QRCODE" /* QR */
36483
+ }
36484
+ },
36485
+ { $count: "count" }
36486
+ ]
36312
36487
  }
36313
36488
  }
36314
36489
  ]).toArray();
@@ -36393,16 +36568,35 @@ function UseAccessManagementRepo() {
36393
36568
  case terms.length >= 3:
36394
36569
  return {
36395
36570
  $and: [
36396
- { $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] } },
36397
- { $expr: { $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()] } },
36398
- { $expr: { $eq: [{ $toLower: "$level.units.name" }, getAfterSecondSlash(search)] } }
36571
+ {
36572
+ $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] }
36573
+ },
36574
+ {
36575
+ $expr: {
36576
+ $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()]
36577
+ }
36578
+ },
36579
+ {
36580
+ $expr: {
36581
+ $eq: [
36582
+ { $toLower: "$level.units.name" },
36583
+ getAfterSecondSlash(search)
36584
+ ]
36585
+ }
36586
+ }
36399
36587
  ]
36400
36588
  };
36401
36589
  case terms.length === 2:
36402
36590
  return {
36403
36591
  $and: [
36404
- { $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] } },
36405
- { $expr: { $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()] } }
36592
+ {
36593
+ $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] }
36594
+ },
36595
+ {
36596
+ $expr: {
36597
+ $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()]
36598
+ }
36599
+ }
36406
36600
  ]
36407
36601
  };
36408
36602
  default:
@@ -36430,220 +36624,386 @@ function UseAccessManagementRepo() {
36430
36624
  site
36431
36625
  };
36432
36626
  const searchQuery = buildSearchQuery(search);
36433
- const result = await collectionName("buildings").aggregate([
36434
- // ✅ Match early with index-friendly query
36435
- {
36436
- $match: {
36437
- ...defaultQuery,
36438
- status: { $eq: "active" }
36439
- }
36440
- },
36441
- // ✅ Only project needed fields before heavy lookups
36442
- {
36443
- $project: {
36444
- _id: 1,
36445
- name: 1,
36446
- site: 1,
36447
- block: 1
36448
- }
36449
- },
36450
- // ✅ Use localField/foreignField for better index usage
36451
- {
36452
- $lookup: {
36453
- from: "building-levels",
36454
- localField: "_id",
36455
- foreignField: "block",
36456
- pipeline: [
36457
- { $match: { status: { $ne: "deleted" } } },
36458
- {
36459
- $lookup: {
36460
- from: "building-units",
36461
- localField: "_id",
36462
- foreignField: "level",
36463
- pipeline: [
36464
- { $match: { status: { $ne: "deleted" }, site } },
36465
- { $project: { _id: 1, name: 1 } }
36466
- ],
36467
- as: "units"
36468
- }
36469
- },
36470
- {
36471
- $match: { "units.0": { $exists: true } }
36472
- },
36473
- {
36474
- $project: {
36475
- _id: 1,
36476
- level: 1,
36477
- units: 1
36627
+ const result = await collectionName("buildings").aggregate(
36628
+ [
36629
+ // ✅ Match early with index-friendly query
36630
+ {
36631
+ $match: {
36632
+ ...defaultQuery,
36633
+ status: { $eq: "active" }
36634
+ }
36635
+ },
36636
+ // ✅ Only project needed fields before heavy lookups
36637
+ {
36638
+ $project: {
36639
+ _id: 1,
36640
+ name: 1,
36641
+ site: 1,
36642
+ block: 1
36643
+ }
36644
+ },
36645
+ // ✅ Use localField/foreignField for better index usage
36646
+ {
36647
+ $lookup: {
36648
+ from: "building-levels",
36649
+ localField: "_id",
36650
+ foreignField: "block",
36651
+ pipeline: [
36652
+ { $match: { status: { $ne: "deleted" } } },
36653
+ {
36654
+ $lookup: {
36655
+ from: "building-units",
36656
+ localField: "_id",
36657
+ foreignField: "level",
36658
+ pipeline: [
36659
+ { $match: { status: { $ne: "deleted" }, site } },
36660
+ { $project: { _id: 1, name: 1 } }
36661
+ ],
36662
+ as: "units"
36663
+ }
36664
+ },
36665
+ {
36666
+ $match: { "units.0": { $exists: true } }
36667
+ },
36668
+ {
36669
+ $project: {
36670
+ _id: 1,
36671
+ level: 1,
36672
+ units: 1
36673
+ }
36478
36674
  }
36479
- }
36480
- ],
36481
- as: "level"
36482
- }
36483
- },
36484
- // ✅ Filter out buildings with no levels early
36485
- {
36486
- $match: { "level.0": { $exists: true } }
36487
- },
36488
- // ✅ Unwind to flatten the hierarchy
36489
- {
36490
- $unwind: {
36491
- path: "$level",
36492
- preserveNullAndEmptyArrays: false
36493
- }
36494
- },
36495
- {
36496
- $unwind: {
36497
- path: "$level.units",
36498
- preserveNullAndEmptyArrays: false
36499
- }
36500
- },
36501
- // // Groups by unit _id and keeps only the first occurrence
36502
- // {
36503
- // $group: {
36504
- // _id: "$level.units._id",
36505
- // doc: { $first: "$$ROOT" },
36506
- // },
36507
- // },
36508
- // {
36509
- // $replaceRoot: { newRoot: "$doc" },
36510
- // },
36511
- // ✅ Apply search filter
36512
- {
36513
- $match: {
36514
- ...searchQuery
36515
- }
36516
- },
36517
- {
36518
- $facet: {
36519
- totalCount: [{ $count: "count" }],
36520
- items: [
36521
- // Sort BEFORE skip/limit for correct pagination
36522
- { $skip: page * limit },
36523
- { $limit: limit },
36524
- // ✅ Users lookup - optimized with index hint
36525
- {
36526
- $lookup: {
36527
- from: "users",
36528
- let: { unit: "$level.units._id" },
36529
- pipeline: [
36530
- {
36531
- $match: {
36532
- $expr: { $eq: ["$unitNumber", "$$unit"] },
36533
- residentType: "House/Unit Owner"
36675
+ ],
36676
+ as: "level"
36677
+ }
36678
+ },
36679
+ // ✅ Filter out buildings with no levels early
36680
+ {
36681
+ $match: { "level.0": { $exists: true } }
36682
+ },
36683
+ // ✅ Unwind to flatten the hierarchy
36684
+ {
36685
+ $unwind: {
36686
+ path: "$level",
36687
+ preserveNullAndEmptyArrays: false
36688
+ }
36689
+ },
36690
+ {
36691
+ $unwind: {
36692
+ path: "$level.units",
36693
+ preserveNullAndEmptyArrays: false
36694
+ }
36695
+ },
36696
+ // // Groups by unit _id and keeps only the first occurrence
36697
+ // {
36698
+ // $group: {
36699
+ // _id: "$level.units._id",
36700
+ // doc: { $first: "$$ROOT" },
36701
+ // },
36702
+ // },
36703
+ // {
36704
+ // $replaceRoot: { newRoot: "$doc" },
36705
+ // },
36706
+ // ✅ Apply search filter
36707
+ {
36708
+ $match: {
36709
+ ...searchQuery
36710
+ }
36711
+ },
36712
+ {
36713
+ $facet: {
36714
+ totalCount: [{ $count: "count" }],
36715
+ items: [
36716
+ // ✅ Sort BEFORE skip/limit for correct pagination
36717
+ { $skip: page * limit },
36718
+ { $limit: limit },
36719
+ // Users lookup - optimized with index hint
36720
+ {
36721
+ $lookup: {
36722
+ from: "users",
36723
+ let: { unit: "$level.units._id" },
36724
+ pipeline: [
36725
+ {
36726
+ $match: {
36727
+ $expr: { $eq: ["$unitNumber", "$$unit"] },
36728
+ residentType: "House/Unit Owner"
36729
+ }
36730
+ },
36731
+ { $limit: 1 },
36732
+ { $project: { _id: 1, givenName: 1, surname: 1 } }
36733
+ ],
36734
+ as: "unitOwner"
36735
+ }
36736
+ },
36737
+ // ✅ Access card lookup - optimized query
36738
+ {
36739
+ $lookup: {
36740
+ from: "access-cards",
36741
+ let: { unit: "$level.units._id" },
36742
+ pipeline: [
36743
+ {
36744
+ $match: {
36745
+ $expr: {
36746
+ $in: [
36747
+ "$$unit",
36748
+ {
36749
+ $cond: [
36750
+ { $isArray: "$assignedUnit" },
36751
+ "$assignedUnit",
36752
+ ["$assignedUnit"]
36753
+ ]
36754
+ }
36755
+ ]
36756
+ },
36757
+ userType
36758
+ }
36759
+ },
36760
+ {
36761
+ $project: {
36762
+ _id: 1,
36763
+ userId: 1,
36764
+ type: 1,
36765
+ cardNo: 1,
36766
+ isActivated: 1,
36767
+ replacementStatus: 1
36768
+ }
36769
+ }
36770
+ ],
36771
+ as: "accessCards"
36772
+ }
36773
+ },
36774
+ // ✅ Compute all card categorization and counts in ONE stage
36775
+ {
36776
+ $addFields: {
36777
+ f_Available: {
36778
+ $filter: {
36779
+ input: "$accessCards",
36780
+ as: "card",
36781
+ cond: {
36782
+ $and: [
36783
+ { $eq: ["$$card.userId", null] },
36784
+ { $eq: ["$$card.isActivated", true] }
36785
+ ]
36786
+ }
36534
36787
  }
36535
36788
  },
36536
- { $limit: 1 },
36537
- { $project: { _id: 1, givenName: 1, surname: 1 } }
36538
- ],
36539
- as: "unitOwner"
36540
- }
36541
- },
36542
- // Access card lookup - optimized query
36543
- {
36544
- $lookup: {
36545
- from: "access-cards",
36546
- let: { unit: "$level.units._id" },
36547
- pipeline: [
36548
- {
36549
- $match: {
36550
- $expr: {
36551
- $in: [
36552
- "$$unit",
36553
- { $cond: [{ $isArray: "$assignedUnit" }, "$assignedUnit", ["$assignedUnit"]] }
36789
+ f_Assigned: {
36790
+ $filter: {
36791
+ input: "$accessCards",
36792
+ as: "card",
36793
+ cond: {
36794
+ $and: [
36795
+ { $ne: ["$$card.userId", null] },
36796
+ { $eq: ["$$card.isActivated", true] }
36554
36797
  ]
36555
- },
36556
- userType
36798
+ }
36557
36799
  }
36558
36800
  },
36559
- { $project: { _id: 1, userId: 1, type: 1, cardNo: 1, isActivated: 1, replacementStatus: 1 } }
36560
- ],
36561
- as: "accessCards"
36562
- }
36563
- },
36564
- // ✅ Compute all card categorization and counts in ONE stage
36565
- {
36566
- $addFields: {
36567
- f_Available: {
36568
- $filter: {
36569
- input: "$accessCards",
36570
- as: "card",
36571
- cond: { $and: [{ $eq: ["$$card.userId", null] }, { $eq: ["$$card.isActivated", true] }] }
36572
- }
36573
- },
36574
- f_Assigned: {
36575
- $filter: {
36576
- input: "$accessCards",
36577
- as: "card",
36578
- cond: { $and: [{ $ne: ["$$card.userId", null] }, { $eq: ["$$card.isActivated", true] }] }
36579
- }
36580
- },
36581
- f_replaced: {
36582
- $filter: {
36583
- input: "$accessCards",
36584
- as: "card",
36585
- cond: { $and: [{ $eq: ["$$card.isActivated", false] }, { $ne: ["$$card.replacementStatus", null] }] }
36586
- }
36587
- },
36588
- f_deleted: {
36589
- $filter: {
36590
- input: "$accessCards",
36591
- as: "card",
36592
- cond: { $and: [{ $eq: ["$$card.isActivated", false] }, { $eq: ["$$card.replacementStatus", null] }] }
36801
+ f_replaced: {
36802
+ $filter: {
36803
+ input: "$accessCards",
36804
+ as: "card",
36805
+ cond: {
36806
+ $and: [
36807
+ { $eq: ["$$card.isActivated", false] },
36808
+ { $ne: ["$$card.replacementStatus", null] }
36809
+ ]
36810
+ }
36811
+ }
36812
+ },
36813
+ f_deleted: {
36814
+ $filter: {
36815
+ input: "$accessCards",
36816
+ as: "card",
36817
+ cond: {
36818
+ $and: [
36819
+ { $eq: ["$$card.isActivated", false] },
36820
+ { $eq: ["$$card.replacementStatus", null] }
36821
+ ]
36822
+ }
36823
+ }
36593
36824
  }
36594
36825
  }
36595
- }
36596
- },
36597
- // ✅ Final projection with all computed fields
36598
- {
36599
- $project: {
36600
- _id: "$level.units._id",
36601
- name: "$level.units.name",
36602
- level: { _id: "$level._id", level: "$level.level" },
36603
- block: { _id: "$_id", name: "$name", block: "$block" },
36604
- site: "$site",
36605
- unit_owner: { $arrayElemAt: ["$unitOwner", 0] },
36606
- available: {
36607
- physical: { $filter: { input: "$f_Available", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36608
- non_physical: { $filter: { input: "$f_Available", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36609
- },
36610
- assigned: {
36611
- physical: { $filter: { input: "$f_Assigned", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36612
- non_physical: { $filter: { input: "$f_Assigned", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36613
- },
36614
- cardCounts: {
36826
+ },
36827
+ // ✅ Final projection with all computed fields
36828
+ {
36829
+ $project: {
36830
+ _id: "$level.units._id",
36831
+ name: "$level.units.name",
36832
+ level: { _id: "$level._id", level: "$level.level" },
36833
+ block: { _id: "$_id", name: "$name", block: "$block" },
36834
+ site: "$site",
36835
+ unit_owner: { $arrayElemAt: ["$unitOwner", 0] },
36615
36836
  available: {
36616
- physical: { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36617
- non_physical: { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36837
+ physical: {
36838
+ $filter: {
36839
+ input: "$f_Available",
36840
+ as: "c",
36841
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36842
+ }
36843
+ },
36844
+ non_physical: {
36845
+ $filter: {
36846
+ input: "$f_Available",
36847
+ as: "c",
36848
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36849
+ }
36850
+ }
36618
36851
  },
36619
36852
  assigned: {
36620
- physical: { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36621
- non_physical: { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36853
+ physical: {
36854
+ $filter: {
36855
+ input: "$f_Assigned",
36856
+ as: "c",
36857
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36858
+ }
36859
+ },
36860
+ non_physical: {
36861
+ $filter: {
36862
+ input: "$f_Assigned",
36863
+ as: "c",
36864
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36865
+ }
36866
+ }
36867
+ },
36868
+ cardCounts: {
36869
+ available: {
36870
+ physical: {
36871
+ $size: {
36872
+ $filter: {
36873
+ input: { $ifNull: ["$f_Available", []] },
36874
+ as: "c",
36875
+ cond: {
36876
+ $eq: ["$$c.type", "NFC" /* NFC */]
36877
+ }
36878
+ }
36879
+ }
36880
+ },
36881
+ non_physical: {
36882
+ $size: {
36883
+ $filter: {
36884
+ input: { $ifNull: ["$f_Available", []] },
36885
+ as: "c",
36886
+ cond: {
36887
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36888
+ }
36889
+ }
36890
+ }
36891
+ }
36892
+ },
36893
+ assigned: {
36894
+ physical: {
36895
+ $size: {
36896
+ $filter: {
36897
+ input: { $ifNull: ["$f_Assigned", []] },
36898
+ as: "c",
36899
+ cond: {
36900
+ $eq: ["$$c.type", "NFC" /* NFC */]
36901
+ }
36902
+ }
36903
+ }
36904
+ },
36905
+ non_physical: {
36906
+ $size: {
36907
+ $filter: {
36908
+ input: { $ifNull: ["$f_Assigned", []] },
36909
+ as: "c",
36910
+ cond: {
36911
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36912
+ }
36913
+ }
36914
+ }
36915
+ }
36916
+ }
36917
+ },
36918
+ replaced: {
36919
+ physical: {
36920
+ $filter: {
36921
+ input: "$f_replaced",
36922
+ as: "c",
36923
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36924
+ }
36925
+ },
36926
+ non_physical: {
36927
+ $filter: {
36928
+ input: "$f_replaced",
36929
+ as: "c",
36930
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36931
+ }
36932
+ }
36933
+ },
36934
+ deleted: {
36935
+ physical: {
36936
+ $filter: {
36937
+ input: "$f_deleted",
36938
+ as: "c",
36939
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36940
+ }
36941
+ },
36942
+ non_physical: {
36943
+ $filter: {
36944
+ input: "$f_deleted",
36945
+ as: "c",
36946
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36947
+ }
36948
+ }
36949
+ },
36950
+ totalCardCount: {
36951
+ $add: [
36952
+ {
36953
+ $size: {
36954
+ $filter: {
36955
+ input: { $ifNull: ["$f_Available", []] },
36956
+ as: "c",
36957
+ cond: {
36958
+ $eq: ["$$c.type", "NFC" /* NFC */]
36959
+ }
36960
+ }
36961
+ }
36962
+ },
36963
+ {
36964
+ $size: {
36965
+ $filter: {
36966
+ input: { $ifNull: ["$f_Available", []] },
36967
+ as: "c",
36968
+ cond: {
36969
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36970
+ }
36971
+ }
36972
+ }
36973
+ },
36974
+ {
36975
+ $size: {
36976
+ $filter: {
36977
+ input: { $ifNull: ["$f_Assigned", []] },
36978
+ as: "c",
36979
+ cond: {
36980
+ $eq: ["$$c.type", "NFC" /* NFC */]
36981
+ }
36982
+ }
36983
+ }
36984
+ },
36985
+ {
36986
+ $size: {
36987
+ $filter: {
36988
+ input: { $ifNull: ["$f_Assigned", []] },
36989
+ as: "c",
36990
+ cond: {
36991
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36992
+ }
36993
+ }
36994
+ }
36995
+ }
36996
+ ]
36622
36997
  }
36623
- },
36624
- replaced: {
36625
- physical: { $filter: { input: "$f_replaced", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36626
- non_physical: { $filter: { input: "$f_replaced", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36627
- },
36628
- deleted: {
36629
- physical: { $filter: { input: "$f_deleted", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36630
- non_physical: { $filter: { input: "$f_deleted", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36631
- },
36632
- totalCardCount: {
36633
- $add: [
36634
- { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36635
- { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } },
36636
- { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36637
- { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36638
- ]
36639
36998
  }
36640
- }
36641
- },
36642
- { $sort: { totalCardCount: -1 } }
36643
- ]
36999
+ },
37000
+ { $sort: { totalCardCount: -1 } }
37001
+ ]
37002
+ }
36644
37003
  }
36645
- }
36646
- ], { allowDiskUse: true }).toArray();
37004
+ ],
37005
+ { allowDiskUse: true }
37006
+ ).toArray();
36647
37007
  const totalCount = result[0]?.totalCount?.[0]?.count ?? 0;
36648
37008
  const items = result[0]?.items ?? [];
36649
37009
  const paginatedResult = (0, import_node_server_utils154.paginate)(items, page, limit, totalCount);
@@ -36662,157 +37022,162 @@ function UseAccessManagementRepo() {
36662
37022
  site: { $in: [site] }
36663
37023
  };
36664
37024
  const searchQuery = buildSearchQuery(search);
36665
- const result = await collectionName("buildings").aggregate([
36666
- // ✅ Match early with index-friendly query
36667
- {
36668
- $match: {
36669
- ...query,
36670
- status: { $ne: "deleted" }
36671
- }
36672
- },
36673
- // ✅ Only project needed fields before heavy lookups
36674
- {
36675
- $project: {
36676
- _id: 1,
36677
- name: 1,
36678
- site: 1
36679
- }
36680
- },
36681
- // ✅ Use localField/foreignField for better index usage
36682
- {
36683
- $lookup: {
36684
- from: "building-levels",
36685
- localField: "_id",
36686
- foreignField: "block",
36687
- pipeline: [
36688
- { $match: { status: { $ne: "deleted" } } },
36689
- {
36690
- $lookup: {
36691
- from: "building-units",
36692
- localField: "_id",
36693
- foreignField: "level",
36694
- pipeline: [
36695
- { $match: { status: { $ne: "deleted" } } },
36696
- { $project: { _id: 1, name: 1 } },
36697
- {
36698
- $lookup: {
36699
- from: "access-cards",
36700
- localField: "_id",
36701
- foreignField: "assignedUnit",
36702
- pipeline: [
36703
- {
36704
- $match: {
36705
- isActivated: true,
36706
- userType,
36707
- type
36708
- }
36709
- },
36710
- {
36711
- $group: {
36712
- _id: null,
36713
- accessLevels: { $addToSet: "$accessLevel" },
36714
- liftAccessLevels: { $addToSet: "$liftAccessLevel" },
36715
- doorNames: { $addToSet: "$doorName" },
36716
- liftNames: { $addToSet: "$liftName" },
36717
- cards: {
36718
- $push: {
36719
- _id: "$_id",
36720
- cardNo: "$cardNo",
36721
- accessLevel: "$accessLevel",
36722
- liftAccessLevel: "$liftAccessLevel",
36723
- doorName: "$doorName",
36724
- liftName: "$liftName"
37025
+ const result = await collectionName("buildings").aggregate(
37026
+ [
37027
+ // ✅ Match early with index-friendly query
37028
+ {
37029
+ $match: {
37030
+ ...query,
37031
+ status: { $ne: "deleted" }
37032
+ }
37033
+ },
37034
+ // ✅ Only project needed fields before heavy lookups
37035
+ {
37036
+ $project: {
37037
+ _id: 1,
37038
+ name: 1,
37039
+ site: 1
37040
+ }
37041
+ },
37042
+ // ✅ Use localField/foreignField for better index usage
37043
+ {
37044
+ $lookup: {
37045
+ from: "building-levels",
37046
+ localField: "_id",
37047
+ foreignField: "block",
37048
+ pipeline: [
37049
+ { $match: { status: { $ne: "deleted" } } },
37050
+ {
37051
+ $lookup: {
37052
+ from: "building-units",
37053
+ localField: "_id",
37054
+ foreignField: "level",
37055
+ pipeline: [
37056
+ { $match: { status: { $ne: "deleted" } } },
37057
+ { $project: { _id: 1, name: 1 } },
37058
+ {
37059
+ $lookup: {
37060
+ from: "access-cards",
37061
+ localField: "_id",
37062
+ foreignField: "assignedUnit",
37063
+ pipeline: [
37064
+ {
37065
+ $match: {
37066
+ isActivated: true,
37067
+ userType,
37068
+ type
37069
+ }
37070
+ },
37071
+ {
37072
+ $group: {
37073
+ _id: null,
37074
+ accessLevels: { $addToSet: "$accessLevel" },
37075
+ liftAccessLevels: {
37076
+ $addToSet: "$liftAccessLevel"
37077
+ },
37078
+ doorNames: { $addToSet: "$doorName" },
37079
+ liftNames: { $addToSet: "$liftName" },
37080
+ cards: {
37081
+ $push: {
37082
+ _id: "$_id",
37083
+ cardNo: "$cardNo",
37084
+ accessLevel: "$accessLevel",
37085
+ liftAccessLevel: "$liftAccessLevel",
37086
+ doorName: "$doorName",
37087
+ liftName: "$liftName"
37088
+ }
36725
37089
  }
36726
37090
  }
37091
+ },
37092
+ {
37093
+ $project: {
37094
+ _id: 0,
37095
+ accessCardCount: {
37096
+ $size: "$cards"
37097
+ },
37098
+ accessLevels: 1,
37099
+ liftAccessLevels: 1,
37100
+ doorNames: 1,
37101
+ liftNames: 1
37102
+ }
36727
37103
  }
36728
- },
36729
- {
36730
- $project: {
36731
- _id: 0,
36732
- accessCardCount: {
36733
- $size: "$cards"
36734
- },
36735
- accessLevels: 1,
36736
- liftAccessLevels: 1,
36737
- doorNames: 1,
36738
- liftNames: 1
36739
- }
36740
- }
36741
- ],
36742
- as: "fAccessCards"
36743
- }
36744
- },
36745
- {
36746
- $match: {
36747
- "fAccessCards.0": { $exists: true }
37104
+ ],
37105
+ as: "fAccessCards"
37106
+ }
37107
+ },
37108
+ {
37109
+ $match: {
37110
+ "fAccessCards.0": { $exists: true }
37111
+ }
36748
37112
  }
36749
- }
36750
- ],
36751
- as: "units"
36752
- }
36753
- },
36754
- {
36755
- $match: { "units.0": { $exists: true } }
36756
- },
36757
- {
36758
- $project: {
36759
- _id: 1,
36760
- level: 1,
36761
- units: 1
37113
+ ],
37114
+ as: "units"
37115
+ }
37116
+ },
37117
+ {
37118
+ $match: { "units.0": { $exists: true } }
37119
+ },
37120
+ {
37121
+ $project: {
37122
+ _id: 1,
37123
+ level: 1,
37124
+ units: 1
37125
+ }
36762
37126
  }
36763
- }
36764
- ],
36765
- as: "level"
36766
- }
36767
- },
36768
- // ✅ Filter out buildings with no levels early
36769
- {
36770
- $match: { "level.0": { $exists: true } }
36771
- },
36772
- // ✅ Unwind to flatten the hierarchy
36773
- {
36774
- $unwind: {
36775
- path: "$level",
36776
- preserveNullAndEmptyArrays: false
36777
- }
36778
- },
36779
- {
36780
- $unwind: {
36781
- path: "$level.units",
36782
- preserveNullAndEmptyArrays: false
36783
- }
36784
- },
36785
- {
36786
- $unwind: {
36787
- path: "$level.units.fAccessCards",
36788
- preserveNullAndEmptyArrays: false
36789
- }
36790
- },
36791
- // // Groups by unit _id and keeps only the first occurrence
36792
- {
36793
- $group: {
36794
- _id: "$level.units._id",
36795
- doc: { $first: "$$ROOT" }
36796
- }
36797
- },
36798
- {
36799
- $replaceRoot: { newRoot: "$doc" }
36800
- },
36801
- // ✅ Apply search filter
36802
- {
36803
- $match: {
36804
- ...searchQuery
36805
- }
36806
- },
36807
- {
36808
- $project: {
36809
- name: 1,
36810
- "level.level": 1,
36811
- "level.units.name": 1,
36812
- "level.units.fAccessCards": 1
37127
+ ],
37128
+ as: "level"
37129
+ }
37130
+ },
37131
+ // ✅ Filter out buildings with no levels early
37132
+ {
37133
+ $match: { "level.0": { $exists: true } }
37134
+ },
37135
+ // ✅ Unwind to flatten the hierarchy
37136
+ {
37137
+ $unwind: {
37138
+ path: "$level",
37139
+ preserveNullAndEmptyArrays: false
37140
+ }
37141
+ },
37142
+ {
37143
+ $unwind: {
37144
+ path: "$level.units",
37145
+ preserveNullAndEmptyArrays: false
37146
+ }
37147
+ },
37148
+ {
37149
+ $unwind: {
37150
+ path: "$level.units.fAccessCards",
37151
+ preserveNullAndEmptyArrays: false
37152
+ }
37153
+ },
37154
+ // // Groups by unit _id and keeps only the first occurrence
37155
+ {
37156
+ $group: {
37157
+ _id: "$level.units._id",
37158
+ doc: { $first: "$$ROOT" }
37159
+ }
37160
+ },
37161
+ {
37162
+ $replaceRoot: { newRoot: "$doc" }
37163
+ },
37164
+ // ✅ Apply search filter
37165
+ {
37166
+ $match: {
37167
+ ...searchQuery
37168
+ }
37169
+ },
37170
+ {
37171
+ $project: {
37172
+ name: 1,
37173
+ "level.level": 1,
37174
+ "level.units.name": 1,
37175
+ "level.units.fAccessCards": 1
37176
+ }
36813
37177
  }
36814
- }
36815
- ], { allowDiskUse: true }).toArray();
37178
+ ],
37179
+ { allowDiskUse: true }
37180
+ ).toArray();
36816
37181
  return result;
36817
37182
  } catch (error) {
36818
37183
  throw new Error(error.message);
@@ -36823,8 +37188,12 @@ function UseAccessManagementRepo() {
36823
37188
  try {
36824
37189
  session?.startTransaction();
36825
37190
  const { userId, cardId, site } = params;
36826
- const allUserId = await Promise.all(userId.map(async (id) => new import_mongodb90.ObjectId(id)));
36827
- const allCardId = await Promise.all(cardId.map(async (id) => new import_mongodb90.ObjectId(id)));
37191
+ const allUserId = await Promise.all(
37192
+ userId.map(async (id) => new import_mongodb90.ObjectId(id))
37193
+ );
37194
+ const allCardId = await Promise.all(
37195
+ cardId.map(async (id) => new import_mongodb90.ObjectId(id))
37196
+ );
36828
37197
  const siteId = new import_mongodb90.ObjectId(site);
36829
37198
  const result = await collection().updateMany(
36830
37199
  {
@@ -36867,16 +37236,19 @@ function UseAccessManagementRepo() {
36867
37236
  liftAccessLevel,
36868
37237
  isActivated: true
36869
37238
  };
36870
- const result = await collection().aggregate([
36871
- {
36872
- $match: query
36873
- },
36874
- {
36875
- $facet: {
36876
- counts: [{ $count: "count" }]
37239
+ const result = await collection().aggregate(
37240
+ [
37241
+ {
37242
+ $match: query
37243
+ },
37244
+ {
37245
+ $facet: {
37246
+ counts: [{ $count: "count" }]
37247
+ }
36877
37248
  }
36878
- }
36879
- ], { allowDiskUse: true }).toArray();
37249
+ ],
37250
+ { allowDiskUse: true }
37251
+ ).toArray();
36880
37252
  return result;
36881
37253
  } catch (error) {
36882
37254
  throw new Error(error.message);
@@ -36910,7 +37282,9 @@ function UseAccessManagementRepo() {
36910
37282
  availableCardNo.push(num);
36911
37283
  num++;
36912
37284
  }
36913
- const cardNumbers = availableCardNo.map((no) => no.toString().padStart(10, "0"));
37285
+ const cardNumbers = availableCardNo.map(
37286
+ (no) => no.toString().padStart(10, "0")
37287
+ );
36914
37288
  const accessCards = [];
36915
37289
  const convertedUnits = unit.map((obj) => new import_mongodb90.ObjectId(obj));
36916
37290
  for (let j = 0; j < (unit.length > 0 ? unit.length : quantity); j++) {
@@ -36970,10 +37344,18 @@ function UseAccessManagementRepo() {
36970
37344
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
36971
37345
  accessGroup: ag
36972
37346
  };
36973
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
37347
+ return readTemplate(
37348
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
37349
+ { ...command }
37350
+ );
36974
37351
  }).flat();
36975
- const response = await sendCommand(commands.join("").toString(), params.acm_url);
36976
- const result = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
37352
+ const response = await sendCommand(
37353
+ commands.join("").toString(),
37354
+ params.acm_url
37355
+ );
37356
+ const result = await (0, import_xml2js2.parseStringPromise)(response, {
37357
+ explicitArray: false
37358
+ });
36977
37359
  if (result && result.RESULT.$.STCODE !== "0") {
36978
37360
  throw new Error("Command failed, server error.");
36979
37361
  }
@@ -37007,7 +37389,11 @@ function UseAccessManagementRepo() {
37007
37389
  } else {
37008
37390
  updateFields.isActivated = true;
37009
37391
  }
37010
- const res = await collection().updateOne({ _id: card._id }, { $set: updateFields }, { session });
37392
+ const res = await collection().updateOne(
37393
+ { _id: card._id },
37394
+ { $set: updateFields },
37395
+ { session }
37396
+ );
37011
37397
  results.push({ nfcId: nfc._id, modifiedCount: res.modifiedCount });
37012
37398
  }
37013
37399
  }
@@ -37034,8 +37420,20 @@ function UseAccessManagementRepo() {
37034
37420
  assignedUnit: null,
37035
37421
  userId: null,
37036
37422
  $or: [
37037
- { $and: [{ doorName: { $ne: null } }, { doorName: { $ne: "" } }, { accessLevel: { $ne: null } }] },
37038
- { $and: [{ liftName: { $ne: null } }, { liftName: { $ne: "" } }, { liftAccessLevel: { $ne: null } }] }
37423
+ {
37424
+ $and: [
37425
+ { doorName: { $ne: null } },
37426
+ { doorName: { $ne: "" } },
37427
+ { accessLevel: { $ne: null } }
37428
+ ]
37429
+ },
37430
+ {
37431
+ $and: [
37432
+ { liftName: { $ne: null } },
37433
+ { liftName: { $ne: "" } },
37434
+ { liftAccessLevel: { $ne: null } }
37435
+ ]
37436
+ }
37039
37437
  ]
37040
37438
  }
37041
37439
  },
@@ -37049,7 +37447,13 @@ function UseAccessManagementRepo() {
37049
37447
  accessLevels: {
37050
37448
  $addToSet: {
37051
37449
  $cond: [
37052
- { $and: [{ $ne: ["$doorName", null] }, { $ne: ["$doorName", ""] }, { $ne: ["$accessLevel", null] }] },
37450
+ {
37451
+ $and: [
37452
+ { $ne: ["$doorName", null] },
37453
+ { $ne: ["$doorName", ""] },
37454
+ { $ne: ["$accessLevel", null] }
37455
+ ]
37456
+ },
37053
37457
  { name: "$doorName", no: "$accessLevel" },
37054
37458
  "$$REMOVE"
37055
37459
  ]
@@ -37058,7 +37462,13 @@ function UseAccessManagementRepo() {
37058
37462
  liftAccessLevels: {
37059
37463
  $addToSet: {
37060
37464
  $cond: [
37061
- { $and: [{ $ne: ["$liftName", null] }, { $ne: ["$liftName", ""] }, { $ne: ["$liftAccessLevel", null] }] },
37465
+ {
37466
+ $and: [
37467
+ { $ne: ["$liftName", null] },
37468
+ { $ne: ["$liftName", ""] },
37469
+ { $ne: ["$liftAccessLevel", null] }
37470
+ ]
37471
+ },
37062
37472
  { name: "$liftName", no: "$liftAccessLevel" },
37063
37473
  "$$REMOVE"
37064
37474
  ]
@@ -37094,7 +37504,14 @@ function UseAccessManagementRepo() {
37094
37504
  const sessionResult = await Promise.all([
37095
37505
  await collection().findOneAndUpdate(
37096
37506
  { _id: id },
37097
- { $set: { remarks, replacementStatus: "Complete", requestDate: /* @__PURE__ */ new Date(), isActivated: false } },
37507
+ {
37508
+ $set: {
37509
+ remarks,
37510
+ replacementStatus: "Complete",
37511
+ requestDate: /* @__PURE__ */ new Date(),
37512
+ isActivated: false
37513
+ }
37514
+ },
37098
37515
  { returnDocument: "after", session }
37099
37516
  ),
37100
37517
  await collection().findOneAndUpdate(
@@ -37126,7 +37543,10 @@ function UseAccessManagementRepo() {
37126
37543
  isActivated: true
37127
37544
  };
37128
37545
  if (search) {
37129
- query.$or = [{ accessLevel: { $regex: search, $options: "i" } }, { cardNo: { $regex: search, $options: "i" } }];
37546
+ query.$or = [
37547
+ { accessLevel: { $regex: search, $options: "i" } },
37548
+ { cardNo: { $regex: search, $options: "i" } }
37549
+ ];
37130
37550
  }
37131
37551
  if (type) {
37132
37552
  query.userType = type;
@@ -37151,14 +37571,22 @@ function UseAccessManagementRepo() {
37151
37571
  {
37152
37572
  $addFields: {
37153
37573
  extractedCardNo: {
37154
- $substr: ["$cardNo", { $subtract: [{ $strLenCP: "$cardNo" }, 5] }, 5]
37574
+ $substr: [
37575
+ "$cardNo",
37576
+ { $subtract: [{ $strLenCP: "$cardNo" }, 5] },
37577
+ 5
37578
+ ]
37155
37579
  }
37156
37580
  }
37157
37581
  },
37158
37582
  {
37159
37583
  $facet: {
37160
37584
  totalCount: [{ $count: "count" }],
37161
- items: [{ $sort: { _id: -1 } }, { $skip: page * limit }, { $limit: limit }]
37585
+ items: [
37586
+ { $sort: { _id: -1 } },
37587
+ { $skip: page * limit },
37588
+ { $limit: limit }
37589
+ ]
37162
37590
  }
37163
37591
  }
37164
37592
  ]).toArray();
@@ -37189,145 +37617,151 @@ function UseAccessManagementRepo() {
37189
37617
  query.replacementStatus = statusFilter;
37190
37618
  }
37191
37619
  if (dateFrom && dateTo) {
37192
- query.requestDate = { $gte: new Date(dateFrom), $lte: new Date(dateTo) };
37620
+ query.requestDate = {
37621
+ $gte: new Date(dateFrom),
37622
+ $lte: new Date(dateTo)
37623
+ };
37193
37624
  } else if (dateFrom) {
37194
37625
  query.requestDate = { $gte: new Date(dateFrom) };
37195
37626
  } else if (dateTo) {
37196
37627
  query.requestDate = { $lte: new Date(dateTo) };
37197
37628
  }
37198
- const res = await collection().aggregate([
37199
- {
37200
- $match: { ...query }
37201
- },
37202
- {
37203
- $lookup: {
37204
- from: "building-units",
37205
- let: { unit: "$assignedUnit" },
37206
- pipeline: [
37207
- {
37208
- $match: {
37209
- $expr: {
37210
- $eq: ["$_id", "$$unit"]
37629
+ const res = await collection().aggregate(
37630
+ [
37631
+ {
37632
+ $match: { ...query }
37633
+ },
37634
+ {
37635
+ $lookup: {
37636
+ from: "building-units",
37637
+ let: { unit: "$assignedUnit" },
37638
+ pipeline: [
37639
+ {
37640
+ $match: {
37641
+ $expr: {
37642
+ $eq: ["$_id", "$$unit"]
37643
+ }
37211
37644
  }
37212
- }
37213
- },
37214
- {
37215
- $project: {
37216
- _id: 1,
37217
- name: 1,
37218
- level: 1
37219
- }
37220
- }
37221
- ],
37222
- as: "unit"
37223
- }
37224
- },
37225
- {
37226
- $unwind: { path: "$unit", preserveNullAndEmptyArrays: true }
37227
- },
37228
- {
37229
- $lookup: {
37230
- from: "building-levels",
37231
- let: { level: "$unit.level" },
37232
- pipeline: [
37233
- {
37234
- $match: {
37235
- $expr: {
37236
- $eq: ["$_id", "$$level"]
37645
+ },
37646
+ {
37647
+ $project: {
37648
+ _id: 1,
37649
+ name: 1,
37650
+ level: 1
37237
37651
  }
37238
37652
  }
37239
- },
37240
- {
37241
- $project: {
37242
- _id: 1,
37243
- level: 1,
37244
- block: 1
37245
- }
37246
- }
37247
- ],
37248
- as: "level"
37249
- }
37250
- },
37251
- {
37252
- $unwind: { path: "$level", preserveNullAndEmptyArrays: true }
37253
- },
37254
- {
37255
- $lookup: {
37256
- from: "buildings",
37257
- let: { block: "$level.block" },
37258
- pipeline: [
37259
- {
37260
- $match: {
37261
- $expr: {
37262
- $eq: ["$_id", "$$block"]
37653
+ ],
37654
+ as: "unit"
37655
+ }
37656
+ },
37657
+ {
37658
+ $unwind: { path: "$unit", preserveNullAndEmptyArrays: true }
37659
+ },
37660
+ {
37661
+ $lookup: {
37662
+ from: "building-levels",
37663
+ let: { level: "$unit.level" },
37664
+ pipeline: [
37665
+ {
37666
+ $match: {
37667
+ $expr: {
37668
+ $eq: ["$_id", "$$level"]
37669
+ }
37670
+ }
37671
+ },
37672
+ {
37673
+ $project: {
37674
+ _id: 1,
37675
+ level: 1,
37676
+ block: 1
37263
37677
  }
37264
37678
  }
37265
- },
37266
- {
37267
- $project: {
37268
- _id: 1,
37269
- name: 1
37270
- }
37271
- }
37272
- ],
37273
- as: "building"
37274
- }
37275
- },
37276
- {
37277
- $unwind: { path: "$building", preserveNullAndEmptyArrays: true }
37278
- },
37279
- {
37280
- $lookup: {
37281
- from: "users",
37282
- let: { id: "$userId" },
37283
- pipeline: [
37284
- {
37285
- $match: {
37286
- $expr: {
37287
- $eq: ["$_id", "$$id"]
37679
+ ],
37680
+ as: "level"
37681
+ }
37682
+ },
37683
+ {
37684
+ $unwind: { path: "$level", preserveNullAndEmptyArrays: true }
37685
+ },
37686
+ {
37687
+ $lookup: {
37688
+ from: "buildings",
37689
+ let: { block: "$level.block" },
37690
+ pipeline: [
37691
+ {
37692
+ $match: {
37693
+ $expr: {
37694
+ $eq: ["$_id", "$$block"]
37695
+ }
37696
+ }
37697
+ },
37698
+ {
37699
+ $project: {
37700
+ _id: 1,
37701
+ name: 1
37288
37702
  }
37289
37703
  }
37290
- },
37291
- {
37292
- $project: {
37293
- givenName: 1,
37294
- surname: 1
37704
+ ],
37705
+ as: "building"
37706
+ }
37707
+ },
37708
+ {
37709
+ $unwind: { path: "$building", preserveNullAndEmptyArrays: true }
37710
+ },
37711
+ {
37712
+ $lookup: {
37713
+ from: "users",
37714
+ let: { id: "$userId" },
37715
+ pipeline: [
37716
+ {
37717
+ $match: {
37718
+ $expr: {
37719
+ $eq: ["$_id", "$$id"]
37720
+ }
37721
+ }
37722
+ },
37723
+ {
37724
+ $project: {
37725
+ givenName: 1,
37726
+ surname: 1
37727
+ }
37295
37728
  }
37296
- }
37297
- ],
37298
- as: "user"
37299
- }
37300
- },
37301
- {
37302
- $unwind: { path: "$user", preserveNullAndEmptyArrays: true }
37303
- },
37304
- {
37305
- $match: { ...searchQuery }
37306
- },
37307
- {
37308
- $facet: {
37309
- data: [
37310
- { $skip: page * limit },
37311
- { $limit: limit },
37312
- {
37313
- $project: {
37314
- _id: 1,
37315
- cardNo: 1,
37316
- accessLevel: 1,
37317
- liftAccessLevel: 1,
37318
- replacementStatus: 1,
37319
- remarks: 1,
37320
- block: "$building.name",
37321
- level: "$level.level",
37322
- unit: "$unit.name",
37323
- user: "$user"
37729
+ ],
37730
+ as: "user"
37731
+ }
37732
+ },
37733
+ {
37734
+ $unwind: { path: "$user", preserveNullAndEmptyArrays: true }
37735
+ },
37736
+ {
37737
+ $match: { ...searchQuery }
37738
+ },
37739
+ {
37740
+ $facet: {
37741
+ data: [
37742
+ { $skip: page * limit },
37743
+ { $limit: limit },
37744
+ {
37745
+ $project: {
37746
+ _id: 1,
37747
+ cardNo: 1,
37748
+ accessLevel: 1,
37749
+ liftAccessLevel: 1,
37750
+ replacementStatus: 1,
37751
+ remarks: 1,
37752
+ block: "$building.name",
37753
+ level: "$level.level",
37754
+ unit: "$unit.name",
37755
+ user: "$user"
37756
+ }
37324
37757
  }
37325
- }
37326
- ],
37327
- totalCount: [{ $count: "count" }]
37758
+ ],
37759
+ totalCount: [{ $count: "count" }]
37760
+ }
37328
37761
  }
37329
- }
37330
- ], { allowDiskUse: true }).toArray();
37762
+ ],
37763
+ { allowDiskUse: true }
37764
+ ).toArray();
37331
37765
  const count = res[0]?.totalCount[0] ? res[0].totalCount[0].count : 0;
37332
37766
  const pagination = (0, import_node_server_utils154.paginate)(res[0].data, page, limit, count);
37333
37767
  return pagination;
@@ -37339,7 +37773,10 @@ function UseAccessManagementRepo() {
37339
37773
  try {
37340
37774
  const { site } = params;
37341
37775
  const siteId = new import_mongodb90.ObjectId(site);
37342
- const res = await collectionName("entrypass-settings").findOne({ site: siteId }, { allowDiskUse: true });
37776
+ const res = await collectionName("entrypass-settings").findOne(
37777
+ { site: siteId },
37778
+ { allowDiskUse: true }
37779
+ );
37343
37780
  return res;
37344
37781
  } catch (error) {
37345
37782
  throw new Error(error.message);
@@ -37349,13 +37786,19 @@ function UseAccessManagementRepo() {
37349
37786
  const session = import_node_server_utils154.useAtlas.getClient()?.startSession();
37350
37787
  try {
37351
37788
  const { dataJson, site } = params;
37352
- const rawItems = JSON.parse(dataJson).filter((_, index) => index !== -1);
37789
+ const rawItems = JSON.parse(dataJson).filter(
37790
+ (_, index) => index !== -1
37791
+ );
37353
37792
  const items = await Promise.all(
37354
37793
  rawItems.map(async (item) => {
37355
37794
  const date = new Date(item["startDate (format MM/DD/YYYY)"]);
37356
37795
  const endDate = new Date(date.setFullYear(date.getFullYear() + 10));
37357
- const cardNumber = String(Number(item["cardNo (number 0-65535 ex. 301)"] || 0)).padStart(6, "0");
37358
- const facilityCode = String(Number(item["facilityCode (number 0-255 ex. 11)"] || 0)).padStart(4, "0");
37796
+ const cardNumber = String(
37797
+ Number(item["cardNo (number 0-65535 ex. 301)"] || 0)
37798
+ ).padStart(6, "0");
37799
+ const facilityCode = String(
37800
+ Number(item["facilityCode (number 0-255 ex. 11)"] || 0)
37801
+ ).padStart(4, "0");
37359
37802
  const pin = item["pin (number 6 digits only)"] ? item["pin (number 6 digits only)"].toString().padStart(6, "0") : "123456";
37360
37803
  const match = item["accessLevel (number ex. 1)"];
37361
37804
  const accessLevel = match ? match : null;
@@ -37386,7 +37829,10 @@ function UseAccessManagementRepo() {
37386
37829
  });
37387
37830
  })
37388
37831
  );
37389
- const result = await collection().insertMany(items, { session, ordered: false });
37832
+ const result = await collection().insertMany(items, {
37833
+ session,
37834
+ ordered: false
37835
+ });
37390
37836
  const mapping = items.map((item, i) => ({
37391
37837
  cardNo: item.cardNo,
37392
37838
  insertedId: result.insertedIds[i]
@@ -37401,8 +37847,19 @@ function UseAccessManagementRepo() {
37401
37847
  let isAborted = false;
37402
37848
  try {
37403
37849
  await session?.startTransaction();
37404
- const { units, quantity, type, site, userType, accessLevel, liftAccessLevel } = params;
37405
- const [convertedUnits, convertedSite] = await Promise.all([Promise.all(units.map((id) => new import_mongodb90.ObjectId(id))), new import_mongodb90.ObjectId(site)]);
37850
+ const {
37851
+ units,
37852
+ quantity,
37853
+ type,
37854
+ site,
37855
+ userType,
37856
+ accessLevel,
37857
+ liftAccessLevel
37858
+ } = params;
37859
+ const [convertedUnits, convertedSite] = await Promise.all([
37860
+ Promise.all(units.map((id) => new import_mongodb90.ObjectId(id))),
37861
+ new import_mongodb90.ObjectId(site)
37862
+ ]);
37406
37863
  const totalRequired = quantity * convertedUnits.length;
37407
37864
  const availableCards = await collection().find({
37408
37865
  assignedUnit: null,
@@ -37422,16 +37879,18 @@ function UseAccessManagementRepo() {
37422
37879
  message: `Insufficient ${type} access cards. Need ${totalRequired}, but only ${availableCards.length} available.`
37423
37880
  };
37424
37881
  }
37425
- const bulkUpdates = availableCards.map((card, index) => ({
37426
- updateOne: {
37427
- filter: { _id: card._id },
37428
- update: {
37429
- $set: {
37430
- assignedUnit: convertedUnits[Math.floor(index / quantity)]
37882
+ const bulkUpdates = availableCards.map(
37883
+ (card, index) => ({
37884
+ updateOne: {
37885
+ filter: { _id: card._id },
37886
+ update: {
37887
+ $set: {
37888
+ assignedUnit: convertedUnits[Math.floor(index / quantity)]
37889
+ }
37431
37890
  }
37432
37891
  }
37433
- }
37434
- }));
37892
+ })
37893
+ );
37435
37894
  await collection().bulkWrite(bulkUpdates, { session });
37436
37895
  await session?.commitTransaction();
37437
37896
  return {
@@ -37452,7 +37911,18 @@ function UseAccessManagementRepo() {
37452
37911
  try {
37453
37912
  const { cardId, remarks } = params;
37454
37913
  const id = new import_mongodb90.ObjectId(cardId);
37455
- const result = await collection().findOneAndUpdate({ _id: id }, { $set: { isActivated: false, updatedAt: /* @__PURE__ */ new Date(), remarks, requestDate: /* @__PURE__ */ new Date() } }, { returnDocument: "after" });
37914
+ const result = await collection().findOneAndUpdate(
37915
+ { _id: id },
37916
+ {
37917
+ $set: {
37918
+ isActivated: false,
37919
+ updatedAt: /* @__PURE__ */ new Date(),
37920
+ remarks,
37921
+ requestDate: /* @__PURE__ */ new Date()
37922
+ }
37923
+ },
37924
+ { returnDocument: "after" }
37925
+ );
37456
37926
  return result;
37457
37927
  } catch (error) {
37458
37928
  throw new Error(error.message);
@@ -37513,7 +37983,13 @@ function UseAccessManagementRepo() {
37513
37983
  const { site, payload } = params;
37514
37984
  const id = new import_mongodb90.ObjectId(site);
37515
37985
  const highestCardNo = await collection().aggregate([
37516
- { $match: { site: id, type: "NFC" /* NFC */, userType: "Visitor/Resident" /* DEFAULT */ } },
37986
+ {
37987
+ $match: {
37988
+ site: id,
37989
+ type: "NFC" /* NFC */,
37990
+ userType: "Visitor/Resident" /* DEFAULT */
37991
+ }
37992
+ },
37517
37993
  {
37518
37994
  $addFields: {
37519
37995
  qrTagCardNoNumeric: { $toInt: "$qrTagCardNo" }
@@ -37533,14 +38009,19 @@ function UseAccessManagementRepo() {
37533
38009
  if (highestCardNo.length > 0) {
37534
38010
  start = highestCardNo[0].qrTagCardNoNumeric || 0;
37535
38011
  }
37536
- const nextCardNumbers = Array.from({ length: payload.length }, (_, i) => String(start + i + 1).padStart(5, "0"));
38012
+ const nextCardNumbers = Array.from(
38013
+ { length: payload.length },
38014
+ (_, i) => String(start + i + 1).padStart(5, "0")
38015
+ );
37537
38016
  const bulkOps = await Promise.all(
37538
38017
  payload.map(async (doc, index) => {
37539
38018
  const id2 = new import_mongodb90.ObjectId(doc._id);
37540
38019
  return {
37541
38020
  updateOne: {
37542
38021
  filter: { _id: id2 },
37543
- update: { $set: { qrTag: doc.qrTag, qrTagCardNo: nextCardNumbers[index] } }
38022
+ update: {
38023
+ $set: { qrTag: doc.qrTag, qrTagCardNo: nextCardNumbers[index] }
38024
+ }
37544
38025
  }
37545
38026
  };
37546
38027
  })
@@ -37582,7 +38063,11 @@ function UseAccessManagementRepo() {
37582
38063
  {
37583
38064
  $addFields: {
37584
38065
  extractedCardNo: {
37585
- $substr: ["$cardNo", { $subtract: [{ $strLenCP: "$cardNo" }, 5] }, 5]
38066
+ $substr: [
38067
+ "$cardNo",
38068
+ { $subtract: [{ $strLenCP: "$cardNo" }, 5] },
38069
+ 5
38070
+ ]
37586
38071
  }
37587
38072
  }
37588
38073
  },
@@ -37620,7 +38105,11 @@ function UseAccessManagementRepo() {
37620
38105
  },
37621
38106
  {
37622
38107
  $facet: {
37623
- items: [{ $skip: page * limit }, { $limit: limit }, { $project: { cardNo: 1 } }],
38108
+ items: [
38109
+ { $skip: page * limit },
38110
+ { $limit: limit },
38111
+ { $project: { cardNo: 1 } }
38112
+ ],
37624
38113
  totalCounts: [{ $count: "count" }]
37625
38114
  }
37626
38115
  }
@@ -37631,7 +38120,9 @@ function UseAccessManagementRepo() {
37631
38120
  _id: unitId
37632
38121
  }
37633
38122
  },
37634
- { $project: { _id: 1, name: 1, buildingName: 1, block: 1, level: 1 } },
38123
+ {
38124
+ $project: { _id: 1, name: 1, buildingName: 1, block: 1, level: 1 }
38125
+ },
37635
38126
  {
37636
38127
  $lookup: {
37637
38128
  from: "building-levels",
@@ -37719,7 +38210,18 @@ function UseAccessManagementRepo() {
37719
38210
  items: [
37720
38211
  { $skip: 0 },
37721
38212
  { $limit: 1 },
37722
- { $project: { _id: -1, accessLevel: 1, accessGroup: 1, userType: 1, doorName: 1, liftName: 1, liftAccessLevel: 1, isLiftCard: 1 } }
38213
+ {
38214
+ $project: {
38215
+ _id: -1,
38216
+ accessLevel: 1,
38217
+ accessGroup: 1,
38218
+ userType: 1,
38219
+ doorName: 1,
38220
+ liftName: 1,
38221
+ liftAccessLevel: 1,
38222
+ isLiftCard: 1
38223
+ }
38224
+ }
37723
38225
  ]
37724
38226
  }
37725
38227
  }
@@ -37768,13 +38270,25 @@ function UseAccessManagementRepo() {
37768
38270
  cardsToAttach = [...cardsId];
37769
38271
  } else if (type === "NFC" /* NFC */) {
37770
38272
  if (nfcCards && nfcCards.length > 0) {
37771
- const objectIds = nfcCards.map((card) => new import_mongodb90.ObjectId(card._id));
38273
+ const objectIds = nfcCards.map(
38274
+ (card) => new import_mongodb90.ObjectId(card._id)
38275
+ );
37772
38276
  cards = await collection().find({ _id: { $in: objectIds } }).toArray();
37773
- const nfcList = objectIds.map((card) => ({ _id: card, status: "In use", updatedAt: /* @__PURE__ */ new Date() }));
38277
+ const nfcList = objectIds.map((card) => ({
38278
+ _id: card,
38279
+ status: "In use",
38280
+ updatedAt: /* @__PURE__ */ new Date()
38281
+ }));
37774
38282
  cardsToAttach = [...nfcList];
37775
38283
  }
37776
38284
  }
37777
- const result = await collectionName("visitor.transactions").findOneAndUpdate({ _id: visitorId }, { $push: { cards: cardsToAttach } }, { session, returnDocument: "after" });
38285
+ const result = await collectionName(
38286
+ "visitor.transactions"
38287
+ ).findOneAndUpdate(
38288
+ { _id: visitorId },
38289
+ { $push: { cards: cardsToAttach } },
38290
+ { session, returnDocument: "after" }
38291
+ );
37778
38292
  const updatedVisitor = result?._id;
37779
38293
  const assignCards = cards.map((card) => card._id);
37780
38294
  if (assignCards.length > 0) {
@@ -37830,10 +38344,18 @@ function UseAccessManagementRepo() {
37830
38344
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
37831
38345
  accessGroup: ag
37832
38346
  };
37833
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
38347
+ return readTemplate(
38348
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
38349
+ { ...command }
38350
+ );
37834
38351
  }).flat();
37835
- const response = await sendCommand(commands.join("").toString(), acm_url);
37836
- serverResult = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
38352
+ const response = await sendCommand(
38353
+ commands.join("").toString(),
38354
+ acm_url
38355
+ );
38356
+ serverResult = await (0, import_xml2js2.parseStringPromise)(response, {
38357
+ explicitArray: false
38358
+ });
37837
38359
  if (result && serverResult.RESULT.$.STCODE !== "0") {
37838
38360
  throw new Error("Command failed, server error.");
37839
38361
  }
@@ -37882,7 +38404,10 @@ function UseAccessManagementRepo() {
37882
38404
  try {
37883
38405
  await session?.startTransaction();
37884
38406
  const userId = new import_mongodb90.ObjectId(params.userId);
37885
- const result = await collection().updateMany({ userId }, { $set: { userId: null, status: "Available", updatedAt: /* @__PURE__ */ new Date() } });
38407
+ const result = await collection().updateMany(
38408
+ { userId },
38409
+ { $set: { userId: null, status: "Available", updatedAt: /* @__PURE__ */ new Date() } }
38410
+ );
37886
38411
  await session?.commitTransaction();
37887
38412
  return result;
37888
38413
  } catch (error) {
@@ -37926,7 +38451,15 @@ function UseAccessManagementRepo() {
37926
38451
  foreignField: "level",
37927
38452
  pipeline: [
37928
38453
  { $match: { status: { $ne: "deleted" } } },
37929
- { $project: { _id: 1, name: 1, buildingName: 1, level: 1, block: 1 } }
38454
+ {
38455
+ $project: {
38456
+ _id: 1,
38457
+ name: 1,
38458
+ buildingName: 1,
38459
+ level: 1,
38460
+ block: 1
38461
+ }
38462
+ }
37930
38463
  ],
37931
38464
  as: "units"
37932
38465
  }
@@ -37947,11 +38480,20 @@ function UseAccessManagementRepo() {
37947
38480
  throw new Error(error.message);
37948
38481
  }
37949
38482
  }
37950
- async function getTransactionsRepo({ page = 1, limit = 10, site, cardNo, url }) {
38483
+ async function getTransactionsRepo({
38484
+ page = 1,
38485
+ limit = 10,
38486
+ site,
38487
+ cardNo,
38488
+ url
38489
+ }) {
37951
38490
  page = page ? page - 1 : 0;
37952
38491
  site = new import_mongodb90.ObjectId(site);
37953
38492
  try {
37954
- let index = await collectionName("access-card-transactions").findOne({}, { sort: { index: -1 } });
38493
+ let index = await collectionName("access-card-transactions").findOne(
38494
+ {},
38495
+ { sort: { index: -1 } }
38496
+ );
37955
38497
  index = index ? index.index : 0;
37956
38498
  const response = await getTransactions(index, url);
37957
38499
  if (response && Array.isArray(response.items) && response.items.length > 0) {
@@ -37960,7 +38502,9 @@ function UseAccessManagementRepo() {
37960
38502
  data: JSON.parse(item.data),
37961
38503
  timestamp: item.timestamp
37962
38504
  }));
37963
- result2 = result2.filter((item) => item.data.Event.ETYPE === "0" && item.data.Event.CARDNO !== "");
38505
+ result2 = result2.filter(
38506
+ (item) => item.data.Event.ETYPE === "0" && item.data.Event.CARDNO !== ""
38507
+ );
37964
38508
  if (result2.length > 0) {
37965
38509
  const transactions = result2.map(
37966
38510
  (item) => new MAccessCardTransaction({
@@ -37971,11 +38515,16 @@ function UseAccessManagementRepo() {
37971
38515
  accessType: item.data.Event.DEVNAME,
37972
38516
  accessStatus: item.data.Event.TRCODE,
37973
38517
  description: item.data.Event.TRDESC,
37974
- accessTime: entryPassDate(item.data.Event.TRDATE, item.data.Event.TRTIME),
38518
+ accessTime: entryPassDate(
38519
+ item.data.Event.TRDATE,
38520
+ item.data.Event.TRTIME
38521
+ ),
37975
38522
  createdAt: /* @__PURE__ */ new Date()
37976
38523
  })
37977
38524
  );
37978
- await collectionName("access-card-transactions").insertMany(transactions);
38525
+ await collectionName("access-card-transactions").insertMany(
38526
+ transactions
38527
+ );
37979
38528
  }
37980
38529
  }
37981
38530
  const result = await collectionName("access-card-transactions").aggregate([
@@ -38046,7 +38595,11 @@ function UseAccessManagementRepo() {
38046
38595
  {
38047
38596
  $facet: {
38048
38597
  totalCount: [{ $count: "count" }],
38049
- items: [{ $sort: { _id: -1 } }, { $skip: page * limit }, { $limit: limit }]
38598
+ items: [
38599
+ { $sort: { _id: -1 } },
38600
+ { $skip: page * limit },
38601
+ { $limit: limit }
38602
+ ]
38050
38603
  }
38051
38604
  }
38052
38605
  ]).toArray();
@@ -38069,7 +38622,9 @@ function UseAccessManagementRepo() {
38069
38622
  if (assignees.length < 1) {
38070
38623
  throw new Error("No user to Assign.");
38071
38624
  }
38072
- assignees = assignees.map((data) => new import_mongodb90.ObjectId(data));
38625
+ assignees = assignees.map(
38626
+ (data) => new import_mongodb90.ObjectId(data)
38627
+ );
38073
38628
  unit = new import_mongodb90.ObjectId(unit);
38074
38629
  let availableCards = [];
38075
38630
  let update = [];
@@ -38079,7 +38634,18 @@ function UseAccessManagementRepo() {
38079
38634
  $match: {
38080
38635
  $expr: {
38081
38636
  $and: [
38082
- { $eq: ["$assignedUnit", unit] },
38637
+ {
38638
+ $in: [
38639
+ unit,
38640
+ {
38641
+ $cond: [
38642
+ { $isArray: "$assignedUnit" },
38643
+ "$assignedUnit",
38644
+ ["$assignedUnit"]
38645
+ ]
38646
+ }
38647
+ ]
38648
+ },
38083
38649
  { $eq: ["$userId", null] },
38084
38650
  { $eq: ["$type", type] },
38085
38651
  { $eq: ["$isActivated", true] }
@@ -38096,7 +38662,10 @@ function UseAccessManagementRepo() {
38096
38662
  card.staffNo = userId.toString().slice(-10);
38097
38663
  return card;
38098
38664
  });
38099
- update = availableCards.slice(0, assignees.length).map((card, index) => ({ _id: card._id, userId: new import_mongodb90.ObjectId(assignees[index]) }));
38665
+ update = availableCards.slice(0, assignees.length).map((card, index) => ({
38666
+ _id: card._id,
38667
+ userId: new import_mongodb90.ObjectId(assignees[index])
38668
+ }));
38100
38669
  const commands = cards.map((item, index) => {
38101
38670
  let ag = null;
38102
38671
  if (item.accessGroup !== void 0) {
@@ -38126,16 +38695,27 @@ function UseAccessManagementRepo() {
38126
38695
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
38127
38696
  accessGroup: ag
38128
38697
  };
38129
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
38698
+ return readTemplate(
38699
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
38700
+ { ...command }
38701
+ );
38130
38702
  }).flat();
38131
38703
  const response = await sendCommand(commands.join("").toString(), acm_url);
38132
- const result = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
38704
+ const result = await (0, import_xml2js2.parseStringPromise)(response, {
38705
+ explicitArray: false
38706
+ });
38133
38707
  console.log("status code", result.RESULT.$.STCODE);
38134
38708
  if (result && result.RESULT.$.STCODE !== "0") {
38135
38709
  throw new Error("Command failed, server error.");
38136
38710
  }
38137
38711
  for (const { _id, userId } of update) {
38138
- await collection().updateOne({ _id }, { $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` } }, { session });
38712
+ await collection().updateOne(
38713
+ { _id },
38714
+ {
38715
+ $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` }
38716
+ },
38717
+ { session }
38718
+ );
38139
38719
  }
38140
38720
  await session?.commitTransaction();
38141
38721
  return "Cards assigned successfully.";
@@ -38151,7 +38731,11 @@ function UseAccessManagementRepo() {
38151
38731
  try {
38152
38732
  session?.startTransaction();
38153
38733
  const id = new import_mongodb90.ObjectId(userId);
38154
- await collection().updateMany({ userId: id }, { $set: { userId: null, status: "Available" } }, { session });
38734
+ await collection().updateMany(
38735
+ { userId: id },
38736
+ { $set: { userId: null, status: "Available" } },
38737
+ { session }
38738
+ );
38155
38739
  session?.commitTransaction();
38156
38740
  return "Successful Checkout";
38157
38741
  } catch (error) {
@@ -38161,7 +38745,11 @@ function UseAccessManagementRepo() {
38161
38745
  await session?.endSession();
38162
38746
  }
38163
38747
  }
38164
- async function uploadTemplateRepo({ site, id, name }) {
38748
+ async function uploadTemplateRepo({
38749
+ site,
38750
+ id,
38751
+ name
38752
+ }) {
38165
38753
  site = new import_mongodb90.ObjectId(site);
38166
38754
  id = new import_mongodb90.ObjectId(id);
38167
38755
  try {
@@ -38174,6 +38762,46 @@ function UseAccessManagementRepo() {
38174
38762
  throw new Error(error.message);
38175
38763
  }
38176
38764
  }
38765
+ async function getResidentsRepo({
38766
+ orgId,
38767
+ siteId,
38768
+ unitId
38769
+ }) {
38770
+ try {
38771
+ orgId = new import_mongodb90.ObjectId(orgId);
38772
+ siteId = new import_mongodb90.ObjectId(siteId);
38773
+ unitId = new import_mongodb90.ObjectId(unitId);
38774
+ const result = await collectionName("users").aggregate([
38775
+ {
38776
+ $match: {
38777
+ $expr: {
38778
+ $and: [
38779
+ { $eq: ["$defaultOrg", orgId] },
38780
+ { $eq: ["$site", siteId] },
38781
+ { $eq: ["$unitId", unitId] }
38782
+ ]
38783
+ }
38784
+ }
38785
+ },
38786
+ {
38787
+ $project: {
38788
+ _id: 1,
38789
+ email: 1,
38790
+ unitName: 1,
38791
+ type: 1,
38792
+ status: 1,
38793
+ name: 1,
38794
+ defaultOrg: 1,
38795
+ site: 1,
38796
+ unitId: 1
38797
+ }
38798
+ }
38799
+ ]).toArray();
38800
+ return result;
38801
+ } catch (error) {
38802
+ throw new Error(error.message);
38803
+ }
38804
+ }
38177
38805
  return {
38178
38806
  createIndexes,
38179
38807
  createIndexForEntrypass,
@@ -38209,7 +38837,8 @@ function UseAccessManagementRepo() {
38209
38837
  getTransactionsRepo,
38210
38838
  assignMultipleCardsRepo,
38211
38839
  visitorCheckoutRepo,
38212
- uploadTemplateRepo
38840
+ uploadTemplateRepo,
38841
+ getResidentsRepo
38213
38842
  };
38214
38843
  }
38215
38844
 
@@ -38253,7 +38882,8 @@ function useAccessManagementSvc() {
38253
38882
  getTransactionsRepo,
38254
38883
  assignMultipleCardsRepo,
38255
38884
  visitorCheckoutRepo,
38256
- uploadTemplateRepo
38885
+ uploadTemplateRepo,
38886
+ getResidentsRepo
38257
38887
  } = UseAccessManagementRepo();
38258
38888
  const addPhysicalCardSvc = async (payload) => {
38259
38889
  try {
@@ -38545,17 +39175,39 @@ function useAccessManagementSvc() {
38545
39175
  throw new Error(err.message);
38546
39176
  }
38547
39177
  };
38548
- const getTransactionsSvc = async ({ page, limit, site, cardNo, url }) => {
39178
+ const getTransactionsSvc = async ({
39179
+ page,
39180
+ limit,
39181
+ site,
39182
+ cardNo,
39183
+ url
39184
+ }) => {
38549
39185
  try {
38550
- const response = await getTransactionsRepo({ page, limit, site, cardNo, url });
39186
+ const response = await getTransactionsRepo({
39187
+ page,
39188
+ limit,
39189
+ site,
39190
+ cardNo,
39191
+ url
39192
+ });
38551
39193
  return response;
38552
39194
  } catch (err) {
38553
39195
  throw new Error(err.message);
38554
39196
  }
38555
39197
  };
38556
- const assignMultipleCardsSvc = async ({ assignees, unit, type, acm_url }) => {
39198
+ const assignMultipleCardsSvc = async ({
39199
+ assignees,
39200
+ unit,
39201
+ type,
39202
+ acm_url
39203
+ }) => {
38557
39204
  try {
38558
- const response = await assignMultipleCardsRepo({ assignees, unit, type, acm_url });
39205
+ const response = await assignMultipleCardsRepo({
39206
+ assignees,
39207
+ unit,
39208
+ type,
39209
+ acm_url
39210
+ });
38559
39211
  return response;
38560
39212
  } catch (err) {
38561
39213
  throw new Error(err.message);
@@ -38569,7 +39221,11 @@ function useAccessManagementSvc() {
38569
39221
  throw new Error(err.message);
38570
39222
  }
38571
39223
  };
38572
- const uploadTemplateSvc = async ({ site, id, name }) => {
39224
+ const uploadTemplateSvc = async ({
39225
+ site,
39226
+ id,
39227
+ name
39228
+ }) => {
38573
39229
  try {
38574
39230
  const response = await uploadTemplateRepo({ site, id, name });
38575
39231
  return response;
@@ -38577,6 +39233,18 @@ function useAccessManagementSvc() {
38577
39233
  throw new Error(err.message);
38578
39234
  }
38579
39235
  };
39236
+ const getResidentsSvc = async ({
39237
+ orgId,
39238
+ siteId,
39239
+ unitId
39240
+ }) => {
39241
+ try {
39242
+ const response = await getResidentsRepo({ orgId, siteId, unitId });
39243
+ return response;
39244
+ } catch (err) {
39245
+ throw new Error(err.message);
39246
+ }
39247
+ };
38580
39248
  return {
38581
39249
  addPhysicalCardSvc,
38582
39250
  addNonPhysicalCardSvc,
@@ -38615,7 +39283,8 @@ function useAccessManagementSvc() {
38615
39283
  getTransactionsSvc,
38616
39284
  assignMultipleCardsSvc,
38617
39285
  visitorCheckoutSvc,
38618
- uploadTemplateSvc
39286
+ uploadTemplateSvc,
39287
+ getResidentsSvc
38619
39288
  };
38620
39289
  }
38621
39290
 
@@ -38659,7 +39328,8 @@ function useAccessManagementController() {
38659
39328
  getTransactionsSvc,
38660
39329
  assignMultipleCardsSvc,
38661
39330
  visitorCheckoutSvc,
38662
- uploadTemplateSvc
39331
+ uploadTemplateSvc,
39332
+ getResidentsSvc
38663
39333
  } = useAccessManagementSvc();
38664
39334
  const addPhysicalCard = async (req, res) => {
38665
39335
  try {
@@ -38908,11 +39578,25 @@ function useAccessManagementController() {
38908
39578
  search: import_joi86.default.string().optional().allow("", null),
38909
39579
  userType: import_joi86.default.string().required()
38910
39580
  });
38911
- const { error } = schema2.validate({ page, limit, site, organization, search, userType });
39581
+ const { error } = schema2.validate({
39582
+ page,
39583
+ limit,
39584
+ site,
39585
+ organization,
39586
+ search,
39587
+ userType
39588
+ });
38912
39589
  if (error) {
38913
39590
  return res.status(400).json({ message: error.message });
38914
39591
  }
38915
- const result = await userTypeAccessCardsSvc({ page, limit, search, site, organization, userType });
39592
+ const result = await userTypeAccessCardsSvc({
39593
+ page,
39594
+ limit,
39595
+ search,
39596
+ site,
39597
+ organization,
39598
+ userType
39599
+ });
38916
39600
  return res.status(200).json({ message: "Success", data: result });
38917
39601
  } catch (error) {
38918
39602
  return res.status(500).json({
@@ -38923,7 +39607,12 @@ function useAccessManagementController() {
38923
39607
  };
38924
39608
  const assignedAccessCards = async (req, res) => {
38925
39609
  try {
38926
- const { site, userType, type, search = "" } = req.query;
39610
+ const {
39611
+ site,
39612
+ userType,
39613
+ type,
39614
+ search = ""
39615
+ } = req.query;
38927
39616
  const schema2 = import_joi86.default.object({
38928
39617
  site: import_joi86.default.string().hex().required(),
38929
39618
  userType: import_joi86.default.string().required(),
@@ -38934,7 +39623,12 @@ function useAccessManagementController() {
38934
39623
  if (error) {
38935
39624
  return res.status(400).json({ message: error.message });
38936
39625
  }
38937
- const result = await assignedAccessCardsSvc({ site, userType, type, search });
39626
+ const result = await assignedAccessCardsSvc({
39627
+ site,
39628
+ userType,
39629
+ type,
39630
+ search
39631
+ });
38938
39632
  return res.status(200).json({ message: "Success", data: result });
38939
39633
  } catch (error) {
38940
39634
  return res.status(500).json({
@@ -38980,11 +39674,23 @@ function useAccessManagementController() {
38980
39674
  userType: import_joi86.default.string().valid(...Object.values(EAccessCardUserTypes)).required(),
38981
39675
  type: import_joi86.default.string().valid(...Object.values(EAccessCardTypes)).required()
38982
39676
  });
38983
- const { error } = schema2.validate({ accessLevel, liftAccessLevel, site, userType, type });
39677
+ const { error } = schema2.validate({
39678
+ accessLevel,
39679
+ liftAccessLevel,
39680
+ site,
39681
+ userType,
39682
+ type
39683
+ });
38984
39684
  if (error) {
38985
39685
  return res.status(400).json({ message: error.message });
38986
39686
  }
38987
- const result = await accessandLiftCardsSvc({ accessLevel, liftAccessLevel, site, userType, type });
39687
+ const result = await accessandLiftCardsSvc({
39688
+ accessLevel,
39689
+ liftAccessLevel,
39690
+ site,
39691
+ userType,
39692
+ type
39693
+ });
38988
39694
  return res.status(200).json({ message: "Success", data: result });
38989
39695
  } catch (error) {
38990
39696
  return res.status(500).json({
@@ -39071,11 +39777,23 @@ function useAccessManagementController() {
39071
39777
  issuedCardId: import_joi86.default.string().required(),
39072
39778
  userId: import_joi86.default.string().hex().required()
39073
39779
  });
39074
- const { error } = schema2.validate({ cardId, remarks, unitId, issuedCardId, userId });
39780
+ const { error } = schema2.validate({
39781
+ cardId,
39782
+ remarks,
39783
+ unitId,
39784
+ issuedCardId,
39785
+ userId
39786
+ });
39075
39787
  if (error) {
39076
39788
  return res.status(400).json({ message: error.message });
39077
39789
  }
39078
- const result = await cardReplacementSvc({ cardId, remarks, unitId, issuedCardId, userId });
39790
+ const result = await cardReplacementSvc({
39791
+ cardId,
39792
+ remarks,
39793
+ unitId,
39794
+ issuedCardId,
39795
+ userId
39796
+ });
39079
39797
  return res.status(200).json({ message: "Success", data: result });
39080
39798
  } catch (error) {
39081
39799
  return res.status(500).json({
@@ -39104,7 +39822,13 @@ function useAccessManagementController() {
39104
39822
  if (error) {
39105
39823
  return res.status(400).json({ message: error.message });
39106
39824
  }
39107
- const result = await visitorAccessCardsSvc({ site, page, limit, type, search });
39825
+ const result = await visitorAccessCardsSvc({
39826
+ site,
39827
+ page,
39828
+ limit,
39829
+ type,
39830
+ search
39831
+ });
39108
39832
  return res.status(200).json({ message: "Success", data: result });
39109
39833
  } catch (error) {
39110
39834
  return res.status(500).json({
@@ -39133,11 +39857,27 @@ function useAccessManagementController() {
39133
39857
  limit: import_joi86.default.number().optional().default(10),
39134
39858
  site: import_joi86.default.string().hex().required()
39135
39859
  });
39136
- const { error } = schema2.validate({ search, statusFilter, dateFrom, dateTo, page, limit, site });
39860
+ const { error } = schema2.validate({
39861
+ search,
39862
+ statusFilter,
39863
+ dateFrom,
39864
+ dateTo,
39865
+ page,
39866
+ limit,
39867
+ site
39868
+ });
39137
39869
  if (error) {
39138
39870
  return res.status(400).json({ message: error.message });
39139
39871
  }
39140
- const result = await getCardReplacementSvc({ site, page, limit, search, statusFilter, dateFrom, dateTo });
39872
+ const result = await getCardReplacementSvc({
39873
+ site,
39874
+ page,
39875
+ limit,
39876
+ search,
39877
+ statusFilter,
39878
+ dateFrom,
39879
+ dateTo
39880
+ });
39141
39881
  return res.status(200).json({ message: "Success", data: result });
39142
39882
  } catch (error) {
39143
39883
  return res.status(500).json({
@@ -39183,7 +39923,15 @@ function useAccessManagementController() {
39183
39923
  };
39184
39924
  const assignAccessCardToUnit = async (req, res) => {
39185
39925
  try {
39186
- const { units, type, quantity, site, userType, accessLevel, liftAccessLevel } = req.body;
39926
+ const {
39927
+ units,
39928
+ type,
39929
+ quantity,
39930
+ site,
39931
+ userType,
39932
+ accessLevel,
39933
+ liftAccessLevel
39934
+ } = req.body;
39187
39935
  const schema2 = import_joi86.default.object({
39188
39936
  units: import_joi86.default.array().items(import_joi86.default.string().hex()).required(),
39189
39937
  quantity: import_joi86.default.number().required(),
@@ -39193,11 +39941,27 @@ function useAccessManagementController() {
39193
39941
  accessLevel: import_joi86.default.string().optional().allow("", null),
39194
39942
  liftAccessLevel: import_joi86.default.string().optional().allow("", null)
39195
39943
  });
39196
- const { error } = schema2.validate({ units, quantity, type, site, userType, accessLevel, liftAccessLevel });
39944
+ const { error } = schema2.validate({
39945
+ units,
39946
+ quantity,
39947
+ type,
39948
+ site,
39949
+ userType,
39950
+ accessLevel,
39951
+ liftAccessLevel
39952
+ });
39197
39953
  if (error) {
39198
39954
  return res.status(400).json({ message: error.message });
39199
39955
  }
39200
- const result = await assignAccessCardToUnitSvc({ units, quantity, type, site, userType, accessLevel, liftAccessLevel });
39956
+ const result = await assignAccessCardToUnitSvc({
39957
+ units,
39958
+ quantity,
39959
+ type,
39960
+ site,
39961
+ userType,
39962
+ accessLevel,
39963
+ liftAccessLevel
39964
+ });
39201
39965
  return res.status(200).json({ message: "Success", data: result });
39202
39966
  } catch (error) {
39203
39967
  return res.status(500).json({
@@ -39295,7 +40059,12 @@ function useAccessManagementController() {
39295
40059
  };
39296
40060
  const availableCardContractors = async (req, res) => {
39297
40061
  try {
39298
- const { siteId, unitId, page = 1, limit = 20 } = req.query;
40062
+ const {
40063
+ siteId,
40064
+ unitId,
40065
+ page = 1,
40066
+ limit = 20
40067
+ } = req.query;
39299
40068
  const type = req.params.type;
39300
40069
  const schema2 = import_joi86.default.object({
39301
40070
  siteId: import_joi86.default.string().hex().required(),
@@ -39308,7 +40077,13 @@ function useAccessManagementController() {
39308
40077
  if (error) {
39309
40078
  return res.status(400).json({ message: error.message });
39310
40079
  }
39311
- const result = await availableCardContractorsSvc({ siteId, unitId, page, limit, type });
40080
+ const result = await availableCardContractorsSvc({
40081
+ siteId,
40082
+ unitId,
40083
+ page,
40084
+ limit,
40085
+ type
40086
+ });
39312
40087
  return res.status(200).json({ message: "Success", data: result });
39313
40088
  } catch (error) {
39314
40089
  return res.status(500).json({
@@ -39319,7 +40094,11 @@ function useAccessManagementController() {
39319
40094
  };
39320
40095
  const vmsgenerateQrCodes = async (req, res) => {
39321
40096
  try {
39322
- const { site, unitId, quantity = 100 } = req.body;
40097
+ const {
40098
+ site,
40099
+ unitId,
40100
+ quantity = 100
40101
+ } = req.body;
39323
40102
  const schema2 = import_joi86.default.object({
39324
40103
  site: import_joi86.default.string().hex().length(24).required(),
39325
40104
  unitId: import_joi86.default.string().hex().length(24).required(),
@@ -39330,7 +40109,12 @@ function useAccessManagementController() {
39330
40109
  return res.status(400).json({ message: error.message });
39331
40110
  }
39332
40111
  const normalizedUnitId = [unitId];
39333
- const result = await vmsgenerateQrCodesSvc({ site, unitId, normalizedUnitId, quantity });
40112
+ const result = await vmsgenerateQrCodesSvc({
40113
+ site,
40114
+ unitId,
40115
+ normalizedUnitId,
40116
+ quantity
40117
+ });
39334
40118
  return res.status(200).json({ message: "Success", data: result });
39335
40119
  } catch (error) {
39336
40120
  return res.status(500).json({
@@ -39341,21 +40125,50 @@ function useAccessManagementController() {
39341
40125
  };
39342
40126
  const addVisitorAccessCard = async (req, res) => {
39343
40127
  try {
39344
- const { site, unitId, quantity = 1, type, nfcCards, visitorId, acm_url } = req.body;
40128
+ const {
40129
+ site,
40130
+ unitId,
40131
+ quantity = 1,
40132
+ type,
40133
+ nfcCards,
40134
+ visitorId,
40135
+ acm_url
40136
+ } = req.body;
39345
40137
  const schema2 = import_joi86.default.object({
39346
40138
  site: import_joi86.default.string().hex().length(24).required(),
39347
40139
  unitId: import_joi86.default.string().hex().length(24).required(),
39348
40140
  quantity: import_joi86.default.number().allow(null, "").optional(),
39349
40141
  type: import_joi86.default.string().required(),
39350
- nfcCards: import_joi86.default.array().items(import_joi86.default.object({ _id: import_joi86.default.string().hex().required(), cardNo: import_joi86.default.string().required() })).required(),
40142
+ nfcCards: import_joi86.default.array().items(
40143
+ import_joi86.default.object({
40144
+ _id: import_joi86.default.string().hex().required(),
40145
+ cardNo: import_joi86.default.string().required()
40146
+ })
40147
+ ).required(),
39351
40148
  acm_url: import_joi86.default.string().required(),
39352
40149
  visitorId: import_joi86.default.string().hex().length(24).required()
39353
40150
  });
39354
- const { error } = schema2.validate({ site, unitId, quantity, type, nfcCards, visitorId, acm_url });
40151
+ const { error } = schema2.validate({
40152
+ site,
40153
+ unitId,
40154
+ quantity,
40155
+ type,
40156
+ nfcCards,
40157
+ visitorId,
40158
+ acm_url
40159
+ });
39355
40160
  if (error) {
39356
40161
  return res.status(400).json({ message: error.message });
39357
40162
  }
39358
- const result = await addVisitorAccessCardSvc({ site, unitId, quantity, type, nfcCards, visitorId, acm_url });
40163
+ const result = await addVisitorAccessCardSvc({
40164
+ site,
40165
+ unitId,
40166
+ quantity,
40167
+ type,
40168
+ nfcCards,
40169
+ visitorId,
40170
+ acm_url
40171
+ });
39359
40172
  return res.status(200).json({ message: "Success", data: result });
39360
40173
  } catch (error) {
39361
40174
  return res.status(500).json({
@@ -39403,7 +40216,11 @@ function useAccessManagementController() {
39403
40216
  });
39404
40217
  }
39405
40218
  };
39406
- const removeAccessCard = async ({ cardNo, staffNo, url }) => {
40219
+ const removeAccessCard = async ({
40220
+ cardNo,
40221
+ staffNo,
40222
+ url
40223
+ }) => {
39407
40224
  return removeAccessGroup({ cardNo, staffNo, url });
39408
40225
  };
39409
40226
  const getBlockLevelAndUnitList = async (req, res) => {
@@ -39422,7 +40239,13 @@ function useAccessManagementController() {
39422
40239
  }
39423
40240
  };
39424
40241
  const getTransactions2 = async (req, res) => {
39425
- const { page = 1, limit = 10, site, cardNo, url } = req.query;
40242
+ const {
40243
+ page = 1,
40244
+ limit = 10,
40245
+ site,
40246
+ cardNo,
40247
+ url
40248
+ } = req.query;
39426
40249
  const schema2 = import_joi86.default.object({
39427
40250
  page: import_joi86.default.number().required(),
39428
40251
  limit: import_joi86.default.number().optional().default(10),
@@ -39461,7 +40284,12 @@ function useAccessManagementController() {
39461
40284
  if (error) {
39462
40285
  throw new Error(`${error.message}`);
39463
40286
  }
39464
- const result = await assignMultipleCardsSvc({ assignees, unit, type, acm_url });
40287
+ const result = await assignMultipleCardsSvc({
40288
+ assignees,
40289
+ unit,
40290
+ type,
40291
+ acm_url
40292
+ });
39465
40293
  return res.status(200).json({ message: "Success", data: result });
39466
40294
  } catch (error) {
39467
40295
  return res.status(400).json({
@@ -39504,6 +40332,27 @@ function useAccessManagementController() {
39504
40332
  });
39505
40333
  }
39506
40334
  };
40335
+ const getResidents = async (req, res) => {
40336
+ try {
40337
+ const { orgId, siteId, unitId } = req.query;
40338
+ const schema2 = import_joi86.default.object({
40339
+ orgId: import_joi86.default.string().hex().required(),
40340
+ siteId: import_joi86.default.string().hex().required(),
40341
+ unitId: import_joi86.default.string().hex().required()
40342
+ });
40343
+ const { error } = schema2.validate({ orgId, siteId, unitId });
40344
+ if (error) {
40345
+ return res.status(400).json({ message: error.message });
40346
+ }
40347
+ const result = await getResidentsSvc({ orgId, siteId, unitId });
40348
+ return res.status(200).json({ data: result });
40349
+ } catch (error) {
40350
+ return res.status(400).json({
40351
+ data: null,
40352
+ message: error.message
40353
+ });
40354
+ }
40355
+ };
39507
40356
  return {
39508
40357
  addPhysicalCard,
39509
40358
  addNonPhysicalCard,
@@ -39540,7 +40389,8 @@ function useAccessManagementController() {
39540
40389
  getTransactions: getTransactions2,
39541
40390
  assignMultipleCards,
39542
40391
  visitorCheckout,
39543
- uploadTemplate
40392
+ uploadTemplate,
40393
+ getResidents
39544
40394
  };
39545
40395
  }
39546
40396
 
@@ -54004,11 +54854,712 @@ function usePostPrelovedController() {
54004
54854
  updateStatus
54005
54855
  };
54006
54856
  }
54857
+
54858
+ // src/models/category-preloved.model.ts
54859
+ var import_joi134 = __toESM(require("joi"));
54860
+ var import_mongodb131 = require("mongodb");
54861
+ var schemaCategoryPreloved = import_joi134.default.object({
54862
+ name: import_joi134.default.string().required(),
54863
+ createdBy: import_joi134.default.string().hex().optional().allow("", null),
54864
+ site: import_joi134.default.string().hex().optional().allow("", null)
54865
+ });
54866
+ var schemaUpdateCategoryPreloved = import_joi134.default.object({
54867
+ name: import_joi134.default.string().optional().allow("", null),
54868
+ site: import_joi134.default.string().hex().optional().allow("", null)
54869
+ });
54870
+ function MCategoryPreloved(value) {
54871
+ const { error } = schemaCategoryPreloved.validate(value);
54872
+ if (error) {
54873
+ throw new Error(error.details[0].message);
54874
+ }
54875
+ if (value.createdBy && typeof value.createdBy === "string") {
54876
+ try {
54877
+ value.createdBy = new import_mongodb131.ObjectId(value.createdBy);
54878
+ } catch {
54879
+ throw new Error("Invalid createdBy ID.");
54880
+ }
54881
+ }
54882
+ if (value.site && typeof value.site === "string") {
54883
+ try {
54884
+ value.site = new import_mongodb131.ObjectId(value.site);
54885
+ } catch {
54886
+ throw new Error("Invalid site ID.");
54887
+ }
54888
+ }
54889
+ return {
54890
+ name: value.name ?? "",
54891
+ createdBy: value.createdBy ?? "",
54892
+ site: value.site ?? null,
54893
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
54894
+ updatedAt: value.updatedAt ?? null
54895
+ };
54896
+ }
54897
+
54898
+ // src/repositories/category-preloved.repo.ts
54899
+ var import_node_server_utils234 = require("@7365admin1/node-server-utils");
54900
+ var import_mongodb132 = require("mongodb");
54901
+ function useCategoryPrelovedRepo() {
54902
+ const db = import_node_server_utils234.useAtlas.getDb();
54903
+ if (!db) {
54904
+ throw new import_node_server_utils234.InternalServerError("Unable to connect to server.");
54905
+ }
54906
+ const CATEGORY_COLLECTION = "category-preloved";
54907
+ const collection = db.collection(CATEGORY_COLLECTION);
54908
+ async function getAll({
54909
+ search = "",
54910
+ site
54911
+ } = {}) {
54912
+ if (site) {
54913
+ try {
54914
+ site = new import_mongodb132.ObjectId(site);
54915
+ } catch {
54916
+ throw new import_node_server_utils234.BadRequestError("Invalid site ID format.");
54917
+ }
54918
+ }
54919
+ const query = {
54920
+ ...site && { site },
54921
+ ...search && { name: { $regex: search, $options: "i" } }
54922
+ };
54923
+ try {
54924
+ return await collection.find(query).sort({ name: 1 }).toArray();
54925
+ } catch (error) {
54926
+ console.error("Error in category-preloved getAll:", error);
54927
+ throw error;
54928
+ }
54929
+ }
54930
+ return { getAll };
54931
+ }
54932
+
54933
+ // src/controllers/category-preloved.controller.ts
54934
+ var import_node_server_utils235 = require("@7365admin1/node-server-utils");
54935
+ var import_joi135 = __toESM(require("joi"));
54936
+ function useCategoryPrelovedController() {
54937
+ const { getAll: _getAll } = useCategoryPrelovedRepo();
54938
+ async function getAll(req, res, next) {
54939
+ const schema2 = import_joi135.default.object({
54940
+ search: import_joi135.default.string().optional().allow("", null),
54941
+ site: import_joi135.default.string().hex().length(24).optional().allow("", null)
54942
+ });
54943
+ const { error, value } = schema2.validate(req.query, { abortEarly: false });
54944
+ if (error) {
54945
+ const messages = error.details.map((d) => d.message).join(", ");
54946
+ import_node_server_utils235.logger.log({ level: "error", message: messages });
54947
+ next(new import_node_server_utils235.BadRequestError(messages));
54948
+ return;
54949
+ }
54950
+ try {
54951
+ const data = await _getAll(value);
54952
+ res.status(200).json({ data });
54953
+ return;
54954
+ } catch (error2) {
54955
+ import_node_server_utils235.logger.log({ level: "error", message: error2.message });
54956
+ next(error2);
54957
+ return;
54958
+ }
54959
+ }
54960
+ return { getAll };
54961
+ }
54962
+
54963
+ // src/models/subcategory-preloved.model.ts
54964
+ var import_joi136 = __toESM(require("joi"));
54965
+ var import_mongodb133 = require("mongodb");
54966
+ var schemaSubcategoryPreloved = import_joi136.default.object({
54967
+ name: import_joi136.default.string().required(),
54968
+ createdBy: import_joi136.default.string().hex().optional().allow("", null),
54969
+ site: import_joi136.default.string().hex().optional().allow("", null),
54970
+ category_id: import_joi136.default.string().hex().required()
54971
+ });
54972
+ var schemaUpdateSubcategoryPreloved = import_joi136.default.object({
54973
+ name: import_joi136.default.string().optional().allow("", null),
54974
+ site: import_joi136.default.string().hex().optional().allow("", null),
54975
+ category_id: import_joi136.default.string().hex().optional().allow("", null)
54976
+ });
54977
+ function MSubcategoryPreloved(value) {
54978
+ const { error } = schemaSubcategoryPreloved.validate(value);
54979
+ if (error) {
54980
+ throw new Error(error.details[0].message);
54981
+ }
54982
+ if (value.createdBy && typeof value.createdBy === "string") {
54983
+ try {
54984
+ value.createdBy = new import_mongodb133.ObjectId(value.createdBy);
54985
+ } catch {
54986
+ throw new Error("Invalid createdBy ID.");
54987
+ }
54988
+ }
54989
+ if (value.site && typeof value.site === "string") {
54990
+ try {
54991
+ value.site = new import_mongodb133.ObjectId(value.site);
54992
+ } catch {
54993
+ throw new Error("Invalid site ID.");
54994
+ }
54995
+ }
54996
+ if (value.category_id && typeof value.category_id === "string") {
54997
+ try {
54998
+ value.category_id = new import_mongodb133.ObjectId(value.category_id);
54999
+ } catch {
55000
+ throw new Error("Invalid category ID.");
55001
+ }
55002
+ }
55003
+ return {
55004
+ name: value.name ?? "",
55005
+ createdBy: value.createdBy ?? "",
55006
+ site: value.site ?? null,
55007
+ category_id: value.category_id ?? "",
55008
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
55009
+ updatedAt: value.updatedAt ?? null
55010
+ };
55011
+ }
55012
+
55013
+ // src/repositories/subcategory-preloved.repo.ts
55014
+ var import_node_server_utils236 = require("@7365admin1/node-server-utils");
55015
+ var import_mongodb134 = require("mongodb");
55016
+ function useSubcategoryPrelovedRepo() {
55017
+ const db = import_node_server_utils236.useAtlas.getDb();
55018
+ if (!db) {
55019
+ throw new import_node_server_utils236.InternalServerError("Unable to connect to server.");
55020
+ }
55021
+ const SUBCATEGORY_COLLECTION = "subcategory-preloved";
55022
+ const collection = db.collection(SUBCATEGORY_COLLECTION);
55023
+ async function getAll({
55024
+ search = "",
55025
+ site,
55026
+ category_id
55027
+ } = {}) {
55028
+ if (site) {
55029
+ try {
55030
+ site = new import_mongodb134.ObjectId(site);
55031
+ } catch {
55032
+ throw new import_node_server_utils236.BadRequestError("Invalid site ID format.");
55033
+ }
55034
+ }
55035
+ if (category_id) {
55036
+ try {
55037
+ category_id = new import_mongodb134.ObjectId(category_id);
55038
+ } catch {
55039
+ throw new import_node_server_utils236.BadRequestError("Invalid category ID format.");
55040
+ }
55041
+ }
55042
+ const query = {
55043
+ ...site && { site },
55044
+ ...category_id && { category_id },
55045
+ ...search && { name: { $regex: search, $options: "i" } }
55046
+ };
55047
+ try {
55048
+ return await collection.find(query).sort({ name: 1 }).toArray();
55049
+ } catch (error) {
55050
+ throw error;
55051
+ }
55052
+ }
55053
+ return { getAll };
55054
+ }
55055
+
55056
+ // src/controllers/subcategory-preloved.controller.ts
55057
+ var import_node_server_utils237 = require("@7365admin1/node-server-utils");
55058
+ var import_joi137 = __toESM(require("joi"));
55059
+ function useSubcategoryPrelovedController() {
55060
+ const { getAll: _getAll } = useSubcategoryPrelovedRepo();
55061
+ async function getAll(req, res, next) {
55062
+ const schema2 = import_joi137.default.object({
55063
+ search: import_joi137.default.string().optional().allow("", null),
55064
+ site: import_joi137.default.string().hex().length(24).optional().allow("", null),
55065
+ category_id: import_joi137.default.string().hex().length(24).optional().allow("", null)
55066
+ });
55067
+ const { error, value } = schema2.validate(req.query, { abortEarly: false });
55068
+ if (error) {
55069
+ const messages = error.details.map((d) => d.message).join(", ");
55070
+ import_node_server_utils237.logger.log({ level: "error", message: messages });
55071
+ next(new import_node_server_utils237.BadRequestError(messages));
55072
+ return;
55073
+ }
55074
+ try {
55075
+ const data = await _getAll(value);
55076
+ res.status(200).json({ data });
55077
+ return;
55078
+ } catch (error2) {
55079
+ import_node_server_utils237.logger.log({ level: "error", message: error2.message });
55080
+ next(error2);
55081
+ return;
55082
+ }
55083
+ }
55084
+ return { getAll };
55085
+ }
55086
+
55087
+ // src/models/online-forms-v2.model.ts
55088
+ var import_joi138 = __toESM(require("joi"));
55089
+ var import_mongodb135 = require("mongodb");
55090
+ var FormEntryStatus = /* @__PURE__ */ ((FormEntryStatus2) => {
55091
+ FormEntryStatus2["ACTIVE"] = "active";
55092
+ FormEntryStatus2["INACTIVE"] = "inactive";
55093
+ FormEntryStatus2["DELETED"] = "deleted";
55094
+ return FormEntryStatus2;
55095
+ })(FormEntryStatus || {});
55096
+ var schemaFormEntry = import_joi138.default.object({
55097
+ _id: import_joi138.default.string().hex().optional().allow("", null),
55098
+ formType: import_joi138.default.string().required(),
55099
+ fields: import_joi138.default.object().pattern(
55100
+ import_joi138.default.string(),
55101
+ import_joi138.default.alternatives().try(
55102
+ import_joi138.default.string(),
55103
+ import_joi138.default.number(),
55104
+ import_joi138.default.boolean(),
55105
+ import_joi138.default.valid(null)
55106
+ )
55107
+ ).required(),
55108
+ status: import_joi138.default.string().optional().allow("", null),
55109
+ org: import_joi138.default.string().hex().optional().allow("", null),
55110
+ site: import_joi138.default.string().hex().optional().allow("", null),
55111
+ createdAt: import_joi138.default.date().optional().allow("", null),
55112
+ updatedAt: import_joi138.default.date().optional().allow("", null),
55113
+ deletedAt: import_joi138.default.date().optional().allow("", null)
55114
+ });
55115
+ var schemaUpdateFormEntry = import_joi138.default.object({
55116
+ _id: import_joi138.default.string().hex().required(),
55117
+ formType: import_joi138.default.string().optional().allow("", null),
55118
+ fields: import_joi138.default.object().pattern(
55119
+ import_joi138.default.string(),
55120
+ import_joi138.default.alternatives().try(
55121
+ import_joi138.default.string(),
55122
+ import_joi138.default.number(),
55123
+ import_joi138.default.boolean(),
55124
+ import_joi138.default.valid(null)
55125
+ )
55126
+ ).optional(),
55127
+ status: import_joi138.default.string().optional().allow("", null),
55128
+ createdAt: import_joi138.default.date().optional().allow("", null),
55129
+ updatedAt: import_joi138.default.date().optional().allow("", null),
55130
+ deletedAt: import_joi138.default.date().optional().allow("", null)
55131
+ });
55132
+ function MFormEntry(value) {
55133
+ const { error } = schemaFormEntry.validate(value);
55134
+ if (error) {
55135
+ throw new Error(error.details[0].message);
55136
+ }
55137
+ if (value._id && typeof value._id === "string") {
55138
+ try {
55139
+ value._id = new import_mongodb135.ObjectId(value._id);
55140
+ } catch {
55141
+ throw new Error("Invalid ID.");
55142
+ }
55143
+ }
55144
+ if (value.org && typeof value.org === "string") {
55145
+ try {
55146
+ value.org = new import_mongodb135.ObjectId(value.org);
55147
+ } catch {
55148
+ throw new Error("Invalid org ID.");
55149
+ }
55150
+ }
55151
+ if (value.site && typeof value.site === "string") {
55152
+ try {
55153
+ value.site = new import_mongodb135.ObjectId(value.site);
55154
+ } catch {
55155
+ throw new Error("Invalid site ID.");
55156
+ }
55157
+ }
55158
+ return {
55159
+ _id: value._id,
55160
+ formType: value.formType,
55161
+ fields: value.fields,
55162
+ status: value.status,
55163
+ org: value.org,
55164
+ site: value.site,
55165
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
55166
+ updatedAt: value.updatedAt ?? null,
55167
+ deletedAt: value.deletedAt ?? null
55168
+ };
55169
+ }
55170
+
55171
+ // src/repositories/online-forms-v2.repository.ts
55172
+ var import_node_server_utils238 = require("@7365admin1/node-server-utils");
55173
+ var online_forms_namespace_collection = "online-forms";
55174
+ function useFormEntryRepo() {
55175
+ const db = import_node_server_utils238.useAtlas.getDb();
55176
+ if (!db) {
55177
+ throw new import_node_server_utils238.InternalServerError("Unable to connect to server.");
55178
+ }
55179
+ const collection = db.collection(online_forms_namespace_collection);
55180
+ const { delNamespace, getCache, setCache } = (0, import_node_server_utils238.useCache)(
55181
+ online_forms_namespace_collection
55182
+ );
55183
+ async function createTextIndex() {
55184
+ try {
55185
+ await collection.createIndex({
55186
+ name: "text"
55187
+ });
55188
+ } catch (error) {
55189
+ throw new import_node_server_utils238.InternalServerError(
55190
+ "Failed to create text index on online form."
55191
+ );
55192
+ }
55193
+ }
55194
+ async function add(value, session) {
55195
+ try {
55196
+ value = MFormEntry(value);
55197
+ const res = await collection.insertOne(value, { session });
55198
+ delNamespace().then(() => {
55199
+ import_node_server_utils238.logger.info(
55200
+ `Cache cleared for namespace: ${online_forms_namespace_collection}`
55201
+ );
55202
+ }).catch((err) => {
55203
+ import_node_server_utils238.logger.error(
55204
+ `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
55205
+ err
55206
+ );
55207
+ });
55208
+ return res.insertedId;
55209
+ } catch (error) {
55210
+ const isDuplicated = error.message.includes("duplicate");
55211
+ if (isDuplicated) {
55212
+ throw new import_node_server_utils238.BadRequestError("Online Form already exists.");
55213
+ }
55214
+ throw error;
55215
+ }
55216
+ }
55217
+ return {
55218
+ add,
55219
+ createTextIndex
55220
+ };
55221
+ }
55222
+
55223
+ // src/controllers/online-forms-v2.controller.ts
55224
+ var import_node_server_utils239 = require("@7365admin1/node-server-utils");
55225
+ var import_exceljs3 = __toESM(require("exceljs"));
55226
+ var import_fs6 = __toESM(require("fs"));
55227
+ function useFormEntryController() {
55228
+ const { add: _add } = useFormEntryRepo();
55229
+ function toCamelCase(str) {
55230
+ return str.replace(/\s(.)/g, (_, char) => char.toUpperCase()).replace(/\s+/g, "").replace(/^(.)/, (_, char) => char.toLowerCase());
55231
+ }
55232
+ function normalizeKeys(obj) {
55233
+ const normalized = {};
55234
+ for (const [key, value] of Object.entries(obj)) {
55235
+ normalized[toCamelCase(key)] = value;
55236
+ }
55237
+ return normalized;
55238
+ }
55239
+ async function uploadFormEntrys(req, res, next) {
55240
+ try {
55241
+ if (!req.file) {
55242
+ next(new import_node_server_utils239.BadRequestError("Excel file is required."));
55243
+ return;
55244
+ }
55245
+ const workbook = new import_exceljs3.default.Workbook();
55246
+ await workbook.xlsx.readFile(req.file.path);
55247
+ const worksheet = workbook.worksheets[0];
55248
+ if (!worksheet) {
55249
+ next(new import_node_server_utils239.BadRequestError("No worksheet found in uploaded Excel file."));
55250
+ return;
55251
+ }
55252
+ const headerRow = worksheet.getRow(1);
55253
+ const headers = headerRow.values.slice(1).map((h) => String(h ?? "").trim());
55254
+ const fields = {};
55255
+ headers.forEach((header) => {
55256
+ fields[header] = null;
55257
+ });
55258
+ const formType = req.file.originalname.replace(/\.[^/.]+$/, "");
55259
+ const normalizedFields = normalizeKeys(fields);
55260
+ const payload = {
55261
+ formType,
55262
+ fields: normalizedFields,
55263
+ status: "active" /* ACTIVE */
55264
+ };
55265
+ const { error, value } = schemaFormEntry.validate(payload, {
55266
+ abortEarly: false
55267
+ });
55268
+ if (error) {
55269
+ const messages = error.details.map((d) => d.message).join(", ");
55270
+ import_node_server_utils239.logger.log({ level: "error", message: messages });
55271
+ next(new import_node_server_utils239.BadRequestError(messages));
55272
+ return;
55273
+ }
55274
+ const result = await _add(value);
55275
+ res.status(201).json(result);
55276
+ import_fs6.default.unlink(req.file.path, () => {
55277
+ });
55278
+ } catch (error) {
55279
+ import_node_server_utils239.logger.log({ level: "error", message: error.message });
55280
+ next(error);
55281
+ }
55282
+ }
55283
+ return {
55284
+ uploadFormEntrys
55285
+ };
55286
+ }
55287
+
55288
+ // src/models/building-level.model.ts
55289
+ var import_node_server_utils240 = require("@7365admin1/node-server-utils");
55290
+ var import_mongodb136 = require("mongodb");
55291
+ var import_joi139 = __toESM(require("joi"));
55292
+ var import_node_server_utils241 = require("@7365admin1/node-server-utils");
55293
+ var BuildingLevelStatus = /* @__PURE__ */ ((BuildingLevelStatus2) => {
55294
+ BuildingLevelStatus2["ACTIVE"] = "active";
55295
+ BuildingLevelStatus2["DELETED"] = "deleted";
55296
+ return BuildingLevelStatus2;
55297
+ })(BuildingLevelStatus || {});
55298
+ var schemaBuildingLevel = import_joi139.default.object({
55299
+ org: import_joi139.default.string().hex().optional(),
55300
+ site: import_joi139.default.string().hex().optional(),
55301
+ blockId: import_joi139.default.string().hex().optional(),
55302
+ name: import_joi139.default.string().optional(),
55303
+ status: import_joi139.default.string().valid(...Object.values(BuildingLevelStatus)).optional(),
55304
+ createdAt: import_joi139.default.date().optional(),
55305
+ updatedAt: import_joi139.default.date().optional().allow(null),
55306
+ deletedAt: import_joi139.default.date().optional().allow(null)
55307
+ });
55308
+ function MBuildingLevel(value) {
55309
+ const { error } = schemaBuildingLevel.validate(value);
55310
+ if (error) {
55311
+ import_node_server_utils241.logger.info(`Building Level Model: ${error.message}`);
55312
+ throw new import_node_server_utils240.BadRequestError(error.message);
55313
+ }
55314
+ if (value.org && typeof value.org === "string") {
55315
+ try {
55316
+ value.org = new import_mongodb136.ObjectId(value.org);
55317
+ } catch {
55318
+ throw new import_node_server_utils240.BadRequestError("Invalid org ID format");
55319
+ }
55320
+ }
55321
+ if (value.site && typeof value.site === "string") {
55322
+ try {
55323
+ value.site = new import_mongodb136.ObjectId(value.site);
55324
+ } catch {
55325
+ throw new import_node_server_utils240.BadRequestError("Invalid site ID format");
55326
+ }
55327
+ }
55328
+ if (value.blockId && typeof value.blockId === "string") {
55329
+ try {
55330
+ value.blockId = new import_mongodb136.ObjectId(value.blockId);
55331
+ } catch {
55332
+ throw new import_node_server_utils240.BadRequestError("Invalid block ID format");
55333
+ }
55334
+ }
55335
+ return {
55336
+ _id: new import_mongodb136.ObjectId(),
55337
+ org: value.org ?? void 0,
55338
+ site: value.site ?? void 0,
55339
+ blockId: value.blockId ?? void 0,
55340
+ name: value.name ?? "",
55341
+ status: value.status ?? "active" /* ACTIVE */,
55342
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
55343
+ updatedAt: value.updatedAt ?? null,
55344
+ deletedAt: value.deletedAt ?? null
55345
+ };
55346
+ }
55347
+
55348
+ // src/repositories/building-level.repository.ts
55349
+ var import_node_server_utils242 = require("@7365admin1/node-server-utils");
55350
+ var building_level_namespace_collection = "building-levels";
55351
+ function useBuildingLevelRepo() {
55352
+ const db = import_node_server_utils242.useAtlas.getDb();
55353
+ if (!db) {
55354
+ throw new Error("Unable to connect to server.");
55355
+ }
55356
+ const collection = db.collection(building_level_namespace_collection);
55357
+ const { getCache, setCache, delNamespace, delCache } = (0, import_node_server_utils242.useCache)(
55358
+ building_level_namespace_collection
55359
+ );
55360
+ function delCachedData() {
55361
+ delNamespace().then(() => {
55362
+ import_node_server_utils242.logger.log({
55363
+ level: "info",
55364
+ message: `Cache namespace cleared for ${building_level_namespace_collection}`
55365
+ });
55366
+ }).catch((err) => {
55367
+ import_node_server_utils242.logger.log({
55368
+ level: "error",
55369
+ message: `Failed to clear cache namespace for ${building_level_namespace_collection}: ${err.message}`
55370
+ });
55371
+ });
55372
+ }
55373
+ async function add(value, session) {
55374
+ try {
55375
+ value = MBuildingLevel(value);
55376
+ const res = await collection.insertOne(value, { session });
55377
+ delCachedData();
55378
+ return res.insertedId;
55379
+ } catch (error) {
55380
+ import_node_server_utils242.logger.log({
55381
+ level: "error",
55382
+ message: error.message
55383
+ });
55384
+ const isDuplicated = error.message.includes("duplicate");
55385
+ if (isDuplicated) {
55386
+ throw new import_node_server_utils242.BadRequestError("Building unit already exists.");
55387
+ }
55388
+ if (error instanceof import_node_server_utils242.AppError) {
55389
+ throw error;
55390
+ } else {
55391
+ throw new Error("Failed to create building unit.");
55392
+ }
55393
+ }
55394
+ }
55395
+ async function getAll({
55396
+ search = "",
55397
+ page = 1,
55398
+ limit = 10,
55399
+ sort = {},
55400
+ site = "",
55401
+ status = "active"
55402
+ } = {}) {
55403
+ page = page > 0 ? page - 1 : 0;
55404
+ const query = {
55405
+ status,
55406
+ ...search && { $text: { $search: search } },
55407
+ ...site && { site: (0, import_node_server_utils242.toObjectId)(site) }
55408
+ };
55409
+ const cacheParams = {
55410
+ page,
55411
+ limit,
55412
+ sort: JSON.stringify(sort),
55413
+ ...search && { search },
55414
+ ...site && { site },
55415
+ ...status && { status }
55416
+ };
55417
+ const cacheKey = (0, import_node_server_utils242.makeCacheKey)(
55418
+ building_level_namespace_collection,
55419
+ cacheParams
55420
+ );
55421
+ import_node_server_utils242.logger.log({
55422
+ level: "info",
55423
+ message: `Cache key for getAll building units: ${cacheKey}`
55424
+ });
55425
+ try {
55426
+ const cached = await getCache(cacheKey);
55427
+ if (cached) {
55428
+ import_node_server_utils242.logger.log({
55429
+ level: "info",
55430
+ message: `Cache hit for getAll building units: ${cacheKey}`
55431
+ });
55432
+ return cached;
55433
+ }
55434
+ const sortStage = Object.keys(sort).length > 0 ? { $sort: sort } : { $sort: { latestDate: -1 } };
55435
+ const items = await collection.aggregate([
55436
+ { $match: query },
55437
+ {
55438
+ $addFields: {
55439
+ latestDate: { $max: ["$updatedAt", "$createdAt"] }
55440
+ }
55441
+ },
55442
+ sortStage,
55443
+ { $unset: "latestDate" },
55444
+ { $skip: page * limit },
55445
+ { $limit: limit }
55446
+ ]).toArray();
55447
+ const length = await collection.countDocuments(query);
55448
+ const data = (0, import_node_server_utils242.paginate)(items, page, limit, length);
55449
+ setCache(cacheKey, data, 600).then(() => {
55450
+ import_node_server_utils242.logger.log({
55451
+ level: "info",
55452
+ message: `Cache set for getAll building units: ${cacheKey}`
55453
+ });
55454
+ }).catch((err) => {
55455
+ import_node_server_utils242.logger.log({
55456
+ level: "error",
55457
+ message: `Failed to set cache for getAll building units: ${err.message}`
55458
+ });
55459
+ });
55460
+ return data;
55461
+ } catch (error) {
55462
+ console.log(error);
55463
+ import_node_server_utils242.logger.log({ level: "error", message: `${error}` });
55464
+ throw error;
55465
+ }
55466
+ }
55467
+ return {
55468
+ // createIndexes,
55469
+ add,
55470
+ getAll
55471
+ };
55472
+ }
55473
+
55474
+ // src/services/building-level.service.ts
55475
+ var import_node_server_utils243 = require("@7365admin1/node-server-utils");
55476
+ function useBuildingLevelService() {
55477
+ const { add: _add } = useBuildingLevelRepo();
55478
+ async function add(value) {
55479
+ const session = import_node_server_utils243.useAtlas.getClient()?.startSession();
55480
+ try {
55481
+ session?.startTransaction();
55482
+ await _add(value, session);
55483
+ await session?.commitTransaction();
55484
+ return "Successfully added building level.";
55485
+ } catch (error) {
55486
+ await session?.abortTransaction();
55487
+ throw error;
55488
+ } finally {
55489
+ session?.endSession();
55490
+ }
55491
+ }
55492
+ return {
55493
+ add
55494
+ };
55495
+ }
55496
+
55497
+ // src/controllers/building-level.controller.ts
55498
+ var import_node_server_utils244 = require("@7365admin1/node-server-utils");
55499
+ var import_joi140 = __toESM(require("joi"));
55500
+ function useBuildingLevelController() {
55501
+ const { add: _add } = useBuildingLevelService();
55502
+ const { getAll: _getAll } = useBuildingLevelRepo();
55503
+ async function add(req, res, next) {
55504
+ try {
55505
+ const { error, value } = schemaBuildingLevel.validate(req.body, {
55506
+ abortEarly: false
55507
+ });
55508
+ if (error) {
55509
+ const messages = error.details.map((d) => d.message).join(", ");
55510
+ import_node_server_utils244.logger.log({ level: "error", message: messages });
55511
+ next(new import_node_server_utils244.BadRequestError(messages));
55512
+ return;
55513
+ }
55514
+ const result = await _add(value);
55515
+ res.status(201).json(result);
55516
+ } catch (error) {
55517
+ next(error);
55518
+ }
55519
+ }
55520
+ async function getAll(req, res, next) {
55521
+ try {
55522
+ const validation = import_joi140.default.object({
55523
+ page: import_joi140.default.number().min(1).optional().default(1),
55524
+ limit: import_joi140.default.number().min(1).optional().default(20),
55525
+ search: import_joi140.default.string().optional().allow("", null),
55526
+ site: import_joi140.default.string().hex().length(24).optional().allow("", null),
55527
+ status: import_joi140.default.string().valid(...Object.values(BuildingLevelStatus)).default("active" /* ACTIVE */)
55528
+ });
55529
+ const { error, value } = validation.validate(req.query, {
55530
+ abortEarly: false
55531
+ });
55532
+ if (error) {
55533
+ const messages = error.details.map((d) => d.message);
55534
+ import_node_server_utils244.logger.log({ level: "error", message: messages.join(", ") });
55535
+ next(new import_node_server_utils244.BadRequestError(messages.join(", ")));
55536
+ return;
55537
+ }
55538
+ const { page, limit, status, site, search } = value;
55539
+ const result = await _getAll({
55540
+ page,
55541
+ limit,
55542
+ status,
55543
+ site,
55544
+ search
55545
+ });
55546
+ res.json(result);
55547
+ return;
55548
+ } catch (error) {
55549
+ next(error);
55550
+ }
55551
+ }
55552
+ return {
55553
+ add,
55554
+ getAll
55555
+ };
55556
+ }
54007
55557
  // Annotate the CommonJS export names for ESM import in node:
54008
55558
  0 && (module.exports = {
54009
55559
  ANPRMode,
54010
55560
  AccessTypeProps,
54011
55561
  AppServiceType,
55562
+ BuildingLevelStatus,
54012
55563
  BuildingStatus,
54013
55564
  BulletinOrder,
54014
55565
  BulletinRecipient,
@@ -54031,6 +55582,7 @@ function usePostPrelovedController() {
54031
55582
  EventType,
54032
55583
  FacilitySort,
54033
55584
  FacilityStatus,
55585
+ FormEntryStatus,
54034
55586
  GuestSort,
54035
55587
  GuestStatus,
54036
55588
  MAccessCard,
@@ -54041,9 +55593,11 @@ function usePostPrelovedController() {
54041
55593
  MBillingConfiguration,
54042
55594
  MBillingItem,
54043
55595
  MBuilding,
55596
+ MBuildingLevel,
54044
55597
  MBuildingUnit,
54045
55598
  MBulletinBoard,
54046
55599
  MBulletinVideo,
55600
+ MCategoryPreloved,
54047
55601
  MChat,
54048
55602
  MCustomer,
54049
55603
  MCustomerSite,
@@ -54052,6 +55606,7 @@ function usePostPrelovedController() {
54052
55606
  MEventManagement,
54053
55607
  MFeedback,
54054
55608
  MFile,
55609
+ MFormEntry,
54055
55610
  MGuestManagement,
54056
55611
  MIncidentReport,
54057
55612
  MManpowerDesignations,
@@ -54088,6 +55643,7 @@ function usePostPrelovedController() {
54088
55643
  MSiteFacility,
54089
55644
  MSiteFacilityBooking,
54090
55645
  MStatementOfAccount,
55646
+ MSubcategoryPreloved,
54091
55647
  MSubscription,
54092
55648
  MUnitBilling,
54093
55649
  MUser,
@@ -54135,6 +55691,7 @@ function usePostPrelovedController() {
54135
55691
  allowedNatures,
54136
55692
  attendanceSchema,
54137
55693
  attendanceSettingsSchema,
55694
+ building_level_namespace_collection,
54138
55695
  building_units_namespace_collection,
54139
55696
  buildings_namespace_collection,
54140
55697
  bulletin_boards_namespace_collection,
@@ -54163,6 +55720,7 @@ function usePostPrelovedController() {
54163
55720
  nfcPatrolSettingsSchema,
54164
55721
  nfcPatrolSettingsSchemaUpdate,
54165
55722
  occurrence_book_namespace_collection,
55723
+ online_forms_namespace_collection,
54166
55724
  orgSchema,
54167
55725
  overnight_parking_requests_namespace_collection,
54168
55726
  parseDahuaFind,
@@ -54178,15 +55736,18 @@ function usePostPrelovedController() {
54178
55736
  schemaBillingConfiguration,
54179
55737
  schemaBillingItem,
54180
55738
  schemaBuilding,
55739
+ schemaBuildingLevel,
54181
55740
  schemaBuildingUnit,
54182
55741
  schemaBuildingUpdateOptions,
54183
55742
  schemaBulletinBoard,
54184
55743
  schemaBulletinVideo,
55744
+ schemaCategoryPreloved,
54185
55745
  schemaCustomerSite,
54186
55746
  schemaDocumentManagement,
54187
55747
  schemaEntryPassSettings,
54188
55748
  schemaEventManagement,
54189
55749
  schemaFiles,
55750
+ schemaFormEntry,
54190
55751
  schemaGuestManagement,
54191
55752
  schemaIncidentReport,
54192
55753
  schemaNfcPatrolLog,
@@ -54211,12 +55772,15 @@ function usePostPrelovedController() {
54211
55772
  schemaSiteFacility,
54212
55773
  schemaSiteFacilityBooking,
54213
55774
  schemaStatementOfAccount,
55775
+ schemaSubcategoryPreloved,
54214
55776
  schemaUnitBilling,
54215
55777
  schemaUpdateBulletinBoard,
54216
55778
  schemaUpdateBulletinVideo,
55779
+ schemaUpdateCategoryPreloved,
54217
55780
  schemaUpdateDocumentManagement,
54218
55781
  schemaUpdateEntryPassSettings,
54219
55782
  schemaUpdateEventManagement,
55783
+ schemaUpdateFormEntry,
54220
55784
  schemaUpdateGuestManagement,
54221
55785
  schemaUpdateIncidentReport,
54222
55786
  schemaUpdateOccurrenceBook,
@@ -54238,6 +55802,7 @@ function usePostPrelovedController() {
54238
55802
  schemaUpdateSiteFacilityBooking,
54239
55803
  schemaUpdateSiteUnitBilling,
54240
55804
  schemaUpdateStatementOfAccount,
55805
+ schemaUpdateSubcategoryPreloved,
54241
55806
  schemaUpdateVisTrans,
54242
55807
  schemaVehicleTransaction,
54243
55808
  schemaVisitorTransaction,
@@ -54263,6 +55828,9 @@ function usePostPrelovedController() {
54263
55828
  useAuthService,
54264
55829
  useAuthServiceV2,
54265
55830
  useBuildingController,
55831
+ useBuildingLevelController,
55832
+ useBuildingLevelRepo,
55833
+ useBuildingLevelService,
54266
55834
  useBuildingRepo,
54267
55835
  useBuildingService,
54268
55836
  useBuildingUnitController,
@@ -54274,6 +55842,8 @@ function usePostPrelovedController() {
54274
55842
  useBulletinVideoController,
54275
55843
  useBulletinVideoRepo,
54276
55844
  useBulletinVideoService,
55845
+ useCategoryPrelovedController,
55846
+ useCategoryPrelovedRepo,
54277
55847
  useChatController,
54278
55848
  useChatRepo,
54279
55849
  useCounterModel,
@@ -54300,6 +55870,8 @@ function usePostPrelovedController() {
54300
55870
  useFileController,
54301
55871
  useFileRepo,
54302
55872
  useFileService,
55873
+ useFormEntryController,
55874
+ useFormEntryRepo,
54303
55875
  useGuestManagementController,
54304
55876
  useGuestManagementRepo,
54305
55877
  useGuestManagementService,
@@ -54409,6 +55981,8 @@ function usePostPrelovedController() {
54409
55981
  useSiteUnitBillingService,
54410
55982
  useStatementOfAccountController,
54411
55983
  useStatementOfAccountRepo,
55984
+ useSubcategoryPrelovedController,
55985
+ useSubcategoryPrelovedRepo,
54412
55986
  useSubscriptionController,
54413
55987
  useSubscriptionRepo,
54414
55988
  useSubscriptionService,