@7365admin1/core 2.53.0 → 2.55.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
@@ -155,6 +155,7 @@ __export(src_exports, {
155
155
  allowedNatures: () => allowedNatures,
156
156
  attendanceSchema: () => attendanceSchema,
157
157
  attendanceSettingsSchema: () => attendanceSettingsSchema,
158
+ building_units_namespace_collection: () => building_units_namespace_collection,
158
159
  buildings_namespace_collection: () => buildings_namespace_collection,
159
160
  bulletin_boards_namespace_collection: () => bulletin_boards_namespace_collection,
160
161
  calculatePercentage: () => calculatePercentage,
@@ -4485,12 +4486,13 @@ function useOrgRepo() {
4485
4486
  status = "active",
4486
4487
  nature = ""
4487
4488
  }) {
4488
- page = page > 0 ? page - 1 : 0;
4489
4489
  const query = { status };
4490
4490
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
4491
4491
  const cacheOptions = {
4492
4492
  status,
4493
- sort
4493
+ sort,
4494
+ page,
4495
+ limit
4494
4496
  };
4495
4497
  if (search) {
4496
4498
  query.$text = { $search: search };
@@ -4506,11 +4508,12 @@ function useOrgRepo() {
4506
4508
  import_node_server_utils17.logger.info(`Cache hit for key: ${cacheKey}`);
4507
4509
  return cachedData;
4508
4510
  }
4511
+ const normalizedPage = page > 0 ? page - 1 : 0;
4509
4512
  try {
4510
4513
  const items = await collection.aggregate([
4511
4514
  { $match: query },
4512
4515
  { $sort: sort },
4513
- { $skip: page * limit },
4516
+ { $skip: normalizedPage * limit },
4514
4517
  { $limit: limit },
4515
4518
  {
4516
4519
  $project: {
@@ -4524,7 +4527,7 @@ function useOrgRepo() {
4524
4527
  }
4525
4528
  ]).toArray();
4526
4529
  const length = await collection.countDocuments(query);
4527
- const data = (0, import_node_server_utils17.paginate)(items, page, limit, length);
4530
+ const data = (0, import_node_server_utils17.paginate)(items, normalizedPage, limit, length);
4528
4531
  setCache(cacheKey, data, 15 * 60).then(() => {
4529
4532
  import_node_server_utils17.logger.info(`Cache set for key: ${cacheKey}`);
4530
4533
  }).catch((err) => {
@@ -5658,11 +5661,16 @@ function useVerificationService() {
5658
5661
  const existing = await useVerificationRepo().findOne({
5659
5662
  type,
5660
5663
  email,
5661
- "metadata.org": metadata?.org,
5662
- "metadata.siteId": metadata?.siteId
5664
+ "metadata.app": metadata.app
5663
5665
  });
5664
- if (existing)
5666
+ if (existing) {
5667
+ if (existing.status === "complete") {
5668
+ throw new import_node_server_utils21.BadRequestError(
5669
+ `User already completed invite for app: ${metadata.app}`
5670
+ );
5671
+ }
5665
5672
  return existing._id;
5673
+ }
5666
5674
  const value = {
5667
5675
  type,
5668
5676
  email,
@@ -7894,6 +7902,7 @@ function useVerificationController() {
7894
7902
  createServiceProviderInvite: _createServiceProviderInvite,
7895
7903
  createForgetPassword: _createForgetPassword,
7896
7904
  verify: _verify,
7905
+ updateStatusById: _updateStatusById,
7897
7906
  cancelUserInvitation: _cancelUserInvitation
7898
7907
  } = useVerificationService();
7899
7908
  const { getVerifications: _getVerifications } = useVerificationRepo();
@@ -8107,6 +8116,28 @@ function useVerificationController() {
8107
8116
  return;
8108
8117
  }
8109
8118
  }
8119
+ async function updateVerificationStatus(req, res, next) {
8120
+ const validation = import_joi16.default.object({
8121
+ id: import_joi16.default.string().hex().required(),
8122
+ status: import_joi16.default.string().valid("pending", "complete", "expired", "cancelled").required()
8123
+ });
8124
+ const { error } = validation.validate(req.body);
8125
+ if (error) {
8126
+ import_node_server_utils32.logger.log({ level: "error", message: error.message });
8127
+ next(new import_node_server_utils32.BadRequestError(error.message));
8128
+ return;
8129
+ }
8130
+ try {
8131
+ const { id, status } = req.body;
8132
+ const result = await _updateStatusById(id, status);
8133
+ res.json({ message: result });
8134
+ return;
8135
+ } catch (error2) {
8136
+ import_node_server_utils32.logger.log({ level: "error", message: error2.message });
8137
+ next(error2);
8138
+ return;
8139
+ }
8140
+ }
8110
8141
  async function cancelUserInvitation(req, res, next) {
8111
8142
  const validation = import_joi16.default.string().hex().required();
8112
8143
  const otpId = req.params.id;
@@ -8134,6 +8165,7 @@ function useVerificationController() {
8134
8165
  createServiceProviderInvite,
8135
8166
  createForgetPassword,
8136
8167
  verify,
8168
+ updateVerificationStatus,
8137
8169
  cancelUserInvitation,
8138
8170
  createSimpleUserInvite
8139
8171
  };
@@ -13922,9 +13954,26 @@ function useVisitorTransactionRepo() {
13922
13954
  ...status && { status },
13923
13955
  ...tab == "Overnight Parking" && { isOvernightParking: true }
13924
13956
  };
13925
- sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
13957
+ sort = Object.keys(sort).length > 0 ? sort : { latestDate: -1 };
13926
13958
  try {
13927
- const basePipeline = [{ $match: query }];
13959
+ const basePipeline = [
13960
+ { $match: query },
13961
+ {
13962
+ $addFields: {
13963
+ latestDate: {
13964
+ $max: ["$createdAt", "$updatedAt"]
13965
+ }
13966
+ }
13967
+ },
13968
+ { $sort: { latestDate: -1 } },
13969
+ { $skip: skip },
13970
+ { $limit: limit },
13971
+ {
13972
+ $project: {
13973
+ latestDate: 0
13974
+ }
13975
+ }
13976
+ ];
13928
13977
  const [items, countResult] = await Promise.all([
13929
13978
  collection.aggregate([
13930
13979
  ...basePipeline,
@@ -14064,9 +14113,6 @@ function useVisitorTransactionRepo() {
14064
14113
  as: "passKeys"
14065
14114
  }
14066
14115
  },
14067
- { $sort: sort },
14068
- { $skip: skip },
14069
- { $limit: limit },
14070
14116
  {
14071
14117
  $lookup: {
14072
14118
  from: "users",
@@ -16044,14 +16090,16 @@ function MBuildingUnit(value) {
16044
16090
 
16045
16091
  // src/repositories/building-unit.repository.ts
16046
16092
  var import_mongodb45 = require("mongodb");
16093
+ var building_units_namespace_collection = "building-units";
16047
16094
  function useBuildingUnitRepo() {
16048
16095
  const db = import_node_server_utils73.useAtlas.getDb();
16049
16096
  if (!db) {
16050
16097
  throw new Error("Unable to connect to server.");
16051
16098
  }
16052
- const namespace_collection = "building-units";
16053
- const collection = db.collection(namespace_collection);
16054
- const { getCache, setCache, delNamespace, delCache } = (0, import_node_server_utils73.useCache)(namespace_collection);
16099
+ const collection = db.collection(building_units_namespace_collection);
16100
+ const { getCache, setCache, delNamespace, delCache } = (0, import_node_server_utils73.useCache)(
16101
+ building_units_namespace_collection
16102
+ );
16055
16103
  async function createIndexes() {
16056
16104
  try {
16057
16105
  await collection.createIndexes([
@@ -16077,12 +16125,12 @@ function useBuildingUnitRepo() {
16077
16125
  delNamespace().then(() => {
16078
16126
  import_node_server_utils73.logger.log({
16079
16127
  level: "info",
16080
- message: `Cache namespace cleared for ${namespace_collection}`
16128
+ message: `Cache namespace cleared for ${building_units_namespace_collection}`
16081
16129
  });
16082
16130
  }).catch((err) => {
16083
16131
  import_node_server_utils73.logger.log({
16084
16132
  level: "error",
16085
- message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
16133
+ message: `Failed to clear cache namespace for ${building_units_namespace_collection}: ${err.message}`
16086
16134
  });
16087
16135
  });
16088
16136
  }
@@ -16229,7 +16277,10 @@ function useBuildingUnitRepo() {
16229
16277
  ...building && { building },
16230
16278
  ...status && { status }
16231
16279
  };
16232
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, cacheParams);
16280
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(
16281
+ building_units_namespace_collection,
16282
+ cacheParams
16283
+ );
16233
16284
  import_node_server_utils73.logger.log({
16234
16285
  level: "info",
16235
16286
  message: `Cache key for getAll building units: ${cacheKey}`
@@ -16300,7 +16351,9 @@ function useBuildingUnitRepo() {
16300
16351
  } catch (error) {
16301
16352
  throw new import_node_server_utils73.BadRequestError("Invalid ID.");
16302
16353
  }
16303
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, { _id: String(_id) });
16354
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(building_units_namespace_collection, {
16355
+ _id: String(_id)
16356
+ });
16304
16357
  try {
16305
16358
  const cached = await getCache(cacheKey);
16306
16359
  if (cached) {
@@ -16343,7 +16396,7 @@ function useBuildingUnitRepo() {
16343
16396
  } catch (error) {
16344
16397
  throw new import_node_server_utils73.BadRequestError("Invalid building ID.");
16345
16398
  }
16346
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, {
16399
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(building_units_namespace_collection, {
16347
16400
  building: String(building),
16348
16401
  level
16349
16402
  });
@@ -16417,7 +16470,7 @@ function useBuildingUnitRepo() {
16417
16470
  } catch (error) {
16418
16471
  throw new import_node_server_utils73.BadRequestError("Invalid building ID.");
16419
16472
  }
16420
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, {
16473
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(building_units_namespace_collection, {
16421
16474
  building: String(building)
16422
16475
  });
16423
16476
  try {
@@ -16491,7 +16544,10 @@ function useBuildingUnitRepo() {
16491
16544
  block,
16492
16545
  level
16493
16546
  };
16494
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, cacheOptions);
16547
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(
16548
+ building_units_namespace_collection,
16549
+ cacheOptions
16550
+ );
16495
16551
  const cachedData = await getCache(cacheKey);
16496
16552
  if (cachedData) {
16497
16553
  import_node_server_utils73.logger.info(`Cache hit for key: ${cacheKey}`);
@@ -16529,7 +16585,10 @@ function useBuildingUnitRepo() {
16529
16585
  const cacheOptions = {
16530
16586
  site: site.toString()
16531
16587
  };
16532
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, cacheOptions);
16588
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(
16589
+ building_units_namespace_collection,
16590
+ cacheOptions
16591
+ );
16533
16592
  const cachedData = await getCache(cacheKey);
16534
16593
  if (cachedData) {
16535
16594
  import_node_server_utils73.logger.info(`Cache hit for key: ${cacheKey}`);
@@ -16577,7 +16636,10 @@ function useBuildingUnitRepo() {
16577
16636
  { deletedAt: "" }
16578
16637
  ]
16579
16638
  };
16580
- const cacheKey = (0, import_node_server_utils73.makeCacheKey)(namespace_collection, cacheOptions);
16639
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(
16640
+ building_units_namespace_collection,
16641
+ cacheOptions
16642
+ );
16581
16643
  try {
16582
16644
  const cached = await getCache(cacheKey);
16583
16645
  if (cached) {
@@ -16613,6 +16675,54 @@ function useBuildingUnitRepo() {
16613
16675
  }
16614
16676
  }
16615
16677
  }
16678
+ async function getBySiteBuildingLevel(site, block, level) {
16679
+ try {
16680
+ site = new import_mongodb45.ObjectId(site);
16681
+ } catch (error) {
16682
+ throw new import_node_server_utils73.BadRequestError("Invalid site ID.");
16683
+ }
16684
+ const cacheKey = (0, import_node_server_utils73.makeCacheKey)(building_units_namespace_collection, {
16685
+ site: site.toString(),
16686
+ block,
16687
+ level
16688
+ });
16689
+ try {
16690
+ const cached = await getCache(cacheKey);
16691
+ if (cached) {
16692
+ import_node_server_utils73.logger.log({
16693
+ level: "info",
16694
+ message: `Cache hit for getById building unit: ${cacheKey}`
16695
+ });
16696
+ return cached;
16697
+ }
16698
+ const query = {
16699
+ site,
16700
+ block,
16701
+ level,
16702
+ status: "active"
16703
+ };
16704
+ console.log(query);
16705
+ const result = await collection.findOne(query);
16706
+ setCache(cacheKey, result, 300).then(() => {
16707
+ import_node_server_utils73.logger.log({
16708
+ level: "info",
16709
+ message: `Cache set for building unit by id: ${cacheKey}`
16710
+ });
16711
+ }).catch((err) => {
16712
+ import_node_server_utils73.logger.log({
16713
+ level: "error",
16714
+ message: `Failed to set cache for building unit by id: ${err.message}`
16715
+ });
16716
+ });
16717
+ return result;
16718
+ } catch (error) {
16719
+ if (error instanceof import_node_server_utils73.AppError) {
16720
+ throw error;
16721
+ } else {
16722
+ throw new import_node_server_utils73.InternalServerError("Failed to get building unit.");
16723
+ }
16724
+ }
16725
+ }
16616
16726
  return {
16617
16727
  createIndexes,
16618
16728
  add,
@@ -16626,7 +16736,8 @@ function useBuildingUnitRepo() {
16626
16736
  updateByBuildingId,
16627
16737
  getBuildingUnits,
16628
16738
  getBuildingUnitsWithOwner,
16629
- getUnitByBlockLevelUnitNumber
16739
+ getUnitByBlockLevelUnitNumber,
16740
+ getBySiteBuildingLevel
16630
16741
  };
16631
16742
  }
16632
16743
 
@@ -19288,6 +19399,7 @@ function useBuildingRepo() {
19288
19399
  throw new Error("Failed to create index on buildings. " + error.message);
19289
19400
  }
19290
19401
  }
19402
+ const { getBySiteBuildingLevel: _getBySiteBuildingLevel } = useBuildingUnitRepo();
19291
19403
  async function add(value, session) {
19292
19404
  try {
19293
19405
  value = MBuilding(value);
@@ -19523,6 +19635,94 @@ function useBuildingRepo() {
19523
19635
  }
19524
19636
  }
19525
19637
  }
19638
+ async function getBuildingLevelWithUnits(site, block) {
19639
+ try {
19640
+ site = new import_mongodb49.ObjectId(site);
19641
+ } catch (error) {
19642
+ throw new import_node_server_utils82.BadRequestError("Invalid ID.");
19643
+ }
19644
+ const query = {
19645
+ site,
19646
+ _id: new import_mongodb49.ObjectId(block)
19647
+ };
19648
+ const cacheOptions = { ...query };
19649
+ const cacheKey = (0, import_node_server_utils82.makeCacheKey)(buildings_namespace_collection, cacheOptions);
19650
+ try {
19651
+ console.log(query);
19652
+ const result = await collection.aggregate([
19653
+ {
19654
+ $match: {
19655
+ ...query
19656
+ }
19657
+ },
19658
+ {
19659
+ $lookup: {
19660
+ from: "building-levels",
19661
+ let: { buildingId: "$_id" },
19662
+ pipeline: [
19663
+ {
19664
+ $match: {
19665
+ $expr: { $eq: ["$block", "$$buildingId"] }
19666
+ }
19667
+ },
19668
+ {
19669
+ $lookup: {
19670
+ from: "building-units",
19671
+ let: { levelId: "$_id" },
19672
+ pipeline: [
19673
+ {
19674
+ $match: {
19675
+ $expr: {
19676
+ $and: [
19677
+ { $eq: ["$site", site] },
19678
+ { $eq: ["$block", "$$buildingId"] },
19679
+ { $eq: ["$level", "$$levelId"] },
19680
+ { $eq: ["$status", "active"] }
19681
+ ]
19682
+ }
19683
+ }
19684
+ }
19685
+ ],
19686
+ as: "buildingUnits"
19687
+ }
19688
+ },
19689
+ // discard levels that have no active units
19690
+ {
19691
+ $match: {
19692
+ $expr: { $gt: [{ $size: "$buildingUnits" }, 0] }
19693
+ }
19694
+ }
19695
+ ],
19696
+ as: "buildingLevels"
19697
+ }
19698
+ },
19699
+ {
19700
+ $project: {
19701
+ "_id": 1,
19702
+ "site": 1,
19703
+ "name": 1,
19704
+ "block": 1,
19705
+ "status": 1,
19706
+ "buildingFloorPlan": 1,
19707
+ "createdAt": 1,
19708
+ "updatedAt": 1,
19709
+ "deletedAt": 1,
19710
+ "levels": "$buildingLevels"
19711
+ }
19712
+ }
19713
+ ]).toArray();
19714
+ if (!result) {
19715
+ throw new import_node_server_utils82.BadRequestError("Building not found.");
19716
+ }
19717
+ return result;
19718
+ } catch (error) {
19719
+ if (error instanceof import_node_server_utils82.AppError) {
19720
+ throw error;
19721
+ } else {
19722
+ throw new import_node_server_utils82.InternalServerError("Failed to get building.");
19723
+ }
19724
+ }
19725
+ }
19526
19726
  function delCachedData() {
19527
19727
  delNamespace().then(() => {
19528
19728
  import_node_server_utils82.logger.log({
@@ -19543,7 +19743,8 @@ function useBuildingRepo() {
19543
19743
  getById,
19544
19744
  updateById,
19545
19745
  deleteById,
19546
- getBuildingLevel
19746
+ getBuildingLevel,
19747
+ getBuildingLevelWithUnits
19547
19748
  };
19548
19749
  }
19549
19750
 
@@ -19697,7 +19898,8 @@ function useBuildingController() {
19697
19898
  const {
19698
19899
  getAll: _getAll,
19699
19900
  getById: _getById,
19700
- getBuildingLevel: _getBuildingLevel
19901
+ getBuildingLevel: _getBuildingLevel,
19902
+ getBuildingLevelWithUnits: _getBuildingLevelWithUnits
19701
19903
  } = useBuildingRepo();
19702
19904
  const {
19703
19905
  updateById: _updateById,
@@ -19966,6 +20168,26 @@ function useBuildingController() {
19966
20168
  next(error);
19967
20169
  }
19968
20170
  }
20171
+ async function getBuildingLevelWithUnits(req, res, next) {
20172
+ const site = req.params.site ?? "";
20173
+ let block = req.query.block;
20174
+ const validation = import_joi44.default.object({
20175
+ site: import_joi44.default.string().hex().required(),
20176
+ block: import_joi44.default.string().required()
20177
+ });
20178
+ const { error } = validation.validate({ site, block });
20179
+ if (error) {
20180
+ next(new import_node_server_utils84.BadRequestError(error.message));
20181
+ return;
20182
+ }
20183
+ try {
20184
+ const siteBlock = await _getBuildingLevelWithUnits(site, block);
20185
+ res.json(siteBlock);
20186
+ return;
20187
+ } catch (error2) {
20188
+ next(error2);
20189
+ }
20190
+ }
19969
20191
  return {
19970
20192
  createBuilding,
19971
20193
  getAll,
@@ -19973,7 +20195,8 @@ function useBuildingController() {
19973
20195
  updateById,
19974
20196
  deleteById,
19975
20197
  getBuildingLevel,
19976
- uploadSpreadsheetBuilding
20198
+ uploadSpreadsheetBuilding,
20199
+ getBuildingLevelWithUnits
19977
20200
  };
19978
20201
  }
19979
20202
 
@@ -23832,7 +24055,10 @@ function useVisitorTransactionService() {
23832
24055
  nric: value.nric,
23833
24056
  start,
23834
24057
  end,
23835
- recNo: value.recNo
24058
+ recNo: value.recNo,
24059
+ ...value.block && { block: value.block },
24060
+ ...value.level && { level: value.level },
24061
+ ...value.unit && { unit: new import_mongodb59.ObjectId(value.unit) }
23836
24062
  };
23837
24063
  await addVehicle(vehiclePayload);
23838
24064
  } else {
@@ -23964,6 +24190,8 @@ function useVisitorTransactionService() {
23964
24190
  }
23965
24191
  if (value.unit) {
23966
24192
  value.unit = typeof value.unit === "string" ? new import_mongodb59.ObjectId(value.unit) : value.unit;
24193
+ const unit = await _getUnitById(value.unit);
24194
+ value.unitName = unit?.name;
23967
24195
  }
23968
24196
  await _updateVisitorTansactionById(id, value, session);
23969
24197
  await session?.commitTransaction();
@@ -32677,21 +32905,23 @@ function useEventManagementController() {
32677
32905
  }
32678
32906
  }
32679
32907
  async function deleteEventManagementById(req, res, next) {
32680
- const validation = import_joi82.default.string().hex().required();
32681
- const _id = req.params.id;
32682
- const { error } = validation.validate(_id);
32683
- if (error) {
32684
- import_node_server_utils148.logger.log({ level: "error", message: error.message });
32685
- next(new import_node_server_utils148.BadRequestError(error.message));
32686
- return;
32687
- }
32688
32908
  try {
32909
+ const schema2 = import_joi82.default.object({
32910
+ _id: import_joi82.default.string().hex().length(24).required()
32911
+ });
32912
+ const { error, value } = schema2.validate({ _id: req.params.id });
32913
+ if (error) {
32914
+ import_node_server_utils148.logger.log({ level: "error", message: error.message });
32915
+ next(new import_node_server_utils148.BadRequestError(error.message));
32916
+ return;
32917
+ }
32918
+ const { _id } = value;
32689
32919
  await _deleteEventManagementById(_id);
32690
32920
  res.status(200).json({ message: "Successfully deleted event." });
32691
32921
  return;
32692
- } catch (error2) {
32693
- import_node_server_utils148.logger.log({ level: "error", message: error2.message });
32694
- next(error2);
32922
+ } catch (error) {
32923
+ import_node_server_utils148.logger.log({ level: "error", message: error.message });
32924
+ next(error);
32695
32925
  return;
32696
32926
  }
32697
32927
  }
@@ -36262,7 +36492,111 @@ function UseAccessManagementRepo() {
36262
36492
  const items = result[0].items;
36263
36493
  return (0, import_node_server_utils153.paginate)(items, page, limit, length);
36264
36494
  } catch (error) {
36265
- return Promise.reject("Server internal error.");
36495
+ throw new Error(error.message);
36496
+ }
36497
+ }
36498
+ async function assignMultipleCardsRepo({
36499
+ assignees,
36500
+ unit,
36501
+ type,
36502
+ acm_url
36503
+ }) {
36504
+ const session = import_node_server_utils153.useAtlas.getClient()?.startSession();
36505
+ try {
36506
+ session?.startTransaction();
36507
+ if (assignees.length < 1) {
36508
+ throw new Error("No user to Assign.");
36509
+ }
36510
+ assignees = assignees.map((data) => new import_mongodb90.ObjectId(data));
36511
+ unit = new import_mongodb90.ObjectId(unit);
36512
+ let availableCards = [];
36513
+ let update = [];
36514
+ let cards = [];
36515
+ availableCards = await collection().aggregate([
36516
+ {
36517
+ $match: {
36518
+ $expr: {
36519
+ $and: [
36520
+ { $eq: ["$assignedUnit", unit] },
36521
+ { $eq: ["$userId", null] },
36522
+ { $eq: ["$type", type] },
36523
+ { $eq: ["$isActivated", true] }
36524
+ ]
36525
+ }
36526
+ }
36527
+ }
36528
+ ]).toArray();
36529
+ if (assignees.length > availableCards.length) {
36530
+ throw new Error(`Not enough ${type} cards available.`);
36531
+ }
36532
+ cards = availableCards?.slice(0, assignees.length).map((card, index) => {
36533
+ const userId = new import_mongodb90.ObjectId(assignees[index].toString());
36534
+ card.staffNo = userId.toString().slice(-10);
36535
+ return card;
36536
+ });
36537
+ update = availableCards.slice(0, assignees.length).map((card, index) => ({ _id: card._id, userId: new import_mongodb90.ObjectId(assignees[index]) }));
36538
+ const commands = cards.map((item, index) => {
36539
+ let ag = null;
36540
+ if (item.accessGroup !== void 0) {
36541
+ if (item.accessGroup?.length > 0) {
36542
+ ag = item.accessGroup.map((g) => `<GROUP_NAME>${g}</GROUP_NAME>`).join("\n ");
36543
+ }
36544
+ }
36545
+ const command = {
36546
+ commandId1: index * 2 + 1,
36547
+ commandId2: index * 2 + 2,
36548
+ staffName: `STAFF-${item._id.toString().slice(-10)}`,
36549
+ staffNo1: `STAFF-${item._id.toString().slice(-10)}`,
36550
+ staffNo2: `STAFF-${item._id.toString().slice(-10)}`,
36551
+ dateOfJoin: formatEntryPassDate(item.startDate),
36552
+ accessLevel: item.accessLevel ?? "0",
36553
+ cardNo: item.cardNo,
36554
+ pin: typeof item.pin === "string" && item.pin.trim() !== "" ? item.pin : "123456",
36555
+ startDate: formatEntryPassDate(item.startDate),
36556
+ endDate: formatEntryPassDate(item.endDate),
36557
+ cardType: 0,
36558
+ isActivated: item.isActivated ? 1 : 0,
36559
+ isAntiPassBack: item.isAntiPassBack ? 1 : 0,
36560
+ isLiftCard: item.isLiftCard ? 1 : 0,
36561
+ isLiftActivate: item.isLiftCard ? 1 : 0,
36562
+ liftAccessLevel: item.liftAccessLevel || 1,
36563
+ liftAccessStartDate: formatEntryPassDate(item.liftAccessStartDate) || "19770510",
36564
+ liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
36565
+ accessGroup: ag
36566
+ };
36567
+ return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
36568
+ }).flat();
36569
+ const response = await sendCommand(commands.join("").toString(), acm_url);
36570
+ const result = await (0, import_xml2js2.parseStringPromise)(response, { explicitArray: false });
36571
+ console.log("status code", result.RESULT.$.STCODE);
36572
+ if (result && result.RESULT.$.STCODE !== "0") {
36573
+ throw new Error("Command failed, server error.");
36574
+ }
36575
+ for (const { _id, userId } of update) {
36576
+ await collection().updateOne({ _id }, { $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` } }, { session });
36577
+ }
36578
+ await session?.commitTransaction();
36579
+ return "Cards assigned successfully.";
36580
+ } catch (error) {
36581
+ await session?.abortTransaction();
36582
+ throw new Error(error.message);
36583
+ } finally {
36584
+ await session?.endSession();
36585
+ }
36586
+ }
36587
+ async function visitorCheckoutRepo({ userId }) {
36588
+ const session = import_node_server_utils153.useAtlas.getClient()?.startSession();
36589
+ try {
36590
+ session?.startTransaction();
36591
+ const id = new import_mongodb90.ObjectId(userId);
36592
+ await collection().updateMany({ userId: id }, { $set: { userId: null, status: "Available" } }, { session });
36593
+ session?.commitTransaction();
36594
+ return "Successful Checkout";
36595
+ } catch (error) {
36596
+ await session?.abortTransaction();
36597
+ throw new Error(error.message);
36598
+ } finally {
36599
+ await session?.endSession();
36266
36600
  }
36267
36601
  }
36268
36602
  return {
@@ -36297,7 +36631,9 @@ function UseAccessManagementRepo() {
36297
36631
  checkoutVisitorRepo,
36298
36632
  getBlockLevelAndUnitListRepo,
36299
36633
  indexCombination,
36300
- getTransactionsRepo
36634
+ getTransactionsRepo,
36635
+ assignMultipleCardsRepo,
36636
+ visitorCheckoutRepo
36301
36637
  };
36302
36638
  }
36303
36639
 
@@ -36338,7 +36674,9 @@ function useAccessManagementSvc() {
36338
36674
  signQrCodeRepo,
36339
36675
  checkoutVisitorRepo,
36340
36676
  getBlockLevelAndUnitListRepo,
36341
- getTransactionsRepo
36677
+ getTransactionsRepo,
36678
+ assignMultipleCardsRepo,
36679
+ visitorCheckoutRepo
36342
36680
  } = UseAccessManagementRepo();
36343
36681
  const addPhysicalCardSvc = async (payload) => {
36344
36682
  try {
@@ -36634,6 +36972,22 @@ function useAccessManagementSvc() {
36634
36972
  try {
36635
36973
  const response = await getTransactionsRepo({ page, limit, site, cardNo, url });
36636
36974
  return response;
36975
+ } catch (err) {
36976
+ throw new Error(err.message);
36977
+ }
36978
+ };
36979
+ const assignMultipleCardsSvc = async ({ assignees, unit, type, acm_url }) => {
36980
+ try {
36981
+ const response = await assignMultipleCardsRepo({ assignees, unit, type, acm_url });
36982
+ return response;
36983
+ } catch (err) {
36984
+ throw new Error(err.message);
36985
+ }
36986
+ };
36987
+ const visitorCheckoutSvc = async ({ userId }) => {
36988
+ try {
36989
+ const response = await visitorCheckoutRepo({ userId });
36990
+ return response;
36637
36991
  } catch (err) {
36638
36992
  return Promise.reject("Server internal error.");
36639
36993
  }
@@ -36673,7 +37027,9 @@ function useAccessManagementSvc() {
36673
37027
  signQrCodeSvc,
36674
37028
  checkoutVisitorSvc,
36675
37029
  getBlockLevelAndUnitListSvc,
36676
- getTransactionsSvc
37030
+ getTransactionsSvc,
37031
+ assignMultipleCardsSvc,
37032
+ visitorCheckoutSvc
36677
37033
  };
36678
37034
  }
36679
37035
 
@@ -36714,7 +37070,9 @@ function useAccessManagementController() {
36714
37070
  signQrCodeSvc,
36715
37071
  checkoutVisitorSvc,
36716
37072
  getBlockLevelAndUnitListSvc,
36717
- getTransactionsSvc
37073
+ getTransactionsSvc,
37074
+ assignMultipleCardsSvc,
37075
+ visitorCheckoutSvc
36718
37076
  } = useAccessManagementSvc();
36719
37077
  const addPhysicalCard = async (req, res) => {
36720
37078
  try {
@@ -37498,6 +37856,39 @@ function useAccessManagementController() {
37498
37856
  });
37499
37857
  return res.json(result);
37500
37858
  } catch (error2) {
37859
+ return res.status(400).json({
37860
+ data: null,
37861
+ message: error2.message
37862
+ });
37863
+ }
37864
+ };
37865
+ const assignMultipleCards = async (req, res) => {
37866
+ try {
37867
+ const { assignees, unit, type, acm_url } = req.body;
37868
+ const schema2 = import_joi85.default.object({
37869
+ assignees: import_joi85.default.array().items(import_joi85.default.string().hex()).required(),
37870
+ type: import_joi85.default.string().required(),
37871
+ unit: import_joi85.default.string().hex().required()
37872
+ });
37873
+ const { error } = schema2.validate({ assignees, type, unit });
37874
+ if (error) {
37875
+ throw new Error(`${error.message}`);
37876
+ }
37877
+ const result = await assignMultipleCardsSvc({ assignees, unit, type, acm_url });
37878
+ return res.status(200).json({ message: "Success", data: result });
37879
+ } catch (error) {
37880
+ return res.status(400).json({
37881
+ data: null,
37882
+ message: error.message
37883
+ });
37884
+ }
37885
+ };
37886
+ const visitorCheckout = async (req, res) => {
37887
+ try {
37888
+ const userId = req.params.userId;
37889
+ const result = await visitorCheckoutSvc({ userId });
37890
+ return res.status(200).json({ message: "Success", data: result });
37891
+ } catch (error) {
37501
37892
  return Promise.reject("Internal Server Error");
37502
37893
  }
37503
37894
  };
@@ -37534,7 +37925,9 @@ function useAccessManagementController() {
37534
37925
  checkoutVisitor,
37535
37926
  removeAccessCard,
37536
37927
  getBlockLevelAndUnitList,
37537
- getTransactions: getTransactions2
37928
+ getTransactions: getTransactions2,
37929
+ assignMultipleCards,
37930
+ visitorCheckout
37538
37931
  };
37539
37932
  }
37540
37933
 
@@ -51572,6 +51965,7 @@ function useRoleControllerV2() {
51572
51965
  allowedNatures,
51573
51966
  attendanceSchema,
51574
51967
  attendanceSettingsSchema,
51968
+ building_units_namespace_collection,
51575
51969
  buildings_namespace_collection,
51576
51970
  bulletin_boards_namespace_collection,
51577
51971
  calculatePercentage,