@7365admin1/core 3.9.0 → 3.11.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
@@ -20897,7 +20897,8 @@ var schemaUpdateVisTrans = Joi37.object({
20897
20897
  ).optional().allow(null),
20898
20898
  contact: Joi37.string().optional().allow(null, "")
20899
20899
  })
20900
- ).optional().allow(null)
20900
+ ).optional().allow(null),
20901
+ updatedBy: Joi37.string().hex().length(24).optional()
20901
20902
  });
20902
20903
  function MVisitorTransaction(value) {
20903
20904
  const { error } = schemaVisitorTransaction.validate(value, {
@@ -21547,10 +21548,44 @@ function useVisitorTransactionRepo() {
21547
21548
  value.manualCheckout = true;
21548
21549
  }
21549
21550
  try {
21551
+ const updateFields = {};
21552
+ const arrayFilters = [];
21553
+ Object.keys(value).forEach((key) => {
21554
+ if (key !== "visitorPass" && key !== "passKeys") {
21555
+ const typedKey = key;
21556
+ updateFields[key] = value[typedKey];
21557
+ }
21558
+ });
21559
+ if (Array.isArray(value.visitorPass)) {
21560
+ value.visitorPass.forEach((item, index) => {
21561
+ const elementKey = `vElem${index}`;
21562
+ Object.keys(item).forEach((itemKey) => {
21563
+ if (itemKey !== "keyId") {
21564
+ const typedItemKey = itemKey;
21565
+ let itemValue = item[typedItemKey];
21566
+ updateFields[`visitorPass.$[${elementKey}].${itemKey}`] = itemValue;
21567
+ }
21568
+ });
21569
+ arrayFilters.push({ [`${elementKey}.keyId`]: new ObjectId41(item.keyId) });
21570
+ });
21571
+ }
21572
+ if (Array.isArray(value.passKeys)) {
21573
+ value.passKeys.forEach((item, index) => {
21574
+ const elementKey = `pElem${index}`;
21575
+ Object.keys(item).forEach((itemKey) => {
21576
+ if (itemKey !== "keyId") {
21577
+ const typedItemKey = itemKey;
21578
+ let itemValue = item[typedItemKey];
21579
+ updateFields[`passKeys.$[${elementKey}].${itemKey}`] = itemValue;
21580
+ }
21581
+ });
21582
+ arrayFilters.push({ [`${elementKey}.keyId`]: new ObjectId41(item.keyId) });
21583
+ });
21584
+ }
21550
21585
  const result = await collection.updateOne(
21551
- { _id },
21552
- { $set: value },
21553
- { session }
21586
+ { _id: new ObjectId41(_id) },
21587
+ { $set: updateFields },
21588
+ { arrayFilters, session }
21554
21589
  );
21555
21590
  return result;
21556
21591
  } catch (error) {
@@ -33351,10 +33386,12 @@ var KeyRepo = class {
33351
33386
  return Promise.reject("Server internal error.");
33352
33387
  }
33353
33388
  }
33354
- static async updateKeyById(keyId, key, site, session, isChild) {
33389
+ static async updateKeyById(keyId, key, site, session, isChild, visitorId) {
33355
33390
  keyId = await convertObjectIdUtil2(keyId, "keyId");
33356
33391
  if (site)
33357
33392
  site = await convertObjectIdUtil2(site, "Site");
33393
+ if (visitorId)
33394
+ visitorId = await convertObjectIdUtil2(visitorId, "visitor Id");
33358
33395
  if (key.updatedBy)
33359
33396
  key.updatedBy = await convertObjectIdUtil2(key.updatedBy, "Updated By");
33360
33397
  if (!key.status)
@@ -33371,7 +33408,6 @@ var KeyRepo = class {
33371
33408
  { session }
33372
33409
  );
33373
33410
  let setKeys = [];
33374
- console.log("updateKeyById result", result);
33375
33411
  if (result.modifiedCount > 0) {
33376
33412
  const updatedDocs = await this.collection().find(find).toArray();
33377
33413
  if (Array.isArray(updatedDocs) && updatedDocs.length > 0) {
@@ -33380,6 +33416,10 @@ var KeyRepo = class {
33380
33416
  keyItem["passOrKeyId"] = item?._id;
33381
33417
  keyItem["_id"] = new ObjectId61();
33382
33418
  keyItem["previousStatus"] = item?.status;
33419
+ if (visitorId) {
33420
+ console.log("visitorId true key.repo");
33421
+ keyItem["visitorId"] = visitorId;
33422
+ }
33383
33423
  setKeys.push(keyItem);
33384
33424
  });
33385
33425
  }
@@ -33541,7 +33581,7 @@ async function send(userIds, title, body, data, isForMAMobileApp = false, appSlu
33541
33581
  if (isForMAMobileApp) {
33542
33582
  tokens = await PushTokenRepo.findTokensByUserIds(userIds, appSlug);
33543
33583
  } else {
33544
- tokens = await PushTokenRepo.findTokensByUserIds(userIds);
33584
+ tokens = await PushTokenRepo.findTokensByUserIds(userIds, appSlug);
33545
33585
  }
33546
33586
  if (!tokens.length)
33547
33587
  return;
@@ -33589,6 +33629,37 @@ var NotificationService = class {
33589
33629
  "iservice365-resident-mobile-app"
33590
33630
  );
33591
33631
  }
33632
+ static async onlineFormRequestStatusUpdated(payload) {
33633
+ let screen = "";
33634
+ let params = {};
33635
+ if (payload.status === "pending" || payload.status === "resubmission") {
33636
+ screen = "/(user)/(online-forms)/form-fill";
33637
+ params = {
33638
+ id: payload.onlineFormId.toString(),
33639
+ submissionStatus: payload.status ?? ""
33640
+ };
33641
+ } else {
33642
+ screen = "/(user)/(online-forms)/submission-detail";
33643
+ params = {
33644
+ id: payload.onlineFormId.toString(),
33645
+ status: payload.status ?? ""
33646
+ };
33647
+ }
33648
+ await send(
33649
+ toStringArray(payload.to),
33650
+ "Online Form",
33651
+ `Your online form has been updated to ${payload.status}.`,
33652
+ {
33653
+ onlineFormId: payload.onlineFormId.toString(),
33654
+ status: payload.status,
33655
+ module: "onlineForm",
33656
+ screen,
33657
+ params
33658
+ },
33659
+ false,
33660
+ "iservice365-resident-mobile-app"
33661
+ );
33662
+ }
33592
33663
  static async bulletinBoardCreatedForMA(payload) {
33593
33664
  await send(
33594
33665
  toStringArray(payload.to),
@@ -33644,6 +33715,14 @@ var NotificationService = class {
33644
33715
  }
33645
33716
  };
33646
33717
 
33718
+ // src/utils/valid-values.ts
33719
+ var VALID_STATUSES = /* @__PURE__ */ new Set([
33720
+ "In Use",
33721
+ "Available",
33722
+ "Damaged",
33723
+ "Lost"
33724
+ ]);
33725
+
33647
33726
  // src/services/visitor-transaction.service.ts
33648
33727
  function useVisitorTransactionService() {
33649
33728
  const MailerConfig = {
@@ -33832,48 +33911,26 @@ function useVisitorTransactionService() {
33832
33911
  const chunk = value.members.slice(i, i + chunkSize);
33833
33912
  for (const member of chunk) {
33834
33913
  await KeyRepo.checkPassKeyAvailability(member.visitorPass, member.passKeys);
33835
- if (Array.isArray(member.visitorPass)) {
33836
- for (const item of member.visitorPass) {
33837
- console.log("Type of keyId:", typeof item.keyId);
33838
- console.log("item visitorPass", item);
33839
- await KeyRepo.updateKeyById(
33840
- item.keyId,
33841
- {
33842
- status: "In Use" /* IN_USE */,
33843
- updatedBy: value.createdBy
33844
- },
33845
- value.site,
33846
- session
33847
- );
33848
- item.receivedDate = /* @__PURE__ */ new Date();
33849
- item.status = "Not Returned" /* NOT_RETURNED */;
33850
- item.lastUpdate = null;
33851
- item.remarks = "";
33852
- }
33853
- }
33854
- if (Array.isArray(member.passKeys)) {
33855
- for (const item of member.passKeys) {
33856
- await KeyRepo.updateKeyById(
33857
- item.keyId,
33858
- {
33859
- status: "In Use" /* IN_USE */,
33860
- updatedBy: value.createdBy
33861
- },
33862
- value.site,
33863
- session
33864
- );
33865
- item.receivedDate = /* @__PURE__ */ new Date();
33866
- item.status = "Not Returned" /* NOT_RETURNED */;
33867
- item.lastUpdate = null;
33868
- item.remarks = "";
33869
- }
33870
- }
33871
33914
  }
33872
33915
  await Promise.all(
33873
- chunk.map((member) => {
33916
+ chunk.map(async (member) => {
33874
33917
  const clonedMember = structuredClone(member);
33875
33918
  const { visitorPass, passKeys } = clonedMember;
33876
- return _add(
33919
+ const preparedVisitorPass = Array.isArray(visitorPass) ? visitorPass.map((item) => ({
33920
+ ...item,
33921
+ receivedDate: /* @__PURE__ */ new Date(),
33922
+ status: "Not Returned" /* NOT_RETURNED */,
33923
+ lastUpdate: null,
33924
+ remarks: ""
33925
+ })) : [];
33926
+ const preparedPassKeys = Array.isArray(passKeys) ? passKeys.map((item) => ({
33927
+ ...item,
33928
+ receivedDate: /* @__PURE__ */ new Date(),
33929
+ status: "Not Returned" /* NOT_RETURNED */,
33930
+ lastUpdate: null,
33931
+ remarks: ""
33932
+ })) : [];
33933
+ const visitorId = await _add(
33877
33934
  {
33878
33935
  ...clonedMember,
33879
33936
  block,
@@ -33887,13 +33944,38 @@ function useVisitorTransactionService() {
33887
33944
  remarks,
33888
33945
  contractorType,
33889
33946
  checkIn: start,
33890
- // expiredAt: end,
33891
- visitorPass: visitorPass ?? [],
33892
- passKeys: passKeys ?? [],
33947
+ visitorPass: preparedVisitorPass,
33948
+ passKeys: preparedPassKeys,
33893
33949
  status: "registered" /* REGISTERED */
33894
33950
  },
33895
33951
  session
33896
33952
  );
33953
+ console.log("visitorId service", visitorId);
33954
+ for (const item of preparedVisitorPass) {
33955
+ await KeyRepo.updateKeyById(
33956
+ item.keyId,
33957
+ {
33958
+ status: "In Use" /* IN_USE */,
33959
+ updatedBy: value.createdBy
33960
+ },
33961
+ value.site,
33962
+ session,
33963
+ void 0,
33964
+ visitorId
33965
+ );
33966
+ }
33967
+ for (const item of preparedPassKeys) {
33968
+ await KeyRepo.updateKeyById(
33969
+ item.keyId,
33970
+ {
33971
+ status: "In Use" /* IN_USE */,
33972
+ updatedBy: value.createdBy,
33973
+ visitorId
33974
+ },
33975
+ value.site,
33976
+ session
33977
+ );
33978
+ }
33897
33979
  })
33898
33980
  );
33899
33981
  }
@@ -33922,6 +34004,7 @@ function useVisitorTransactionService() {
33922
34004
  throw new BadRequestError100("This plate number is blocklisted");
33923
34005
  }
33924
34006
  await KeyRepo.checkPassKeyAvailability(value.visitorPass, value.passKeys);
34007
+ const result = await _add(value, session);
33925
34008
  if (Array.isArray(value.visitorPass)) {
33926
34009
  for (const item of value.visitorPass) {
33927
34010
  await KeyRepo.updateKeyById(
@@ -33931,7 +34014,9 @@ function useVisitorTransactionService() {
33931
34014
  updatedBy: value.createdBy
33932
34015
  },
33933
34016
  value.site,
33934
- session
34017
+ session,
34018
+ void 0,
34019
+ result
33935
34020
  );
33936
34021
  item.receivedDate = /* @__PURE__ */ new Date();
33937
34022
  item.status = "Not Returned" /* NOT_RETURNED */;
@@ -33948,7 +34033,9 @@ function useVisitorTransactionService() {
33948
34033
  updatedBy: value.createdBy
33949
34034
  },
33950
34035
  value.site,
33951
- session
34036
+ session,
34037
+ void 0,
34038
+ result
33952
34039
  );
33953
34040
  item.receivedDate = /* @__PURE__ */ new Date();
33954
34041
  item.status = "Not Returned" /* NOT_RETURNED */;
@@ -33956,7 +34043,6 @@ function useVisitorTransactionService() {
33956
34043
  item.remarks = "";
33957
34044
  }
33958
34045
  }
33959
- const result = await _add(value, session);
33960
34046
  await session?.commitTransaction();
33961
34047
  let openBarrier = null;
33962
34048
  const isOpenBarrier = allowedPersonTypes.includes(value?.type) || camera?.ANPRSwitches?.openBarrierPickUpDropOff == true;
@@ -34030,52 +34116,6 @@ function useVisitorTransactionService() {
34030
34116
  if (found === 1)
34031
34117
  throw new BadRequestError100("This plate number is blocklisted");
34032
34118
  }
34033
- if (Array.isArray(value.visitorPass) && value.visitorPass.length > 0) {
34034
- const keptVisitorPass = [];
34035
- for (const vp of value.visitorPass) {
34036
- const updatePayload = {
34037
- ...vp.status && { status: vp.status },
34038
- ...vp.remarks && { remarks: vp.remarks }
34039
- };
34040
- const visitorPassId = typeof vp === "string" || vp instanceof ObjectId62 ? vp : vp.keyId;
34041
- await KeyRepo.updateKeyById(
34042
- visitorPassId,
34043
- updatePayload,
34044
- value.site
34045
- );
34046
- if (typeof vp !== "string" && !(vp instanceof ObjectId62)) {
34047
- keptVisitorPass.push({
34048
- keyId: new ObjectId62(visitorPassId)
34049
- });
34050
- }
34051
- }
34052
- value.visitorPass = keptVisitorPass;
34053
- }
34054
- if (value.passKeys && Array.isArray(value.passKeys) && value.passKeys.length > 0) {
34055
- const keptPassKeys = [];
34056
- for (const pk of value.passKeys) {
34057
- try {
34058
- const updatePayload = {
34059
- ...pk.status && { status: pk.status },
34060
- ...pk.remarks && { remarks: pk.remarks }
34061
- };
34062
- const passKeyId = typeof pk === "string" || pk instanceof ObjectId62 ? pk : pk.keyId;
34063
- await KeyRepo.updateKeyById(
34064
- passKeyId,
34065
- updatePayload,
34066
- value.site
34067
- );
34068
- if (typeof pk !== "string" && !(pk instanceof ObjectId62)) {
34069
- keptPassKeys.push({
34070
- keyId: new ObjectId62(passKeyId)
34071
- });
34072
- }
34073
- } catch (error) {
34074
- throw error;
34075
- }
34076
- }
34077
- value.passKeys = keptPassKeys;
34078
- }
34079
34119
  if (value.checkIn) {
34080
34120
  const parsed = new Date(value.checkIn);
34081
34121
  value.checkIn = isNaN(parsed.getTime()) ? null : parsed;
@@ -34092,6 +34132,61 @@ function useVisitorTransactionService() {
34092
34132
  const unit = await _getUnitById(value.unit);
34093
34133
  value.unitName = unit?.name;
34094
34134
  }
34135
+ if (value.updatedBy) {
34136
+ value.updatedBy = await convertObjectIdUtil2(value.updatedBy, "updatedBy Id");
34137
+ }
34138
+ if (Array.isArray(value.visitorPass)) {
34139
+ for (const item of value.visitorPass) {
34140
+ let status = "Invalid";
34141
+ if (item?.status == "Returned" /* RETURNED */) {
34142
+ status = "Available" /* AVAILABLE */;
34143
+ } else if (item?.status == "Not Returned" /* NOT_RETURNED */) {
34144
+ status = "In Use" /* IN_USE */;
34145
+ } else if (item?.status && VALID_STATUSES.has(item.status)) {
34146
+ status = item.status;
34147
+ } else {
34148
+ throw new Error("Invalid Visitor Pass Status");
34149
+ }
34150
+ await KeyRepo.updateKeyById(
34151
+ item.keyId,
34152
+ {
34153
+ status,
34154
+ updatedBy: value.updatedBy
34155
+ },
34156
+ value.site,
34157
+ session,
34158
+ void 0,
34159
+ id
34160
+ );
34161
+ item.lastUpdate = /* @__PURE__ */ new Date();
34162
+ }
34163
+ }
34164
+ if (Array.isArray(value.passKeys)) {
34165
+ for (const item of value.passKeys) {
34166
+ let status = "Invalid";
34167
+ if (item?.status == "Returned" /* RETURNED */) {
34168
+ status = "Available" /* AVAILABLE */;
34169
+ } else if (item?.status == "Not Returned" /* NOT_RETURNED */) {
34170
+ status = "In Use" /* IN_USE */;
34171
+ } else if (item?.status && VALID_STATUSES.has(item.status)) {
34172
+ status = item.status;
34173
+ } else {
34174
+ throw new Error("Invalid Visitor Pass Status");
34175
+ }
34176
+ await KeyRepo.updateKeyById(
34177
+ item.keyId,
34178
+ {
34179
+ status,
34180
+ updatedBy: value.updatedBy
34181
+ },
34182
+ value.site,
34183
+ session,
34184
+ void 0,
34185
+ id
34186
+ );
34187
+ item.lastUpdate = /* @__PURE__ */ new Date();
34188
+ }
34189
+ }
34095
34190
  await _updateVisitorTansactionById(id, value, session);
34096
34191
  const allowedPersonTypes = [
34097
34192
  "contractor" /* CONTRACTOR */,
@@ -57911,7 +58006,8 @@ function useNewDashboardRepo() {
57911
58006
  site,
57912
58007
  serviceType,
57913
58008
  page = 1,
57914
- limit = 10
58009
+ limit = 10,
58010
+ period = "today" /* TODAY */
57915
58011
  }) {
57916
58012
  page = page > 0 ? page - 1 : 0;
57917
58013
  const cacheOptions = { serviceType, page, limit };
@@ -57921,9 +58017,7 @@ function useNewDashboardRepo() {
57921
58017
  } catch {
57922
58018
  throw new BadRequestError182("Invalid site ID format.");
57923
58019
  }
57924
- const todayStart = moment2.tz("Asia/Singapore").startOf("day").toDate();
57925
- const todayEnd = moment2.tz("Asia/Singapore").endOf("day").toDate();
57926
- const todayRange = { $gte: todayStart, $lte: todayEnd };
58020
+ const todayRange = getDateRange(period);
57927
58021
  try {
57928
58022
  const [items, countResult] = await Promise.all([
57929
58023
  areaChecklistCollection.aggregate([
@@ -57999,7 +58093,8 @@ function useNewDashboardRepo() {
57999
58093
  site,
58000
58094
  serviceType,
58001
58095
  page = 1,
58002
- limit = 10
58096
+ limit = 10,
58097
+ period = "today" /* TODAY */
58003
58098
  }) {
58004
58099
  page = page > 0 ? page - 1 : 0;
58005
58100
  const cacheOptions = { serviceType, page, limit };
@@ -58009,8 +58104,9 @@ function useNewDashboardRepo() {
58009
58104
  } catch {
58010
58105
  throw new BadRequestError182("Invalid site ID format.");
58011
58106
  }
58012
- const todayStart = moment2.tz("Asia/Singapore").startOf("day").toDate();
58013
- const todayEnd = moment2.tz("Asia/Singapore").endOf("day").toDate();
58107
+ const periodRange = getDateRange(period);
58108
+ const todayStart = periodRange.$gte;
58109
+ const todayEnd = periodRange.$lte;
58014
58110
  const todayStartStr = todayStart.toISOString();
58015
58111
  const todayEndStr = todayEnd.toISOString();
58016
58112
  try {
@@ -58127,7 +58223,8 @@ function useNewDashboardRepo() {
58127
58223
  site,
58128
58224
  serviceType,
58129
58225
  page = 1,
58130
- limit = 10
58226
+ limit = 10,
58227
+ period = "today" /* TODAY */
58131
58228
  }) {
58132
58229
  page = page > 0 ? page - 1 : 0;
58133
58230
  const cacheOptions = { serviceType, page, limit };
@@ -58138,10 +58235,14 @@ function useNewDashboardRepo() {
58138
58235
  throw new BadRequestError182("Invalid site ID format.");
58139
58236
  }
58140
58237
  const workOrderService = workOrderServiceMap[serviceType] ?? serviceType;
58238
+ const matchQuery = { site, service: workOrderService };
58239
+ if (period) {
58240
+ matchQuery.createdAt = getDateRange(period);
58241
+ }
58141
58242
  try {
58142
58243
  const [items, length] = await Promise.all([
58143
58244
  feedbackCollection.aggregate([
58144
- { $match: { site, service: workOrderService } },
58245
+ { $match: matchQuery },
58145
58246
  { $sort: { createdAt: -1, _id: -1 } },
58146
58247
  {
58147
58248
  $lookup: {
@@ -58164,7 +58265,7 @@ function useNewDashboardRepo() {
58164
58265
  { $skip: page * limit },
58165
58266
  { $limit: limit }
58166
58267
  ]).toArray(),
58167
- feedbackCollection.countDocuments({ site, service: workOrderService })
58268
+ feedbackCollection.countDocuments(matchQuery)
58168
58269
  ]);
58169
58270
  const data = paginate51(items, page, limit, length);
58170
58271
  return data;
@@ -58324,6 +58425,7 @@ function useNewDashboardController() {
58324
58425
  const validation = Joi112.object({
58325
58426
  site: Joi112.string().hex().required(),
58326
58427
  serviceType: Joi112.string().valid(...Object.values(AppServiceType)).required(),
58428
+ period: Joi112.string().valid(...Object.values(Period)).default("today" /* TODAY */),
58327
58429
  page: Joi112.number().min(1).optional().allow("", null),
58328
58430
  limit: Joi112.number().min(1).optional().allow("", null)
58329
58431
  });
@@ -58335,12 +58437,14 @@ function useNewDashboardController() {
58335
58437
  }
58336
58438
  const site = req.params.site;
58337
58439
  const serviceType = req.params.serviceType;
58440
+ const period = req.query.period;
58338
58441
  const page = parseInt(req.query.page) ?? 1;
58339
58442
  const limit = parseInt(req.query.limit) ?? 10;
58340
58443
  try {
58341
58444
  const data = await _getServiceTodayTaskSchedule({
58342
58445
  site,
58343
58446
  serviceType,
58447
+ period,
58344
58448
  page,
58345
58449
  limit
58346
58450
  });
@@ -58357,6 +58461,7 @@ function useNewDashboardController() {
58357
58461
  const validation = Joi112.object({
58358
58462
  site: Joi112.string().hex().required(),
58359
58463
  serviceType: Joi112.string().valid(...Object.values(AppServiceType)).required(),
58464
+ period: Joi112.string().valid(...Object.values(Period)).default("today" /* TODAY */),
58360
58465
  page: Joi112.number().min(1).optional().allow("", null),
58361
58466
  limit: Joi112.number().min(1).optional().allow("", null)
58362
58467
  });
@@ -58368,12 +58473,14 @@ function useNewDashboardController() {
58368
58473
  }
58369
58474
  const site = req.params.site;
58370
58475
  const serviceType = req.params.serviceType;
58476
+ const period = req.query.period;
58371
58477
  const page = parseInt(req.query.page) ?? 1;
58372
58478
  const limit = parseInt(req.query.limit) ?? 10;
58373
58479
  try {
58374
58480
  const data = await _getServiceStaffAttendance({
58375
58481
  site,
58376
58482
  serviceType,
58483
+ period,
58377
58484
  page,
58378
58485
  limit
58379
58486
  });
@@ -58390,6 +58497,7 @@ function useNewDashboardController() {
58390
58497
  const validation = Joi112.object({
58391
58498
  site: Joi112.string().hex().required(),
58392
58499
  serviceType: Joi112.string().valid(...Object.values(AppServiceType)).required(),
58500
+ period: Joi112.string().valid(...Object.values(Period)).default("today" /* TODAY */),
58393
58501
  page: Joi112.number().min(1).optional().allow("", null),
58394
58502
  limit: Joi112.number().min(1).optional().allow("", null)
58395
58503
  });
@@ -58401,12 +58509,14 @@ function useNewDashboardController() {
58401
58509
  }
58402
58510
  const site = req.params.site;
58403
58511
  const serviceType = req.params.serviceType;
58512
+ const period = req.query.period;
58404
58513
  const page = parseInt(req.query.page) ?? 1;
58405
58514
  const limit = parseInt(req.query.limit) ?? 10;
58406
58515
  try {
58407
58516
  const data = await _getServiceRecentFeedbacks({
58408
58517
  site,
58409
58518
  serviceType,
58519
+ period,
58410
58520
  page,
58411
58521
  limit
58412
58522
  });
@@ -60736,7 +60846,6 @@ function useHrmLabsAttendanceSrvc() {
60736
60846
  };
60737
60847
  } catch (error) {
60738
60848
  logger171.error(error.message || error);
60739
- console.log("Error fetching attendance data:", error);
60740
60849
  return { success: false, message: error?.message || "Internal Server Error!", items: [], pages: 0, pageRange: "0-0 of 0", count: {} };
60741
60850
  }
60742
60851
  }
@@ -60850,7 +60959,6 @@ function useHrmLabsAttendanceSrvc() {
60850
60959
  return { totalCount };
60851
60960
  } catch (error) {
60852
60961
  logger171.error(error.message || error);
60853
- console.log("Error fetching attendance data count:", error);
60854
60962
  return { success: false, message: error?.message || "Internal Server Error!", totalCount: null };
60855
60963
  }
60856
60964
  }
@@ -61022,7 +61130,6 @@ function useHrmLabsAttendanceSrvc() {
61022
61130
  };
61023
61131
  } catch (error) {
61024
61132
  logger171.error(error.message || error);
61025
- console.log("Error fetching attendance data:", error);
61026
61133
  return { success: false, message: error?.message || "Internal Server Error!", items: [], count: {}, countPerJobTitle: {}, totalCount: null, countPerStatus: {} };
61027
61134
  }
61028
61135
  }
@@ -61129,7 +61236,6 @@ function useHrmLabsAttendanceSrvc() {
61129
61236
  };
61130
61237
  } catch (error) {
61131
61238
  logger171.error(error.message || error);
61132
- console.log("Error fetching attendance data:", error);
61133
61239
  return { success: false, message: error?.message || "Internal Server Error!", chartCount: null };
61134
61240
  }
61135
61241
  }
@@ -67004,13 +67110,14 @@ var BidStatus = /* @__PURE__ */ ((BidStatus3) => {
67004
67110
  var schemaBidPreloved = Joi145.object({
67005
67111
  type: Joi145.string().valid(...Object.values(BidType)).required(),
67006
67112
  postId: Joi145.string().hex().length(24).required(),
67113
+ receiverId: Joi145.string().hex().length(24).required(),
67114
+ buyerId: Joi145.string().hex().length(24).required(),
67007
67115
  price: Joi145.when("type", {
67008
67116
  is: "bid" /* BID */,
67009
67117
  then: Joi145.number().required(),
67010
67118
  otherwise: Joi145.number().optional().allow(null)
67011
67119
  }),
67012
67120
  message: Joi145.string().optional().allow("", null),
67013
- buyerId: Joi145.string().hex().length(24).optional().allow("", null),
67014
67121
  status: Joi145.string().valid(...Object.values(BidStatus)).optional().default("pending" /* PENDING */)
67015
67122
  });
67016
67123
  var schemaUpdateBidPreloved = Joi145.object({
@@ -67071,14 +67178,88 @@ function useBidPrelovedRepo() {
67071
67178
  throw new InternalServerError82("Unable to update bid.");
67072
67179
  return "Bid updated successfully.";
67073
67180
  }
67074
- return { add, updateStatus };
67181
+ async function getById(_id) {
67182
+ if (typeof _id === "string")
67183
+ _id = new ObjectId150(_id);
67184
+ const result = await collection.findOne({ _id });
67185
+ if (!result)
67186
+ throw new NotFoundError61("Bid not found.");
67187
+ return result;
67188
+ }
67189
+ return { add, getById, updateStatus };
67075
67190
  }
67076
67191
 
67077
67192
  // src/controllers/bid-preloved.controller.ts
67078
67193
  import { BadRequestError as BadRequestError224, logger as logger194 } from "@7365admin1/node-server-utils";
67079
67194
  import Joi146 from "joi";
67195
+
67196
+ // src/services/bid-preloved.service.ts
67197
+ import { InternalServerError as InternalServerError83, useAtlas as useAtlas128 } from "@7365admin1/node-server-utils";
67198
+ function useBidPrelovedService() {
67199
+ const { add: _addBid } = useBidPrelovedRepo();
67200
+ const { add: _addChannel, getByParticipants: _getByParticipants } = useChannelPrelovedRepo();
67201
+ const { add: _addChat } = useChatPrelovedRepo();
67202
+ async function createBid(value) {
67203
+ const client = useAtlas128.getClient();
67204
+ if (!client)
67205
+ throw new InternalServerError83("Unable to connect to server.");
67206
+ const buyerId = value.buyerId;
67207
+ const receiverId = value.receiverId;
67208
+ const postId = value.postId;
67209
+ const messageText = value.message || "";
67210
+ const session = client.startSession();
67211
+ session.startTransaction();
67212
+ try {
67213
+ const bidId = await _addBid(value, session);
67214
+ const existingChannel = await _getByParticipants(
67215
+ buyerId,
67216
+ receiverId,
67217
+ postId
67218
+ );
67219
+ let channelId;
67220
+ if (existingChannel) {
67221
+ channelId = existingChannel._id.toString();
67222
+ } else {
67223
+ const newChannelId = await _addChannel(
67224
+ {
67225
+ senderId: buyerId,
67226
+ receiverId,
67227
+ postId
67228
+ },
67229
+ session
67230
+ );
67231
+ channelId = newChannelId.toString();
67232
+ }
67233
+ await _addChat(
67234
+ {
67235
+ channelId,
67236
+ senderId: buyerId,
67237
+ postId,
67238
+ bidId: bidId.toString(),
67239
+ message: {
67240
+ text: messageText,
67241
+ date: (/* @__PURE__ */ new Date()).toISOString(),
67242
+ senderId: buyerId
67243
+ }
67244
+ },
67245
+ session
67246
+ );
67247
+ await session.commitTransaction();
67248
+ return { bidId };
67249
+ } catch (error) {
67250
+ await session.abortTransaction();
67251
+ throw error;
67252
+ } finally {
67253
+ session.endSession();
67254
+ }
67255
+ }
67256
+ return { createBid };
67257
+ }
67258
+
67259
+ // src/controllers/bid-preloved.controller.ts
67080
67260
  function useBidPrelovedController() {
67081
- const { add: _add, updateStatus: _updateStatus } = useBidPrelovedRepo();
67261
+ const { createBid: _createBid } = useBidPrelovedService();
67262
+ const { getById: _getById, updateStatus: _updateStatus } = useBidPrelovedRepo();
67082
67263
  async function add(req, res, next) {
67083
67264
  const { error, value } = schemaBidPreloved.validate(req.body, {
67084
67265
  abortEarly: false
@@ -67090,9 +67271,10 @@ function useBidPrelovedController() {
67090
67271
  return;
67091
67272
  }
67092
67273
  try {
67093
- const data = await _add(value);
67274
+ const data = await _createBid(value);
67094
67275
  res.status(201).json(data);
67095
67276
  } catch (error2) {
67277
+ console.log("error", error2);
67096
67278
  logger194.log({ level: "error", message: error2.message });
67097
67279
  next(error2);
67098
67280
  }
@@ -67125,7 +67307,25 @@ function useBidPrelovedController() {
67125
67307
  next(error);
67126
67308
  }
67127
67309
  }
67128
- return { add, updateStatus };
67310
+ async function getById(req, res, next) {
67311
+ const paramsSchema = Joi146.object({
67312
+ id: Joi146.string().hex().length(24).required()
67313
+ });
67314
+ const { error, value: params } = paramsSchema.validate(req.params);
67315
+ if (error) {
67316
+ logger194.log({ level: "error", message: error.message });
67317
+ next(new BadRequestError224(error.message));
67318
+ return;
67319
+ }
67320
+ try {
67321
+ const data = await _getById(params.id);
67322
+ res.status(200).json(data);
67323
+ } catch (error2) {
67324
+ logger194.log({ level: "error", message: error2.message });
67325
+ next(error2);
67326
+ }
67327
+ }
67328
+ return { add, getById, updateStatus };
67129
67329
  }
67130
67330
 
67131
67331
  // src/models/online-forms-v2.model.ts
@@ -67259,32 +67459,33 @@ var residentFormEntry = Joi147.object({
67259
67459
  // src/repositories/online-forms-v2.repository.ts
67260
67460
  import {
67261
67461
  BadRequestError as BadRequestError225,
67262
- InternalServerError as InternalServerError83,
67462
+ InternalServerError as InternalServerError84,
67263
67463
  logger as logger195,
67264
67464
  makeCacheKey as makeCacheKey65,
67265
67465
  NotFoundError as NotFoundError62,
67266
67466
  paginate as paginate64,
67267
- useAtlas as useAtlas128,
67467
+ useAtlas as useAtlas129,
67268
67468
  useCache as useCache69
67269
67469
  } from "@7365admin1/node-server-utils";
67270
67470
  import { ObjectId as ObjectId152 } from "mongodb";
67271
67471
  var online_forms_namespace_collection = "online-forms";
67272
67472
  function useFormEntryRepo() {
67273
- const db = useAtlas128.getDb();
67473
+ const db = useAtlas129.getDb();
67274
67474
  if (!db) {
67275
- throw new InternalServerError83("Unable to connect to server.");
67475
+ throw new InternalServerError84("Unable to connect to server.");
67276
67476
  }
67277
67477
  const collection = db.collection(online_forms_namespace_collection);
67278
67478
  const { delNamespace, getCache, setCache } = useCache69(
67279
67479
  online_forms_namespace_collection
67280
67480
  );
67481
+ const { getUserById } = useUserRepo();
67281
67482
  async function createTextIndex() {
67282
67483
  try {
67283
67484
  await collection.createIndex({
67284
67485
  name: "text"
67285
67486
  });
67286
67487
  } catch (error) {
67287
- throw new InternalServerError83(
67488
+ throw new InternalServerError84(
67288
67489
  "Failed to create text index on online form."
67289
67490
  );
67290
67491
  }
@@ -67293,16 +67494,6 @@ function useFormEntryRepo() {
67293
67494
  try {
67294
67495
  value = MFormEntry(value);
67295
67496
  const res = await collection.insertOne(value, { session });
67296
- delNamespace().then(() => {
67297
- logger195.info(
67298
- `Cache cleared for namespace: ${online_forms_namespace_collection}`
67299
- );
67300
- }).catch((err) => {
67301
- logger195.error(
67302
- `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
67303
- err
67304
- );
67305
- });
67306
67497
  return res.insertedId;
67307
67498
  } catch (error) {
67308
67499
  const isDuplicated = error.message.includes("duplicate");
@@ -67325,18 +67516,10 @@ function useFormEntryRepo() {
67325
67516
  sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
67326
67517
  site = new ObjectId152(site);
67327
67518
  org = new ObjectId152(org);
67328
- const cacheOptions = {
67329
- page,
67330
- limit,
67331
- status,
67332
- sort: JSON.stringify(sort),
67333
- site,
67334
- ...search && { search }
67335
- };
67336
67519
  const query = {
67337
67520
  site,
67338
- status,
67339
- org
67521
+ status
67522
+ // org,
67340
67523
  };
67341
67524
  if (search && search !== "") {
67342
67525
  query.$or = [
@@ -67344,15 +67527,6 @@ function useFormEntryRepo() {
67344
67527
  { unitNumber: { $regex: search, $options: "i" } }
67345
67528
  ];
67346
67529
  }
67347
- const cacheKey = makeCacheKey65(
67348
- online_forms_namespace_collection,
67349
- cacheOptions
67350
- );
67351
- const cachedData = await getCache(cacheKey);
67352
- if (cachedData) {
67353
- logger195.info(`Cache hit for key: ${cacheKey}`);
67354
- return cachedData;
67355
- }
67356
67530
  try {
67357
67531
  const items = await collection.aggregate([
67358
67532
  { $match: query },
@@ -67378,23 +67552,12 @@ function useFormEntryRepo() {
67378
67552
  ]).toArray();
67379
67553
  const length = await collection.countDocuments(query);
67380
67554
  const data = paginate64(items, page, limit, length);
67381
- setCache(cacheKey, data, 15 * 60).then(() => {
67382
- logger195.info(`Cache set for key: ${cacheKey}`);
67383
- }).catch((err) => {
67384
- logger195.error(`Failed to set cache for key: ${cacheKey}`, err);
67385
- });
67386
67555
  return data;
67387
67556
  } catch (error) {
67388
67557
  throw error;
67389
67558
  }
67390
67559
  }
67391
67560
  async function getFormEntryById(_id) {
67392
- const cacheKey = makeCacheKey65(online_forms_namespace_collection, { _id });
67393
- const cachedData = await getCache(cacheKey);
67394
- if (cachedData) {
67395
- logger195.info(`Cache hit for key: ${cacheKey}`);
67396
- return cachedData;
67397
- }
67398
67561
  try {
67399
67562
  _id = new ObjectId152(_id);
67400
67563
  } catch (error) {
@@ -67406,11 +67569,6 @@ function useFormEntryRepo() {
67406
67569
  if (!data) {
67407
67570
  throw new NotFoundError62("Document not found.");
67408
67571
  }
67409
- setCache(cacheKey, data, 15 * 60).then(() => {
67410
- logger195.info(`Cache set for key: ${cacheKey}`);
67411
- }).catch((err) => {
67412
- logger195.error(`Failed to set cache for key: ${cacheKey}`, err);
67413
- });
67414
67572
  return data;
67415
67573
  } catch (error) {
67416
67574
  throw error;
@@ -67429,17 +67587,21 @@ function useFormEntryRepo() {
67429
67587
  };
67430
67588
  const res = await collection.updateOne({ _id }, { $set: updateValue });
67431
67589
  if (res.modifiedCount === 0) {
67432
- throw new InternalServerError83("Unable to update online form.");
67590
+ throw new InternalServerError84("Unable to update online form.");
67433
67591
  }
67434
- delNamespace().then(() => {
67435
- logger195.info(
67436
- `Cache cleared for namespace: ${online_forms_namespace_collection}`
67437
- );
67438
- }).catch((err) => {
67439
- logger195.error(
67440
- `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
67441
- err
67442
- );
67592
+ const onlineFormRequest = await collection.findOne({ _id });
67593
+ if (!onlineFormRequest) {
67594
+ throw new NotFoundError62("Online form not found.");
67595
+ }
67596
+ const user = await getUserById(onlineFormRequest.userId.toString());
67597
+ if (!user || !user._id) {
67598
+ throw new NotFoundError62("User not found.");
67599
+ }
67600
+ const userId = user._id.toString();
67601
+ await NotificationService.onlineFormRequestStatusUpdated({
67602
+ to: userId,
67603
+ onlineFormId: onlineFormRequest._id,
67604
+ status: onlineFormRequest.status
67443
67605
  });
67444
67606
  return res.modifiedCount;
67445
67607
  } catch (error) {
@@ -67464,16 +67626,8 @@ function useFormEntryRepo() {
67464
67626
  { session }
67465
67627
  );
67466
67628
  if (res.modifiedCount === 0) {
67467
- throw new InternalServerError83("Unable to delete online form.");
67629
+ throw new InternalServerError84("Unable to delete online form.");
67468
67630
  }
67469
- delNamespace().then(() => {
67470
- logger195.info(`Cache cleared for namespace: ${online_forms_namespace_collection}`);
67471
- }).catch((err) => {
67472
- logger195.error(
67473
- `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
67474
- err
67475
- );
67476
- });
67477
67631
  return res.modifiedCount;
67478
67632
  } catch (error) {
67479
67633
  throw new Error(error.message);
@@ -67485,16 +67639,6 @@ function useFormEntryRepo() {
67485
67639
  value.org = new ObjectId152(value.org);
67486
67640
  value.userId = new ObjectId152(value.userId);
67487
67641
  const res = await collection.insertOne(value, { session });
67488
- delNamespace().then(() => {
67489
- logger195.info(
67490
- `Cache cleared for namespace: ${online_forms_namespace_collection}`
67491
- );
67492
- }).catch((err) => {
67493
- logger195.error(
67494
- `Failed to clear cache for namespace: ${online_forms_namespace_collection}`,
67495
- err
67496
- );
67497
- });
67498
67642
  return res.insertedId;
67499
67643
  } catch (error) {
67500
67644
  const isDuplicated = error.message.includes("duplicate");
@@ -67504,21 +67648,64 @@ function useFormEntryRepo() {
67504
67648
  throw error;
67505
67649
  }
67506
67650
  }
67507
- async function residentForm({ userId, site, org }) {
67651
+ async function residentForm({
67652
+ userId,
67653
+ site,
67654
+ org,
67655
+ search = "",
67656
+ page = 1,
67657
+ limit = 10,
67658
+ sort = {}
67659
+ }) {
67660
+ page = page > 0 ? page - 1 : 0;
67661
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
67662
+ const user = new ObjectId152(userId);
67663
+ const siteId = new ObjectId152(site);
67664
+ const orgId = new ObjectId152(org);
67665
+ const cacheOptions = {
67666
+ page,
67667
+ limit,
67668
+ sort: JSON.stringify(sort),
67669
+ userId: user,
67670
+ site: siteId,
67671
+ org: orgId,
67672
+ ...search && { search }
67673
+ };
67674
+ const query = {
67675
+ userId: user,
67676
+ site: siteId,
67677
+ org: orgId
67678
+ };
67679
+ if (search && search !== "") {
67680
+ query.$or = [
67681
+ { typeOfForm: { $regex: search, $options: "i" } },
67682
+ { unitNumber: { $regex: search, $options: "i" } }
67683
+ ];
67684
+ }
67685
+ const cacheKey = makeCacheKey65(
67686
+ online_forms_namespace_collection,
67687
+ cacheOptions
67688
+ );
67689
+ const cachedData = await getCache(cacheKey);
67690
+ if (cachedData) {
67691
+ logger195.info(`Cache hit for key: ${cacheKey}`);
67692
+ return cachedData;
67693
+ }
67508
67694
  try {
67509
- const user = new ObjectId152(userId);
67510
- const siteId = new ObjectId152(site);
67511
- const orgId = new ObjectId152(org);
67512
- const res = await collection.aggregate([
67513
- {
67514
- $match: {
67515
- userId: user,
67516
- site: siteId,
67517
- org: orgId
67518
- }
67519
- }
67695
+ const items = await collection.aggregate([
67696
+ { $match: query },
67697
+ { $sort: sort },
67698
+ { $skip: page * limit },
67699
+ { $limit: limit }
67520
67700
  ]).toArray();
67521
- return res;
67701
+ const length = await collection.countDocuments(query);
67702
+ const data = paginate64(items, page, limit, length);
67703
+ setCache(cacheKey, data, 15 * 60).then(() => {
67704
+ logger195.info(`Cache set for key: ${cacheKey}`);
67705
+ }).catch((err) => {
67706
+ logger195.error(`Failed to set cache for key: ${cacheKey}`, err);
67707
+ });
67708
+ return data;
67522
67709
  } catch (error) {
67523
67710
  throw error;
67524
67711
  }
@@ -67750,20 +67937,25 @@ function useFormEntryController() {
67750
67937
  }
67751
67938
  async function residentForm(req, res, next) {
67752
67939
  try {
67753
- const { site, userId, org } = req.query;
67754
67940
  const residentFormPayload = Joi148.object({
67755
67941
  org: Joi148.string().hex().required(),
67756
67942
  site: Joi148.string().hex().required(),
67757
- userId: Joi148.string().hex().required()
67943
+ userId: Joi148.string().hex().required(),
67944
+ search: Joi148.string().optional().allow("", null),
67945
+ page: Joi148.number().integer().min(1).allow("", null).default(1),
67946
+ limit: Joi148.number().integer().min(1).max(100).allow("", null).default(10)
67947
+ });
67948
+ const { error, value } = residentFormPayload.validate(req.query, {
67949
+ abortEarly: true
67758
67950
  });
67759
- const { error } = residentFormPayload.validate({ site, userId, org }, { abortEarly: true });
67760
67951
  if (error) {
67761
67952
  const messages = error.details.map((d) => d.message).join(", ");
67762
67953
  logger196.log({ level: "error", message: messages });
67763
67954
  next(new BadRequestError226(messages));
67764
67955
  return;
67765
67956
  }
67766
- const result = await _residentForm({ userId, site, org });
67957
+ const { site, userId, org, search, page, limit } = value;
67958
+ const result = await _residentForm({ userId, site, org, search, page, limit });
67767
67959
  res.json(result);
67768
67960
  } catch (error) {
67769
67961
  logger196.log({ level: "error", message: error.message });
@@ -67784,11 +67976,11 @@ function useFormEntryController() {
67784
67976
  }
67785
67977
 
67786
67978
  // src/services/building-level.service.ts
67787
- import { useAtlas as useAtlas129 } from "@7365admin1/node-server-utils";
67979
+ import { useAtlas as useAtlas130 } from "@7365admin1/node-server-utils";
67788
67980
  function useBuildingLevelService() {
67789
67981
  const { add: _add, updateLevelById: _updateLevelById } = useBuildingLevelRepo();
67790
67982
  async function add(value) {
67791
- const session = useAtlas129.getClient()?.startSession();
67983
+ const session = useAtlas130.getClient()?.startSession();
67792
67984
  try {
67793
67985
  session?.startTransaction();
67794
67986
  await _add(value, session);
@@ -67802,7 +67994,7 @@ function useBuildingLevelService() {
67802
67994
  }
67803
67995
  }
67804
67996
  async function updateLevelById(_id, value) {
67805
- const session = useAtlas129.getClient()?.startSession();
67997
+ const session = useAtlas130.getClient()?.startSession();
67806
67998
  try {
67807
67999
  session?.startTransaction();
67808
68000
  await _updateLevelById(_id, value, session);
@@ -68288,17 +68480,17 @@ function MHidAmicoIdentity(value) {
68288
68480
  // src/repositories/hid-amico.repo.ts
68289
68481
  import {
68290
68482
  BadRequestError as BadRequestError229,
68291
- InternalServerError as InternalServerError84,
68483
+ InternalServerError as InternalServerError85,
68292
68484
  logger as logger199,
68293
68485
  paginate as paginate65,
68294
- useAtlas as useAtlas130
68486
+ useAtlas as useAtlas131
68295
68487
  } from "@7365admin1/node-server-utils";
68296
68488
  import { ObjectId as ObjectId154 } from "mongodb";
68297
68489
  function useHidAmicoRepo() {
68298
68490
  function db() {
68299
- const instance = useAtlas130.getDb();
68491
+ const instance = useAtlas131.getDb();
68300
68492
  if (!instance) {
68301
- throw new InternalServerError84("Unable to connect to server.");
68493
+ throw new InternalServerError85("Unable to connect to server.");
68302
68494
  }
68303
68495
  return instance;
68304
68496
  }