@7365admin1/core 2.64.0 → 2.66.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
@@ -55,6 +55,7 @@ __export(src_exports, {
55
55
  EventType: () => EventType,
56
56
  FacilitySort: () => FacilitySort,
57
57
  FacilityStatus: () => FacilityStatus,
58
+ FormEntryStatus: () => FormEntryStatus,
58
59
  GuestSort: () => GuestSort,
59
60
  GuestStatus: () => GuestStatus,
60
61
  MAccessCard: () => MAccessCard,
@@ -76,6 +77,7 @@ __export(src_exports, {
76
77
  MEventManagement: () => MEventManagement,
77
78
  MFeedback: () => MFeedback,
78
79
  MFile: () => MFile,
80
+ MFormEntry: () => MFormEntry,
79
81
  MGuestManagement: () => MGuestManagement,
80
82
  MIncidentReport: () => MIncidentReport,
81
83
  MManpowerDesignations: () => MManpowerDesignations,
@@ -187,6 +189,7 @@ __export(src_exports, {
187
189
  nfcPatrolSettingsSchema: () => nfcPatrolSettingsSchema,
188
190
  nfcPatrolSettingsSchemaUpdate: () => nfcPatrolSettingsSchemaUpdate,
189
191
  occurrence_book_namespace_collection: () => occurrence_book_namespace_collection,
192
+ online_forms_namespace_collection: () => online_forms_namespace_collection,
190
193
  orgSchema: () => orgSchema,
191
194
  overnight_parking_requests_namespace_collection: () => overnight_parking_requests_namespace_collection,
192
195
  parseDahuaFind: () => parseDahuaFind,
@@ -211,6 +214,7 @@ __export(src_exports, {
211
214
  schemaEntryPassSettings: () => schemaEntryPassSettings,
212
215
  schemaEventManagement: () => schemaEventManagement,
213
216
  schemaFiles: () => schemaFiles,
217
+ schemaFormEntry: () => schemaFormEntry,
214
218
  schemaGuestManagement: () => schemaGuestManagement,
215
219
  schemaIncidentReport: () => schemaIncidentReport,
216
220
  schemaNfcPatrolLog: () => schemaNfcPatrolLog,
@@ -241,6 +245,7 @@ __export(src_exports, {
241
245
  schemaUpdateDocumentManagement: () => schemaUpdateDocumentManagement,
242
246
  schemaUpdateEntryPassSettings: () => schemaUpdateEntryPassSettings,
243
247
  schemaUpdateEventManagement: () => schemaUpdateEventManagement,
248
+ schemaUpdateFormEntry: () => schemaUpdateFormEntry,
244
249
  schemaUpdateGuestManagement: () => schemaUpdateGuestManagement,
245
250
  schemaUpdateIncidentReport: () => schemaUpdateIncidentReport,
246
251
  schemaUpdateOccurrenceBook: () => schemaUpdateOccurrenceBook,
@@ -253,6 +258,7 @@ __export(src_exports, {
253
258
  schemaUpdatePatrolQuestion: () => schemaUpdatePatrolQuestion,
254
259
  schemaUpdatePatrolRoute: () => schemaUpdatePatrolRoute,
255
260
  schemaUpdatePerson: () => schemaUpdatePerson,
261
+ schemaUpdatePost: () => schemaUpdatePost,
256
262
  schemaUpdateServiceProviderBilling: () => schemaUpdateServiceProviderBilling,
257
263
  schemaUpdateSiteBillingConfiguration: () => schemaUpdateSiteBillingConfiguration,
258
264
  schemaUpdateSiteBillingItem: () => schemaUpdateSiteBillingItem,
@@ -323,6 +329,8 @@ __export(src_exports, {
323
329
  useFileController: () => useFileController,
324
330
  useFileRepo: () => useFileRepo,
325
331
  useFileService: () => useFileService,
332
+ useFormEntryController: () => useFormEntryController,
333
+ useFormEntryRepo: () => useFormEntryRepo,
326
334
  useGuestManagementController: () => useGuestManagementController,
327
335
  useGuestManagementRepo: () => useGuestManagementRepo,
328
336
  useGuestManagementService: () => useGuestManagementService,
@@ -587,7 +595,15 @@ var userSchema = import_joi2.default.object({
587
595
  email: import_joi2.default.string().email().required(),
588
596
  password: import_joi2.default.string().min(8).required(),
589
597
  name: import_joi2.default.string().required(),
590
- defaultOrg: import_joi2.default.string().hex().optional().allow("", null)
598
+ defaultOrg: import_joi2.default.string().hex().optional().allow("", null),
599
+ status: import_joi2.default.string().optional().allow("", null),
600
+ block: import_joi2.default.number().optional().allow(null),
601
+ level: import_joi2.default.string().optional().allow("", null),
602
+ type: import_joi2.default.string().optional().allow("", null),
603
+ unitName: import_joi2.default.string().optional().allow("", null),
604
+ contact: import_joi2.default.string().optional().allow("", null),
605
+ site: import_joi2.default.string().hex().optional().allow("", null),
606
+ unitId: import_joi2.default.string().hex().optional().allow("", null)
591
607
  });
592
608
  function MUser(value) {
593
609
  const { error } = userSchema.validate(value);
@@ -601,12 +617,33 @@ function MUser(value) {
601
617
  throw new import_node_server_utils3.BadRequestError("Invalid default org ID format.");
602
618
  }
603
619
  }
620
+ if (value.site && typeof value.site === "string") {
621
+ try {
622
+ value.site = new import_mongodb.ObjectId(value.site);
623
+ } catch {
624
+ throw new import_node_server_utils3.BadRequestError("Invalid site ID format.");
625
+ }
626
+ }
627
+ if (value.unitId && typeof value.unitId === "string") {
628
+ try {
629
+ value.unitId = new import_mongodb.ObjectId(value.unitId);
630
+ } catch {
631
+ throw new import_node_server_utils3.BadRequestError("Invalid unit ID format.");
632
+ }
633
+ }
604
634
  return {
605
635
  email: value.email,
606
636
  password: value.password,
607
637
  name: value.name ?? "",
608
638
  defaultOrg: value.defaultOrg ?? "",
609
- status: "active" /* ACTIVE */,
639
+ status: value.status ?? "active" /* ACTIVE */,
640
+ block: value.block ?? null,
641
+ level: value.level ?? "",
642
+ type: value.type ?? "",
643
+ unitName: value.unitName ?? "",
644
+ contact: value.contact ?? "",
645
+ site: value.site ?? "",
646
+ unitId: value.unitId ?? "",
610
647
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
611
648
  updatedAt: value.updatedAt ?? "",
612
649
  deletedAt: value.deletedAt ?? ""
@@ -4752,6 +4789,30 @@ function useOrgRepo() {
4752
4789
  throw error;
4753
4790
  }
4754
4791
  }
4792
+ async function getOrgsByEmail(email) {
4793
+ const cacheKey = (0, import_node_server_utils17.makeCacheKey)(namespace_collection, {
4794
+ type: "many",
4795
+ email
4796
+ });
4797
+ const cachedData = await getCache(cacheKey);
4798
+ if (cachedData) {
4799
+ import_node_server_utils17.logger.info(`Cache hit for key: ${cacheKey}`);
4800
+ return cachedData;
4801
+ }
4802
+ try {
4803
+ const data = await collection.find({
4804
+ email
4805
+ }).toArray();
4806
+ setCache(cacheKey, data, 15 * 60).then(() => {
4807
+ import_node_server_utils17.logger.info(`Cache set for key: ${cacheKey}`);
4808
+ }).catch((err) => {
4809
+ import_node_server_utils17.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
4810
+ });
4811
+ return data;
4812
+ } catch (error) {
4813
+ throw error;
4814
+ }
4815
+ }
4755
4816
  async function updateFieldById({
4756
4817
  _id,
4757
4818
  field,
@@ -4854,7 +4915,8 @@ function useOrgRepo() {
4854
4915
  getByEmail,
4855
4916
  updateFieldById,
4856
4917
  updateStatusById,
4857
- deleteById
4918
+ deleteById,
4919
+ getOrgsByEmail
4858
4920
  };
4859
4921
  }
4860
4922
 
@@ -5854,7 +5916,6 @@ function useVerificationService() {
5854
5916
  await getSiteById(metadata.siteId);
5855
5917
  }
5856
5918
  const verificationIds = [];
5857
- const invitedApps = [];
5858
5919
  for (const app of apps) {
5859
5920
  await useVerificationRepo().findOne({
5860
5921
  type,
@@ -5877,34 +5938,32 @@ function useVerificationService() {
5877
5938
  };
5878
5939
  const createdId = await add(value);
5879
5940
  verificationIds.push(createdId.toString());
5880
- invitedApps.push(app);
5941
+ const link = `${APP_MAIN}/verify/invitation/${createdId}`;
5942
+ const emailContent = (0, import_node_server_utils21.compileHandlebar)({
5943
+ context: {
5944
+ email,
5945
+ validity: VERIFICATION_USER_INVITE_DURATION,
5946
+ link,
5947
+ hasPropertyManagement: app === "property_management_agency",
5948
+ hasSecurity: app === "security_agency",
5949
+ hasCleaning: app === "cleaning_services",
5950
+ hasMechanical: app === "mechanical_electrical_services",
5951
+ hasLandscape: app === "landscaping_services",
5952
+ hasPestControl: app === "pest_control_services",
5953
+ hasPoolMaintenance: app === "pool_maintenance_services"
5954
+ },
5955
+ filePath: (0, import_node_server_utils21.getDirectory)(
5956
+ __dirname,
5957
+ "./public/handlebars/user-invite"
5958
+ )
5959
+ });
5960
+ await mailer.sendMail({
5961
+ to: email,
5962
+ subject: "User Invite",
5963
+ html: emailContent,
5964
+ sender: "iService365"
5965
+ });
5881
5966
  }
5882
- const link = `${APP_MAIN}/verify/invitation/${verificationIds[0]}`;
5883
- const appsSet = new Set(invitedApps);
5884
- const emailContent = (0, import_node_server_utils21.compileHandlebar)({
5885
- context: {
5886
- email,
5887
- validity: VERIFICATION_USER_INVITE_DURATION,
5888
- link,
5889
- hasPropertyManagement: appsSet.has("property_management_agency"),
5890
- hasSecurity: appsSet.has("security_agency"),
5891
- hasCleaning: appsSet.has("cleaning_services"),
5892
- hasMechanical: appsSet.has("mechanical_electrical_services"),
5893
- hasLandscape: appsSet.has("landscaping_services"),
5894
- hasPestControl: appsSet.has("pest_control_services"),
5895
- hasPoolMaintenance: appsSet.has("pool_maintenance_services")
5896
- },
5897
- filePath: (0, import_node_server_utils21.getDirectory)(
5898
- __dirname,
5899
- "./public/handlebars/user-invite"
5900
- )
5901
- });
5902
- await mailer.sendMail({
5903
- to: email,
5904
- subject: "User Invite",
5905
- html: emailContent,
5906
- sender: "iService365"
5907
- });
5908
5967
  return verificationIds;
5909
5968
  }
5910
5969
  async function createSimpleMemberInvite({
@@ -8374,7 +8433,7 @@ function useVerificationController() {
8374
8433
  siteId: import_joi16.default.string().hex().optional().allow("", null),
8375
8434
  siteName: import_joi16.default.string().optional().allow("", null)
8376
8435
  });
8377
- const { error } = validation.validate(payload);
8436
+ const { error, value } = validation.validate(payload);
8378
8437
  if (error) {
8379
8438
  import_node_server_utils32.logger.log({
8380
8439
  level: "error",
@@ -8383,15 +8442,17 @@ function useVerificationController() {
8383
8442
  next(new import_node_server_utils32.BadRequestError(error.message));
8384
8443
  return;
8385
8444
  }
8386
- const email = req.body.email ?? "";
8387
- const app = req.body.app ?? [];
8388
- const role = req.body.role ?? "";
8389
- const name = req.body.name ?? "";
8390
- const org = req.body.org ?? "";
8391
- const siteId = req.body.siteId ?? "";
8392
- const siteName = req.body.siteName ?? "";
8393
8445
  try {
8394
- await _createSimpleUserInvite({
8446
+ const {
8447
+ email,
8448
+ app,
8449
+ role,
8450
+ name,
8451
+ org,
8452
+ siteId,
8453
+ siteName
8454
+ } = value;
8455
+ const verificationIds = await _createSimpleUserInvite({
8395
8456
  email,
8396
8457
  metadata: {
8397
8458
  app,
@@ -8403,7 +8464,9 @@ function useVerificationController() {
8403
8464
  }
8404
8465
  });
8405
8466
  res.status(201).json({
8406
- message: "Successfully invited user."
8467
+ message: "Successfully invited user.",
8468
+ totalInvites: verificationIds.length,
8469
+ verificationIds
8407
8470
  });
8408
8471
  return;
8409
8472
  } catch (error2) {
@@ -8859,7 +8922,8 @@ function useOrgController() {
8859
8922
  getByEmail: _getByEmail,
8860
8923
  getAll: _getAll,
8861
8924
  add: _add,
8862
- update: _update
8925
+ update: _update,
8926
+ getOrgsByEmail: _getOrgsByEmail
8863
8927
  } = useOrgRepo();
8864
8928
  async function add(req, res, next) {
8865
8929
  const validation = import_joi18.default.object({
@@ -9043,6 +9107,30 @@ function useOrgController() {
9043
9107
  return;
9044
9108
  }
9045
9109
  }
9110
+ async function getOrgsByEmail(req, res, next) {
9111
+ const validation = import_joi18.default.object({
9112
+ email: import_joi18.default.string().email().required()
9113
+ });
9114
+ const query = {
9115
+ email: req.params.email
9116
+ };
9117
+ const { error } = validation.validate(query);
9118
+ if (error) {
9119
+ import_node_server_utils35.logger.log({ level: "error", message: error.message });
9120
+ next(new import_node_server_utils35.BadRequestError(error.message));
9121
+ return;
9122
+ }
9123
+ const email = req.params.email;
9124
+ try {
9125
+ const data = await _getOrgsByEmail(email);
9126
+ res.json(data);
9127
+ return;
9128
+ } catch (error2) {
9129
+ import_node_server_utils35.logger.log({ level: "error", message: error2.message });
9130
+ next(error2);
9131
+ return;
9132
+ }
9133
+ }
9046
9134
  async function update(req, res, next) {
9047
9135
  const validation = import_joi18.default.object({
9048
9136
  name: import_joi18.default.string().optional(),
@@ -9076,7 +9164,8 @@ function useOrgController() {
9076
9164
  getByName,
9077
9165
  getById,
9078
9166
  getByEmail,
9079
- update
9167
+ update,
9168
+ getOrgsByEmail
9080
9169
  };
9081
9170
  }
9082
9171
 
@@ -12573,6 +12662,33 @@ function useServiceProviderRepo() {
12573
12662
  throw error;
12574
12663
  }
12575
12664
  }
12665
+ async function updateStatusById(_id, status) {
12666
+ try {
12667
+ _id = new import_mongodb34.ObjectId(_id);
12668
+ } catch (error) {
12669
+ throw new import_node_server_utils56.BadRequestError("Invalid service provider ID format.");
12670
+ }
12671
+ try {
12672
+ const result = await collection.updateOne(
12673
+ { _id },
12674
+ { $set: { status, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } }
12675
+ );
12676
+ if (!result.matchedCount) {
12677
+ throw new import_node_server_utils56.NotFoundError("Service provider not found.");
12678
+ }
12679
+ delNamespace().then(() => {
12680
+ import_node_server_utils56.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
12681
+ }).catch((err) => {
12682
+ import_node_server_utils56.logger.error(
12683
+ `Failed to clear cache for namespace: ${namespace_collection}`,
12684
+ err
12685
+ );
12686
+ });
12687
+ return result;
12688
+ } catch (error) {
12689
+ throw error;
12690
+ }
12691
+ }
12576
12692
  return {
12577
12693
  createTextIndex,
12578
12694
  createUniqueIndex,
@@ -12582,7 +12698,8 @@ function useServiceProviderRepo() {
12582
12698
  getServiceProviderTypes,
12583
12699
  getServiceProviderById,
12584
12700
  getByServiceProviderOrgIdType,
12585
- getByEmail
12701
+ getByEmail,
12702
+ updateStatusById
12586
12703
  };
12587
12704
  }
12588
12705
 
@@ -13358,7 +13475,8 @@ function useServiceProviderController() {
13358
13475
  getServiceProviderTypes: _getServiceProviderTypes,
13359
13476
  getServiceProviderById: _getServiceProviderById,
13360
13477
  getServiceProviders: _getServiceProviders,
13361
- getByServiceProviderOrgIdType: _getByServiceProviderOrgIdType
13478
+ getByServiceProviderOrgIdType: _getByServiceProviderOrgIdType,
13479
+ updateStatusById: _updateStatusById
13362
13480
  } = useServiceProviderRepo();
13363
13481
  const { createServiceProvider: _createServiceProvider } = useServiceProviderService();
13364
13482
  const { createServiceProvider: _add } = useServiceProviderRepo();
@@ -13572,6 +13690,30 @@ function useServiceProviderController() {
13572
13690
  return;
13573
13691
  }
13574
13692
  }
13693
+ async function updateStatusById(req, res, next) {
13694
+ const validation = import_joi31.default.object({
13695
+ id: import_joi31.default.string().hex().required(),
13696
+ status: import_joi31.default.string().valid("active", "inactive").required()
13697
+ });
13698
+ const { error, value } = validation.validate({
13699
+ id: req.params.id,
13700
+ status: req.body.status
13701
+ });
13702
+ if (error) {
13703
+ import_node_server_utils62.logger.log({ level: "error", message: error.message });
13704
+ next(new import_node_server_utils62.BadRequestError(error.message));
13705
+ return;
13706
+ }
13707
+ try {
13708
+ await _updateStatusById(value.id, value.status);
13709
+ res.json({ message: "Service provider status updated successfully." });
13710
+ return;
13711
+ } catch (error2) {
13712
+ import_node_server_utils62.logger.log({ level: "error", message: error2.message });
13713
+ next(error2);
13714
+ return;
13715
+ }
13716
+ }
13575
13717
  return {
13576
13718
  createServiceProvider,
13577
13719
  getServiceProviders,
@@ -13580,7 +13722,8 @@ function useServiceProviderController() {
13580
13722
  getServiceProviderTypes,
13581
13723
  getServiceProviderById,
13582
13724
  getByServiceProviderOrgIdType,
13583
- add
13725
+ add,
13726
+ updateStatusById
13584
13727
  };
13585
13728
  }
13586
13729
 
@@ -26604,7 +26747,14 @@ function usePersonService() {
26604
26747
  password: hashedPassword,
26605
26748
  name: value.name,
26606
26749
  status: value.platform == "mobile" ? "pending" : "active",
26607
- defaultOrg: value.org?.toString() || ""
26750
+ defaultOrg: value.org?.toString() || "",
26751
+ block: value.block,
26752
+ level: value.level,
26753
+ type: value.type,
26754
+ unitName: value.unitName,
26755
+ contact: value.contact,
26756
+ site: value.site?.toString() || "",
26757
+ unitId: value.unit?.toString() || ""
26608
26758
  };
26609
26759
  const userId = await addUser(user, session);
26610
26760
  value.user = userId.toString();
@@ -36250,10 +36400,42 @@ function UseAccessManagementRepo() {
36250
36400
  },
36251
36401
  {
36252
36402
  $facet: {
36253
- available_physical: [{ $match: { assignedUnit: { $eq: null }, type: "NFC" /* NFC */ } }, { $count: "count" }],
36254
- available_non_physical: [{ $match: { assignedUnit: { $eq: null }, type: "QRCODE" /* QR */ } }, { $count: "count" }],
36255
- assigned_physical: [{ $match: { assignedUnit: { $ne: null }, type: "NFC" /* NFC */ } }, { $count: "count" }],
36256
- assigned_non_physical: [{ $match: { assignedUnit: { $ne: null }, type: "QRCODE" /* QR */ } }, { $count: "count" }]
36403
+ available_physical: [
36404
+ {
36405
+ $match: {
36406
+ assignedUnit: { $eq: null },
36407
+ type: "NFC" /* NFC */
36408
+ }
36409
+ },
36410
+ { $count: "count" }
36411
+ ],
36412
+ available_non_physical: [
36413
+ {
36414
+ $match: {
36415
+ assignedUnit: { $eq: null },
36416
+ type: "QRCODE" /* QR */
36417
+ }
36418
+ },
36419
+ { $count: "count" }
36420
+ ],
36421
+ assigned_physical: [
36422
+ {
36423
+ $match: {
36424
+ assignedUnit: { $ne: null },
36425
+ type: "NFC" /* NFC */
36426
+ }
36427
+ },
36428
+ { $count: "count" }
36429
+ ],
36430
+ assigned_non_physical: [
36431
+ {
36432
+ $match: {
36433
+ assignedUnit: { $ne: null },
36434
+ type: "QRCODE" /* QR */
36435
+ }
36436
+ },
36437
+ { $count: "count" }
36438
+ ]
36257
36439
  }
36258
36440
  }
36259
36441
  ]).toArray();
@@ -36338,16 +36520,35 @@ function UseAccessManagementRepo() {
36338
36520
  case terms.length >= 3:
36339
36521
  return {
36340
36522
  $and: [
36341
- { $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] } },
36342
- { $expr: { $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()] } },
36343
- { $expr: { $eq: [{ $toLower: "$level.units.name" }, getAfterSecondSlash(search)] } }
36523
+ {
36524
+ $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] }
36525
+ },
36526
+ {
36527
+ $expr: {
36528
+ $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()]
36529
+ }
36530
+ },
36531
+ {
36532
+ $expr: {
36533
+ $eq: [
36534
+ { $toLower: "$level.units.name" },
36535
+ getAfterSecondSlash(search)
36536
+ ]
36537
+ }
36538
+ }
36344
36539
  ]
36345
36540
  };
36346
36541
  case terms.length === 2:
36347
36542
  return {
36348
36543
  $and: [
36349
- { $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] } },
36350
- { $expr: { $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()] } }
36544
+ {
36545
+ $expr: { $eq: [{ $toLower: "$name" }, terms[0].toLowerCase()] }
36546
+ },
36547
+ {
36548
+ $expr: {
36549
+ $eq: [{ $toLower: "$level.level" }, terms[1].toLowerCase()]
36550
+ }
36551
+ }
36351
36552
  ]
36352
36553
  };
36353
36554
  default:
@@ -36375,220 +36576,386 @@ function UseAccessManagementRepo() {
36375
36576
  site
36376
36577
  };
36377
36578
  const searchQuery = buildSearchQuery(search);
36378
- const result = await collectionName("buildings").aggregate([
36379
- // ✅ Match early with index-friendly query
36380
- {
36381
- $match: {
36382
- ...defaultQuery,
36383
- status: { $eq: "active" }
36384
- }
36385
- },
36386
- // ✅ Only project needed fields before heavy lookups
36387
- {
36388
- $project: {
36389
- _id: 1,
36390
- name: 1,
36391
- site: 1,
36392
- block: 1
36393
- }
36394
- },
36395
- // ✅ Use localField/foreignField for better index usage
36396
- {
36397
- $lookup: {
36398
- from: "building-levels",
36399
- localField: "_id",
36400
- foreignField: "block",
36401
- pipeline: [
36402
- { $match: { status: { $ne: "deleted" } } },
36403
- {
36404
- $lookup: {
36405
- from: "building-units",
36406
- localField: "_id",
36407
- foreignField: "level",
36408
- pipeline: [
36409
- { $match: { status: { $ne: "deleted" }, site } },
36410
- { $project: { _id: 1, name: 1 } }
36411
- ],
36412
- as: "units"
36413
- }
36414
- },
36415
- {
36416
- $match: { "units.0": { $exists: true } }
36417
- },
36418
- {
36419
- $project: {
36420
- _id: 1,
36421
- level: 1,
36422
- units: 1
36579
+ const result = await collectionName("buildings").aggregate(
36580
+ [
36581
+ // ✅ Match early with index-friendly query
36582
+ {
36583
+ $match: {
36584
+ ...defaultQuery,
36585
+ status: { $eq: "active" }
36586
+ }
36587
+ },
36588
+ // ✅ Only project needed fields before heavy lookups
36589
+ {
36590
+ $project: {
36591
+ _id: 1,
36592
+ name: 1,
36593
+ site: 1,
36594
+ block: 1
36595
+ }
36596
+ },
36597
+ // ✅ Use localField/foreignField for better index usage
36598
+ {
36599
+ $lookup: {
36600
+ from: "building-levels",
36601
+ localField: "_id",
36602
+ foreignField: "block",
36603
+ pipeline: [
36604
+ { $match: { status: { $ne: "deleted" } } },
36605
+ {
36606
+ $lookup: {
36607
+ from: "building-units",
36608
+ localField: "_id",
36609
+ foreignField: "level",
36610
+ pipeline: [
36611
+ { $match: { status: { $ne: "deleted" }, site } },
36612
+ { $project: { _id: 1, name: 1 } }
36613
+ ],
36614
+ as: "units"
36615
+ }
36616
+ },
36617
+ {
36618
+ $match: { "units.0": { $exists: true } }
36619
+ },
36620
+ {
36621
+ $project: {
36622
+ _id: 1,
36623
+ level: 1,
36624
+ units: 1
36625
+ }
36423
36626
  }
36424
- }
36425
- ],
36426
- as: "level"
36427
- }
36428
- },
36429
- // ✅ Filter out buildings with no levels early
36430
- {
36431
- $match: { "level.0": { $exists: true } }
36432
- },
36433
- // ✅ Unwind to flatten the hierarchy
36434
- {
36435
- $unwind: {
36436
- path: "$level",
36437
- preserveNullAndEmptyArrays: false
36438
- }
36439
- },
36440
- {
36441
- $unwind: {
36442
- path: "$level.units",
36443
- preserveNullAndEmptyArrays: false
36444
- }
36445
- },
36446
- // // Groups by unit _id and keeps only the first occurrence
36447
- // {
36448
- // $group: {
36449
- // _id: "$level.units._id",
36450
- // doc: { $first: "$$ROOT" },
36451
- // },
36452
- // },
36453
- // {
36454
- // $replaceRoot: { newRoot: "$doc" },
36455
- // },
36456
- // ✅ Apply search filter
36457
- {
36458
- $match: {
36459
- ...searchQuery
36460
- }
36461
- },
36462
- {
36463
- $facet: {
36464
- totalCount: [{ $count: "count" }],
36465
- items: [
36466
- // Sort BEFORE skip/limit for correct pagination
36467
- { $skip: page * limit },
36468
- { $limit: limit },
36469
- // ✅ Users lookup - optimized with index hint
36470
- {
36471
- $lookup: {
36472
- from: "users",
36473
- let: { unit: "$level.units._id" },
36474
- pipeline: [
36475
- {
36476
- $match: {
36477
- $expr: { $eq: ["$unitNumber", "$$unit"] },
36478
- residentType: "House/Unit Owner"
36627
+ ],
36628
+ as: "level"
36629
+ }
36630
+ },
36631
+ // ✅ Filter out buildings with no levels early
36632
+ {
36633
+ $match: { "level.0": { $exists: true } }
36634
+ },
36635
+ // ✅ Unwind to flatten the hierarchy
36636
+ {
36637
+ $unwind: {
36638
+ path: "$level",
36639
+ preserveNullAndEmptyArrays: false
36640
+ }
36641
+ },
36642
+ {
36643
+ $unwind: {
36644
+ path: "$level.units",
36645
+ preserveNullAndEmptyArrays: false
36646
+ }
36647
+ },
36648
+ // // Groups by unit _id and keeps only the first occurrence
36649
+ // {
36650
+ // $group: {
36651
+ // _id: "$level.units._id",
36652
+ // doc: { $first: "$$ROOT" },
36653
+ // },
36654
+ // },
36655
+ // {
36656
+ // $replaceRoot: { newRoot: "$doc" },
36657
+ // },
36658
+ // ✅ Apply search filter
36659
+ {
36660
+ $match: {
36661
+ ...searchQuery
36662
+ }
36663
+ },
36664
+ {
36665
+ $facet: {
36666
+ totalCount: [{ $count: "count" }],
36667
+ items: [
36668
+ // ✅ Sort BEFORE skip/limit for correct pagination
36669
+ { $skip: page * limit },
36670
+ { $limit: limit },
36671
+ // Users lookup - optimized with index hint
36672
+ {
36673
+ $lookup: {
36674
+ from: "users",
36675
+ let: { unit: "$level.units._id" },
36676
+ pipeline: [
36677
+ {
36678
+ $match: {
36679
+ $expr: { $eq: ["$unitNumber", "$$unit"] },
36680
+ residentType: "House/Unit Owner"
36681
+ }
36682
+ },
36683
+ { $limit: 1 },
36684
+ { $project: { _id: 1, givenName: 1, surname: 1 } }
36685
+ ],
36686
+ as: "unitOwner"
36687
+ }
36688
+ },
36689
+ // ✅ Access card lookup - optimized query
36690
+ {
36691
+ $lookup: {
36692
+ from: "access-cards",
36693
+ let: { unit: "$level.units._id" },
36694
+ pipeline: [
36695
+ {
36696
+ $match: {
36697
+ $expr: {
36698
+ $in: [
36699
+ "$$unit",
36700
+ {
36701
+ $cond: [
36702
+ { $isArray: "$assignedUnit" },
36703
+ "$assignedUnit",
36704
+ ["$assignedUnit"]
36705
+ ]
36706
+ }
36707
+ ]
36708
+ },
36709
+ userType
36710
+ }
36711
+ },
36712
+ {
36713
+ $project: {
36714
+ _id: 1,
36715
+ userId: 1,
36716
+ type: 1,
36717
+ cardNo: 1,
36718
+ isActivated: 1,
36719
+ replacementStatus: 1
36720
+ }
36721
+ }
36722
+ ],
36723
+ as: "accessCards"
36724
+ }
36725
+ },
36726
+ // ✅ Compute all card categorization and counts in ONE stage
36727
+ {
36728
+ $addFields: {
36729
+ f_Available: {
36730
+ $filter: {
36731
+ input: "$accessCards",
36732
+ as: "card",
36733
+ cond: {
36734
+ $and: [
36735
+ { $eq: ["$$card.userId", null] },
36736
+ { $eq: ["$$card.isActivated", true] }
36737
+ ]
36738
+ }
36479
36739
  }
36480
36740
  },
36481
- { $limit: 1 },
36482
- { $project: { _id: 1, givenName: 1, surname: 1 } }
36483
- ],
36484
- as: "unitOwner"
36485
- }
36486
- },
36487
- // Access card lookup - optimized query
36488
- {
36489
- $lookup: {
36490
- from: "access-cards",
36491
- let: { unit: "$level.units._id" },
36492
- pipeline: [
36493
- {
36494
- $match: {
36495
- $expr: {
36496
- $in: [
36497
- "$$unit",
36498
- { $cond: [{ $isArray: "$assignedUnit" }, "$assignedUnit", ["$assignedUnit"]] }
36741
+ f_Assigned: {
36742
+ $filter: {
36743
+ input: "$accessCards",
36744
+ as: "card",
36745
+ cond: {
36746
+ $and: [
36747
+ { $ne: ["$$card.userId", null] },
36748
+ { $eq: ["$$card.isActivated", true] }
36499
36749
  ]
36500
- },
36501
- userType
36750
+ }
36502
36751
  }
36503
36752
  },
36504
- { $project: { _id: 1, userId: 1, type: 1, cardNo: 1, isActivated: 1, replacementStatus: 1 } }
36505
- ],
36506
- as: "accessCards"
36507
- }
36508
- },
36509
- // ✅ Compute all card categorization and counts in ONE stage
36510
- {
36511
- $addFields: {
36512
- f_Available: {
36513
- $filter: {
36514
- input: "$accessCards",
36515
- as: "card",
36516
- cond: { $and: [{ $eq: ["$$card.userId", null] }, { $eq: ["$$card.isActivated", true] }] }
36517
- }
36518
- },
36519
- f_Assigned: {
36520
- $filter: {
36521
- input: "$accessCards",
36522
- as: "card",
36523
- cond: { $and: [{ $ne: ["$$card.userId", null] }, { $eq: ["$$card.isActivated", true] }] }
36524
- }
36525
- },
36526
- f_replaced: {
36527
- $filter: {
36528
- input: "$accessCards",
36529
- as: "card",
36530
- cond: { $and: [{ $eq: ["$$card.isActivated", false] }, { $ne: ["$$card.replacementStatus", null] }] }
36531
- }
36532
- },
36533
- f_deleted: {
36534
- $filter: {
36535
- input: "$accessCards",
36536
- as: "card",
36537
- cond: { $and: [{ $eq: ["$$card.isActivated", false] }, { $eq: ["$$card.replacementStatus", null] }] }
36753
+ f_replaced: {
36754
+ $filter: {
36755
+ input: "$accessCards",
36756
+ as: "card",
36757
+ cond: {
36758
+ $and: [
36759
+ { $eq: ["$$card.isActivated", false] },
36760
+ { $ne: ["$$card.replacementStatus", null] }
36761
+ ]
36762
+ }
36763
+ }
36764
+ },
36765
+ f_deleted: {
36766
+ $filter: {
36767
+ input: "$accessCards",
36768
+ as: "card",
36769
+ cond: {
36770
+ $and: [
36771
+ { $eq: ["$$card.isActivated", false] },
36772
+ { $eq: ["$$card.replacementStatus", null] }
36773
+ ]
36774
+ }
36775
+ }
36538
36776
  }
36539
36777
  }
36540
- }
36541
- },
36542
- // ✅ Final projection with all computed fields
36543
- {
36544
- $project: {
36545
- _id: "$level.units._id",
36546
- name: "$level.units.name",
36547
- level: { _id: "$level._id", level: "$level.level" },
36548
- block: { _id: "$_id", name: "$name", block: "$block" },
36549
- site: "$site",
36550
- unit_owner: { $arrayElemAt: ["$unitOwner", 0] },
36551
- available: {
36552
- physical: { $filter: { input: "$f_Available", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36553
- non_physical: { $filter: { input: "$f_Available", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36554
- },
36555
- assigned: {
36556
- physical: { $filter: { input: "$f_Assigned", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36557
- non_physical: { $filter: { input: "$f_Assigned", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36558
- },
36559
- cardCounts: {
36778
+ },
36779
+ // ✅ Final projection with all computed fields
36780
+ {
36781
+ $project: {
36782
+ _id: "$level.units._id",
36783
+ name: "$level.units.name",
36784
+ level: { _id: "$level._id", level: "$level.level" },
36785
+ block: { _id: "$_id", name: "$name", block: "$block" },
36786
+ site: "$site",
36787
+ unit_owner: { $arrayElemAt: ["$unitOwner", 0] },
36560
36788
  available: {
36561
- physical: { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36562
- non_physical: { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36789
+ physical: {
36790
+ $filter: {
36791
+ input: "$f_Available",
36792
+ as: "c",
36793
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36794
+ }
36795
+ },
36796
+ non_physical: {
36797
+ $filter: {
36798
+ input: "$f_Available",
36799
+ as: "c",
36800
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36801
+ }
36802
+ }
36563
36803
  },
36564
36804
  assigned: {
36565
- physical: { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36566
- non_physical: { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36805
+ physical: {
36806
+ $filter: {
36807
+ input: "$f_Assigned",
36808
+ as: "c",
36809
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36810
+ }
36811
+ },
36812
+ non_physical: {
36813
+ $filter: {
36814
+ input: "$f_Assigned",
36815
+ as: "c",
36816
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36817
+ }
36818
+ }
36819
+ },
36820
+ cardCounts: {
36821
+ available: {
36822
+ physical: {
36823
+ $size: {
36824
+ $filter: {
36825
+ input: { $ifNull: ["$f_Available", []] },
36826
+ as: "c",
36827
+ cond: {
36828
+ $eq: ["$$c.type", "NFC" /* NFC */]
36829
+ }
36830
+ }
36831
+ }
36832
+ },
36833
+ non_physical: {
36834
+ $size: {
36835
+ $filter: {
36836
+ input: { $ifNull: ["$f_Available", []] },
36837
+ as: "c",
36838
+ cond: {
36839
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36840
+ }
36841
+ }
36842
+ }
36843
+ }
36844
+ },
36845
+ assigned: {
36846
+ physical: {
36847
+ $size: {
36848
+ $filter: {
36849
+ input: { $ifNull: ["$f_Assigned", []] },
36850
+ as: "c",
36851
+ cond: {
36852
+ $eq: ["$$c.type", "NFC" /* NFC */]
36853
+ }
36854
+ }
36855
+ }
36856
+ },
36857
+ non_physical: {
36858
+ $size: {
36859
+ $filter: {
36860
+ input: { $ifNull: ["$f_Assigned", []] },
36861
+ as: "c",
36862
+ cond: {
36863
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36864
+ }
36865
+ }
36866
+ }
36867
+ }
36868
+ }
36869
+ },
36870
+ replaced: {
36871
+ physical: {
36872
+ $filter: {
36873
+ input: "$f_replaced",
36874
+ as: "c",
36875
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36876
+ }
36877
+ },
36878
+ non_physical: {
36879
+ $filter: {
36880
+ input: "$f_replaced",
36881
+ as: "c",
36882
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36883
+ }
36884
+ }
36885
+ },
36886
+ deleted: {
36887
+ physical: {
36888
+ $filter: {
36889
+ input: "$f_deleted",
36890
+ as: "c",
36891
+ cond: { $eq: ["$$c.type", "NFC" /* NFC */] }
36892
+ }
36893
+ },
36894
+ non_physical: {
36895
+ $filter: {
36896
+ input: "$f_deleted",
36897
+ as: "c",
36898
+ cond: { $eq: ["$$c.type", "QRCODE" /* QR */] }
36899
+ }
36900
+ }
36901
+ },
36902
+ totalCardCount: {
36903
+ $add: [
36904
+ {
36905
+ $size: {
36906
+ $filter: {
36907
+ input: { $ifNull: ["$f_Available", []] },
36908
+ as: "c",
36909
+ cond: {
36910
+ $eq: ["$$c.type", "NFC" /* NFC */]
36911
+ }
36912
+ }
36913
+ }
36914
+ },
36915
+ {
36916
+ $size: {
36917
+ $filter: {
36918
+ input: { $ifNull: ["$f_Available", []] },
36919
+ as: "c",
36920
+ cond: {
36921
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36922
+ }
36923
+ }
36924
+ }
36925
+ },
36926
+ {
36927
+ $size: {
36928
+ $filter: {
36929
+ input: { $ifNull: ["$f_Assigned", []] },
36930
+ as: "c",
36931
+ cond: {
36932
+ $eq: ["$$c.type", "NFC" /* NFC */]
36933
+ }
36934
+ }
36935
+ }
36936
+ },
36937
+ {
36938
+ $size: {
36939
+ $filter: {
36940
+ input: { $ifNull: ["$f_Assigned", []] },
36941
+ as: "c",
36942
+ cond: {
36943
+ $eq: ["$$c.type", "QRCODE" /* QR */]
36944
+ }
36945
+ }
36946
+ }
36947
+ }
36948
+ ]
36567
36949
  }
36568
- },
36569
- replaced: {
36570
- physical: { $filter: { input: "$f_replaced", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36571
- non_physical: { $filter: { input: "$f_replaced", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36572
- },
36573
- deleted: {
36574
- physical: { $filter: { input: "$f_deleted", as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } },
36575
- non_physical: { $filter: { input: "$f_deleted", as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } }
36576
- },
36577
- totalCardCount: {
36578
- $add: [
36579
- { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36580
- { $size: { $filter: { input: { $ifNull: ["$f_Available", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } },
36581
- { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "NFC" /* NFC */] } } } },
36582
- { $size: { $filter: { input: { $ifNull: ["$f_Assigned", []] }, as: "c", cond: { $eq: ["$$c.type", "QRCODE" /* QR */] } } } }
36583
- ]
36584
36950
  }
36585
- }
36586
- },
36587
- { $sort: { totalCardCount: -1 } }
36588
- ]
36951
+ },
36952
+ { $sort: { totalCardCount: -1 } }
36953
+ ]
36954
+ }
36589
36955
  }
36590
- }
36591
- ], { allowDiskUse: true }).toArray();
36956
+ ],
36957
+ { allowDiskUse: true }
36958
+ ).toArray();
36592
36959
  const totalCount = result[0]?.totalCount?.[0]?.count ?? 0;
36593
36960
  const items = result[0]?.items ?? [];
36594
36961
  const paginatedResult = (0, import_node_server_utils154.paginate)(items, page, limit, totalCount);
@@ -36607,157 +36974,162 @@ function UseAccessManagementRepo() {
36607
36974
  site: { $in: [site] }
36608
36975
  };
36609
36976
  const searchQuery = buildSearchQuery(search);
36610
- const result = await collectionName("buildings").aggregate([
36611
- // ✅ Match early with index-friendly query
36612
- {
36613
- $match: {
36614
- ...query,
36615
- status: { $ne: "deleted" }
36616
- }
36617
- },
36618
- // ✅ Only project needed fields before heavy lookups
36619
- {
36620
- $project: {
36621
- _id: 1,
36622
- name: 1,
36623
- site: 1
36624
- }
36625
- },
36626
- // ✅ Use localField/foreignField for better index usage
36627
- {
36628
- $lookup: {
36629
- from: "building-levels",
36630
- localField: "_id",
36631
- foreignField: "block",
36632
- pipeline: [
36633
- { $match: { status: { $ne: "deleted" } } },
36634
- {
36635
- $lookup: {
36636
- from: "building-units",
36637
- localField: "_id",
36638
- foreignField: "level",
36639
- pipeline: [
36640
- { $match: { status: { $ne: "deleted" } } },
36641
- { $project: { _id: 1, name: 1 } },
36642
- {
36643
- $lookup: {
36644
- from: "access-cards",
36645
- localField: "_id",
36646
- foreignField: "assignedUnit",
36647
- pipeline: [
36648
- {
36649
- $match: {
36650
- isActivated: true,
36651
- userType,
36652
- type
36653
- }
36654
- },
36655
- {
36656
- $group: {
36657
- _id: null,
36658
- accessLevels: { $addToSet: "$accessLevel" },
36659
- liftAccessLevels: { $addToSet: "$liftAccessLevel" },
36660
- doorNames: { $addToSet: "$doorName" },
36661
- liftNames: { $addToSet: "$liftName" },
36662
- cards: {
36663
- $push: {
36664
- _id: "$_id",
36665
- cardNo: "$cardNo",
36666
- accessLevel: "$accessLevel",
36667
- liftAccessLevel: "$liftAccessLevel",
36668
- doorName: "$doorName",
36669
- liftName: "$liftName"
36977
+ const result = await collectionName("buildings").aggregate(
36978
+ [
36979
+ // ✅ Match early with index-friendly query
36980
+ {
36981
+ $match: {
36982
+ ...query,
36983
+ status: { $ne: "deleted" }
36984
+ }
36985
+ },
36986
+ // ✅ Only project needed fields before heavy lookups
36987
+ {
36988
+ $project: {
36989
+ _id: 1,
36990
+ name: 1,
36991
+ site: 1
36992
+ }
36993
+ },
36994
+ // ✅ Use localField/foreignField for better index usage
36995
+ {
36996
+ $lookup: {
36997
+ from: "building-levels",
36998
+ localField: "_id",
36999
+ foreignField: "block",
37000
+ pipeline: [
37001
+ { $match: { status: { $ne: "deleted" } } },
37002
+ {
37003
+ $lookup: {
37004
+ from: "building-units",
37005
+ localField: "_id",
37006
+ foreignField: "level",
37007
+ pipeline: [
37008
+ { $match: { status: { $ne: "deleted" } } },
37009
+ { $project: { _id: 1, name: 1 } },
37010
+ {
37011
+ $lookup: {
37012
+ from: "access-cards",
37013
+ localField: "_id",
37014
+ foreignField: "assignedUnit",
37015
+ pipeline: [
37016
+ {
37017
+ $match: {
37018
+ isActivated: true,
37019
+ userType,
37020
+ type
37021
+ }
37022
+ },
37023
+ {
37024
+ $group: {
37025
+ _id: null,
37026
+ accessLevels: { $addToSet: "$accessLevel" },
37027
+ liftAccessLevels: {
37028
+ $addToSet: "$liftAccessLevel"
37029
+ },
37030
+ doorNames: { $addToSet: "$doorName" },
37031
+ liftNames: { $addToSet: "$liftName" },
37032
+ cards: {
37033
+ $push: {
37034
+ _id: "$_id",
37035
+ cardNo: "$cardNo",
37036
+ accessLevel: "$accessLevel",
37037
+ liftAccessLevel: "$liftAccessLevel",
37038
+ doorName: "$doorName",
37039
+ liftName: "$liftName"
37040
+ }
36670
37041
  }
36671
37042
  }
37043
+ },
37044
+ {
37045
+ $project: {
37046
+ _id: 0,
37047
+ accessCardCount: {
37048
+ $size: "$cards"
37049
+ },
37050
+ accessLevels: 1,
37051
+ liftAccessLevels: 1,
37052
+ doorNames: 1,
37053
+ liftNames: 1
37054
+ }
36672
37055
  }
36673
- },
36674
- {
36675
- $project: {
36676
- _id: 0,
36677
- accessCardCount: {
36678
- $size: "$cards"
36679
- },
36680
- accessLevels: 1,
36681
- liftAccessLevels: 1,
36682
- doorNames: 1,
36683
- liftNames: 1
36684
- }
36685
- }
36686
- ],
36687
- as: "fAccessCards"
36688
- }
36689
- },
36690
- {
36691
- $match: {
36692
- "fAccessCards.0": { $exists: true }
37056
+ ],
37057
+ as: "fAccessCards"
37058
+ }
37059
+ },
37060
+ {
37061
+ $match: {
37062
+ "fAccessCards.0": { $exists: true }
37063
+ }
36693
37064
  }
36694
- }
36695
- ],
36696
- as: "units"
36697
- }
36698
- },
36699
- {
36700
- $match: { "units.0": { $exists: true } }
36701
- },
36702
- {
36703
- $project: {
36704
- _id: 1,
36705
- level: 1,
36706
- units: 1
37065
+ ],
37066
+ as: "units"
37067
+ }
37068
+ },
37069
+ {
37070
+ $match: { "units.0": { $exists: true } }
37071
+ },
37072
+ {
37073
+ $project: {
37074
+ _id: 1,
37075
+ level: 1,
37076
+ units: 1
37077
+ }
36707
37078
  }
36708
- }
36709
- ],
36710
- as: "level"
36711
- }
36712
- },
36713
- // ✅ Filter out buildings with no levels early
36714
- {
36715
- $match: { "level.0": { $exists: true } }
36716
- },
36717
- // ✅ Unwind to flatten the hierarchy
36718
- {
36719
- $unwind: {
36720
- path: "$level",
36721
- preserveNullAndEmptyArrays: false
36722
- }
36723
- },
36724
- {
36725
- $unwind: {
36726
- path: "$level.units",
36727
- preserveNullAndEmptyArrays: false
36728
- }
36729
- },
36730
- {
36731
- $unwind: {
36732
- path: "$level.units.fAccessCards",
36733
- preserveNullAndEmptyArrays: false
36734
- }
36735
- },
36736
- // // Groups by unit _id and keeps only the first occurrence
36737
- {
36738
- $group: {
36739
- _id: "$level.units._id",
36740
- doc: { $first: "$$ROOT" }
36741
- }
36742
- },
36743
- {
36744
- $replaceRoot: { newRoot: "$doc" }
36745
- },
36746
- // ✅ Apply search filter
36747
- {
36748
- $match: {
36749
- ...searchQuery
36750
- }
36751
- },
36752
- {
36753
- $project: {
36754
- name: 1,
36755
- "level.level": 1,
36756
- "level.units.name": 1,
36757
- "level.units.fAccessCards": 1
37079
+ ],
37080
+ as: "level"
37081
+ }
37082
+ },
37083
+ // ✅ Filter out buildings with no levels early
37084
+ {
37085
+ $match: { "level.0": { $exists: true } }
37086
+ },
37087
+ // ✅ Unwind to flatten the hierarchy
37088
+ {
37089
+ $unwind: {
37090
+ path: "$level",
37091
+ preserveNullAndEmptyArrays: false
37092
+ }
37093
+ },
37094
+ {
37095
+ $unwind: {
37096
+ path: "$level.units",
37097
+ preserveNullAndEmptyArrays: false
37098
+ }
37099
+ },
37100
+ {
37101
+ $unwind: {
37102
+ path: "$level.units.fAccessCards",
37103
+ preserveNullAndEmptyArrays: false
37104
+ }
37105
+ },
37106
+ // // Groups by unit _id and keeps only the first occurrence
37107
+ {
37108
+ $group: {
37109
+ _id: "$level.units._id",
37110
+ doc: { $first: "$$ROOT" }
37111
+ }
37112
+ },
37113
+ {
37114
+ $replaceRoot: { newRoot: "$doc" }
37115
+ },
37116
+ // ✅ Apply search filter
37117
+ {
37118
+ $match: {
37119
+ ...searchQuery
37120
+ }
37121
+ },
37122
+ {
37123
+ $project: {
37124
+ name: 1,
37125
+ "level.level": 1,
37126
+ "level.units.name": 1,
37127
+ "level.units.fAccessCards": 1
37128
+ }
36758
37129
  }
36759
- }
36760
- ], { allowDiskUse: true }).toArray();
37130
+ ],
37131
+ { allowDiskUse: true }
37132
+ ).toArray();
36761
37133
  return result;
36762
37134
  } catch (error) {
36763
37135
  throw new Error(error.message);
@@ -36768,8 +37140,12 @@ function UseAccessManagementRepo() {
36768
37140
  try {
36769
37141
  session?.startTransaction();
36770
37142
  const { userId, cardId, site } = params;
36771
- const allUserId = await Promise.all(userId.map(async (id) => new import_mongodb90.ObjectId(id)));
36772
- const allCardId = await Promise.all(cardId.map(async (id) => new import_mongodb90.ObjectId(id)));
37143
+ const allUserId = await Promise.all(
37144
+ userId.map(async (id) => new import_mongodb90.ObjectId(id))
37145
+ );
37146
+ const allCardId = await Promise.all(
37147
+ cardId.map(async (id) => new import_mongodb90.ObjectId(id))
37148
+ );
36773
37149
  const siteId = new import_mongodb90.ObjectId(site);
36774
37150
  const result = await collection().updateMany(
36775
37151
  {
@@ -36812,16 +37188,19 @@ function UseAccessManagementRepo() {
36812
37188
  liftAccessLevel,
36813
37189
  isActivated: true
36814
37190
  };
36815
- const result = await collection().aggregate([
36816
- {
36817
- $match: query
36818
- },
36819
- {
36820
- $facet: {
36821
- counts: [{ $count: "count" }]
37191
+ const result = await collection().aggregate(
37192
+ [
37193
+ {
37194
+ $match: query
37195
+ },
37196
+ {
37197
+ $facet: {
37198
+ counts: [{ $count: "count" }]
37199
+ }
36822
37200
  }
36823
- }
36824
- ], { allowDiskUse: true }).toArray();
37201
+ ],
37202
+ { allowDiskUse: true }
37203
+ ).toArray();
36825
37204
  return result;
36826
37205
  } catch (error) {
36827
37206
  throw new Error(error.message);
@@ -36855,7 +37234,9 @@ function UseAccessManagementRepo() {
36855
37234
  availableCardNo.push(num);
36856
37235
  num++;
36857
37236
  }
36858
- const cardNumbers = availableCardNo.map((no) => no.toString().padStart(10, "0"));
37237
+ const cardNumbers = availableCardNo.map(
37238
+ (no) => no.toString().padStart(10, "0")
37239
+ );
36859
37240
  const accessCards = [];
36860
37241
  const convertedUnits = unit.map((obj) => new import_mongodb90.ObjectId(obj));
36861
37242
  for (let j = 0; j < (unit.length > 0 ? unit.length : quantity); j++) {
@@ -36915,10 +37296,18 @@ function UseAccessManagementRepo() {
36915
37296
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
36916
37297
  accessGroup: ag
36917
37298
  };
36918
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
37299
+ return readTemplate(
37300
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
37301
+ { ...command }
37302
+ );
36919
37303
  }).flat();
36920
- const response = await sendCommand(commands.join("").toString(), params.acm_url);
36921
- const result = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
37304
+ const response = await sendCommand(
37305
+ commands.join("").toString(),
37306
+ params.acm_url
37307
+ );
37308
+ const result = await (0, import_xml2js2.parseStringPromise)(response, {
37309
+ explicitArray: false
37310
+ });
36922
37311
  if (result && result.RESULT.$.STCODE !== "0") {
36923
37312
  throw new Error("Command failed, server error.");
36924
37313
  }
@@ -36952,7 +37341,11 @@ function UseAccessManagementRepo() {
36952
37341
  } else {
36953
37342
  updateFields.isActivated = true;
36954
37343
  }
36955
- const res = await collection().updateOne({ _id: card._id }, { $set: updateFields }, { session });
37344
+ const res = await collection().updateOne(
37345
+ { _id: card._id },
37346
+ { $set: updateFields },
37347
+ { session }
37348
+ );
36956
37349
  results.push({ nfcId: nfc._id, modifiedCount: res.modifiedCount });
36957
37350
  }
36958
37351
  }
@@ -36979,8 +37372,20 @@ function UseAccessManagementRepo() {
36979
37372
  assignedUnit: null,
36980
37373
  userId: null,
36981
37374
  $or: [
36982
- { $and: [{ doorName: { $ne: null } }, { doorName: { $ne: "" } }, { accessLevel: { $ne: null } }] },
36983
- { $and: [{ liftName: { $ne: null } }, { liftName: { $ne: "" } }, { liftAccessLevel: { $ne: null } }] }
37375
+ {
37376
+ $and: [
37377
+ { doorName: { $ne: null } },
37378
+ { doorName: { $ne: "" } },
37379
+ { accessLevel: { $ne: null } }
37380
+ ]
37381
+ },
37382
+ {
37383
+ $and: [
37384
+ { liftName: { $ne: null } },
37385
+ { liftName: { $ne: "" } },
37386
+ { liftAccessLevel: { $ne: null } }
37387
+ ]
37388
+ }
36984
37389
  ]
36985
37390
  }
36986
37391
  },
@@ -36994,7 +37399,13 @@ function UseAccessManagementRepo() {
36994
37399
  accessLevels: {
36995
37400
  $addToSet: {
36996
37401
  $cond: [
36997
- { $and: [{ $ne: ["$doorName", null] }, { $ne: ["$doorName", ""] }, { $ne: ["$accessLevel", null] }] },
37402
+ {
37403
+ $and: [
37404
+ { $ne: ["$doorName", null] },
37405
+ { $ne: ["$doorName", ""] },
37406
+ { $ne: ["$accessLevel", null] }
37407
+ ]
37408
+ },
36998
37409
  { name: "$doorName", no: "$accessLevel" },
36999
37410
  "$$REMOVE"
37000
37411
  ]
@@ -37003,7 +37414,13 @@ function UseAccessManagementRepo() {
37003
37414
  liftAccessLevels: {
37004
37415
  $addToSet: {
37005
37416
  $cond: [
37006
- { $and: [{ $ne: ["$liftName", null] }, { $ne: ["$liftName", ""] }, { $ne: ["$liftAccessLevel", null] }] },
37417
+ {
37418
+ $and: [
37419
+ { $ne: ["$liftName", null] },
37420
+ { $ne: ["$liftName", ""] },
37421
+ { $ne: ["$liftAccessLevel", null] }
37422
+ ]
37423
+ },
37007
37424
  { name: "$liftName", no: "$liftAccessLevel" },
37008
37425
  "$$REMOVE"
37009
37426
  ]
@@ -37039,7 +37456,14 @@ function UseAccessManagementRepo() {
37039
37456
  const sessionResult = await Promise.all([
37040
37457
  await collection().findOneAndUpdate(
37041
37458
  { _id: id },
37042
- { $set: { remarks, replacementStatus: "Complete", requestDate: /* @__PURE__ */ new Date(), isActivated: false } },
37459
+ {
37460
+ $set: {
37461
+ remarks,
37462
+ replacementStatus: "Complete",
37463
+ requestDate: /* @__PURE__ */ new Date(),
37464
+ isActivated: false
37465
+ }
37466
+ },
37043
37467
  { returnDocument: "after", session }
37044
37468
  ),
37045
37469
  await collection().findOneAndUpdate(
@@ -37071,7 +37495,10 @@ function UseAccessManagementRepo() {
37071
37495
  isActivated: true
37072
37496
  };
37073
37497
  if (search) {
37074
- query.$or = [{ accessLevel: { $regex: search, $options: "i" } }, { cardNo: { $regex: search, $options: "i" } }];
37498
+ query.$or = [
37499
+ { accessLevel: { $regex: search, $options: "i" } },
37500
+ { cardNo: { $regex: search, $options: "i" } }
37501
+ ];
37075
37502
  }
37076
37503
  if (type) {
37077
37504
  query.userType = type;
@@ -37096,14 +37523,22 @@ function UseAccessManagementRepo() {
37096
37523
  {
37097
37524
  $addFields: {
37098
37525
  extractedCardNo: {
37099
- $substr: ["$cardNo", { $subtract: [{ $strLenCP: "$cardNo" }, 5] }, 5]
37526
+ $substr: [
37527
+ "$cardNo",
37528
+ { $subtract: [{ $strLenCP: "$cardNo" }, 5] },
37529
+ 5
37530
+ ]
37100
37531
  }
37101
37532
  }
37102
37533
  },
37103
37534
  {
37104
37535
  $facet: {
37105
37536
  totalCount: [{ $count: "count" }],
37106
- items: [{ $sort: { _id: -1 } }, { $skip: page * limit }, { $limit: limit }]
37537
+ items: [
37538
+ { $sort: { _id: -1 } },
37539
+ { $skip: page * limit },
37540
+ { $limit: limit }
37541
+ ]
37107
37542
  }
37108
37543
  }
37109
37544
  ]).toArray();
@@ -37134,145 +37569,151 @@ function UseAccessManagementRepo() {
37134
37569
  query.replacementStatus = statusFilter;
37135
37570
  }
37136
37571
  if (dateFrom && dateTo) {
37137
- query.requestDate = { $gte: new Date(dateFrom), $lte: new Date(dateTo) };
37572
+ query.requestDate = {
37573
+ $gte: new Date(dateFrom),
37574
+ $lte: new Date(dateTo)
37575
+ };
37138
37576
  } else if (dateFrom) {
37139
37577
  query.requestDate = { $gte: new Date(dateFrom) };
37140
37578
  } else if (dateTo) {
37141
37579
  query.requestDate = { $lte: new Date(dateTo) };
37142
37580
  }
37143
- const res = await collection().aggregate([
37144
- {
37145
- $match: { ...query }
37146
- },
37147
- {
37148
- $lookup: {
37149
- from: "building-units",
37150
- let: { unit: "$assignedUnit" },
37151
- pipeline: [
37152
- {
37153
- $match: {
37154
- $expr: {
37155
- $eq: ["$_id", "$$unit"]
37581
+ const res = await collection().aggregate(
37582
+ [
37583
+ {
37584
+ $match: { ...query }
37585
+ },
37586
+ {
37587
+ $lookup: {
37588
+ from: "building-units",
37589
+ let: { unit: "$assignedUnit" },
37590
+ pipeline: [
37591
+ {
37592
+ $match: {
37593
+ $expr: {
37594
+ $eq: ["$_id", "$$unit"]
37595
+ }
37156
37596
  }
37157
- }
37158
- },
37159
- {
37160
- $project: {
37161
- _id: 1,
37162
- name: 1,
37163
- level: 1
37164
- }
37165
- }
37166
- ],
37167
- as: "unit"
37168
- }
37169
- },
37170
- {
37171
- $unwind: { path: "$unit", preserveNullAndEmptyArrays: true }
37172
- },
37173
- {
37174
- $lookup: {
37175
- from: "building-levels",
37176
- let: { level: "$unit.level" },
37177
- pipeline: [
37178
- {
37179
- $match: {
37180
- $expr: {
37181
- $eq: ["$_id", "$$level"]
37597
+ },
37598
+ {
37599
+ $project: {
37600
+ _id: 1,
37601
+ name: 1,
37602
+ level: 1
37182
37603
  }
37183
37604
  }
37184
- },
37185
- {
37186
- $project: {
37187
- _id: 1,
37188
- level: 1,
37189
- block: 1
37190
- }
37191
- }
37192
- ],
37193
- as: "level"
37194
- }
37195
- },
37196
- {
37197
- $unwind: { path: "$level", preserveNullAndEmptyArrays: true }
37198
- },
37199
- {
37200
- $lookup: {
37201
- from: "buildings",
37202
- let: { block: "$level.block" },
37203
- pipeline: [
37204
- {
37205
- $match: {
37206
- $expr: {
37207
- $eq: ["$_id", "$$block"]
37605
+ ],
37606
+ as: "unit"
37607
+ }
37608
+ },
37609
+ {
37610
+ $unwind: { path: "$unit", preserveNullAndEmptyArrays: true }
37611
+ },
37612
+ {
37613
+ $lookup: {
37614
+ from: "building-levels",
37615
+ let: { level: "$unit.level" },
37616
+ pipeline: [
37617
+ {
37618
+ $match: {
37619
+ $expr: {
37620
+ $eq: ["$_id", "$$level"]
37621
+ }
37622
+ }
37623
+ },
37624
+ {
37625
+ $project: {
37626
+ _id: 1,
37627
+ level: 1,
37628
+ block: 1
37208
37629
  }
37209
37630
  }
37210
- },
37211
- {
37212
- $project: {
37213
- _id: 1,
37214
- name: 1
37215
- }
37216
- }
37217
- ],
37218
- as: "building"
37219
- }
37220
- },
37221
- {
37222
- $unwind: { path: "$building", preserveNullAndEmptyArrays: true }
37223
- },
37224
- {
37225
- $lookup: {
37226
- from: "users",
37227
- let: { id: "$userId" },
37228
- pipeline: [
37229
- {
37230
- $match: {
37231
- $expr: {
37232
- $eq: ["$_id", "$$id"]
37631
+ ],
37632
+ as: "level"
37633
+ }
37634
+ },
37635
+ {
37636
+ $unwind: { path: "$level", preserveNullAndEmptyArrays: true }
37637
+ },
37638
+ {
37639
+ $lookup: {
37640
+ from: "buildings",
37641
+ let: { block: "$level.block" },
37642
+ pipeline: [
37643
+ {
37644
+ $match: {
37645
+ $expr: {
37646
+ $eq: ["$_id", "$$block"]
37647
+ }
37648
+ }
37649
+ },
37650
+ {
37651
+ $project: {
37652
+ _id: 1,
37653
+ name: 1
37233
37654
  }
37234
37655
  }
37235
- },
37236
- {
37237
- $project: {
37238
- givenName: 1,
37239
- surname: 1
37656
+ ],
37657
+ as: "building"
37658
+ }
37659
+ },
37660
+ {
37661
+ $unwind: { path: "$building", preserveNullAndEmptyArrays: true }
37662
+ },
37663
+ {
37664
+ $lookup: {
37665
+ from: "users",
37666
+ let: { id: "$userId" },
37667
+ pipeline: [
37668
+ {
37669
+ $match: {
37670
+ $expr: {
37671
+ $eq: ["$_id", "$$id"]
37672
+ }
37673
+ }
37674
+ },
37675
+ {
37676
+ $project: {
37677
+ givenName: 1,
37678
+ surname: 1
37679
+ }
37240
37680
  }
37241
- }
37242
- ],
37243
- as: "user"
37244
- }
37245
- },
37246
- {
37247
- $unwind: { path: "$user", preserveNullAndEmptyArrays: true }
37248
- },
37249
- {
37250
- $match: { ...searchQuery }
37251
- },
37252
- {
37253
- $facet: {
37254
- data: [
37255
- { $skip: page * limit },
37256
- { $limit: limit },
37257
- {
37258
- $project: {
37259
- _id: 1,
37260
- cardNo: 1,
37261
- accessLevel: 1,
37262
- liftAccessLevel: 1,
37263
- replacementStatus: 1,
37264
- remarks: 1,
37265
- block: "$building.name",
37266
- level: "$level.level",
37267
- unit: "$unit.name",
37268
- user: "$user"
37681
+ ],
37682
+ as: "user"
37683
+ }
37684
+ },
37685
+ {
37686
+ $unwind: { path: "$user", preserveNullAndEmptyArrays: true }
37687
+ },
37688
+ {
37689
+ $match: { ...searchQuery }
37690
+ },
37691
+ {
37692
+ $facet: {
37693
+ data: [
37694
+ { $skip: page * limit },
37695
+ { $limit: limit },
37696
+ {
37697
+ $project: {
37698
+ _id: 1,
37699
+ cardNo: 1,
37700
+ accessLevel: 1,
37701
+ liftAccessLevel: 1,
37702
+ replacementStatus: 1,
37703
+ remarks: 1,
37704
+ block: "$building.name",
37705
+ level: "$level.level",
37706
+ unit: "$unit.name",
37707
+ user: "$user"
37708
+ }
37269
37709
  }
37270
- }
37271
- ],
37272
- totalCount: [{ $count: "count" }]
37710
+ ],
37711
+ totalCount: [{ $count: "count" }]
37712
+ }
37273
37713
  }
37274
- }
37275
- ], { allowDiskUse: true }).toArray();
37714
+ ],
37715
+ { allowDiskUse: true }
37716
+ ).toArray();
37276
37717
  const count = res[0]?.totalCount[0] ? res[0].totalCount[0].count : 0;
37277
37718
  const pagination = (0, import_node_server_utils154.paginate)(res[0].data, page, limit, count);
37278
37719
  return pagination;
@@ -37284,7 +37725,10 @@ function UseAccessManagementRepo() {
37284
37725
  try {
37285
37726
  const { site } = params;
37286
37727
  const siteId = new import_mongodb90.ObjectId(site);
37287
- const res = await collectionName("entrypass-settings").findOne({ site: siteId }, { allowDiskUse: true });
37728
+ const res = await collectionName("entrypass-settings").findOne(
37729
+ { site: siteId },
37730
+ { allowDiskUse: true }
37731
+ );
37288
37732
  return res;
37289
37733
  } catch (error) {
37290
37734
  throw new Error(error.message);
@@ -37294,13 +37738,19 @@ function UseAccessManagementRepo() {
37294
37738
  const session = import_node_server_utils154.useAtlas.getClient()?.startSession();
37295
37739
  try {
37296
37740
  const { dataJson, site } = params;
37297
- const rawItems = JSON.parse(dataJson).filter((_, index) => index !== -1);
37741
+ const rawItems = JSON.parse(dataJson).filter(
37742
+ (_, index) => index !== -1
37743
+ );
37298
37744
  const items = await Promise.all(
37299
37745
  rawItems.map(async (item) => {
37300
37746
  const date = new Date(item["startDate (format MM/DD/YYYY)"]);
37301
37747
  const endDate = new Date(date.setFullYear(date.getFullYear() + 10));
37302
- const cardNumber = String(Number(item["cardNo (number 0-65535 ex. 301)"] || 0)).padStart(6, "0");
37303
- const facilityCode = String(Number(item["facilityCode (number 0-255 ex. 11)"] || 0)).padStart(4, "0");
37748
+ const cardNumber = String(
37749
+ Number(item["cardNo (number 0-65535 ex. 301)"] || 0)
37750
+ ).padStart(6, "0");
37751
+ const facilityCode = String(
37752
+ Number(item["facilityCode (number 0-255 ex. 11)"] || 0)
37753
+ ).padStart(4, "0");
37304
37754
  const pin = item["pin (number 6 digits only)"] ? item["pin (number 6 digits only)"].toString().padStart(6, "0") : "123456";
37305
37755
  const match = item["accessLevel (number ex. 1)"];
37306
37756
  const accessLevel = match ? match : null;
@@ -37331,7 +37781,10 @@ function UseAccessManagementRepo() {
37331
37781
  });
37332
37782
  })
37333
37783
  );
37334
- const result = await collection().insertMany(items, { session, ordered: false });
37784
+ const result = await collection().insertMany(items, {
37785
+ session,
37786
+ ordered: false
37787
+ });
37335
37788
  const mapping = items.map((item, i) => ({
37336
37789
  cardNo: item.cardNo,
37337
37790
  insertedId: result.insertedIds[i]
@@ -37346,8 +37799,19 @@ function UseAccessManagementRepo() {
37346
37799
  let isAborted = false;
37347
37800
  try {
37348
37801
  await session?.startTransaction();
37349
- const { units, quantity, type, site, userType, accessLevel, liftAccessLevel } = params;
37350
- const [convertedUnits, convertedSite] = await Promise.all([Promise.all(units.map((id) => new import_mongodb90.ObjectId(id))), new import_mongodb90.ObjectId(site)]);
37802
+ const {
37803
+ units,
37804
+ quantity,
37805
+ type,
37806
+ site,
37807
+ userType,
37808
+ accessLevel,
37809
+ liftAccessLevel
37810
+ } = params;
37811
+ const [convertedUnits, convertedSite] = await Promise.all([
37812
+ Promise.all(units.map((id) => new import_mongodb90.ObjectId(id))),
37813
+ new import_mongodb90.ObjectId(site)
37814
+ ]);
37351
37815
  const totalRequired = quantity * convertedUnits.length;
37352
37816
  const availableCards = await collection().find({
37353
37817
  assignedUnit: null,
@@ -37367,16 +37831,18 @@ function UseAccessManagementRepo() {
37367
37831
  message: `Insufficient ${type} access cards. Need ${totalRequired}, but only ${availableCards.length} available.`
37368
37832
  };
37369
37833
  }
37370
- const bulkUpdates = availableCards.map((card, index) => ({
37371
- updateOne: {
37372
- filter: { _id: card._id },
37373
- update: {
37374
- $set: {
37375
- assignedUnit: convertedUnits[Math.floor(index / quantity)]
37834
+ const bulkUpdates = availableCards.map(
37835
+ (card, index) => ({
37836
+ updateOne: {
37837
+ filter: { _id: card._id },
37838
+ update: {
37839
+ $set: {
37840
+ assignedUnit: convertedUnits[Math.floor(index / quantity)]
37841
+ }
37376
37842
  }
37377
37843
  }
37378
- }
37379
- }));
37844
+ })
37845
+ );
37380
37846
  await collection().bulkWrite(bulkUpdates, { session });
37381
37847
  await session?.commitTransaction();
37382
37848
  return {
@@ -37397,7 +37863,18 @@ function UseAccessManagementRepo() {
37397
37863
  try {
37398
37864
  const { cardId, remarks } = params;
37399
37865
  const id = new import_mongodb90.ObjectId(cardId);
37400
- const result = await collection().findOneAndUpdate({ _id: id }, { $set: { isActivated: false, updatedAt: /* @__PURE__ */ new Date(), remarks, requestDate: /* @__PURE__ */ new Date() } }, { returnDocument: "after" });
37866
+ const result = await collection().findOneAndUpdate(
37867
+ { _id: id },
37868
+ {
37869
+ $set: {
37870
+ isActivated: false,
37871
+ updatedAt: /* @__PURE__ */ new Date(),
37872
+ remarks,
37873
+ requestDate: /* @__PURE__ */ new Date()
37874
+ }
37875
+ },
37876
+ { returnDocument: "after" }
37877
+ );
37401
37878
  return result;
37402
37879
  } catch (error) {
37403
37880
  throw new Error(error.message);
@@ -37458,7 +37935,13 @@ function UseAccessManagementRepo() {
37458
37935
  const { site, payload } = params;
37459
37936
  const id = new import_mongodb90.ObjectId(site);
37460
37937
  const highestCardNo = await collection().aggregate([
37461
- { $match: { site: id, type: "NFC" /* NFC */, userType: "Visitor/Resident" /* DEFAULT */ } },
37938
+ {
37939
+ $match: {
37940
+ site: id,
37941
+ type: "NFC" /* NFC */,
37942
+ userType: "Visitor/Resident" /* DEFAULT */
37943
+ }
37944
+ },
37462
37945
  {
37463
37946
  $addFields: {
37464
37947
  qrTagCardNoNumeric: { $toInt: "$qrTagCardNo" }
@@ -37478,14 +37961,19 @@ function UseAccessManagementRepo() {
37478
37961
  if (highestCardNo.length > 0) {
37479
37962
  start = highestCardNo[0].qrTagCardNoNumeric || 0;
37480
37963
  }
37481
- const nextCardNumbers = Array.from({ length: payload.length }, (_, i) => String(start + i + 1).padStart(5, "0"));
37964
+ const nextCardNumbers = Array.from(
37965
+ { length: payload.length },
37966
+ (_, i) => String(start + i + 1).padStart(5, "0")
37967
+ );
37482
37968
  const bulkOps = await Promise.all(
37483
37969
  payload.map(async (doc, index) => {
37484
37970
  const id2 = new import_mongodb90.ObjectId(doc._id);
37485
37971
  return {
37486
37972
  updateOne: {
37487
37973
  filter: { _id: id2 },
37488
- update: { $set: { qrTag: doc.qrTag, qrTagCardNo: nextCardNumbers[index] } }
37974
+ update: {
37975
+ $set: { qrTag: doc.qrTag, qrTagCardNo: nextCardNumbers[index] }
37976
+ }
37489
37977
  }
37490
37978
  };
37491
37979
  })
@@ -37527,7 +38015,11 @@ function UseAccessManagementRepo() {
37527
38015
  {
37528
38016
  $addFields: {
37529
38017
  extractedCardNo: {
37530
- $substr: ["$cardNo", { $subtract: [{ $strLenCP: "$cardNo" }, 5] }, 5]
38018
+ $substr: [
38019
+ "$cardNo",
38020
+ { $subtract: [{ $strLenCP: "$cardNo" }, 5] },
38021
+ 5
38022
+ ]
37531
38023
  }
37532
38024
  }
37533
38025
  },
@@ -37565,7 +38057,11 @@ function UseAccessManagementRepo() {
37565
38057
  },
37566
38058
  {
37567
38059
  $facet: {
37568
- items: [{ $skip: page * limit }, { $limit: limit }, { $project: { cardNo: 1 } }],
38060
+ items: [
38061
+ { $skip: page * limit },
38062
+ { $limit: limit },
38063
+ { $project: { cardNo: 1 } }
38064
+ ],
37569
38065
  totalCounts: [{ $count: "count" }]
37570
38066
  }
37571
38067
  }
@@ -37576,7 +38072,9 @@ function UseAccessManagementRepo() {
37576
38072
  _id: unitId
37577
38073
  }
37578
38074
  },
37579
- { $project: { _id: 1, name: 1, buildingName: 1, block: 1, level: 1 } },
38075
+ {
38076
+ $project: { _id: 1, name: 1, buildingName: 1, block: 1, level: 1 }
38077
+ },
37580
38078
  {
37581
38079
  $lookup: {
37582
38080
  from: "building-levels",
@@ -37664,7 +38162,18 @@ function UseAccessManagementRepo() {
37664
38162
  items: [
37665
38163
  { $skip: 0 },
37666
38164
  { $limit: 1 },
37667
- { $project: { _id: -1, accessLevel: 1, accessGroup: 1, userType: 1, doorName: 1, liftName: 1, liftAccessLevel: 1, isLiftCard: 1 } }
38165
+ {
38166
+ $project: {
38167
+ _id: -1,
38168
+ accessLevel: 1,
38169
+ accessGroup: 1,
38170
+ userType: 1,
38171
+ doorName: 1,
38172
+ liftName: 1,
38173
+ liftAccessLevel: 1,
38174
+ isLiftCard: 1
38175
+ }
38176
+ }
37668
38177
  ]
37669
38178
  }
37670
38179
  }
@@ -37713,13 +38222,25 @@ function UseAccessManagementRepo() {
37713
38222
  cardsToAttach = [...cardsId];
37714
38223
  } else if (type === "NFC" /* NFC */) {
37715
38224
  if (nfcCards && nfcCards.length > 0) {
37716
- const objectIds = nfcCards.map((card) => new import_mongodb90.ObjectId(card._id));
38225
+ const objectIds = nfcCards.map(
38226
+ (card) => new import_mongodb90.ObjectId(card._id)
38227
+ );
37717
38228
  cards = await collection().find({ _id: { $in: objectIds } }).toArray();
37718
- const nfcList = objectIds.map((card) => ({ _id: card, status: "In use", updatedAt: /* @__PURE__ */ new Date() }));
38229
+ const nfcList = objectIds.map((card) => ({
38230
+ _id: card,
38231
+ status: "In use",
38232
+ updatedAt: /* @__PURE__ */ new Date()
38233
+ }));
37719
38234
  cardsToAttach = [...nfcList];
37720
38235
  }
37721
38236
  }
37722
- const result = await collectionName("visitor.transactions").findOneAndUpdate({ _id: visitorId }, { $push: { cards: cardsToAttach } }, { session, returnDocument: "after" });
38237
+ const result = await collectionName(
38238
+ "visitor.transactions"
38239
+ ).findOneAndUpdate(
38240
+ { _id: visitorId },
38241
+ { $push: { cards: cardsToAttach } },
38242
+ { session, returnDocument: "after" }
38243
+ );
37723
38244
  const updatedVisitor = result?._id;
37724
38245
  const assignCards = cards.map((card) => card._id);
37725
38246
  if (assignCards.length > 0) {
@@ -37775,10 +38296,18 @@ function UseAccessManagementRepo() {
37775
38296
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
37776
38297
  accessGroup: ag
37777
38298
  };
37778
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
38299
+ return readTemplate(
38300
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
38301
+ { ...command }
38302
+ );
37779
38303
  }).flat();
37780
- const response = await sendCommand(commands.join("").toString(), acm_url);
37781
- serverResult = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
38304
+ const response = await sendCommand(
38305
+ commands.join("").toString(),
38306
+ acm_url
38307
+ );
38308
+ serverResult = await (0, import_xml2js2.parseStringPromise)(response, {
38309
+ explicitArray: false
38310
+ });
37782
38311
  if (result && serverResult.RESULT.$.STCODE !== "0") {
37783
38312
  throw new Error("Command failed, server error.");
37784
38313
  }
@@ -37827,7 +38356,10 @@ function UseAccessManagementRepo() {
37827
38356
  try {
37828
38357
  await session?.startTransaction();
37829
38358
  const userId = new import_mongodb90.ObjectId(params.userId);
37830
- const result = await collection().updateMany({ userId }, { $set: { userId: null, status: "Available", updatedAt: /* @__PURE__ */ new Date() } });
38359
+ const result = await collection().updateMany(
38360
+ { userId },
38361
+ { $set: { userId: null, status: "Available", updatedAt: /* @__PURE__ */ new Date() } }
38362
+ );
37831
38363
  await session?.commitTransaction();
37832
38364
  return result;
37833
38365
  } catch (error) {
@@ -37871,7 +38403,15 @@ function UseAccessManagementRepo() {
37871
38403
  foreignField: "level",
37872
38404
  pipeline: [
37873
38405
  { $match: { status: { $ne: "deleted" } } },
37874
- { $project: { _id: 1, name: 1, buildingName: 1, level: 1, block: 1 } }
38406
+ {
38407
+ $project: {
38408
+ _id: 1,
38409
+ name: 1,
38410
+ buildingName: 1,
38411
+ level: 1,
38412
+ block: 1
38413
+ }
38414
+ }
37875
38415
  ],
37876
38416
  as: "units"
37877
38417
  }
@@ -37892,11 +38432,20 @@ function UseAccessManagementRepo() {
37892
38432
  throw new Error(error.message);
37893
38433
  }
37894
38434
  }
37895
- async function getTransactionsRepo({ page = 1, limit = 10, site, cardNo, url }) {
38435
+ async function getTransactionsRepo({
38436
+ page = 1,
38437
+ limit = 10,
38438
+ site,
38439
+ cardNo,
38440
+ url
38441
+ }) {
37896
38442
  page = page ? page - 1 : 0;
37897
38443
  site = new import_mongodb90.ObjectId(site);
37898
38444
  try {
37899
- let index = await collectionName("access-card-transactions").findOne({}, { sort: { index: -1 } });
38445
+ let index = await collectionName("access-card-transactions").findOne(
38446
+ {},
38447
+ { sort: { index: -1 } }
38448
+ );
37900
38449
  index = index ? index.index : 0;
37901
38450
  const response = await getTransactions(index, url);
37902
38451
  if (response && Array.isArray(response.items) && response.items.length > 0) {
@@ -37905,7 +38454,9 @@ function UseAccessManagementRepo() {
37905
38454
  data: JSON.parse(item.data),
37906
38455
  timestamp: item.timestamp
37907
38456
  }));
37908
- result2 = result2.filter((item) => item.data.Event.ETYPE === "0" && item.data.Event.CARDNO !== "");
38457
+ result2 = result2.filter(
38458
+ (item) => item.data.Event.ETYPE === "0" && item.data.Event.CARDNO !== ""
38459
+ );
37909
38460
  if (result2.length > 0) {
37910
38461
  const transactions = result2.map(
37911
38462
  (item) => new MAccessCardTransaction({
@@ -37916,11 +38467,16 @@ function UseAccessManagementRepo() {
37916
38467
  accessType: item.data.Event.DEVNAME,
37917
38468
  accessStatus: item.data.Event.TRCODE,
37918
38469
  description: item.data.Event.TRDESC,
37919
- accessTime: entryPassDate(item.data.Event.TRDATE, item.data.Event.TRTIME),
38470
+ accessTime: entryPassDate(
38471
+ item.data.Event.TRDATE,
38472
+ item.data.Event.TRTIME
38473
+ ),
37920
38474
  createdAt: /* @__PURE__ */ new Date()
37921
38475
  })
37922
38476
  );
37923
- await collectionName("access-card-transactions").insertMany(transactions);
38477
+ await collectionName("access-card-transactions").insertMany(
38478
+ transactions
38479
+ );
37924
38480
  }
37925
38481
  }
37926
38482
  const result = await collectionName("access-card-transactions").aggregate([
@@ -37991,7 +38547,11 @@ function UseAccessManagementRepo() {
37991
38547
  {
37992
38548
  $facet: {
37993
38549
  totalCount: [{ $count: "count" }],
37994
- items: [{ $sort: { _id: -1 } }, { $skip: page * limit }, { $limit: limit }]
38550
+ items: [
38551
+ { $sort: { _id: -1 } },
38552
+ { $skip: page * limit },
38553
+ { $limit: limit }
38554
+ ]
37995
38555
  }
37996
38556
  }
37997
38557
  ]).toArray();
@@ -38014,7 +38574,9 @@ function UseAccessManagementRepo() {
38014
38574
  if (assignees.length < 1) {
38015
38575
  throw new Error("No user to Assign.");
38016
38576
  }
38017
- assignees = assignees.map((data) => new import_mongodb90.ObjectId(data));
38577
+ assignees = assignees.map(
38578
+ (data) => new import_mongodb90.ObjectId(data)
38579
+ );
38018
38580
  unit = new import_mongodb90.ObjectId(unit);
38019
38581
  let availableCards = [];
38020
38582
  let update = [];
@@ -38024,7 +38586,18 @@ function UseAccessManagementRepo() {
38024
38586
  $match: {
38025
38587
  $expr: {
38026
38588
  $and: [
38027
- { $eq: ["$assignedUnit", unit] },
38589
+ {
38590
+ $in: [
38591
+ unit,
38592
+ {
38593
+ $cond: [
38594
+ { $isArray: "$assignedUnit" },
38595
+ "$assignedUnit",
38596
+ ["$assignedUnit"]
38597
+ ]
38598
+ }
38599
+ ]
38600
+ },
38028
38601
  { $eq: ["$userId", null] },
38029
38602
  { $eq: ["$type", type] },
38030
38603
  { $eq: ["$isActivated", true] }
@@ -38041,7 +38614,10 @@ function UseAccessManagementRepo() {
38041
38614
  card.staffNo = userId.toString().slice(-10);
38042
38615
  return card;
38043
38616
  });
38044
- update = availableCards.slice(0, assignees.length).map((card, index) => ({ _id: card._id, userId: new import_mongodb90.ObjectId(assignees[index]) }));
38617
+ update = availableCards.slice(0, assignees.length).map((card, index) => ({
38618
+ _id: card._id,
38619
+ userId: new import_mongodb90.ObjectId(assignees[index])
38620
+ }));
38045
38621
  const commands = cards.map((item, index) => {
38046
38622
  let ag = null;
38047
38623
  if (item.accessGroup !== void 0) {
@@ -38071,16 +38647,27 @@ function UseAccessManagementRepo() {
38071
38647
  liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
38072
38648
  accessGroup: ag
38073
38649
  };
38074
- return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
38650
+ return readTemplate(
38651
+ `${item.accessLevel !== null ? "add-card" : "add-card-lift"}`,
38652
+ { ...command }
38653
+ );
38075
38654
  }).flat();
38076
38655
  const response = await sendCommand(commands.join("").toString(), acm_url);
38077
- const result = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
38656
+ const result = await (0, import_xml2js2.parseStringPromise)(response, {
38657
+ explicitArray: false
38658
+ });
38078
38659
  console.log("status code", result.RESULT.$.STCODE);
38079
38660
  if (result && result.RESULT.$.STCODE !== "0") {
38080
38661
  throw new Error("Command failed, server error.");
38081
38662
  }
38082
38663
  for (const { _id, userId } of update) {
38083
- await collection().updateOne({ _id }, { $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` } }, { session });
38664
+ await collection().updateOne(
38665
+ { _id },
38666
+ {
38667
+ $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` }
38668
+ },
38669
+ { session }
38670
+ );
38084
38671
  }
38085
38672
  await session?.commitTransaction();
38086
38673
  return "Cards assigned successfully.";
@@ -38096,7 +38683,11 @@ function UseAccessManagementRepo() {
38096
38683
  try {
38097
38684
  session?.startTransaction();
38098
38685
  const id = new import_mongodb90.ObjectId(userId);
38099
- await collection().updateMany({ userId: id }, { $set: { userId: null, status: "Available" } }, { session });
38686
+ await collection().updateMany(
38687
+ { userId: id },
38688
+ { $set: { userId: null, status: "Available" } },
38689
+ { session }
38690
+ );
38100
38691
  session?.commitTransaction();
38101
38692
  return "Successful Checkout";
38102
38693
  } catch (error) {
@@ -38106,7 +38697,11 @@ function UseAccessManagementRepo() {
38106
38697
  await session?.endSession();
38107
38698
  }
38108
38699
  }
38109
- async function uploadTemplateRepo({ site, id, name }) {
38700
+ async function uploadTemplateRepo({
38701
+ site,
38702
+ id,
38703
+ name
38704
+ }) {
38110
38705
  site = new import_mongodb90.ObjectId(site);
38111
38706
  id = new import_mongodb90.ObjectId(id);
38112
38707
  try {
@@ -38119,6 +38714,46 @@ function UseAccessManagementRepo() {
38119
38714
  throw new Error(error.message);
38120
38715
  }
38121
38716
  }
38717
+ async function getResidentsRepo({
38718
+ orgId,
38719
+ siteId,
38720
+ unitId
38721
+ }) {
38722
+ try {
38723
+ orgId = new import_mongodb90.ObjectId(orgId);
38724
+ siteId = new import_mongodb90.ObjectId(siteId);
38725
+ unitId = new import_mongodb90.ObjectId(unitId);
38726
+ const result = await collectionName("users").aggregate([
38727
+ {
38728
+ $match: {
38729
+ $expr: {
38730
+ $and: [
38731
+ { $eq: ["$defaultOrg", orgId] },
38732
+ { $eq: ["$site", siteId] },
38733
+ { $eq: ["$unitId", unitId] }
38734
+ ]
38735
+ }
38736
+ }
38737
+ },
38738
+ {
38739
+ $project: {
38740
+ _id: 1,
38741
+ email: 1,
38742
+ unitName: 1,
38743
+ type: 1,
38744
+ status: 1,
38745
+ name: 1,
38746
+ defaultOrg: 1,
38747
+ site: 1,
38748
+ unitId: 1
38749
+ }
38750
+ }
38751
+ ]).toArray();
38752
+ return result;
38753
+ } catch (error) {
38754
+ throw new Error(error.message);
38755
+ }
38756
+ }
38122
38757
  return {
38123
38758
  createIndexes,
38124
38759
  createIndexForEntrypass,
@@ -38154,7 +38789,8 @@ function UseAccessManagementRepo() {
38154
38789
  getTransactionsRepo,
38155
38790
  assignMultipleCardsRepo,
38156
38791
  visitorCheckoutRepo,
38157
- uploadTemplateRepo
38792
+ uploadTemplateRepo,
38793
+ getResidentsRepo
38158
38794
  };
38159
38795
  }
38160
38796
 
@@ -38198,7 +38834,8 @@ function useAccessManagementSvc() {
38198
38834
  getTransactionsRepo,
38199
38835
  assignMultipleCardsRepo,
38200
38836
  visitorCheckoutRepo,
38201
- uploadTemplateRepo
38837
+ uploadTemplateRepo,
38838
+ getResidentsRepo
38202
38839
  } = UseAccessManagementRepo();
38203
38840
  const addPhysicalCardSvc = async (payload) => {
38204
38841
  try {
@@ -38490,17 +39127,39 @@ function useAccessManagementSvc() {
38490
39127
  throw new Error(err.message);
38491
39128
  }
38492
39129
  };
38493
- const getTransactionsSvc = async ({ page, limit, site, cardNo, url }) => {
39130
+ const getTransactionsSvc = async ({
39131
+ page,
39132
+ limit,
39133
+ site,
39134
+ cardNo,
39135
+ url
39136
+ }) => {
38494
39137
  try {
38495
- const response = await getTransactionsRepo({ page, limit, site, cardNo, url });
39138
+ const response = await getTransactionsRepo({
39139
+ page,
39140
+ limit,
39141
+ site,
39142
+ cardNo,
39143
+ url
39144
+ });
38496
39145
  return response;
38497
39146
  } catch (err) {
38498
39147
  throw new Error(err.message);
38499
39148
  }
38500
39149
  };
38501
- const assignMultipleCardsSvc = async ({ assignees, unit, type, acm_url }) => {
39150
+ const assignMultipleCardsSvc = async ({
39151
+ assignees,
39152
+ unit,
39153
+ type,
39154
+ acm_url
39155
+ }) => {
38502
39156
  try {
38503
- const response = await assignMultipleCardsRepo({ assignees, unit, type, acm_url });
39157
+ const response = await assignMultipleCardsRepo({
39158
+ assignees,
39159
+ unit,
39160
+ type,
39161
+ acm_url
39162
+ });
38504
39163
  return response;
38505
39164
  } catch (err) {
38506
39165
  throw new Error(err.message);
@@ -38514,7 +39173,11 @@ function useAccessManagementSvc() {
38514
39173
  throw new Error(err.message);
38515
39174
  }
38516
39175
  };
38517
- const uploadTemplateSvc = async ({ site, id, name }) => {
39176
+ const uploadTemplateSvc = async ({
39177
+ site,
39178
+ id,
39179
+ name
39180
+ }) => {
38518
39181
  try {
38519
39182
  const response = await uploadTemplateRepo({ site, id, name });
38520
39183
  return response;
@@ -38522,6 +39185,18 @@ function useAccessManagementSvc() {
38522
39185
  throw new Error(err.message);
38523
39186
  }
38524
39187
  };
39188
+ const getResidentsSvc = async ({
39189
+ orgId,
39190
+ siteId,
39191
+ unitId
39192
+ }) => {
39193
+ try {
39194
+ const response = await getResidentsRepo({ orgId, siteId, unitId });
39195
+ return response;
39196
+ } catch (err) {
39197
+ throw new Error(err.message);
39198
+ }
39199
+ };
38525
39200
  return {
38526
39201
  addPhysicalCardSvc,
38527
39202
  addNonPhysicalCardSvc,
@@ -38560,7 +39235,8 @@ function useAccessManagementSvc() {
38560
39235
  getTransactionsSvc,
38561
39236
  assignMultipleCardsSvc,
38562
39237
  visitorCheckoutSvc,
38563
- uploadTemplateSvc
39238
+ uploadTemplateSvc,
39239
+ getResidentsSvc
38564
39240
  };
38565
39241
  }
38566
39242
 
@@ -38604,7 +39280,8 @@ function useAccessManagementController() {
38604
39280
  getTransactionsSvc,
38605
39281
  assignMultipleCardsSvc,
38606
39282
  visitorCheckoutSvc,
38607
- uploadTemplateSvc
39283
+ uploadTemplateSvc,
39284
+ getResidentsSvc
38608
39285
  } = useAccessManagementSvc();
38609
39286
  const addPhysicalCard = async (req, res) => {
38610
39287
  try {
@@ -38853,11 +39530,25 @@ function useAccessManagementController() {
38853
39530
  search: import_joi86.default.string().optional().allow("", null),
38854
39531
  userType: import_joi86.default.string().required()
38855
39532
  });
38856
- const { error } = schema2.validate({ page, limit, site, organization, search, userType });
39533
+ const { error } = schema2.validate({
39534
+ page,
39535
+ limit,
39536
+ site,
39537
+ organization,
39538
+ search,
39539
+ userType
39540
+ });
38857
39541
  if (error) {
38858
39542
  return res.status(400).json({ message: error.message });
38859
39543
  }
38860
- const result = await userTypeAccessCardsSvc({ page, limit, search, site, organization, userType });
39544
+ const result = await userTypeAccessCardsSvc({
39545
+ page,
39546
+ limit,
39547
+ search,
39548
+ site,
39549
+ organization,
39550
+ userType
39551
+ });
38861
39552
  return res.status(200).json({ message: "Success", data: result });
38862
39553
  } catch (error) {
38863
39554
  return res.status(500).json({
@@ -38868,7 +39559,12 @@ function useAccessManagementController() {
38868
39559
  };
38869
39560
  const assignedAccessCards = async (req, res) => {
38870
39561
  try {
38871
- const { site, userType, type, search = "" } = req.query;
39562
+ const {
39563
+ site,
39564
+ userType,
39565
+ type,
39566
+ search = ""
39567
+ } = req.query;
38872
39568
  const schema2 = import_joi86.default.object({
38873
39569
  site: import_joi86.default.string().hex().required(),
38874
39570
  userType: import_joi86.default.string().required(),
@@ -38879,7 +39575,12 @@ function useAccessManagementController() {
38879
39575
  if (error) {
38880
39576
  return res.status(400).json({ message: error.message });
38881
39577
  }
38882
- const result = await assignedAccessCardsSvc({ site, userType, type, search });
39578
+ const result = await assignedAccessCardsSvc({
39579
+ site,
39580
+ userType,
39581
+ type,
39582
+ search
39583
+ });
38883
39584
  return res.status(200).json({ message: "Success", data: result });
38884
39585
  } catch (error) {
38885
39586
  return res.status(500).json({
@@ -38925,11 +39626,23 @@ function useAccessManagementController() {
38925
39626
  userType: import_joi86.default.string().valid(...Object.values(EAccessCardUserTypes)).required(),
38926
39627
  type: import_joi86.default.string().valid(...Object.values(EAccessCardTypes)).required()
38927
39628
  });
38928
- const { error } = schema2.validate({ accessLevel, liftAccessLevel, site, userType, type });
39629
+ const { error } = schema2.validate({
39630
+ accessLevel,
39631
+ liftAccessLevel,
39632
+ site,
39633
+ userType,
39634
+ type
39635
+ });
38929
39636
  if (error) {
38930
39637
  return res.status(400).json({ message: error.message });
38931
39638
  }
38932
- const result = await accessandLiftCardsSvc({ accessLevel, liftAccessLevel, site, userType, type });
39639
+ const result = await accessandLiftCardsSvc({
39640
+ accessLevel,
39641
+ liftAccessLevel,
39642
+ site,
39643
+ userType,
39644
+ type
39645
+ });
38933
39646
  return res.status(200).json({ message: "Success", data: result });
38934
39647
  } catch (error) {
38935
39648
  return res.status(500).json({
@@ -39016,11 +39729,23 @@ function useAccessManagementController() {
39016
39729
  issuedCardId: import_joi86.default.string().required(),
39017
39730
  userId: import_joi86.default.string().hex().required()
39018
39731
  });
39019
- const { error } = schema2.validate({ cardId, remarks, unitId, issuedCardId, userId });
39732
+ const { error } = schema2.validate({
39733
+ cardId,
39734
+ remarks,
39735
+ unitId,
39736
+ issuedCardId,
39737
+ userId
39738
+ });
39020
39739
  if (error) {
39021
39740
  return res.status(400).json({ message: error.message });
39022
39741
  }
39023
- const result = await cardReplacementSvc({ cardId, remarks, unitId, issuedCardId, userId });
39742
+ const result = await cardReplacementSvc({
39743
+ cardId,
39744
+ remarks,
39745
+ unitId,
39746
+ issuedCardId,
39747
+ userId
39748
+ });
39024
39749
  return res.status(200).json({ message: "Success", data: result });
39025
39750
  } catch (error) {
39026
39751
  return res.status(500).json({
@@ -39049,7 +39774,13 @@ function useAccessManagementController() {
39049
39774
  if (error) {
39050
39775
  return res.status(400).json({ message: error.message });
39051
39776
  }
39052
- const result = await visitorAccessCardsSvc({ site, page, limit, type, search });
39777
+ const result = await visitorAccessCardsSvc({
39778
+ site,
39779
+ page,
39780
+ limit,
39781
+ type,
39782
+ search
39783
+ });
39053
39784
  return res.status(200).json({ message: "Success", data: result });
39054
39785
  } catch (error) {
39055
39786
  return res.status(500).json({
@@ -39078,11 +39809,27 @@ function useAccessManagementController() {
39078
39809
  limit: import_joi86.default.number().optional().default(10),
39079
39810
  site: import_joi86.default.string().hex().required()
39080
39811
  });
39081
- const { error } = schema2.validate({ search, statusFilter, dateFrom, dateTo, page, limit, site });
39812
+ const { error } = schema2.validate({
39813
+ search,
39814
+ statusFilter,
39815
+ dateFrom,
39816
+ dateTo,
39817
+ page,
39818
+ limit,
39819
+ site
39820
+ });
39082
39821
  if (error) {
39083
39822
  return res.status(400).json({ message: error.message });
39084
39823
  }
39085
- const result = await getCardReplacementSvc({ site, page, limit, search, statusFilter, dateFrom, dateTo });
39824
+ const result = await getCardReplacementSvc({
39825
+ site,
39826
+ page,
39827
+ limit,
39828
+ search,
39829
+ statusFilter,
39830
+ dateFrom,
39831
+ dateTo
39832
+ });
39086
39833
  return res.status(200).json({ message: "Success", data: result });
39087
39834
  } catch (error) {
39088
39835
  return res.status(500).json({
@@ -39128,7 +39875,15 @@ function useAccessManagementController() {
39128
39875
  };
39129
39876
  const assignAccessCardToUnit = async (req, res) => {
39130
39877
  try {
39131
- const { units, type, quantity, site, userType, accessLevel, liftAccessLevel } = req.body;
39878
+ const {
39879
+ units,
39880
+ type,
39881
+ quantity,
39882
+ site,
39883
+ userType,
39884
+ accessLevel,
39885
+ liftAccessLevel
39886
+ } = req.body;
39132
39887
  const schema2 = import_joi86.default.object({
39133
39888
  units: import_joi86.default.array().items(import_joi86.default.string().hex()).required(),
39134
39889
  quantity: import_joi86.default.number().required(),
@@ -39138,11 +39893,27 @@ function useAccessManagementController() {
39138
39893
  accessLevel: import_joi86.default.string().optional().allow("", null),
39139
39894
  liftAccessLevel: import_joi86.default.string().optional().allow("", null)
39140
39895
  });
39141
- const { error } = schema2.validate({ units, quantity, type, site, userType, accessLevel, liftAccessLevel });
39896
+ const { error } = schema2.validate({
39897
+ units,
39898
+ quantity,
39899
+ type,
39900
+ site,
39901
+ userType,
39902
+ accessLevel,
39903
+ liftAccessLevel
39904
+ });
39142
39905
  if (error) {
39143
39906
  return res.status(400).json({ message: error.message });
39144
39907
  }
39145
- const result = await assignAccessCardToUnitSvc({ units, quantity, type, site, userType, accessLevel, liftAccessLevel });
39908
+ const result = await assignAccessCardToUnitSvc({
39909
+ units,
39910
+ quantity,
39911
+ type,
39912
+ site,
39913
+ userType,
39914
+ accessLevel,
39915
+ liftAccessLevel
39916
+ });
39146
39917
  return res.status(200).json({ message: "Success", data: result });
39147
39918
  } catch (error) {
39148
39919
  return res.status(500).json({
@@ -39240,7 +40011,12 @@ function useAccessManagementController() {
39240
40011
  };
39241
40012
  const availableCardContractors = async (req, res) => {
39242
40013
  try {
39243
- const { siteId, unitId, page = 1, limit = 20 } = req.query;
40014
+ const {
40015
+ siteId,
40016
+ unitId,
40017
+ page = 1,
40018
+ limit = 20
40019
+ } = req.query;
39244
40020
  const type = req.params.type;
39245
40021
  const schema2 = import_joi86.default.object({
39246
40022
  siteId: import_joi86.default.string().hex().required(),
@@ -39253,7 +40029,13 @@ function useAccessManagementController() {
39253
40029
  if (error) {
39254
40030
  return res.status(400).json({ message: error.message });
39255
40031
  }
39256
- const result = await availableCardContractorsSvc({ siteId, unitId, page, limit, type });
40032
+ const result = await availableCardContractorsSvc({
40033
+ siteId,
40034
+ unitId,
40035
+ page,
40036
+ limit,
40037
+ type
40038
+ });
39257
40039
  return res.status(200).json({ message: "Success", data: result });
39258
40040
  } catch (error) {
39259
40041
  return res.status(500).json({
@@ -39264,7 +40046,11 @@ function useAccessManagementController() {
39264
40046
  };
39265
40047
  const vmsgenerateQrCodes = async (req, res) => {
39266
40048
  try {
39267
- const { site, unitId, quantity = 100 } = req.body;
40049
+ const {
40050
+ site,
40051
+ unitId,
40052
+ quantity = 100
40053
+ } = req.body;
39268
40054
  const schema2 = import_joi86.default.object({
39269
40055
  site: import_joi86.default.string().hex().length(24).required(),
39270
40056
  unitId: import_joi86.default.string().hex().length(24).required(),
@@ -39275,7 +40061,12 @@ function useAccessManagementController() {
39275
40061
  return res.status(400).json({ message: error.message });
39276
40062
  }
39277
40063
  const normalizedUnitId = [unitId];
39278
- const result = await vmsgenerateQrCodesSvc({ site, unitId, normalizedUnitId, quantity });
40064
+ const result = await vmsgenerateQrCodesSvc({
40065
+ site,
40066
+ unitId,
40067
+ normalizedUnitId,
40068
+ quantity
40069
+ });
39279
40070
  return res.status(200).json({ message: "Success", data: result });
39280
40071
  } catch (error) {
39281
40072
  return res.status(500).json({
@@ -39286,21 +40077,50 @@ function useAccessManagementController() {
39286
40077
  };
39287
40078
  const addVisitorAccessCard = async (req, res) => {
39288
40079
  try {
39289
- const { site, unitId, quantity = 1, type, nfcCards, visitorId, acm_url } = req.body;
40080
+ const {
40081
+ site,
40082
+ unitId,
40083
+ quantity = 1,
40084
+ type,
40085
+ nfcCards,
40086
+ visitorId,
40087
+ acm_url
40088
+ } = req.body;
39290
40089
  const schema2 = import_joi86.default.object({
39291
40090
  site: import_joi86.default.string().hex().length(24).required(),
39292
40091
  unitId: import_joi86.default.string().hex().length(24).required(),
39293
40092
  quantity: import_joi86.default.number().allow(null, "").optional(),
39294
40093
  type: import_joi86.default.string().required(),
39295
- nfcCards: import_joi86.default.array().items(import_joi86.default.object({ _id: import_joi86.default.string().hex().required(), cardNo: import_joi86.default.string().required() })).required(),
40094
+ nfcCards: import_joi86.default.array().items(
40095
+ import_joi86.default.object({
40096
+ _id: import_joi86.default.string().hex().required(),
40097
+ cardNo: import_joi86.default.string().required()
40098
+ })
40099
+ ).required(),
39296
40100
  acm_url: import_joi86.default.string().required(),
39297
40101
  visitorId: import_joi86.default.string().hex().length(24).required()
39298
40102
  });
39299
- const { error } = schema2.validate({ site, unitId, quantity, type, nfcCards, visitorId, acm_url });
40103
+ const { error } = schema2.validate({
40104
+ site,
40105
+ unitId,
40106
+ quantity,
40107
+ type,
40108
+ nfcCards,
40109
+ visitorId,
40110
+ acm_url
40111
+ });
39300
40112
  if (error) {
39301
40113
  return res.status(400).json({ message: error.message });
39302
40114
  }
39303
- const result = await addVisitorAccessCardSvc({ site, unitId, quantity, type, nfcCards, visitorId, acm_url });
40115
+ const result = await addVisitorAccessCardSvc({
40116
+ site,
40117
+ unitId,
40118
+ quantity,
40119
+ type,
40120
+ nfcCards,
40121
+ visitorId,
40122
+ acm_url
40123
+ });
39304
40124
  return res.status(200).json({ message: "Success", data: result });
39305
40125
  } catch (error) {
39306
40126
  return res.status(500).json({
@@ -39348,7 +40168,11 @@ function useAccessManagementController() {
39348
40168
  });
39349
40169
  }
39350
40170
  };
39351
- const removeAccessCard = async ({ cardNo, staffNo, url }) => {
40171
+ const removeAccessCard = async ({
40172
+ cardNo,
40173
+ staffNo,
40174
+ url
40175
+ }) => {
39352
40176
  return removeAccessGroup({ cardNo, staffNo, url });
39353
40177
  };
39354
40178
  const getBlockLevelAndUnitList = async (req, res) => {
@@ -39367,7 +40191,13 @@ function useAccessManagementController() {
39367
40191
  }
39368
40192
  };
39369
40193
  const getTransactions2 = async (req, res) => {
39370
- const { page = 1, limit = 10, site, cardNo, url } = req.query;
40194
+ const {
40195
+ page = 1,
40196
+ limit = 10,
40197
+ site,
40198
+ cardNo,
40199
+ url
40200
+ } = req.query;
39371
40201
  const schema2 = import_joi86.default.object({
39372
40202
  page: import_joi86.default.number().required(),
39373
40203
  limit: import_joi86.default.number().optional().default(10),
@@ -39406,7 +40236,12 @@ function useAccessManagementController() {
39406
40236
  if (error) {
39407
40237
  throw new Error(`${error.message}`);
39408
40238
  }
39409
- const result = await assignMultipleCardsSvc({ assignees, unit, type, acm_url });
40239
+ const result = await assignMultipleCardsSvc({
40240
+ assignees,
40241
+ unit,
40242
+ type,
40243
+ acm_url
40244
+ });
39410
40245
  return res.status(200).json({ message: "Success", data: result });
39411
40246
  } catch (error) {
39412
40247
  return res.status(400).json({
@@ -39449,6 +40284,27 @@ function useAccessManagementController() {
39449
40284
  });
39450
40285
  }
39451
40286
  };
40287
+ const getResidents = async (req, res) => {
40288
+ try {
40289
+ const { orgId, siteId, unitId } = req.query;
40290
+ const schema2 = import_joi86.default.object({
40291
+ orgId: import_joi86.default.string().hex().required(),
40292
+ siteId: import_joi86.default.string().hex().required(),
40293
+ unitId: import_joi86.default.string().hex().required()
40294
+ });
40295
+ const { error } = schema2.validate({ orgId, siteId, unitId });
40296
+ if (error) {
40297
+ return res.status(400).json({ message: error.message });
40298
+ }
40299
+ const result = await getResidentsSvc({ orgId, siteId, unitId });
40300
+ return res.status(200).json({ data: result });
40301
+ } catch (error) {
40302
+ return res.status(400).json({
40303
+ data: null,
40304
+ message: error.message
40305
+ });
40306
+ }
40307
+ };
39452
40308
  return {
39453
40309
  addPhysicalCard,
39454
40310
  addNonPhysicalCard,
@@ -39485,7 +40341,8 @@ function useAccessManagementController() {
39485
40341
  getTransactions: getTransactions2,
39486
40342
  assignMultipleCards,
39487
40343
  visitorCheckout,
39488
- uploadTemplate
40344
+ uploadTemplate,
40345
+ getResidents
39489
40346
  };
39490
40347
  }
39491
40348
 
@@ -53444,6 +54301,7 @@ var import_joi132 = __toESM(require("joi"));
53444
54301
  var import_mongodb129 = require("mongodb");
53445
54302
  var PostStatus = /* @__PURE__ */ ((PostStatus2) => {
53446
54303
  PostStatus2["PUBLISHED"] = "published";
54304
+ PostStatus2["RESERVED"] = "reserved";
53447
54305
  PostStatus2["SOLD"] = "sold";
53448
54306
  PostStatus2["DELETED"] = "deleted";
53449
54307
  return PostStatus2;
@@ -53476,6 +54334,17 @@ var schemaPost = import_joi132.default.object({
53476
54334
  updatedAt: import_joi132.default.date().optional().allow(null),
53477
54335
  deletedAt: import_joi132.default.date().optional().allow(null)
53478
54336
  });
54337
+ var schemaUpdatePost = import_joi132.default.object({
54338
+ _id: import_joi132.default.string().hex().required(),
54339
+ title: import_joi132.default.string().optional().allow("", null),
54340
+ description: import_joi132.default.string().optional().allow("", null),
54341
+ attachments: import_joi132.default.array().items(import_joi132.default.string().hex().optional()).optional().allow(null),
54342
+ category: import_joi132.default.array().items(import_joi132.default.string().hex().optional()).optional().allow(null),
54343
+ currency: import_joi132.default.string().optional().allow("", null),
54344
+ price: import_joi132.default.number().optional(),
54345
+ status: import_joi132.default.string().valid(...Object.values(PostStatus)).optional().allow(null),
54346
+ reserverId: import_joi132.default.string().hex().optional().allow("", null)
54347
+ });
53479
54348
  function MPost(value) {
53480
54349
  const { error } = schemaPost.validate(value);
53481
54350
  if (error) {
@@ -53693,10 +54562,79 @@ function usePostPrelovedRepo() {
53693
54562
  throw error;
53694
54563
  }
53695
54564
  }
54565
+ async function updateById(_id, value, session) {
54566
+ try {
54567
+ _id = new import_mongodb130.ObjectId(_id);
54568
+ } catch {
54569
+ throw new import_node_server_utils232.BadRequestError("Invalid post ID format.");
54570
+ }
54571
+ value.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
54572
+ try {
54573
+ const res = await collection.updateOne(
54574
+ { _id },
54575
+ { $set: value },
54576
+ { session }
54577
+ );
54578
+ if (res.modifiedCount === 0) {
54579
+ throw new import_node_server_utils232.InternalServerError("Unable to update post.");
54580
+ }
54581
+ return res;
54582
+ } catch (error) {
54583
+ throw error;
54584
+ }
54585
+ }
54586
+ async function deleteById(_id, session) {
54587
+ try {
54588
+ _id = new import_mongodb130.ObjectId(_id);
54589
+ } catch {
54590
+ throw new import_node_server_utils232.BadRequestError("Invalid post ID format.");
54591
+ }
54592
+ try {
54593
+ const res = await collection.updateOne(
54594
+ { _id },
54595
+ {
54596
+ $set: {
54597
+ status: "deleted" /* DELETED */,
54598
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
54599
+ deletedAt: (/* @__PURE__ */ new Date()).toISOString()
54600
+ }
54601
+ },
54602
+ { session }
54603
+ );
54604
+ if (res.modifiedCount === 0) {
54605
+ throw new import_node_server_utils232.InternalServerError("Unable to delete post.");
54606
+ }
54607
+ return res.modifiedCount;
54608
+ } catch (error) {
54609
+ throw error;
54610
+ }
54611
+ }
54612
+ async function updateStatus(_id, status, session) {
54613
+ try {
54614
+ _id = new import_mongodb130.ObjectId(_id);
54615
+ } catch {
54616
+ throw new import_node_server_utils232.BadRequestError("Invalid post ID format.");
54617
+ }
54618
+ try {
54619
+ const res = await collection.updateOne(
54620
+ { _id },
54621
+ { $set: { status, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
54622
+ { session }
54623
+ );
54624
+ if (res.modifiedCount === 0)
54625
+ throw new import_node_server_utils232.InternalServerError("Unable to update post status.");
54626
+ return res;
54627
+ } catch (error) {
54628
+ throw error;
54629
+ }
54630
+ }
53696
54631
  return {
53697
54632
  add,
53698
54633
  getById,
53699
- getAll
54634
+ getAll,
54635
+ updateById,
54636
+ deleteById,
54637
+ updateStatus
53700
54638
  };
53701
54639
  }
53702
54640
 
@@ -53707,7 +54645,10 @@ function usePostPrelovedController() {
53707
54645
  const {
53708
54646
  add: _add,
53709
54647
  getById: _getById,
53710
- getAll: _getAll
54648
+ getAll: _getAll,
54649
+ updateById: _updateById,
54650
+ deleteById: _deleteById,
54651
+ updateStatus: _updateStatus
53711
54652
  } = usePostPrelovedRepo();
53712
54653
  async function add(req, res, next) {
53713
54654
  const { error, value } = schemaPost.validate(req.body, {
@@ -53790,10 +54731,280 @@ function usePostPrelovedController() {
53790
54731
  return;
53791
54732
  }
53792
54733
  }
54734
+ async function updateById(req, res, next) {
54735
+ const _id = req.params.id;
54736
+ const payload = { _id, ...req.body };
54737
+ const { error } = schemaUpdatePost.validate(payload, {
54738
+ abortEarly: false
54739
+ });
54740
+ if (error) {
54741
+ const messages = error.details.map((d) => d.message).join(", ");
54742
+ import_node_server_utils233.logger.log({ level: "error", message: messages });
54743
+ next(new import_node_server_utils233.BadRequestError(messages));
54744
+ return;
54745
+ }
54746
+ try {
54747
+ const data = await _updateById(_id, req.body);
54748
+ res.status(200).json(data);
54749
+ return;
54750
+ } catch (error2) {
54751
+ import_node_server_utils233.logger.log({ level: "error", message: error2.message });
54752
+ next(error2);
54753
+ return;
54754
+ }
54755
+ }
54756
+ async function deleteById(req, res, next) {
54757
+ const schema2 = import_joi133.default.object({
54758
+ _id: import_joi133.default.string().hex().length(24).required()
54759
+ });
54760
+ const { error, value } = schema2.validate({ _id: req.params.id });
54761
+ if (error) {
54762
+ import_node_server_utils233.logger.log({ level: "error", message: error.message });
54763
+ next(new import_node_server_utils233.BadRequestError(error.message));
54764
+ return;
54765
+ }
54766
+ try {
54767
+ const data = await _deleteById(value._id);
54768
+ res.status(200).json({ message: "Successfully deleted post." });
54769
+ return;
54770
+ } catch (error2) {
54771
+ import_node_server_utils233.logger.log({ level: "error", message: error2.message });
54772
+ next(error2);
54773
+ return;
54774
+ }
54775
+ }
54776
+ async function updateStatus(req, res, next) {
54777
+ const schema2 = import_joi133.default.object({
54778
+ _id: import_joi133.default.string().hex().length(24).required(),
54779
+ status: import_joi133.default.string().valid(...Object.values(PostStatus)).required()
54780
+ });
54781
+ const { error, value } = schema2.validate({
54782
+ _id: req.params.id,
54783
+ status: req.body.status
54784
+ });
54785
+ if (error) {
54786
+ import_node_server_utils233.logger.log({ level: "error", message: error.message });
54787
+ next(new import_node_server_utils233.BadRequestError(error.message));
54788
+ return;
54789
+ }
54790
+ try {
54791
+ const data = await _updateStatus(value._id, value.status);
54792
+ res.status(200).json(data);
54793
+ return;
54794
+ } catch (error2) {
54795
+ import_node_server_utils233.logger.log({ level: "error", message: error2.message });
54796
+ next(error2);
54797
+ return;
54798
+ }
54799
+ }
53793
54800
  return {
53794
54801
  add,
53795
54802
  getById,
53796
- getAll
54803
+ getAll,
54804
+ updateById,
54805
+ deleteById,
54806
+ updateStatus
54807
+ };
54808
+ }
54809
+
54810
+ // src/models/online-forms-v2.model.ts
54811
+ var import_joi134 = __toESM(require("joi"));
54812
+ var import_mongodb131 = require("mongodb");
54813
+ var FormEntryStatus = /* @__PURE__ */ ((FormEntryStatus2) => {
54814
+ FormEntryStatus2["ACTIVE"] = "active";
54815
+ FormEntryStatus2["INACTIVE"] = "inactive";
54816
+ FormEntryStatus2["DELETED"] = "deleted";
54817
+ return FormEntryStatus2;
54818
+ })(FormEntryStatus || {});
54819
+ var schemaFormEntry = import_joi134.default.object({
54820
+ _id: import_joi134.default.string().hex().optional().allow("", null),
54821
+ formType: import_joi134.default.string().required(),
54822
+ fields: import_joi134.default.object().pattern(
54823
+ import_joi134.default.string(),
54824
+ import_joi134.default.alternatives().try(
54825
+ import_joi134.default.string(),
54826
+ import_joi134.default.number(),
54827
+ import_joi134.default.boolean(),
54828
+ import_joi134.default.valid(null)
54829
+ )
54830
+ ).required(),
54831
+ status: import_joi134.default.string().optional().allow("", null),
54832
+ org: import_joi134.default.string().hex().optional().allow("", null),
54833
+ site: import_joi134.default.string().hex().optional().allow("", null),
54834
+ createdAt: import_joi134.default.date().optional().allow("", null),
54835
+ updatedAt: import_joi134.default.date().optional().allow("", null),
54836
+ deletedAt: import_joi134.default.date().optional().allow("", null)
54837
+ });
54838
+ var schemaUpdateFormEntry = import_joi134.default.object({
54839
+ _id: import_joi134.default.string().hex().required(),
54840
+ formType: import_joi134.default.string().optional().allow("", null),
54841
+ fields: import_joi134.default.object().pattern(
54842
+ import_joi134.default.string(),
54843
+ import_joi134.default.alternatives().try(
54844
+ import_joi134.default.string(),
54845
+ import_joi134.default.number(),
54846
+ import_joi134.default.boolean(),
54847
+ import_joi134.default.valid(null)
54848
+ )
54849
+ ).optional(),
54850
+ status: import_joi134.default.string().optional().allow("", null),
54851
+ createdAt: import_joi134.default.date().optional().allow("", null),
54852
+ updatedAt: import_joi134.default.date().optional().allow("", null),
54853
+ deletedAt: import_joi134.default.date().optional().allow("", null)
54854
+ });
54855
+ function MFormEntry(value) {
54856
+ const { error } = schemaFormEntry.validate(value);
54857
+ if (error) {
54858
+ throw new Error(error.details[0].message);
54859
+ }
54860
+ if (value._id && typeof value._id === "string") {
54861
+ try {
54862
+ value._id = new import_mongodb131.ObjectId(value._id);
54863
+ } catch {
54864
+ throw new Error("Invalid ID.");
54865
+ }
54866
+ }
54867
+ if (value.org && typeof value.org === "string") {
54868
+ try {
54869
+ value.org = new import_mongodb131.ObjectId(value.org);
54870
+ } catch {
54871
+ throw new Error("Invalid org ID.");
54872
+ }
54873
+ }
54874
+ if (value.site && typeof value.site === "string") {
54875
+ try {
54876
+ value.site = new import_mongodb131.ObjectId(value.site);
54877
+ } catch {
54878
+ throw new Error("Invalid site ID.");
54879
+ }
54880
+ }
54881
+ return {
54882
+ _id: value._id,
54883
+ formType: value.formType,
54884
+ fields: value.fields,
54885
+ status: value.status,
54886
+ org: value.org,
54887
+ site: value.site,
54888
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
54889
+ updatedAt: value.updatedAt ?? null,
54890
+ deletedAt: value.deletedAt ?? null
54891
+ };
54892
+ }
54893
+
54894
+ // src/repositories/online-forms-v2.repository.ts
54895
+ var import_node_server_utils234 = require("@7365admin1/node-server-utils");
54896
+ var online_forms_namespace_collection = "online-forms";
54897
+ function useFormEntryRepo() {
54898
+ const db = import_node_server_utils234.useAtlas.getDb();
54899
+ if (!db) {
54900
+ throw new import_node_server_utils234.InternalServerError("Unable to connect to server.");
54901
+ }
54902
+ const collection = db.collection(online_forms_namespace_collection);
54903
+ const { delNamespace, getCache, setCache } = (0, import_node_server_utils234.useCache)(
54904
+ online_forms_namespace_collection
54905
+ );
54906
+ async function createTextIndex() {
54907
+ try {
54908
+ await collection.createIndex({
54909
+ name: "text"
54910
+ });
54911
+ } catch (error) {
54912
+ throw new import_node_server_utils234.InternalServerError(
54913
+ "Failed to create text index on online form."
54914
+ );
54915
+ }
54916
+ }
54917
+ async function add(value, session) {
54918
+ try {
54919
+ value = MFormEntry(value);
54920
+ const res = await collection.insertOne(value, { session });
54921
+ delNamespace().then(() => {
54922
+ import_node_server_utils234.logger.info(
54923
+ `Cache cleared for namespace: ${online_forms_namespace_collection}`
54924
+ );
54925
+ }).catch((err) => {
54926
+ import_node_server_utils234.logger.error(
54927
+ `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
54928
+ err
54929
+ );
54930
+ });
54931
+ return res.insertedId;
54932
+ } catch (error) {
54933
+ const isDuplicated = error.message.includes("duplicate");
54934
+ if (isDuplicated) {
54935
+ throw new import_node_server_utils234.BadRequestError("Online Form already exists.");
54936
+ }
54937
+ throw error;
54938
+ }
54939
+ }
54940
+ return {
54941
+ add,
54942
+ createTextIndex
54943
+ };
54944
+ }
54945
+
54946
+ // src/controllers/online-forms-v2.controller.ts
54947
+ var import_node_server_utils235 = require("@7365admin1/node-server-utils");
54948
+ var import_exceljs3 = __toESM(require("exceljs"));
54949
+ var import_fs6 = __toESM(require("fs"));
54950
+ function useFormEntryController() {
54951
+ const { add: _add } = useFormEntryRepo();
54952
+ function toCamelCase(str) {
54953
+ return str.replace(/\s(.)/g, (_, char) => char.toUpperCase()).replace(/\s+/g, "").replace(/^(.)/, (_, char) => char.toLowerCase());
54954
+ }
54955
+ function normalizeKeys(obj) {
54956
+ const normalized = {};
54957
+ for (const [key, value] of Object.entries(obj)) {
54958
+ normalized[toCamelCase(key)] = value;
54959
+ }
54960
+ return normalized;
54961
+ }
54962
+ async function uploadFormEntrys(req, res, next) {
54963
+ try {
54964
+ if (!req.file) {
54965
+ next(new import_node_server_utils235.BadRequestError("Excel file is required."));
54966
+ return;
54967
+ }
54968
+ const workbook = new import_exceljs3.default.Workbook();
54969
+ await workbook.xlsx.readFile(req.file.path);
54970
+ const worksheet = workbook.worksheets[0];
54971
+ if (!worksheet) {
54972
+ next(new import_node_server_utils235.BadRequestError("No worksheet found in uploaded Excel file."));
54973
+ return;
54974
+ }
54975
+ const headerRow = worksheet.getRow(1);
54976
+ const headers = headerRow.values.slice(1).map((h) => String(h ?? "").trim());
54977
+ const fields = {};
54978
+ headers.forEach((header) => {
54979
+ fields[header] = null;
54980
+ });
54981
+ const formType = req.file.originalname.replace(/\.[^/.]+$/, "");
54982
+ const normalizedFields = normalizeKeys(fields);
54983
+ const payload = {
54984
+ formType,
54985
+ fields: normalizedFields,
54986
+ status: "active" /* ACTIVE */
54987
+ };
54988
+ const { error, value } = schemaFormEntry.validate(payload, {
54989
+ abortEarly: false
54990
+ });
54991
+ if (error) {
54992
+ const messages = error.details.map((d) => d.message).join(", ");
54993
+ import_node_server_utils235.logger.log({ level: "error", message: messages });
54994
+ next(new import_node_server_utils235.BadRequestError(messages));
54995
+ return;
54996
+ }
54997
+ const result = await _add(value);
54998
+ res.status(201).json(result);
54999
+ import_fs6.default.unlink(req.file.path, () => {
55000
+ });
55001
+ } catch (error) {
55002
+ import_node_server_utils235.logger.log({ level: "error", message: error.message });
55003
+ next(error);
55004
+ }
55005
+ }
55006
+ return {
55007
+ uploadFormEntrys
53797
55008
  };
53798
55009
  }
53799
55010
  // Annotate the CommonJS export names for ESM import in node:
@@ -53823,6 +55034,7 @@ function usePostPrelovedController() {
53823
55034
  EventType,
53824
55035
  FacilitySort,
53825
55036
  FacilityStatus,
55037
+ FormEntryStatus,
53826
55038
  GuestSort,
53827
55039
  GuestStatus,
53828
55040
  MAccessCard,
@@ -53844,6 +55056,7 @@ function usePostPrelovedController() {
53844
55056
  MEventManagement,
53845
55057
  MFeedback,
53846
55058
  MFile,
55059
+ MFormEntry,
53847
55060
  MGuestManagement,
53848
55061
  MIncidentReport,
53849
55062
  MManpowerDesignations,
@@ -53955,6 +55168,7 @@ function usePostPrelovedController() {
53955
55168
  nfcPatrolSettingsSchema,
53956
55169
  nfcPatrolSettingsSchemaUpdate,
53957
55170
  occurrence_book_namespace_collection,
55171
+ online_forms_namespace_collection,
53958
55172
  orgSchema,
53959
55173
  overnight_parking_requests_namespace_collection,
53960
55174
  parseDahuaFind,
@@ -53979,6 +55193,7 @@ function usePostPrelovedController() {
53979
55193
  schemaEntryPassSettings,
53980
55194
  schemaEventManagement,
53981
55195
  schemaFiles,
55196
+ schemaFormEntry,
53982
55197
  schemaGuestManagement,
53983
55198
  schemaIncidentReport,
53984
55199
  schemaNfcPatrolLog,
@@ -54009,6 +55224,7 @@ function usePostPrelovedController() {
54009
55224
  schemaUpdateDocumentManagement,
54010
55225
  schemaUpdateEntryPassSettings,
54011
55226
  schemaUpdateEventManagement,
55227
+ schemaUpdateFormEntry,
54012
55228
  schemaUpdateGuestManagement,
54013
55229
  schemaUpdateIncidentReport,
54014
55230
  schemaUpdateOccurrenceBook,
@@ -54021,6 +55237,7 @@ function usePostPrelovedController() {
54021
55237
  schemaUpdatePatrolQuestion,
54022
55238
  schemaUpdatePatrolRoute,
54023
55239
  schemaUpdatePerson,
55240
+ schemaUpdatePost,
54024
55241
  schemaUpdateServiceProviderBilling,
54025
55242
  schemaUpdateSiteBillingConfiguration,
54026
55243
  schemaUpdateSiteBillingItem,
@@ -54091,6 +55308,8 @@ function usePostPrelovedController() {
54091
55308
  useFileController,
54092
55309
  useFileRepo,
54093
55310
  useFileService,
55311
+ useFormEntryController,
55312
+ useFormEntryRepo,
54094
55313
  useGuestManagementController,
54095
55314
  useGuestManagementRepo,
54096
55315
  useGuestManagementService,