@7365admin1/core 2.54.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.mjs CHANGED
@@ -19475,47 +19475,77 @@ function useBuildingRepo() {
19475
19475
  }
19476
19476
  const query = {
19477
19477
  site,
19478
- block
19478
+ _id: new ObjectId49(block)
19479
19479
  };
19480
19480
  const cacheOptions = { ...query };
19481
19481
  const cacheKey = makeCacheKey26(buildings_namespace_collection, cacheOptions);
19482
19482
  try {
19483
- const cached = await getCache(cacheKey);
19484
- if (cached) {
19485
- logger60.log({
19486
- level: "info",
19487
- message: `Cache hit for getById building: ${cacheKey}`
19488
- });
19489
- return cached;
19490
- }
19491
- const result = await collection.findOne(query);
19483
+ console.log(query);
19484
+ const result = await collection.aggregate([
19485
+ {
19486
+ $match: {
19487
+ ...query
19488
+ }
19489
+ },
19490
+ {
19491
+ $lookup: {
19492
+ from: "building-levels",
19493
+ let: { buildingId: "$_id" },
19494
+ pipeline: [
19495
+ {
19496
+ $match: {
19497
+ $expr: { $eq: ["$block", "$$buildingId"] }
19498
+ }
19499
+ },
19500
+ {
19501
+ $lookup: {
19502
+ from: "building-units",
19503
+ let: { levelId: "$_id" },
19504
+ pipeline: [
19505
+ {
19506
+ $match: {
19507
+ $expr: {
19508
+ $and: [
19509
+ { $eq: ["$site", site] },
19510
+ { $eq: ["$block", "$$buildingId"] },
19511
+ { $eq: ["$level", "$$levelId"] },
19512
+ { $eq: ["$status", "active"] }
19513
+ ]
19514
+ }
19515
+ }
19516
+ }
19517
+ ],
19518
+ as: "buildingUnits"
19519
+ }
19520
+ },
19521
+ // discard levels that have no active units
19522
+ {
19523
+ $match: {
19524
+ $expr: { $gt: [{ $size: "$buildingUnits" }, 0] }
19525
+ }
19526
+ }
19527
+ ],
19528
+ as: "buildingLevels"
19529
+ }
19530
+ },
19531
+ {
19532
+ $project: {
19533
+ "_id": 1,
19534
+ "site": 1,
19535
+ "name": 1,
19536
+ "block": 1,
19537
+ "status": 1,
19538
+ "buildingFloorPlan": 1,
19539
+ "createdAt": 1,
19540
+ "updatedAt": 1,
19541
+ "deletedAt": 1,
19542
+ "levels": "$buildingLevels"
19543
+ }
19544
+ }
19545
+ ]).toArray();
19492
19546
  if (!result) {
19493
19547
  throw new BadRequestError79("Building not found.");
19494
19548
  }
19495
- const validLevels = [];
19496
- for (const level of result.levels ?? []) {
19497
- const units = await _getBySiteBuildingLevel(
19498
- result.site,
19499
- result.block,
19500
- level
19501
- );
19502
- if (units) {
19503
- validLevels.push(level);
19504
- }
19505
- }
19506
- result.levels = validLevels;
19507
- console.log(result);
19508
- setCache(cacheKey, result, 300).then(() => {
19509
- logger60.log({
19510
- level: "info",
19511
- message: `Cache set for building by id: ${cacheKey}`
19512
- });
19513
- }).catch((err) => {
19514
- logger60.log({
19515
- level: "error",
19516
- message: `Failed to set cache for building by id: ${err.message}`
19517
- });
19518
- });
19519
19549
  return result;
19520
19550
  } catch (error) {
19521
19551
  if (error instanceof AppError13) {
@@ -19980,14 +20010,13 @@ function useBuildingController() {
19980
20010
  let block = req.query.block;
19981
20011
  const validation = Joi44.object({
19982
20012
  site: Joi44.string().hex().required(),
19983
- block: Joi44.number().required()
20013
+ block: Joi44.string().required()
19984
20014
  });
19985
20015
  const { error } = validation.validate({ site, block });
19986
20016
  if (error) {
19987
20017
  next(new BadRequestError81(error.message));
19988
20018
  return;
19989
20019
  }
19990
- block = parseInt(block) ?? 0;
19991
20020
  try {
19992
20021
  const siteBlock = await _getBuildingLevelWithUnits(site, block);
19993
20022
  res.json(siteBlock);
@@ -23911,7 +23940,10 @@ function useVisitorTransactionService() {
23911
23940
  nric: value.nric,
23912
23941
  start,
23913
23942
  end,
23914
- recNo: value.recNo
23943
+ recNo: value.recNo,
23944
+ ...value.block && { block: value.block },
23945
+ ...value.level && { level: value.level },
23946
+ ...value.unit && { unit: new ObjectId59(value.unit) }
23915
23947
  };
23916
23948
  await addVehicle(vehiclePayload);
23917
23949
  } else {
@@ -32900,21 +32932,23 @@ function useEventManagementController() {
32900
32932
  }
32901
32933
  }
32902
32934
  async function deleteEventManagementById(req, res, next) {
32903
- const validation = Joi82.string().hex().required();
32904
- const _id = req.params.id;
32905
- const { error } = validation.validate(_id);
32906
- if (error) {
32907
- logger115.log({ level: "error", message: error.message });
32908
- next(new BadRequestError137(error.message));
32909
- return;
32910
- }
32911
32935
  try {
32936
+ const schema2 = Joi82.object({
32937
+ _id: Joi82.string().hex().length(24).required()
32938
+ });
32939
+ const { error, value } = schema2.validate({ _id: req.params.id });
32940
+ if (error) {
32941
+ logger115.log({ level: "error", message: error.message });
32942
+ next(new BadRequestError137(error.message));
32943
+ return;
32944
+ }
32945
+ const { _id } = value;
32912
32946
  await _deleteEventManagementById(_id);
32913
32947
  res.status(200).json({ message: "Successfully deleted event." });
32914
32948
  return;
32915
- } catch (error2) {
32916
- logger115.log({ level: "error", message: error2.message });
32917
- next(error2);
32949
+ } catch (error) {
32950
+ logger115.log({ level: "error", message: error.message });
32951
+ next(error);
32918
32952
  return;
32919
32953
  }
32920
32954
  }
@@ -36502,7 +36536,111 @@ function UseAccessManagementRepo() {
36502
36536
  const items = result[0].items;
36503
36537
  return paginate39(items, page, limit, length);
36504
36538
  } catch (error) {
36505
- return Promise.reject("Server internal error.");
36539
+ throw new Error(error.message);
36540
+ }
36541
+ }
36542
+ async function assignMultipleCardsRepo({
36543
+ assignees,
36544
+ unit,
36545
+ type,
36546
+ acm_url
36547
+ }) {
36548
+ const session = useAtlas76.getClient()?.startSession();
36549
+ try {
36550
+ session?.startTransaction();
36551
+ if (assignees.length < 1) {
36552
+ throw new Error("No user to Assign.");
36553
+ }
36554
+ assignees = assignees.map((data) => new ObjectId90(data));
36555
+ unit = new ObjectId90(unit);
36556
+ let availableCards = [];
36557
+ let update = [];
36558
+ let cards = [];
36559
+ availableCards = await collection().aggregate([
36560
+ {
36561
+ $match: {
36562
+ $expr: {
36563
+ $and: [
36564
+ { $eq: ["$assignedUnit", unit] },
36565
+ { $eq: ["$userId", null] },
36566
+ { $eq: ["$type", type] },
36567
+ { $eq: ["$isActivated", true] }
36568
+ ]
36569
+ }
36570
+ }
36571
+ }
36572
+ ]).toArray();
36573
+ if (assignees.length > availableCards.length) {
36574
+ throw new Error(`Not enough ${type} cards available.`);
36575
+ }
36576
+ cards = availableCards?.slice(0, assignees.length).map((card, index) => {
36577
+ const userId = new ObjectId90(assignees[index].toString());
36578
+ card.staffNo = userId.toString().slice(-10);
36579
+ return card;
36580
+ });
36581
+ update = availableCards.slice(0, assignees.length).map((card, index) => ({ _id: card._id, userId: new ObjectId90(assignees[index]) }));
36582
+ const commands = cards.map((item, index) => {
36583
+ let ag = null;
36584
+ if (item.accessGroup !== void 0) {
36585
+ if (item.accessGroup?.length > 0) {
36586
+ ag = item.accessGroup.map((g) => `<GROUP_NAME>${g}</GROUP_NAME>`).join("\n ");
36587
+ }
36588
+ }
36589
+ const command = {
36590
+ commandId1: index * 2 + 1,
36591
+ commandId2: index * 2 + 2,
36592
+ staffName: `STAFF-${item._id.toString().slice(-10)}`,
36593
+ staffNo1: `STAFF-${item._id.toString().slice(-10)}`,
36594
+ staffNo2: `STAFF-${item._id.toString().slice(-10)}`,
36595
+ dateOfJoin: formatEntryPassDate(item.startDate),
36596
+ accessLevel: item.accessLevel ?? "0",
36597
+ cardNo: item.cardNo,
36598
+ pin: typeof item.pin === "string" && item.pin.trim() !== "" ? item.pin : "123456",
36599
+ startDate: formatEntryPassDate(item.startDate),
36600
+ endDate: formatEntryPassDate(item.endDate),
36601
+ cardType: 0,
36602
+ isActivated: item.isActivated ? 1 : 0,
36603
+ isAntiPassBack: item.isAntiPassBack ? 1 : 0,
36604
+ isLiftCard: item.isLiftCard ? 1 : 0,
36605
+ isLiftActivate: item.isLiftCard ? 1 : 0,
36606
+ liftAccessLevel: item.liftAccessLevel || 1,
36607
+ liftAccessStartDate: formatEntryPassDate(item.liftAccessStartDate) || "19770510",
36608
+ liftAccessEndDate: formatEntryPassDate(item.liftAccessEndDate) || "19770510",
36609
+ accessGroup: ag
36610
+ };
36611
+ return readTemplate(`${item.accessLevel !== null ? "add-card" : "add-card-lift"}`, { ...command });
36612
+ }).flat();
36613
+ const response = await sendCommand(commands.join("").toString(), acm_url);
36614
+ const result = await parseStringPromise2(response, { explicitArray: false });
36615
+ console.log("status code", result.RESULT.$.STCODE);
36616
+ if (result && result.RESULT.$.STCODE !== "0") {
36617
+ throw new Error("Command failed, server error.");
36618
+ }
36619
+ for (const { _id, userId } of update) {
36620
+ await collection().updateOne({ _id }, { $set: { userId, staffNo: `STAFF-${userId.toString().slice(-10)}` } }, { session });
36621
+ }
36622
+ await session?.commitTransaction();
36623
+ return "Cards assigned successfully.";
36624
+ } catch (error) {
36625
+ await session?.abortTransaction();
36626
+ throw new Error(error.message);
36627
+ } finally {
36628
+ await session?.endSession();
36629
+ }
36630
+ }
36631
+ async function visitorCheckoutRepo({ userId }) {
36632
+ const session = useAtlas76.getClient()?.startSession();
36633
+ try {
36634
+ session?.startTransaction();
36635
+ const id = new ObjectId90(userId);
36636
+ await collection().updateMany({ userId: id }, { $set: { userId: null, status: "Available" } }, { session });
36637
+ session?.commitTransaction();
36638
+ return "Successful Checkout";
36639
+ } catch (error) {
36640
+ await session?.abortTransaction();
36641
+ throw new Error(error.message);
36642
+ } finally {
36643
+ await session?.endSession();
36506
36644
  }
36507
36645
  }
36508
36646
  return {
@@ -36537,7 +36675,9 @@ function UseAccessManagementRepo() {
36537
36675
  checkoutVisitorRepo,
36538
36676
  getBlockLevelAndUnitListRepo,
36539
36677
  indexCombination,
36540
- getTransactionsRepo
36678
+ getTransactionsRepo,
36679
+ assignMultipleCardsRepo,
36680
+ visitorCheckoutRepo
36541
36681
  };
36542
36682
  }
36543
36683
 
@@ -36578,7 +36718,9 @@ function useAccessManagementSvc() {
36578
36718
  signQrCodeRepo,
36579
36719
  checkoutVisitorRepo,
36580
36720
  getBlockLevelAndUnitListRepo,
36581
- getTransactionsRepo
36721
+ getTransactionsRepo,
36722
+ assignMultipleCardsRepo,
36723
+ visitorCheckoutRepo
36582
36724
  } = UseAccessManagementRepo();
36583
36725
  const addPhysicalCardSvc = async (payload) => {
36584
36726
  try {
@@ -36874,6 +37016,22 @@ function useAccessManagementSvc() {
36874
37016
  try {
36875
37017
  const response = await getTransactionsRepo({ page, limit, site, cardNo, url });
36876
37018
  return response;
37019
+ } catch (err) {
37020
+ throw new Error(err.message);
37021
+ }
37022
+ };
37023
+ const assignMultipleCardsSvc = async ({ assignees, unit, type, acm_url }) => {
37024
+ try {
37025
+ const response = await assignMultipleCardsRepo({ assignees, unit, type, acm_url });
37026
+ return response;
37027
+ } catch (err) {
37028
+ throw new Error(err.message);
37029
+ }
37030
+ };
37031
+ const visitorCheckoutSvc = async ({ userId }) => {
37032
+ try {
37033
+ const response = await visitorCheckoutRepo({ userId });
37034
+ return response;
36877
37035
  } catch (err) {
36878
37036
  return Promise.reject("Server internal error.");
36879
37037
  }
@@ -36913,7 +37071,9 @@ function useAccessManagementSvc() {
36913
37071
  signQrCodeSvc,
36914
37072
  checkoutVisitorSvc,
36915
37073
  getBlockLevelAndUnitListSvc,
36916
- getTransactionsSvc
37074
+ getTransactionsSvc,
37075
+ assignMultipleCardsSvc,
37076
+ visitorCheckoutSvc
36917
37077
  };
36918
37078
  }
36919
37079
 
@@ -36954,7 +37114,9 @@ function useAccessManagementController() {
36954
37114
  signQrCodeSvc,
36955
37115
  checkoutVisitorSvc,
36956
37116
  getBlockLevelAndUnitListSvc,
36957
- getTransactionsSvc
37117
+ getTransactionsSvc,
37118
+ assignMultipleCardsSvc,
37119
+ visitorCheckoutSvc
36958
37120
  } = useAccessManagementSvc();
36959
37121
  const addPhysicalCard = async (req, res) => {
36960
37122
  try {
@@ -37738,6 +37900,39 @@ function useAccessManagementController() {
37738
37900
  });
37739
37901
  return res.json(result);
37740
37902
  } catch (error2) {
37903
+ return res.status(400).json({
37904
+ data: null,
37905
+ message: error2.message
37906
+ });
37907
+ }
37908
+ };
37909
+ const assignMultipleCards = async (req, res) => {
37910
+ try {
37911
+ const { assignees, unit, type, acm_url } = req.body;
37912
+ const schema2 = Joi85.object({
37913
+ assignees: Joi85.array().items(Joi85.string().hex()).required(),
37914
+ type: Joi85.string().required(),
37915
+ unit: Joi85.string().hex().required()
37916
+ });
37917
+ const { error } = schema2.validate({ assignees, type, unit });
37918
+ if (error) {
37919
+ throw new Error(`${error.message}`);
37920
+ }
37921
+ const result = await assignMultipleCardsSvc({ assignees, unit, type, acm_url });
37922
+ return res.status(200).json({ message: "Success", data: result });
37923
+ } catch (error) {
37924
+ return res.status(400).json({
37925
+ data: null,
37926
+ message: error.message
37927
+ });
37928
+ }
37929
+ };
37930
+ const visitorCheckout = async (req, res) => {
37931
+ try {
37932
+ const userId = req.params.userId;
37933
+ const result = await visitorCheckoutSvc({ userId });
37934
+ return res.status(200).json({ message: "Success", data: result });
37935
+ } catch (error) {
37741
37936
  return Promise.reject("Internal Server Error");
37742
37937
  }
37743
37938
  };
@@ -37774,7 +37969,9 @@ function useAccessManagementController() {
37774
37969
  checkoutVisitor,
37775
37970
  removeAccessCard,
37776
37971
  getBlockLevelAndUnitList,
37777
- getTransactions: getTransactions2
37972
+ getTransactions: getTransactions2,
37973
+ assignMultipleCards,
37974
+ visitorCheckout
37778
37975
  };
37779
37976
  }
37780
37977