@iservice365/module-hygiene 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -33,39 +33,40 @@ __export(src_exports, {
33
33
  MArea: () => MArea,
34
34
  MAreaChecklist: () => MAreaChecklist,
35
35
  MParentChecklist: () => MParentChecklist,
36
+ MSupply: () => MSupply,
36
37
  MUnit: () => MUnit,
37
- MUnitChecklist: () => MUnitChecklist,
38
38
  allowedChecklistStatus: () => allowedChecklistStatus,
39
+ allowedStatus: () => allowedStatus,
40
+ allowedTypes: () => allowedTypes,
39
41
  areaChecklistSchema: () => areaChecklistSchema,
40
42
  areaSchema: () => areaSchema,
41
43
  parentChecklistSchema: () => parentChecklistSchema,
42
- unitChecklistSchema: () => unitChecklistSchema,
44
+ supplySchema: () => supplySchema,
43
45
  unitSchema: () => unitSchema,
44
46
  useAreaChecklistController: () => useAreaChecklistController,
45
47
  useAreaChecklistRepo: () => useAreaChecklistRepo,
48
+ useAreaChecklistService: () => useAreaChecklistService,
46
49
  useAreaController: () => useAreaController,
47
50
  useAreaRepo: () => useAreaRepo,
48
51
  useAreaService: () => useAreaService,
49
52
  useParentChecklistController: () => useParentChecklistController,
50
53
  useParentChecklistRepo: () => useParentChecklistRepo,
51
- useUnitChecklistController: () => useUnitChecklistController,
52
- useUnitChecklistRepo: () => useUnitChecklistRepo,
54
+ useSupplyController: () => useSupplyController,
55
+ useSupplyRepository: () => useSupplyRepository,
53
56
  useUnitController: () => useUnitController,
54
57
  useUnitRepository: () => useUnitRepository,
55
58
  useUnitService: () => useUnitService
56
59
  });
57
60
  module.exports = __toCommonJS(src_exports);
58
61
 
59
- // src/models/hygiene-area.model.ts
60
- var import_node_server_utils = require("@iservice365/node-server-utils");
61
- var import_joi = __toESM(require("joi"));
62
- var import_mongodb = require("mongodb");
63
-
64
62
  // src/models/hygiene-base.model.ts
65
63
  var allowedTypes = ["common", "toilet"];
66
64
  var allowedStatus = ["ready", "ongoing", "completed"];
67
65
 
68
66
  // src/models/hygiene-area.model.ts
67
+ var import_node_server_utils = require("@iservice365/node-server-utils");
68
+ var import_joi = __toESM(require("joi"));
69
+ var import_mongodb = require("mongodb");
69
70
  var areaSchema = import_joi.default.object({
70
71
  site: import_joi.default.string().hex().required(),
71
72
  name: import_joi.default.string().required(),
@@ -315,6 +316,7 @@ function useAreaRepo() {
315
316
  { $match: query },
316
317
  {
317
318
  $project: {
319
+ type: 1,
318
320
  name: 1,
319
321
  set: 1,
320
322
  units: 1
@@ -334,7 +336,38 @@ function useAreaRepo() {
334
336
  throw error;
335
337
  }
336
338
  }
337
- async function updateArea(_id, value) {
339
+ async function verifyAreaByUnitId(unitId) {
340
+ try {
341
+ unitId = new import_mongodb2.ObjectId(unitId);
342
+ } catch (error) {
343
+ throw new import_node_server_utils2.BadRequestError("Invalid unit ID format.");
344
+ }
345
+ const query = {
346
+ "units.unit": unitId,
347
+ status: { $ne: "deleted" }
348
+ };
349
+ const cacheKey = (0, import_node_server_utils2.makeCacheKey)(namespace_collection, {
350
+ verify_unitId: unitId.toString()
351
+ });
352
+ const cachedData = await getCache(cacheKey);
353
+ if (cachedData) {
354
+ import_node_server_utils2.logger.info(`Cache hit for key: ${cacheKey}`);
355
+ return cachedData;
356
+ }
357
+ try {
358
+ const count = await collection.countDocuments(query);
359
+ const result = count > 0;
360
+ setCache(cacheKey, result, 15 * 60).then(() => {
361
+ import_node_server_utils2.logger.info(`Cache set for key: ${cacheKey}`);
362
+ }).catch((err) => {
363
+ import_node_server_utils2.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
364
+ });
365
+ return result;
366
+ } catch (error) {
367
+ throw error;
368
+ }
369
+ }
370
+ async function updateArea(_id, value, session) {
338
371
  try {
339
372
  _id = new import_mongodb2.ObjectId(_id);
340
373
  } catch (error) {
@@ -365,7 +398,11 @@ function useAreaRepo() {
365
398
  }
366
399
  });
367
400
  }
368
- const res = await collection.updateOne({ _id }, { $set: updateValue });
401
+ const res = await collection.updateOne(
402
+ { _id },
403
+ { $set: updateValue },
404
+ { session }
405
+ );
369
406
  if (res.modifiedCount === 0) {
370
407
  throw new import_node_server_utils2.InternalServerError("Unable to update cleaning area.");
371
408
  }
@@ -386,29 +423,25 @@ function useAreaRepo() {
386
423
  throw error;
387
424
  }
388
425
  }
389
- async function updateAreaChecklist(_id, value) {
426
+ async function updateAreaChecklist(unitId, name, session) {
390
427
  try {
391
- _id = new import_mongodb2.ObjectId(_id);
428
+ unitId = new import_mongodb2.ObjectId(unitId);
392
429
  } catch (error) {
393
- throw new import_node_server_utils2.BadRequestError("Invalid area ID format.");
394
- }
395
- if (value.units && Array.isArray(value.units)) {
396
- value.units = value.units.map((item) => {
397
- try {
398
- return {
399
- ...item,
400
- unit: new import_mongodb2.ObjectId(item.unit)
401
- };
402
- } catch (error) {
403
- throw new import_node_server_utils2.BadRequestError(`Invalid unit ID format: ${item.unit}`);
404
- }
405
- });
430
+ throw new import_node_server_utils2.BadRequestError("Invalid unit ID format.");
406
431
  }
407
432
  try {
408
- const updateValue = { ...value, updatedAt: /* @__PURE__ */ new Date() };
409
- const res = await collection.updateOne({ _id }, { $set: updateValue });
433
+ const res = await collection.updateMany(
434
+ { "units.unit": unitId },
435
+ {
436
+ $set: {
437
+ "units.$.name": name,
438
+ updatedAt: /* @__PURE__ */ new Date()
439
+ }
440
+ },
441
+ { session }
442
+ );
410
443
  if (res.modifiedCount === 0) {
411
- throw new import_node_server_utils2.InternalServerError("Unable to update cleaning area.");
444
+ throw new import_node_server_utils2.InternalServerError("Unable to update unit name in areas.");
412
445
  }
413
446
  delNamespace().then(() => {
414
447
  import_node_server_utils2.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
@@ -464,6 +497,7 @@ function useAreaRepo() {
464
497
  getAreas,
465
498
  getAreasForChecklist,
466
499
  getAreaById,
500
+ verifyAreaByUnitId,
467
501
  updateArea,
468
502
  updateAreaChecklist,
469
503
  deleteArea
@@ -499,7 +533,7 @@ function useAreaService() {
499
533
  skippedRows.push(i + 1);
500
534
  continue;
501
535
  }
502
- const areaType = String(row.TYPE).trim();
536
+ const areaType = String(row.TYPE).trim().toLowerCase();
503
537
  if (!areaType) {
504
538
  import_node_server_utils3.logger.warn(`Skipping row ${i + 1} with empty area type`);
505
539
  skippedRows.push(i + 1);
@@ -547,18 +581,22 @@ function useAreaService() {
547
581
  }
548
582
  import_node_server_utils3.logger.info(message);
549
583
  if (insertedAreaIds.length === 0) {
550
- if (duplicateAreas.length > 0 && failedAreas.length === 0) {
551
- throw new import_node_server_utils3.BadRequestError(
552
- `No new areas were created. All ${duplicateAreas.length} areas already exist in the system: ${duplicateAreas.join(", ")}`
553
- );
584
+ if (duplicateAreas.length > 0 && failedAreas.length === 0 && skippedRows.length === 0) {
585
+ return {
586
+ message: `No new areas were created. All ${duplicateAreas.length} areas already exist in the system: ${duplicateAreas.join(", ")}`
587
+ };
554
588
  } else if (failedAreas.length > 0) {
555
589
  throw new import_node_server_utils3.BadRequestError(
556
- `No areas were created. Please check your data format and ensure area names are valid.`
590
+ `No areas were created. ${failedAreas.length} areas failed due to errors. Please check your data format and ensure area names are valid.`
557
591
  );
558
- } else if (skippedRows.length > 0) {
592
+ } else if (skippedRows.length > 0 && duplicateAreas.length === 0) {
559
593
  throw new import_node_server_utils3.BadRequestError(
560
- `No areas were created. All rows contained invalid or missing area names.`
594
+ `No areas were created. All ${skippedRows.length} rows contained invalid or missing data.`
561
595
  );
596
+ } else {
597
+ return {
598
+ message: `No new areas were created. ${duplicateAreas.length} areas already exist, ${skippedRows.length} rows had invalid data.`
599
+ };
562
600
  }
563
601
  }
564
602
  return { message };
@@ -566,10 +604,6 @@ function useAreaService() {
566
604
  import_node_server_utils3.logger.error("Error while uploading area information", error);
567
605
  if (error instanceof import_node_server_utils3.BadRequestError) {
568
606
  throw error;
569
- } else if (error.message.includes("duplicate")) {
570
- throw new import_node_server_utils3.BadRequestError(
571
- `Upload failed due to duplicate area names. Please ensure all area names are unique.`
572
- );
573
607
  } else if (error.message.includes("validation")) {
574
608
  throw new import_node_server_utils3.BadRequestError(
575
609
  "Upload failed due to invalid data format. Please check that all required fields are properly filled."
@@ -622,7 +656,6 @@ function useAreaController() {
622
656
  getAreas: _getAreas,
623
657
  getAreaById: _getAreaById,
624
658
  updateArea: _updateArea,
625
- updateAreaChecklist: _updateAreaChecklist,
626
659
  deleteArea: _deleteById
627
660
  } = useAreaRepo();
628
661
  const { importArea: _importArea } = useAreaService();
@@ -728,36 +761,6 @@ function useAreaController() {
728
761
  return;
729
762
  }
730
763
  }
731
- async function updateAreaChecklist(req, res, next) {
732
- const payload = { id: req.params.id, ...req.body };
733
- const schema = import_joi2.default.object({
734
- id: import_joi2.default.string().hex().required(),
735
- units: import_joi2.default.array().items(
736
- import_joi2.default.object({
737
- unit: import_joi2.default.string().hex().required(),
738
- name: import_joi2.default.string().required()
739
- }).required()
740
- ).min(1).unique("unit", { ignoreUndefined: true }).messages({
741
- "array.unique": "Duplicate area units are not allowed"
742
- })
743
- });
744
- const { error } = schema.validate(payload);
745
- if (error) {
746
- import_node_server_utils4.logger.log({ level: "error", message: error.message });
747
- next(new import_node_server_utils4.BadRequestError(error.message));
748
- return;
749
- }
750
- try {
751
- const { id, ...value } = payload;
752
- await _updateAreaChecklist(id, value);
753
- res.json({ message: "Area updated successfully." });
754
- return;
755
- } catch (error2) {
756
- import_node_server_utils4.logger.log({ level: "error", message: error2.message });
757
- next(error2);
758
- return;
759
- }
760
- }
761
764
  async function deleteArea(req, res, next) {
762
765
  const id = req.params.id;
763
766
  const validation = import_joi2.default.string().hex().required();
@@ -806,7 +809,6 @@ function useAreaController() {
806
809
  getAreas,
807
810
  getAreaById,
808
811
  updateArea,
809
- updateAreaChecklist,
810
812
  deleteArea,
811
813
  importArea
812
814
  };
@@ -960,7 +962,7 @@ function useUnitRepository() {
960
962
  throw error;
961
963
  }
962
964
  }
963
- async function updateUnit(_id, value) {
965
+ async function updateUnit(_id, value, session) {
964
966
  try {
965
967
  _id = new import_mongodb4.ObjectId(_id);
966
968
  } catch (error) {
@@ -968,7 +970,11 @@ function useUnitRepository() {
968
970
  }
969
971
  try {
970
972
  const updateValue = { ...value, updatedAt: /* @__PURE__ */ new Date() };
971
- const res = await collection.updateOne({ _id }, { $set: updateValue });
973
+ const res = await collection.updateOne(
974
+ { _id },
975
+ { $set: updateValue },
976
+ { session }
977
+ );
972
978
  if (res.modifiedCount === 0) {
973
979
  throw new import_node_server_utils6.InternalServerError("Unable to update cleaning unit.");
974
980
  }
@@ -1035,7 +1041,12 @@ function useUnitRepository() {
1035
1041
 
1036
1042
  // src/services/hygiene-unit.service.ts
1037
1043
  function useUnitService() {
1038
- const { createUnit: _createUnit } = useUnitRepository();
1044
+ const {
1045
+ createUnit: _createUnit,
1046
+ updateUnit: _updateUnit,
1047
+ deleteUnit: _deleteUnit
1048
+ } = useUnitRepository();
1049
+ const { verifyAreaByUnitId, updateAreaChecklist } = useAreaRepo();
1039
1050
  async function importUnit({
1040
1051
  dataJson,
1041
1052
  site
@@ -1129,20 +1140,61 @@ function useUnitService() {
1129
1140
  }
1130
1141
  }
1131
1142
  }
1132
- return { importUnit };
1143
+ async function updateUnit(_id, value) {
1144
+ const session = import_node_server_utils7.useAtlas.getClient()?.startSession();
1145
+ try {
1146
+ session?.startTransaction();
1147
+ const result = await _updateUnit(_id, value, session);
1148
+ const isExistingArea = await verifyAreaByUnitId(_id);
1149
+ if (isExistingArea) {
1150
+ await updateAreaChecklist(_id, value.name, session);
1151
+ }
1152
+ await session?.commitTransaction();
1153
+ return result;
1154
+ } catch (error) {
1155
+ import_node_server_utils7.logger.error(`Error updating unit and associated areas:`, error);
1156
+ if (session?.inTransaction()) {
1157
+ await session?.abortTransaction();
1158
+ }
1159
+ throw error;
1160
+ } finally {
1161
+ session?.endSession();
1162
+ }
1163
+ }
1164
+ async function deleteUnit(_id) {
1165
+ const session = import_node_server_utils7.useAtlas.getClient()?.startSession();
1166
+ try {
1167
+ session?.startTransaction();
1168
+ const isExistingArea = await verifyAreaByUnitId(_id);
1169
+ if (isExistingArea) {
1170
+ throw new import_node_server_utils7.BadRequestError("Failed to delete unit, unit is in use.");
1171
+ }
1172
+ const result = await _deleteUnit(_id, session);
1173
+ await session?.commitTransaction();
1174
+ return result;
1175
+ } catch (error) {
1176
+ import_node_server_utils7.logger.error(`Error deleting unit:`, error);
1177
+ if (session?.inTransaction()) {
1178
+ await session?.abortTransaction();
1179
+ }
1180
+ throw error;
1181
+ } finally {
1182
+ session?.endSession();
1183
+ }
1184
+ }
1185
+ return { importUnit, updateUnit, deleteUnit };
1133
1186
  }
1134
1187
 
1135
1188
  // src/controllers/hygiene-unit.controller.ts
1136
1189
  var import_node_server_utils8 = require("@iservice365/node-server-utils");
1137
1190
  var import_joi4 = __toESM(require("joi"));
1138
1191
  function useUnitController() {
1192
+ const { createUnit: _createUnit, getUnits: _getUnits } = useUnitRepository();
1139
1193
  const {
1140
- createUnit: _createUnit,
1141
- getUnits: _getUnits,
1142
1194
  updateUnit: _updateUnit,
1143
- deleteUnit: _deleteUnit
1144
- } = useUnitRepository();
1145
- const { importUnit: _importUnit } = useUnitService();
1195
+ deleteUnit: _deleteUnit,
1196
+ importUnit: _importUnit
1197
+ } = useUnitService();
1146
1198
  async function createUnit(req, res, next) {
1147
1199
  const payload = { ...req.body, ...req.params };
1148
1200
  const { error } = unitSchema.validate(payload);
@@ -1467,164 +1519,37 @@ function useParentChecklistRepo() {
1467
1519
  throw error;
1468
1520
  }
1469
1521
  }
1470
- async function updateParentChecklistStatuses(createdAt) {
1522
+ async function updateParentChecklistStatuses(_id, status, session) {
1471
1523
  try {
1472
- const currentDate = /* @__PURE__ */ new Date();
1473
- const dateToUpdate = createdAt || new Date(currentDate.getTime() - 24 * 60 * 60 * 1e3);
1474
- const startOfDay = new Date(dateToUpdate);
1475
- startOfDay.setUTCHours(0, 0, 0, 0);
1476
- const endOfDay = new Date(dateToUpdate);
1477
- endOfDay.setUTCHours(23, 59, 59, 999);
1478
- import_node_server_utils10.logger.info(
1479
- `Updating parent checklist statuses for date: ${dateToUpdate.toISOString().split("T")[0]}`
1480
- );
1481
- const statusUpdates = await collection.aggregate([
1482
- {
1483
- $match: {
1484
- createdAt: {
1485
- $gte: startOfDay,
1486
- $lte: endOfDay
1487
- }
1488
- }
1489
- },
1490
- {
1491
- $lookup: {
1492
- from: "site.cleaning.schedule.areas",
1493
- let: { parentId: "$_id" },
1494
- pipeline: [
1495
- {
1496
- $match: {
1497
- $expr: { $eq: ["$parentChecklist", "$$parentId"] }
1498
- }
1499
- },
1500
- {
1501
- $group: {
1502
- _id: {
1503
- parentChecklist: "$parentChecklist"
1504
- },
1505
- completedCount: {
1506
- $sum: {
1507
- $cond: [{ $eq: ["$status", "completed"] }, 1, 0]
1508
- }
1509
- },
1510
- ongoingCount: {
1511
- $sum: {
1512
- $cond: [{ $eq: ["$status", "ongoing"] }, 1, 0]
1513
- }
1514
- },
1515
- readyCount: {
1516
- $sum: {
1517
- $cond: [{ $eq: ["$status", "ready"] }, 1, 0]
1518
- }
1519
- },
1520
- totalCount: { $sum: 1 }
1521
- }
1522
- },
1523
- {
1524
- $addFields: {
1525
- finalStatus: {
1526
- $cond: {
1527
- if: {
1528
- $and: [
1529
- { $gt: ["$completedCount", 0] },
1530
- { $eq: ["$ongoingCount", 0] },
1531
- { $eq: ["$readyCount", 0] }
1532
- ]
1533
- },
1534
- then: "completed",
1535
- else: {
1536
- $cond: {
1537
- if: {
1538
- $and: [
1539
- { $eq: ["$completedCount", 0] },
1540
- { $eq: ["$ongoingCount", 0] }
1541
- ]
1542
- },
1543
- then: "expired",
1544
- else: "ongoing"
1545
- }
1546
- }
1547
- }
1548
- },
1549
- completedAt: {
1550
- $cond: {
1551
- if: {
1552
- $and: [
1553
- { $gt: ["$completedCount", 0] },
1554
- { $eq: ["$ongoingCount", 0] },
1555
- { $eq: ["$readyCount", 0] }
1556
- ]
1557
- },
1558
- then: /* @__PURE__ */ new Date(),
1559
- else: null
1560
- }
1561
- }
1562
- }
1563
- }
1564
- ],
1565
- as: "areaStats"
1566
- }
1567
- },
1568
- {
1569
- $match: {
1570
- "areaStats.0": { $exists: true }
1571
- }
1572
- },
1573
- {
1574
- $addFields: {
1575
- areaData: { $arrayElemAt: ["$areaStats", 0] }
1576
- }
1577
- },
1578
- {
1579
- $project: {
1580
- _id: 1,
1581
- newStatus: "$areaData.finalStatus",
1582
- completedAt: "$areaData.completedAt"
1583
- }
1584
- }
1585
- ]).toArray();
1586
- import_node_server_utils10.logger.info(
1587
- `Found ${statusUpdates.length} parent checklists to potentially update`
1524
+ _id = new import_mongodb6.ObjectId(_id);
1525
+ } catch (error) {
1526
+ throw new import_node_server_utils10.BadRequestError("Invalid parent checklist ID format.");
1527
+ }
1528
+ try {
1529
+ const updateValue = {
1530
+ status,
1531
+ updatedAt: /* @__PURE__ */ new Date()
1532
+ };
1533
+ const res = await collection.updateOne(
1534
+ { _id },
1535
+ { $set: updateValue },
1536
+ { session }
1588
1537
  );
1589
- if (statusUpdates.length === 0) {
1590
- import_node_server_utils10.logger.info(
1591
- `No parent checklists found for date range: ${startOfDay.toISOString()} to ${endOfDay.toISOString()}`
1538
+ if (res.modifiedCount === 0) {
1539
+ throw new import_node_server_utils10.InternalServerError(
1540
+ "Unable to update parent checklist status."
1592
1541
  );
1593
- return null;
1594
1542
  }
1595
- const bulkOps = statusUpdates.map((update) => {
1596
- import_node_server_utils10.logger.info(
1597
- `Updating parent checklist ${update._id} with status: ${update.newStatus}`
1543
+ delNamespace().then(() => {
1544
+ import_node_server_utils10.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
1545
+ }).catch((err) => {
1546
+ import_node_server_utils10.logger.error(
1547
+ `Failed to clear cache for namespace: ${namespace_collection}`,
1548
+ err
1598
1549
  );
1599
- return {
1600
- updateOne: {
1601
- filter: { _id: update._id },
1602
- update: {
1603
- $set: {
1604
- status: update.newStatus,
1605
- completedAt: update.completedAt,
1606
- updatedAt: /* @__PURE__ */ new Date()
1607
- }
1608
- }
1609
- }
1610
- };
1611
1550
  });
1612
- let result = null;
1613
- if (bulkOps.length > 0) {
1614
- result = await collection.bulkWrite(bulkOps);
1615
- delNamespace().then(() => {
1616
- import_node_server_utils10.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
1617
- }).catch((err) => {
1618
- import_node_server_utils10.logger.error(
1619
- `Failed to clear cache for namespace: ${namespace_collection}`,
1620
- err
1621
- );
1622
- });
1623
- }
1624
- import_node_server_utils10.logger.info(`Updated statuses for ${bulkOps.length} parent checklists.`);
1625
- return result;
1551
+ return res.modifiedCount;
1626
1552
  } catch (error) {
1627
- import_node_server_utils10.logger.error("Failed to update parent checklist statuses", error);
1628
1553
  throw error;
1629
1554
  }
1630
1555
  }
@@ -1751,6 +1676,7 @@ var areaChecklistSchema = import_joi7.default.object({
1751
1676
  set: import_joi7.default.number().min(0).required(),
1752
1677
  units: import_joi7.default.array().items(
1753
1678
  import_joi7.default.object({
1679
+ unit: import_joi7.default.string().hex().required(),
1754
1680
  name: import_joi7.default.string().required()
1755
1681
  }).required()
1756
1682
  ).min(1).required()
@@ -1775,9 +1701,11 @@ function MAreaChecklist(value) {
1775
1701
  return {
1776
1702
  set: checklistItem.set,
1777
1703
  units: checklistItem.units.map((unit) => ({
1704
+ unit: new import_mongodb7.ObjectId(unit.unit),
1778
1705
  name: unit.name,
1779
1706
  status: "ready",
1780
1707
  remarks: "",
1708
+ completedBy: "",
1781
1709
  timestamp: ""
1782
1710
  }))
1783
1711
  };
@@ -1790,10 +1718,14 @@ function MAreaChecklist(value) {
1790
1718
  checklist: value.checklist || [],
1791
1719
  status: "ready",
1792
1720
  createdAt: /* @__PURE__ */ new Date(),
1721
+ completedAt: "",
1793
1722
  updatedAt: ""
1794
1723
  };
1795
1724
  }
1796
1725
 
1726
+ // src/services/hygiene-area-checklist.service.ts
1727
+ var import_node_server_utils14 = require("@iservice365/node-server-utils");
1728
+
1797
1729
  // src/repositories/hygiene-area-checklist.repository.ts
1798
1730
  var import_node_server_utils13 = require("@iservice365/node-server-utils");
1799
1731
  var import_mongodb8 = require("mongodb");
@@ -1803,13 +1735,8 @@ function useAreaChecklistRepo() {
1803
1735
  throw new import_node_server_utils13.InternalServerError("Unable to connect to server.");
1804
1736
  }
1805
1737
  const namespace_collection = "site.cleaning.schedule.areas";
1806
- const unit_checklist_collection = "site.cleaning.schedule.units";
1807
1738
  const collection = db.collection(namespace_collection);
1808
- const unitChecklistCollection = db.collection(unit_checklist_collection);
1809
1739
  const { delNamespace, setCache, getCache } = (0, import_node_server_utils13.useCache)(namespace_collection);
1810
- const { delNamespace: delUnitNamespace } = (0, import_node_server_utils13.useCache)(
1811
- unit_checklist_collection
1812
- );
1813
1740
  async function createIndex() {
1814
1741
  try {
1815
1742
  await collection.createIndexes([
@@ -1817,7 +1744,8 @@ function useAreaChecklistRepo() {
1817
1744
  { key: { type: 1 } },
1818
1745
  { key: { status: 1 } },
1819
1746
  { key: { createdAt: 1 } },
1820
- { key: { acceptedBy: 1 } }
1747
+ { key: { "checklist.units.unit": 1 } },
1748
+ { key: { "checklist.units.status": 1 } }
1821
1749
  ]);
1822
1750
  } catch (error) {
1823
1751
  throw new import_node_server_utils13.InternalServerError(
@@ -1827,7 +1755,11 @@ function useAreaChecklistRepo() {
1827
1755
  }
1828
1756
  async function createTextIndex() {
1829
1757
  try {
1830
- await collection.createIndex({ name: "text" });
1758
+ await collection.createIndex({
1759
+ name: "text",
1760
+ "checklist.units.name": "text",
1761
+ "checklist.units.remarks": "text"
1762
+ });
1831
1763
  } catch (error) {
1832
1764
  throw new import_node_server_utils13.InternalServerError(
1833
1765
  "Failed to create text index on hygiene checklist area."
@@ -1878,7 +1810,7 @@ function useAreaChecklistRepo() {
1878
1810
  search = "",
1879
1811
  type,
1880
1812
  schedule
1881
- }) {
1813
+ }, session) {
1882
1814
  page = page > 0 ? page - 1 : 0;
1883
1815
  const query = {};
1884
1816
  const cacheOptions = {
@@ -1900,10 +1832,12 @@ function useAreaChecklistRepo() {
1900
1832
  cacheOptions.search = search;
1901
1833
  }
1902
1834
  const cacheKey = (0, import_node_server_utils13.makeCacheKey)(namespace_collection, cacheOptions);
1903
- const cachedData = await getCache(cacheKey);
1904
- if (cachedData) {
1905
- import_node_server_utils13.logger.info(`Cache hit for key: ${cacheKey}`);
1906
- return cachedData;
1835
+ if (!session) {
1836
+ const cachedData = await getCache(cacheKey);
1837
+ if (cachedData) {
1838
+ import_node_server_utils13.logger.info(`Cache hit for key: ${cacheKey}`);
1839
+ return cachedData;
1840
+ }
1907
1841
  }
1908
1842
  try {
1909
1843
  const pipeline = [
@@ -1928,7 +1862,15 @@ function useAreaChecklistRepo() {
1928
1862
  set: {
1929
1863
  $cond: {
1930
1864
  if: { $gt: [{ $size: { $ifNull: ["$checklist", []] } }, 0] },
1931
- then: { $max: "$checklist.set" },
1865
+ then: {
1866
+ $max: {
1867
+ $map: {
1868
+ input: "$checklist",
1869
+ as: "item",
1870
+ in: { $toInt: "$$item.set" }
1871
+ }
1872
+ }
1873
+ },
1932
1874
  else: 0
1933
1875
  }
1934
1876
  }
@@ -1938,8 +1880,8 @@ function useAreaChecklistRepo() {
1938
1880
  { $skip: page * limit },
1939
1881
  { $limit: limit }
1940
1882
  ];
1941
- const items = await collection.aggregate(pipeline).toArray();
1942
- const length = await collection.countDocuments(query);
1883
+ const items = await collection.aggregate(pipeline, { session }).toArray();
1884
+ const length = await collection.countDocuments(query, { session });
1943
1885
  const data = (0, import_node_server_utils13.paginate)(items, page, limit, length);
1944
1886
  setCache(cacheKey, data, 15 * 60).then(() => {
1945
1887
  import_node_server_utils13.logger.info(`Cache set for key: ${cacheKey}`);
@@ -1955,31 +1897,27 @@ function useAreaChecklistRepo() {
1955
1897
  page = 1,
1956
1898
  limit = 10,
1957
1899
  search = "",
1958
- site,
1959
1900
  type,
1960
1901
  schedule,
1961
1902
  status,
1962
- createdAt,
1963
- user
1903
+ createdAt
1964
1904
  }) {
1965
1905
  page = page > 0 ? page - 1 : 0;
1966
- const query = { type };
1906
+ const query = {};
1967
1907
  const cacheOptions = {
1968
1908
  page,
1969
1909
  limit
1970
1910
  };
1971
- try {
1972
- query.site = new import_mongodb8.ObjectId(site);
1973
- cacheOptions.site = site.toString();
1974
- } catch (error) {
1975
- throw new import_node_server_utils13.BadRequestError("Invalid site ID format.");
1976
- }
1977
1911
  try {
1978
1912
  query.schedule = new import_mongodb8.ObjectId(schedule);
1979
1913
  cacheOptions.schedule = schedule.toString();
1980
1914
  } catch (error) {
1981
1915
  throw new import_node_server_utils13.BadRequestError("Invalid parent checklist ID format.");
1982
1916
  }
1917
+ if (type) {
1918
+ query.type = type;
1919
+ cacheOptions.type = type;
1920
+ }
1983
1921
  if (search) {
1984
1922
  query.$text = { $search: search };
1985
1923
  cacheOptions.search = search;
@@ -1997,14 +1935,6 @@ function useAreaChecklistRepo() {
1997
1935
  } else {
1998
1936
  query.status = { $in: ["ongoing", "completed"] };
1999
1937
  }
2000
- if (user) {
2001
- try {
2002
- query.acceptedBy = new import_mongodb8.ObjectId(user);
2003
- cacheOptions.user = user.toString();
2004
- } catch (error) {
2005
- throw new import_node_server_utils13.BadRequestError("Invalid user ID format.");
2006
- }
2007
- }
2008
1938
  const cacheKey = (0, import_node_server_utils13.makeCacheKey)(namespace_collection, cacheOptions);
2009
1939
  const cachedData = await getCache(cacheKey);
2010
1940
  if (cachedData) {
@@ -2014,29 +1944,12 @@ function useAreaChecklistRepo() {
2014
1944
  try {
2015
1945
  const pipeline = [
2016
1946
  { $match: query },
2017
- {
2018
- $lookup: {
2019
- from: "users",
2020
- localField: "acceptedBy",
2021
- foreignField: "_id",
2022
- pipeline: [
2023
- ...search ? [{ $match: { name: { $regex: search, $options: "i" } } }] : [],
2024
- { $project: { name: 1 } }
2025
- ],
2026
- as: "acceptedBy"
2027
- }
2028
- },
2029
- {
2030
- $unwind: {
2031
- path: "$acceptedBy",
2032
- preserveNullAndEmptyArrays: true
2033
- }
2034
- },
2035
1947
  {
2036
1948
  $project: {
2037
1949
  name: 1,
1950
+ type: 1,
2038
1951
  createdAt: 1,
2039
- acceptedByName: "$acceptedBy.name",
1952
+ completedAt: 1,
2040
1953
  status: {
2041
1954
  $switch: {
2042
1955
  branches: [
@@ -2050,9 +1963,22 @@ function useAreaChecklistRepo() {
2050
1963
  default: "$status"
2051
1964
  }
2052
1965
  },
2053
- startedAt: "$acceptedAt",
2054
- endedAt: "$completedAt"
2055
- }
1966
+ set: {
1967
+ $cond: {
1968
+ if: { $gt: [{ $size: { $ifNull: ["$checklist", []] } }, 0] },
1969
+ then: {
1970
+ $max: {
1971
+ $map: {
1972
+ input: "$checklist",
1973
+ as: "item",
1974
+ in: { $toInt: "$$item.set" }
1975
+ }
1976
+ }
1977
+ },
1978
+ else: 0
1979
+ }
1980
+ }
1981
+ }
2056
1982
  },
2057
1983
  { $sort: { status: 1 } },
2058
1984
  { $skip: page * limit },
@@ -2089,75 +2015,120 @@ function useAreaChecklistRepo() {
2089
2015
  const areaPipeline = [
2090
2016
  { $match: { _id } },
2091
2017
  {
2092
- $lookup: {
2093
- from: "users",
2094
- localField: "createdBy",
2095
- foreignField: "_id",
2096
- pipeline: [{ $project: { name: 1 } }],
2097
- as: "createdBy"
2018
+ $project: {
2019
+ name: 1,
2020
+ createdAt: 1,
2021
+ completedAt: 1,
2022
+ status: {
2023
+ $switch: {
2024
+ branches: [
2025
+ { case: { $eq: ["$status", "ready"] }, then: "Ready" },
2026
+ { case: { $eq: ["$status", "ongoing"] }, then: "Ongoing" },
2027
+ {
2028
+ case: { $eq: ["$status", "completed"] },
2029
+ then: "Completed"
2030
+ }
2031
+ ],
2032
+ default: "$status"
2033
+ }
2034
+ }
2035
+ }
2036
+ }
2037
+ ];
2038
+ const unitPipeline = [
2039
+ { $match: { _id } },
2040
+ {
2041
+ $unwind: {
2042
+ path: "$checklist",
2043
+ preserveNullAndEmptyArrays: false
2098
2044
  }
2099
2045
  },
2100
2046
  {
2101
2047
  $unwind: {
2102
- path: "$createdBy",
2103
- preserveNullAndEmptyArrays: true
2048
+ path: "$checklist.units",
2049
+ preserveNullAndEmptyArrays: false
2104
2050
  }
2105
2051
  },
2106
2052
  {
2107
2053
  $lookup: {
2108
2054
  from: "users",
2109
- localField: "acceptedBy",
2110
- foreignField: "_id",
2111
- pipeline: [{ $project: { name: 1 } }],
2112
- as: "acceptedBy"
2055
+ let: { completedById: "$checklist.units.completedBy" },
2056
+ pipeline: [
2057
+ {
2058
+ $match: {
2059
+ $expr: {
2060
+ $and: [
2061
+ { $ne: ["$$completedById", ""] },
2062
+ { $eq: ["$_id", "$$completedById"] }
2063
+ ]
2064
+ }
2065
+ }
2066
+ },
2067
+ { $project: { name: 1 } }
2068
+ ],
2069
+ as: "completedBy"
2113
2070
  }
2114
2071
  },
2115
2072
  {
2116
2073
  $unwind: {
2117
- path: "$acceptedBy",
2074
+ path: "$completedBy",
2118
2075
  preserveNullAndEmptyArrays: true
2119
2076
  }
2120
2077
  },
2121
2078
  {
2122
2079
  $project: {
2123
- name: 1,
2124
- createdAt: 1,
2125
- createdByName: "$createdBy.name",
2126
- startedAt: "$acceptedAt",
2127
- endedAt: "$completedAt",
2080
+ _id: 0,
2081
+ set: "$checklist.set",
2082
+ unit: "$checklist.units.unit",
2083
+ name: "$checklist.units.name",
2084
+ remarks: "$checklist.units.remarks",
2128
2085
  status: {
2129
2086
  $switch: {
2130
2087
  branches: [
2131
- { case: { $eq: ["$status", "ready"] }, then: "Ready" },
2132
- { case: { $eq: ["$status", "ongoing"] }, then: "Ongoing" },
2133
2088
  {
2134
- case: { $eq: ["$status", "completed"] },
2089
+ case: { $eq: ["$checklist.units.status", "ready"] },
2090
+ then: "Ready"
2091
+ },
2092
+ {
2093
+ case: { $eq: ["$checklist.units.status", "completed"] },
2135
2094
  then: "Completed"
2136
2095
  }
2137
2096
  ],
2138
- default: "$status"
2097
+ default: "$checklist.units.status"
2139
2098
  }
2140
2099
  },
2141
- signature: 1,
2142
- acceptedByName: "$acceptedBy.name"
2100
+ completedByName: "$completedBy.name",
2101
+ timestamp: "$checklist.units.timestamp"
2143
2102
  }
2144
- }
2145
- ];
2146
- const unitPipeline = [
2147
- { $match: { areaChecklist: _id } },
2103
+ },
2104
+ { $sort: { set: 1, name: 1 } },
2105
+ {
2106
+ $group: {
2107
+ _id: "$set",
2108
+ units: {
2109
+ $push: {
2110
+ unit: "$unit",
2111
+ name: "$name",
2112
+ status: "$status",
2113
+ remarks: "$remarks",
2114
+ completedByName: "$completedByName",
2115
+ timestamp: "$timestamp"
2116
+ }
2117
+ }
2118
+ }
2119
+ },
2148
2120
  {
2149
2121
  $project: {
2150
- name: 1,
2151
- remarks: "$metadata.remarks",
2152
- attachments: "$metadata.attachments",
2153
- approve: { $ifNull: ["$approve", null] },
2154
- reject: { $ifNull: ["$reject", null] }
2122
+ _id: 0,
2123
+ set: "$_id",
2124
+ units: 1
2155
2125
  }
2156
- }
2126
+ },
2127
+ { $sort: { set: 1 } }
2157
2128
  ];
2158
2129
  const [area, units] = await Promise.all([
2159
2130
  collection.aggregate(areaPipeline).toArray(),
2160
- unitChecklistCollection.aggregate(unitPipeline).toArray()
2131
+ collection.aggregate(unitPipeline).toArray()
2161
2132
  ]);
2162
2133
  if (!area.length) {
2163
2134
  throw new import_node_server_utils13.BadRequestError("Area checklist not found.");
@@ -2176,64 +2147,166 @@ function useAreaChecklistRepo() {
2176
2147
  throw error;
2177
2148
  }
2178
2149
  }
2179
- async function acceptAreaChecklist(_id, acceptedBy) {
2150
+ async function getAreaChecklistUnits({
2151
+ page = 1,
2152
+ limit = 10,
2153
+ search = "",
2154
+ _id
2155
+ }, session) {
2156
+ page = page > 0 ? page - 1 : 0;
2157
+ const query = {};
2158
+ const cacheOptions = {
2159
+ page,
2160
+ limit
2161
+ };
2180
2162
  try {
2181
- _id = new import_mongodb8.ObjectId(_id);
2163
+ query._id = new import_mongodb8.ObjectId(_id);
2164
+ cacheOptions._id = _id.toString();
2182
2165
  } catch (error) {
2183
- throw new import_node_server_utils13.BadRequestError("Invalid area ID format.");
2166
+ throw new import_node_server_utils13.BadRequestError("Invalid area checklist ID format.");
2184
2167
  }
2185
- try {
2186
- acceptedBy = new import_mongodb8.ObjectId(acceptedBy);
2187
- } catch (error) {
2188
- throw new import_node_server_utils13.BadRequestError("Invalid acceptedBy ID format.");
2168
+ if (search) {
2169
+ query.$text = { $search: search };
2170
+ cacheOptions.search = search;
2171
+ }
2172
+ const cacheKey = (0, import_node_server_utils13.makeCacheKey)(namespace_collection, cacheOptions);
2173
+ if (!session) {
2174
+ const cachedData = await getCache(cacheKey);
2175
+ if (cachedData) {
2176
+ import_node_server_utils13.logger.info(`Cache hit for key: ${cacheKey}`);
2177
+ return cachedData;
2178
+ }
2189
2179
  }
2190
2180
  try {
2191
- const now = /* @__PURE__ */ new Date();
2192
- const updateValue = {
2193
- metadata: {
2194
- acceptedBy,
2195
- acceptedAt: now
2181
+ const pipeline = [
2182
+ { $match: query },
2183
+ {
2184
+ $unwind: {
2185
+ path: "$checklist",
2186
+ preserveNullAndEmptyArrays: false
2187
+ }
2196
2188
  },
2197
- updatedAt: now
2198
- };
2199
- const res = await collection.updateOne({ _id }, { $set: updateValue });
2200
- if (res.modifiedCount === 0) {
2201
- throw new import_node_server_utils13.InternalServerError("Unable to update cleaning area.");
2202
- }
2203
- delNamespace().then(() => {
2204
- import_node_server_utils13.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
2189
+ {
2190
+ $unwind: {
2191
+ path: "$checklist.units",
2192
+ preserveNullAndEmptyArrays: false
2193
+ }
2194
+ },
2195
+ {
2196
+ $project: {
2197
+ _id: 0,
2198
+ set: "$checklist.set",
2199
+ unit: "$checklist.units.unit",
2200
+ name: "$checklist.units.name",
2201
+ status: {
2202
+ $switch: {
2203
+ branches: [
2204
+ {
2205
+ case: { $eq: ["$checklist.units.status", "ready"] },
2206
+ then: "Ready"
2207
+ },
2208
+ {
2209
+ case: { $eq: ["$checklist.units.status", "completed"] },
2210
+ then: "Completed"
2211
+ }
2212
+ ],
2213
+ default: "$checklist.units.status"
2214
+ }
2215
+ },
2216
+ remarks: "$checklist.units.remarks"
2217
+ }
2218
+ },
2219
+ { $sort: { set: 1, name: 1 } },
2220
+ {
2221
+ $group: {
2222
+ _id: "$set",
2223
+ units: {
2224
+ $push: {
2225
+ unit: "$unit",
2226
+ name: "$name",
2227
+ status: "$status",
2228
+ remarks: "$remarks"
2229
+ }
2230
+ }
2231
+ }
2232
+ },
2233
+ {
2234
+ $project: {
2235
+ _id: 0,
2236
+ set: "$_id",
2237
+ units: 1
2238
+ }
2239
+ },
2240
+ { $sort: { set: 1 } },
2241
+ { $skip: page * limit },
2242
+ { $limit: limit }
2243
+ ];
2244
+ const countPipeline = [
2245
+ { $match: query },
2246
+ {
2247
+ $unwind: {
2248
+ path: "$checklist",
2249
+ preserveNullAndEmptyArrays: false
2250
+ }
2251
+ },
2252
+ {
2253
+ $group: {
2254
+ _id: "$checklist.set"
2255
+ }
2256
+ },
2257
+ { $count: "total" }
2258
+ ];
2259
+ const [items, countResult] = await Promise.all([
2260
+ collection.aggregate(pipeline, { session }).toArray(),
2261
+ collection.aggregate(countPipeline, { session }).toArray()
2262
+ ]);
2263
+ const length = countResult.length > 0 ? countResult[0].total : 0;
2264
+ const data = (0, import_node_server_utils13.paginate)(items, page, limit, length);
2265
+ setCache(cacheKey, data, 15 * 60).then(() => {
2266
+ import_node_server_utils13.logger.info(`Cache set for key: ${cacheKey}`);
2205
2267
  }).catch((err) => {
2206
- import_node_server_utils13.logger.error(
2207
- `Failed to clear cache for namespace: ${namespace_collection}`,
2208
- err
2209
- );
2268
+ import_node_server_utils13.logger.error(`Failed to set cache for key: ${cacheKey}`, err);
2210
2269
  });
2211
- return res.modifiedCount;
2270
+ return data;
2212
2271
  } catch (error) {
2213
2272
  throw error;
2214
2273
  }
2215
2274
  }
2216
- async function attachImageAreaChecklist(_id, attachments, session) {
2275
+ async function completeAreaChecklistUnits(_id, set, unitId, value, session) {
2217
2276
  try {
2218
2277
  _id = new import_mongodb8.ObjectId(_id);
2219
2278
  } catch (error) {
2220
2279
  throw new import_node_server_utils13.BadRequestError("Invalid area checklist ID format.");
2221
2280
  }
2281
+ try {
2282
+ unitId = new import_mongodb8.ObjectId(unitId);
2283
+ } catch (error) {
2284
+ throw new import_node_server_utils13.BadRequestError("Invalid unit checklist ID format.");
2285
+ }
2222
2286
  try {
2223
2287
  const now = /* @__PURE__ */ new Date();
2224
2288
  const updateValue = {
2225
- metadata: { attachments },
2289
+ "checklist.$[checklist].units.$[unit].timestamp": now,
2290
+ "checklist.$[checklist].units.$[unit].status": "completed",
2226
2291
  updatedAt: now
2227
2292
  };
2293
+ if (value.remarks) {
2294
+ updateValue["checklist.$[checklist].units.$[unit].remarks"] = value.remarks;
2295
+ }
2296
+ if (value.completedBy) {
2297
+ updateValue["checklist.$[checklist].units.$[unit].completedBy"] = new import_mongodb8.ObjectId(value.completedBy);
2298
+ }
2299
+ const arrayFilters = [
2300
+ { "checklist.set": set, "checklist.units.unit": unitId },
2301
+ { "unit.unit": unitId }
2302
+ ];
2228
2303
  const res = await collection.updateOne(
2229
- { _id },
2304
+ { _id, "checklist.set": set, "checklist.units.unit": unitId },
2230
2305
  { $set: updateValue },
2231
- { session }
2306
+ { arrayFilters, session }
2232
2307
  );
2233
2308
  if (res.modifiedCount === 0) {
2234
- throw new import_node_server_utils13.InternalServerError(
2235
- "Unable to update cleaning area checklist."
2236
- );
2309
+ throw new import_node_server_utils13.InternalServerError("Unable to update area checklist unit.");
2237
2310
  }
2238
2311
  delNamespace().then(() => {
2239
2312
  import_node_server_utils13.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
@@ -2243,40 +2316,35 @@ function useAreaChecklistRepo() {
2243
2316
  err
2244
2317
  );
2245
2318
  });
2246
- delUnitNamespace().then(() => {
2247
- import_node_server_utils13.logger.info(
2248
- `Cache cleared for namespace: ${unit_checklist_collection}`
2249
- );
2250
- }).catch((err) => {
2251
- import_node_server_utils13.logger.error(
2252
- `Failed to clear cache for namespace: ${unit_checklist_collection}`,
2253
- err
2254
- );
2255
- });
2256
2319
  return res.modifiedCount;
2257
2320
  } catch (error) {
2321
+ import_node_server_utils13.logger.error("Error updating area checklist unit:", error.message);
2258
2322
  throw error;
2259
2323
  }
2260
2324
  }
2261
- async function submitAreaChecklist(_id, signature) {
2325
+ async function updateAreaChecklistStatus(_id, status, session) {
2262
2326
  try {
2263
2327
  _id = new import_mongodb8.ObjectId(_id);
2264
2328
  } catch (error) {
2265
- throw new import_node_server_utils13.BadRequestError("Invalid area ID format.");
2329
+ throw new import_node_server_utils13.BadRequestError("Invalid area checklist ID format.");
2266
2330
  }
2267
2331
  try {
2268
- const now = /* @__PURE__ */ new Date();
2269
2332
  const updateValue = {
2270
- metadata: {
2271
- signature,
2272
- completedAt: now
2273
- },
2274
- status: "ongoing",
2275
- updatedAt: now
2333
+ status,
2334
+ updatedAt: /* @__PURE__ */ new Date()
2276
2335
  };
2277
- const res = await collection.updateOne({ _id }, { $set: updateValue });
2336
+ if (status === "completed") {
2337
+ updateValue.completedAt = /* @__PURE__ */ new Date();
2338
+ }
2339
+ const res = await collection.updateOne(
2340
+ { _id },
2341
+ { $set: updateValue },
2342
+ { session }
2343
+ );
2278
2344
  if (res.modifiedCount === 0) {
2279
- throw new import_node_server_utils13.InternalServerError("Unable to update cleaning area.");
2345
+ throw new import_node_server_utils13.InternalServerError(
2346
+ "Unable to update area checklist status."
2347
+ );
2280
2348
  }
2281
2349
  delNamespace().then(() => {
2282
2350
  import_node_server_utils13.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
@@ -2291,35 +2359,21 @@ function useAreaChecklistRepo() {
2291
2359
  throw error;
2292
2360
  }
2293
2361
  }
2294
- async function completeAreaChecklist(_id, signature) {
2362
+ async function getAreaChecklistById(_id, session) {
2295
2363
  try {
2296
2364
  _id = new import_mongodb8.ObjectId(_id);
2297
2365
  } catch (error) {
2298
- throw new import_node_server_utils13.BadRequestError("Invalid area ID format.");
2366
+ throw new import_node_server_utils13.BadRequestError("Invalid area checklist ID format.");
2299
2367
  }
2300
2368
  try {
2301
- const now = /* @__PURE__ */ new Date();
2302
- const updateValue = {
2303
- metadata: {
2304
- signature,
2305
- completedAt: now
2306
- },
2307
- status: "completed",
2308
- updatedAt: now
2309
- };
2310
- const res = await collection.updateOne({ _id }, { $set: updateValue });
2311
- if (res.modifiedCount === 0) {
2312
- throw new import_node_server_utils13.InternalServerError("Unable to update cleaning area.");
2369
+ const area = await collection.findOne(
2370
+ { _id },
2371
+ { projection: { schedule: 1, name: 1, type: 1, status: 1 }, session }
2372
+ );
2373
+ if (!area) {
2374
+ throw new import_node_server_utils13.BadRequestError("Area checklist not found.");
2313
2375
  }
2314
- delNamespace().then(() => {
2315
- import_node_server_utils13.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
2316
- }).catch((err) => {
2317
- import_node_server_utils13.logger.error(
2318
- `Failed to clear cache for namespace: ${namespace_collection}`,
2319
- err
2320
- );
2321
- });
2322
- return res.modifiedCount;
2376
+ return area;
2323
2377
  } catch (error) {
2324
2378
  throw error;
2325
2379
  }
@@ -2331,22 +2385,25 @@ function useAreaChecklistRepo() {
2331
2385
  getAllAreaChecklist,
2332
2386
  getAreaChecklistHistory,
2333
2387
  getAreaChecklistHistoryDetails,
2334
- acceptAreaChecklist,
2335
- attachImageAreaChecklist,
2336
- submitAreaChecklist,
2337
- completeAreaChecklist
2388
+ getAreaChecklistUnits,
2389
+ getAreaChecklistById,
2390
+ updateAreaChecklistStatus,
2391
+ completeAreaChecklistUnits
2338
2392
  };
2339
2393
  }
2340
2394
 
2341
- // src/controllers/hygiene-area-checklist.controller.ts
2342
- var import_node_server_utils15 = require("@iservice365/node-server-utils");
2343
- var import_joi8 = __toESM(require("joi"));
2344
-
2345
2395
  // src/services/hygiene-area-checklist.service.ts
2346
- var import_node_server_utils14 = require("@iservice365/node-server-utils");
2347
2396
  function useAreaChecklistService() {
2348
- const { createAreaChecklist: _createAreaChecklist } = useAreaChecklistRepo();
2397
+ const {
2398
+ createAreaChecklist: _createAreaChecklist,
2399
+ getAllAreaChecklist,
2400
+ getAreaChecklistUnits,
2401
+ getAreaChecklistById,
2402
+ completeAreaChecklistUnits: _completeAreaChecklistUnits,
2403
+ updateAreaChecklistStatus
2404
+ } = useAreaChecklistRepo();
2349
2405
  const { getAreasForChecklist } = useAreaRepo();
2406
+ const { updateParentChecklistStatuses } = useParentChecklistRepo();
2350
2407
  async function createAreaChecklist(value) {
2351
2408
  const session = import_node_server_utils14.useAtlas.getClient()?.startSession();
2352
2409
  try {
@@ -2367,14 +2424,13 @@ function useAreaChecklistService() {
2367
2424
  schedule: value.schedule,
2368
2425
  name: area.name,
2369
2426
  type: "common",
2370
- checklist: area.units && area.units.length > 0 ? [
2371
- {
2372
- set: area.set || 0,
2373
- units: area.units.map((unit) => ({
2374
- name: unit.name
2375
- }))
2376
- }
2377
- ] : []
2427
+ checklist: area.units && area.units.length > 0 ? Array.from({ length: area.set || 1 }, (_, index) => ({
2428
+ set: index + 1,
2429
+ units: area.units.map((unit) => ({
2430
+ unit: unit.unit.toString(),
2431
+ name: unit.name
2432
+ }))
2433
+ })) : []
2378
2434
  };
2379
2435
  const insertedId = await _createAreaChecklist(
2380
2436
  checklistData,
@@ -2405,14 +2461,16 @@ function useAreaChecklistService() {
2405
2461
  schedule: value.schedule,
2406
2462
  name: toiletLocation.name,
2407
2463
  type: "toilet",
2408
- checklist: toiletLocation.units && toiletLocation.units.length > 0 ? [
2409
- {
2410
- set: toiletLocation.set || 0,
2464
+ checklist: toiletLocation.units && toiletLocation.units.length > 0 ? Array.from(
2465
+ { length: toiletLocation.set || 1 },
2466
+ (_, index) => ({
2467
+ set: index + 1,
2411
2468
  units: toiletLocation.units.map((unit) => ({
2469
+ unit: unit.unit.toString(),
2412
2470
  name: unit.name
2413
2471
  }))
2414
- }
2415
- ] : []
2472
+ })
2473
+ ) : []
2416
2474
  };
2417
2475
  const insertedId = await _createAreaChecklist(
2418
2476
  checklistData,
@@ -2445,21 +2503,107 @@ function useAreaChecklistService() {
2445
2503
  session?.endSession();
2446
2504
  }
2447
2505
  }
2448
- return { createAreaChecklist };
2506
+ async function completeAreaChecklistUnits(_id, set, unitId, value) {
2507
+ const session = import_node_server_utils14.useAtlas.getClient()?.startSession();
2508
+ try {
2509
+ session?.startTransaction();
2510
+ await _completeAreaChecklistUnits(_id, set, unitId, value, session);
2511
+ const allUnitsResult = await getAreaChecklistUnits(
2512
+ {
2513
+ page: 1,
2514
+ limit: 1e3,
2515
+ _id: _id.toString()
2516
+ },
2517
+ session
2518
+ );
2519
+ let areaStatus = "ready";
2520
+ if (allUnitsResult && allUnitsResult.items && allUnitsResult.items.length > 0) {
2521
+ const sets = allUnitsResult.items;
2522
+ const allUnits = sets.flatMap((set2) => set2.units || []);
2523
+ const readyCount = allUnits.filter(
2524
+ (unit) => unit.status === "Ready"
2525
+ ).length;
2526
+ const completedCount = allUnits.filter(
2527
+ (unit) => unit.status === "Completed"
2528
+ ).length;
2529
+ const totalCount = allUnits.length;
2530
+ if (completedCount === totalCount) {
2531
+ areaStatus = "completed";
2532
+ } else if (readyCount === totalCount) {
2533
+ areaStatus = "ready";
2534
+ } else {
2535
+ areaStatus = "ongoing";
2536
+ }
2537
+ }
2538
+ await updateAreaChecklistStatus(_id, areaStatus, session);
2539
+ const currentArea = await getAreaChecklistById(_id, session);
2540
+ const scheduleId = currentArea.schedule;
2541
+ if (scheduleId) {
2542
+ const allAreasResult = await getAllAreaChecklist(
2543
+ {
2544
+ page: 1,
2545
+ limit: 1e3,
2546
+ schedule: scheduleId.toString()
2547
+ },
2548
+ session
2549
+ );
2550
+ if (allAreasResult && allAreasResult.items && allAreasResult.items.length > 0) {
2551
+ const areas = allAreasResult.items;
2552
+ const readyAreasCount = areas.filter(
2553
+ (area) => area.status === "Ready"
2554
+ ).length;
2555
+ const completedAreasCount = areas.filter(
2556
+ (area) => area.status === "Completed"
2557
+ ).length;
2558
+ const totalAreasCount = areas.length;
2559
+ let parentStatus = "ready";
2560
+ if (completedAreasCount === totalAreasCount) {
2561
+ parentStatus = "completed";
2562
+ } else if (readyAreasCount === totalAreasCount) {
2563
+ parentStatus = "ready";
2564
+ } else {
2565
+ parentStatus = "ongoing";
2566
+ }
2567
+ await updateParentChecklistStatuses(
2568
+ scheduleId,
2569
+ parentStatus,
2570
+ session
2571
+ );
2572
+ } else {
2573
+ import_node_server_utils14.logger.info(
2574
+ "No area checklists found, keeping parent status as ready"
2575
+ );
2576
+ }
2577
+ }
2578
+ await session?.commitTransaction();
2579
+ return;
2580
+ } catch (error) {
2581
+ import_node_server_utils14.logger.error(`Error updating area checklist unit and statuses:`, error);
2582
+ if (session?.inTransaction()) {
2583
+ await session?.abortTransaction();
2584
+ }
2585
+ throw error;
2586
+ } finally {
2587
+ session?.endSession();
2588
+ }
2589
+ }
2590
+ return { createAreaChecklist, completeAreaChecklistUnits };
2449
2591
  }
2450
2592
 
2451
2593
  // src/controllers/hygiene-area-checklist.controller.ts
2594
+ var import_node_server_utils15 = require("@iservice365/node-server-utils");
2595
+ var import_joi8 = __toESM(require("joi"));
2452
2596
  function useAreaChecklistController() {
2453
2597
  const {
2454
2598
  getAllAreaChecklist: _getAllAreaChecklist,
2455
2599
  getAreaChecklistHistory: _getAreaChecklistHistory,
2456
2600
  getAreaChecklistHistoryDetails: _getAreaChecklistHistoryDetails,
2457
- acceptAreaChecklist: _acceptAreaChecklist,
2458
- attachImageAreaChecklist: _attachImageAreaChecklist,
2459
- submitAreaChecklist: _submitAreaChecklist,
2460
- completeAreaChecklist: _completeAreaChecklist
2601
+ getAreaChecklistUnits: _getAreaChecklistUnits
2461
2602
  } = useAreaChecklistRepo();
2462
- const { createAreaChecklist: _createAreaChecklist } = useAreaChecklistService();
2603
+ const {
2604
+ createAreaChecklist: _createAreaChecklist,
2605
+ completeAreaChecklistUnits: _completeAreaChecklistUnits
2606
+ } = useAreaChecklistService();
2463
2607
  async function createAreaChecklist(req, res, next) {
2464
2608
  const payload = {
2465
2609
  site: req.params.site,
@@ -2522,22 +2666,15 @@ function useAreaChecklistController() {
2522
2666
  }
2523
2667
  }
2524
2668
  async function getAreaChecklistHistory(req, res, next) {
2525
- const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
2526
- (acc, [key, value]) => ({ ...acc, [key]: value }),
2527
- {}
2528
- ) : {};
2529
- const user = cookies["user"] || "";
2530
- const query = { ...req.query, ...req.params, user };
2669
+ const query = { ...req.query, ...req.params };
2531
2670
  const validation = import_joi8.default.object({
2532
2671
  page: import_joi8.default.number().min(1).optional().allow("", null),
2533
2672
  limit: import_joi8.default.number().min(1).optional().allow("", null),
2534
2673
  search: import_joi8.default.string().optional().allow("", null),
2535
- site: import_joi8.default.string().hex().required(),
2536
- type: import_joi8.default.string().valid(...allowedTypes).required(),
2674
+ type: import_joi8.default.string().optional().allow("", ...allowedTypes),
2537
2675
  schedule: import_joi8.default.string().hex().required(),
2538
2676
  status: import_joi8.default.string().allow("", null, ...allowedStatus),
2539
- createdAt: import_joi8.default.alternatives().try(import_joi8.default.date(), import_joi8.default.string()).optional().allow("", null),
2540
- user: import_joi8.default.string().hex().optional().allow("", null)
2677
+ createdAt: import_joi8.default.alternatives().try(import_joi8.default.date(), import_joi8.default.string()).optional().allow("", null)
2541
2678
  });
2542
2679
  const { error } = validation.validate(query);
2543
2680
  if (error) {
@@ -2548,7 +2685,6 @@ function useAreaChecklistController() {
2548
2685
  const page = parseInt(req.query.page) ?? 1;
2549
2686
  const limit = parseInt(req.query.limit) ?? 20;
2550
2687
  const search = req.query.search ?? "";
2551
- const site = req.params.site ?? "";
2552
2688
  const type = req.query.type ?? "";
2553
2689
  const schedule = req.params.schedule ?? "";
2554
2690
  const status = req.query.status ?? "";
@@ -2558,12 +2694,10 @@ function useAreaChecklistController() {
2558
2694
  page,
2559
2695
  limit,
2560
2696
  search,
2561
- site,
2562
2697
  type,
2563
2698
  schedule,
2564
2699
  status,
2565
- createdAt,
2566
- user
2700
+ createdAt
2567
2701
  });
2568
2702
  res.json(data);
2569
2703
  return;
@@ -2592,70 +2726,32 @@ function useAreaChecklistController() {
2592
2726
  return;
2593
2727
  }
2594
2728
  }
2595
- async function acceptAreaChecklist(req, res, next) {
2596
- const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
2597
- (acc, [key, value]) => ({ ...acc, [key]: value }),
2598
- {}
2599
- ) : {};
2600
- const acceptedBy = cookies["user"] || "";
2601
- const payload = { id: req.params.id, acceptedBy };
2602
- const validation = import_joi8.default.object({
2603
- id: import_joi8.default.string().hex().required(),
2604
- acceptedBy: import_joi8.default.string().hex().required()
2605
- });
2606
- const { error } = validation.validate(payload);
2607
- if (error) {
2608
- import_node_server_utils15.logger.log({ level: "error", message: error.message });
2609
- next(new import_node_server_utils15.BadRequestError(error.message));
2610
- return;
2611
- }
2612
- try {
2613
- await _acceptAreaChecklist(payload.id, payload.acceptedBy);
2614
- res.json({ message: "Area checklist updated successfully." });
2615
- return;
2616
- } catch (error2) {
2617
- import_node_server_utils15.logger.log({ level: "error", message: error2.message });
2618
- next(error2);
2619
- return;
2620
- }
2621
- }
2622
- async function attachImageAreaChecklist(req, res, next) {
2623
- const payload = { id: req.params.id, attachments: req.body.attachments };
2624
- const validation = import_joi8.default.object({
2625
- id: import_joi8.default.string().hex().required(),
2626
- attachments: import_joi8.default.array().items(import_joi8.default.string()).optional()
2627
- });
2628
- const { error } = validation.validate(payload);
2629
- if (error) {
2630
- import_node_server_utils15.logger.log({ level: "error", message: error.message });
2631
- next(new import_node_server_utils15.BadRequestError(error.message));
2632
- return;
2633
- }
2634
- try {
2635
- await _attachImageAreaChecklist(payload.id, payload.attachments);
2636
- res.json({ message: "Area checklist attachments updated successfully." });
2637
- return;
2638
- } catch (error2) {
2639
- import_node_server_utils15.logger.log({ level: "error", message: error2.message });
2640
- next(error2);
2641
- return;
2642
- }
2643
- }
2644
- async function submitAreaChecklist(req, res, next) {
2645
- const payload = { id: req.params.id, signature: req.body.signature };
2729
+ async function getAreaChecklistUnits(req, res, next) {
2730
+ const query = { ...req.query, ...req.params };
2646
2731
  const validation = import_joi8.default.object({
2647
- id: import_joi8.default.string().hex().required(),
2648
- signature: import_joi8.default.string().required()
2732
+ page: import_joi8.default.number().min(1).optional().allow("", null),
2733
+ limit: import_joi8.default.number().min(1).optional().allow("", null),
2734
+ search: import_joi8.default.string().optional().allow("", null),
2735
+ id: import_joi8.default.string().hex().required()
2649
2736
  });
2650
- const { error } = validation.validate(payload);
2737
+ const { error } = validation.validate(query);
2651
2738
  if (error) {
2652
2739
  import_node_server_utils15.logger.log({ level: "error", message: error.message });
2653
2740
  next(new import_node_server_utils15.BadRequestError(error.message));
2654
2741
  return;
2655
2742
  }
2743
+ const page = parseInt(req.query.page) ?? 1;
2744
+ const limit = parseInt(req.query.limit) ?? 20;
2745
+ const search = req.query.search ?? "";
2746
+ const _id = req.params.id ?? "";
2656
2747
  try {
2657
- await _submitAreaChecklist(payload.id, payload.signature);
2658
- res.json({ message: "Area checklist submitted successfully." });
2748
+ const data = await _getAreaChecklistUnits({
2749
+ page,
2750
+ limit,
2751
+ search,
2752
+ _id
2753
+ });
2754
+ res.json(data);
2659
2755
  return;
2660
2756
  } catch (error2) {
2661
2757
  import_node_server_utils15.logger.log({ level: "error", message: error2.message });
@@ -2663,11 +2759,23 @@ function useAreaChecklistController() {
2663
2759
  return;
2664
2760
  }
2665
2761
  }
2666
- async function completeAreaChecklist(req, res, next) {
2667
- const payload = { id: req.params.id, signature: req.body.signature };
2762
+ async function completeAreaChecklistUnits(req, res, next) {
2763
+ const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
2764
+ (acc, [key, value]) => ({ ...acc, [key]: value }),
2765
+ {}
2766
+ ) : {};
2767
+ const completedBy = cookies["user"] || "";
2768
+ const payload = {
2769
+ ...req.params,
2770
+ ...req.body,
2771
+ completedBy
2772
+ };
2668
2773
  const validation = import_joi8.default.object({
2669
2774
  id: import_joi8.default.string().hex().required(),
2670
- signature: import_joi8.default.string().required()
2775
+ set: import_joi8.default.number().integer().min(1).required(),
2776
+ unit: import_joi8.default.string().hex().required(),
2777
+ remarks: import_joi8.default.string().optional().allow("", null),
2778
+ completedBy: import_joi8.default.string().hex().required()
2671
2779
  });
2672
2780
  const { error } = validation.validate(payload);
2673
2781
  if (error) {
@@ -2676,8 +2784,14 @@ function useAreaChecklistController() {
2676
2784
  return;
2677
2785
  }
2678
2786
  try {
2679
- await _completeAreaChecklist(payload.id, payload.signature);
2680
- res.json({ message: "Area checklist completed successfully." });
2787
+ const { id, set, unit, ...value } = payload;
2788
+ await _completeAreaChecklistUnits(
2789
+ id,
2790
+ parseInt(set),
2791
+ unit,
2792
+ value
2793
+ );
2794
+ res.json({ message: "Area checklist updated successfully." });
2681
2795
  return;
2682
2796
  } catch (error2) {
2683
2797
  import_node_server_utils15.logger.log({ level: "error", message: error2.message });
@@ -2690,30 +2804,25 @@ function useAreaChecklistController() {
2690
2804
  getAllAreaChecklist,
2691
2805
  getAreaChecklistHistory,
2692
2806
  getAreaChecklistHistoryDetails,
2693
- acceptAreaChecklist,
2694
- attachImageAreaChecklist,
2695
- submitAreaChecklist,
2696
- completeAreaChecklist
2807
+ getAreaChecklistUnits,
2808
+ completeAreaChecklistUnits
2697
2809
  };
2698
2810
  }
2699
2811
 
2700
- // src/models/hygiene-unit-checklist.model.ts
2812
+ // src/models/hygiene-supply.model.ts
2701
2813
  var import_node_server_utils16 = require("@iservice365/node-server-utils");
2702
2814
  var import_joi9 = __toESM(require("joi"));
2703
2815
  var import_mongodb9 = require("mongodb");
2704
- var unitChecklistSchema = import_joi9.default.object({
2816
+ var supplySchema = import_joi9.default.object({
2705
2817
  site: import_joi9.default.string().hex().required(),
2706
- type: import_joi9.default.string().valid(...allowedTypes).required(),
2707
- parentChecklist: import_joi9.default.string().hex().required(),
2708
- areaChecklist: import_joi9.default.string().hex().required(),
2709
- unit: import_joi9.default.string().hex().required(),
2710
- name: import_joi9.default.string().optional().allow("", null),
2711
- createdBy: import_joi9.default.string().hex().optional().allow("", null)
2818
+ name: import_joi9.default.string().required(),
2819
+ unitOfMeasurement: import_joi9.default.string().required(),
2820
+ qty: import_joi9.default.number().min(0).required()
2712
2821
  });
2713
- function MUnitChecklist(value) {
2714
- const { error } = unitChecklistSchema.validate(value);
2822
+ function MSupply(value) {
2823
+ const { error } = supplySchema.validate(value);
2715
2824
  if (error) {
2716
- import_node_server_utils16.logger.info(`Hygiene Checklist Unit Model: ${error.message}`);
2825
+ import_node_server_utils16.logger.info(`Hygiene Supply Model: ${error.message}`);
2717
2826
  throw new import_node_server_utils16.BadRequestError(error.message);
2718
2827
  }
2719
2828
  if (value.site) {
@@ -2723,76 +2832,35 @@ function MUnitChecklist(value) {
2723
2832
  throw new import_node_server_utils16.BadRequestError("Invalid site ID format.");
2724
2833
  }
2725
2834
  }
2726
- if (value.parentChecklist) {
2727
- try {
2728
- value.parentChecklist = new import_mongodb9.ObjectId(value.parentChecklist);
2729
- } catch (error2) {
2730
- throw new import_node_server_utils16.BadRequestError("Invalid parent checklist ID format.");
2731
- }
2732
- }
2733
- if (value.areaChecklist) {
2734
- try {
2735
- value.areaChecklist = new import_mongodb9.ObjectId(value.areaChecklist);
2736
- } catch (error2) {
2737
- throw new import_node_server_utils16.BadRequestError("Invalid area checklist ID format.");
2738
- }
2739
- }
2740
- if (value.unit) {
2741
- try {
2742
- value.unit = new import_mongodb9.ObjectId(value.unit);
2743
- } catch (error2) {
2744
- throw new import_node_server_utils16.BadRequestError("Invalid unit ID format.");
2745
- }
2746
- }
2747
- if (value.createdBy) {
2748
- try {
2749
- value.createdBy = new import_mongodb9.ObjectId(value.createdBy);
2750
- } catch (error2) {
2751
- throw new import_node_server_utils16.BadRequestError("Invalid createdBy ID format.");
2752
- }
2753
- }
2754
2835
  return {
2755
2836
  site: value.site,
2756
- type: value.type,
2757
- parentChecklist: value.parentChecklist,
2758
- areaChecklist: value.areaChecklist,
2759
- unit: value.unit,
2760
- name: value.name ?? "",
2761
- approve: false,
2762
- reject: false,
2763
- createdBy: value.createdBy ?? "",
2837
+ name: value.name,
2838
+ unitOfMeasurement: value.unitOfMeasurement,
2839
+ qty: value.qty,
2764
2840
  createdAt: /* @__PURE__ */ new Date(),
2765
- updatedAt: value.updatedAt ?? ""
2841
+ status: "active",
2842
+ updatedAt: "",
2843
+ deletedAt: ""
2766
2844
  };
2767
2845
  }
2768
2846
 
2769
- // src/repositories/hygiene-unit-checklist.repository.ts
2770
- var import_node_server_utils17 = require("@iservice365/node-server-utils");
2847
+ // src/repositories/hygiene-supply.repository.ts
2771
2848
  var import_mongodb10 = require("mongodb");
2772
- function useUnitChecklistRepo() {
2849
+ var import_node_server_utils17 = require("@iservice365/node-server-utils");
2850
+ function useSupplyRepository() {
2773
2851
  const db = import_node_server_utils17.useAtlas.getDb();
2774
2852
  if (!db) {
2775
2853
  throw new import_node_server_utils17.InternalServerError("Unable to connect to server.");
2776
2854
  }
2777
- const namespace_collection = "hygiene-checklist.units";
2855
+ const namespace_collection = "site.supplies";
2778
2856
  const collection = db.collection(namespace_collection);
2779
2857
  const { delNamespace, setCache, getCache } = (0, import_node_server_utils17.useCache)(namespace_collection);
2780
2858
  async function createIndex() {
2781
2859
  try {
2782
- await collection.createIndexes([
2783
- { key: { site: 1 } },
2784
- { key: { type: 1 } },
2785
- { key: { parentChecklist: 1 } },
2786
- { key: { areaChecklist: 1 } },
2787
- { key: { "metadata.workOrder.category": 1 } },
2788
- { key: { "metadata.workOrder.createdBy": 1 } },
2789
- { key: { "metadata.workOrder.serviceProvider": 1 } },
2790
- { key: { "metadata.workOrder.organization": 1 } },
2791
- { key: { "metadata.workOrder.site": 1 } }
2792
- ]);
2860
+ await collection.createIndexes([{ key: { site: 1 } }]);
2793
2861
  } catch (error) {
2794
2862
  throw new import_node_server_utils17.InternalServerError(
2795
- "Failed to create index on hygiene unit checklist."
2863
+ "Failed to create index on hygiene supply."
2796
2864
  );
2797
2865
  }
2798
2866
  }
@@ -2801,13 +2869,25 @@ function useUnitChecklistRepo() {
2801
2869
  await collection.createIndex({ name: "text" });
2802
2870
  } catch (error) {
2803
2871
  throw new import_node_server_utils17.InternalServerError(
2804
- "Failed to create text index on hygiene unit checklist."
2872
+ "Failed to create text index on hygiene supply."
2805
2873
  );
2806
2874
  }
2807
2875
  }
2808
- async function createUnitChecklist(value, session) {
2876
+ async function createUniqueIndex() {
2809
2877
  try {
2810
- value = MUnitChecklist(value);
2878
+ await collection.createIndex(
2879
+ { site: 1, name: 1, deletedAt: 1 },
2880
+ { unique: true }
2881
+ );
2882
+ } catch (error) {
2883
+ throw new import_node_server_utils17.InternalServerError(
2884
+ "Failed to create unique index on hygiene supply."
2885
+ );
2886
+ }
2887
+ }
2888
+ async function createSupply(value, session) {
2889
+ try {
2890
+ value = MSupply(value);
2811
2891
  const res = await collection.insertOne(value, { session });
2812
2892
  delNamespace().then(() => {
2813
2893
  import_node_server_utils17.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
@@ -2819,42 +2899,34 @@ function useUnitChecklistRepo() {
2819
2899
  });
2820
2900
  return res.insertedId;
2821
2901
  } catch (error) {
2902
+ const isDuplicated = error.message.includes("duplicate");
2903
+ if (isDuplicated) {
2904
+ throw new import_node_server_utils17.BadRequestError("Supply already exists.");
2905
+ }
2822
2906
  throw error;
2823
2907
  }
2824
2908
  }
2825
- async function getAllUnitChecklist({
2909
+ async function getSupplies({
2826
2910
  page = 1,
2827
2911
  limit = 10,
2828
2912
  search = "",
2829
- site,
2830
- type,
2831
- parentChecklist,
2832
- areaChecklist
2913
+ site
2833
2914
  }) {
2834
2915
  page = page > 0 ? page - 1 : 0;
2835
- const query = { type };
2916
+ const query = {
2917
+ status: { $ne: "deleted" }
2918
+ };
2836
2919
  const cacheOptions = {
2837
2920
  page,
2838
2921
  limit
2839
2922
  };
2840
2923
  try {
2841
- query.site = new import_mongodb10.ObjectId(site);
2924
+ site = new import_mongodb10.ObjectId(site);
2925
+ query.site = site;
2842
2926
  cacheOptions.site = site.toString();
2843
2927
  } catch (error) {
2844
2928
  throw new import_node_server_utils17.BadRequestError("Invalid site ID format.");
2845
2929
  }
2846
- try {
2847
- query.parentChecklist = new import_mongodb10.ObjectId(parentChecklist);
2848
- cacheOptions.parentChecklist = parentChecklist.toString();
2849
- } catch (error) {
2850
- throw new import_node_server_utils17.BadRequestError("Invalid parent checklist ID format.");
2851
- }
2852
- try {
2853
- query.areaChecklist = new import_mongodb10.ObjectId(areaChecklist);
2854
- cacheOptions.areaChecklist = areaChecklist.toString();
2855
- } catch (error) {
2856
- throw new import_node_server_utils17.BadRequestError("Invalid area checklist ID format.");
2857
- }
2858
2930
  if (search) {
2859
2931
  query.$text = { $search: search };
2860
2932
  cacheOptions.search = search;
@@ -2866,120 +2938,20 @@ function useUnitChecklistRepo() {
2866
2938
  return cachedData;
2867
2939
  }
2868
2940
  try {
2869
- const areaAttachmentsResult = await collection.aggregate([
2870
- { $match: query },
2871
- {
2872
- $lookup: {
2873
- from: "hygiene-checklist.areas",
2874
- localField: "areaChecklist",
2875
- foreignField: "_id",
2876
- pipeline: [
2877
- { $project: { attachments: "$metadata.attachments" } }
2878
- ],
2879
- as: "areaChecklistData"
2880
- }
2881
- },
2882
- {
2883
- $unwind: {
2884
- path: "$areaChecklistData",
2885
- preserveNullAndEmptyArrays: true
2886
- }
2887
- },
2888
- {
2889
- $group: {
2890
- _id: null,
2891
- attachments: { $first: "$areaChecklistData.attachments" }
2892
- }
2893
- }
2894
- ]).toArray();
2895
- const areaAttachments = areaAttachmentsResult.length > 0 ? areaAttachmentsResult[0].attachments || [] : [];
2896
- const pipeline = [
2941
+ const items = await collection.aggregate([
2897
2942
  { $match: query },
2898
- {
2899
- $lookup: {
2900
- from: "organizations",
2901
- localField: "metadata.workOrder.category",
2902
- foreignField: "_id",
2903
- pipeline: [{ $project: { nature: 1 } }],
2904
- as: "categoryData"
2905
- }
2906
- },
2907
- {
2908
- $lookup: {
2909
- from: "users",
2910
- localField: "metadata.workOrder.createdBy",
2911
- foreignField: "_id",
2912
- pipeline: [{ $project: { name: 1 } }],
2913
- as: "createdByData"
2914
- }
2915
- },
2916
- {
2917
- $lookup: {
2918
- from: "service-providers",
2919
- localField: "metadata.workOrder.serviceProvider",
2920
- foreignField: "_id",
2921
- pipeline: [{ $project: { name: 1 } }],
2922
- as: "serviceProviderData"
2923
- }
2924
- },
2925
- {
2926
- $lookup: {
2927
- from: "organizations",
2928
- localField: "metadata.workOrder.organization",
2929
- foreignField: "_id",
2930
- pipeline: [{ $project: { name: 1 } }],
2931
- as: "organizationData"
2932
- }
2933
- },
2934
- {
2935
- $lookup: {
2936
- from: "sites",
2937
- localField: "metadata.workOrder.site",
2938
- foreignField: "_id",
2939
- pipeline: [{ $project: { name: 1 } }],
2940
- as: "siteData"
2941
- }
2942
- },
2943
- {
2944
- $addFields: {
2945
- "metadata.workOrder.categoryName": {
2946
- $arrayElemAt: ["$categoryData.nature", 0]
2947
- },
2948
- "metadata.workOrder.createdByName": {
2949
- $arrayElemAt: ["$createdByData.name", 0]
2950
- },
2951
- "metadata.workOrder.serviceProviderName": {
2952
- $arrayElemAt: ["$serviceProviderData.name", 0]
2953
- },
2954
- "metadata.workOrder.organizationName": {
2955
- $arrayElemAt: ["$organizationData.name", 0]
2956
- },
2957
- "metadata.workOrder.siteName": {
2958
- $arrayElemAt: ["$siteData.name", 0]
2959
- }
2960
- }
2961
- },
2962
2943
  {
2963
2944
  $project: {
2964
2945
  name: 1,
2965
- remarks: "$metadata.remarks",
2966
- attachments: "$metadata.attachments",
2967
- workOrder: "$metadata.workOrder",
2968
- approve: { $ifNull: ["$approve", null] },
2969
- reject: { $ifNull: ["$reject", null] }
2946
+ qty: 1
2970
2947
  }
2971
2948
  },
2972
2949
  { $sort: { _id: -1 } },
2973
2950
  { $skip: page * limit },
2974
2951
  { $limit: limit }
2975
- ];
2976
- const items = await collection.aggregate(pipeline).toArray();
2952
+ ]).toArray();
2977
2953
  const length = await collection.countDocuments(query);
2978
- const paginatedData = (0, import_node_server_utils17.paginate)(items, page, limit, length);
2979
- const data = {
2980
- attachments: areaAttachments,
2981
- ...paginatedData
2982
- };
2954
+ const data = (0, import_node_server_utils17.paginate)(items, page, limit, length);
2983
2955
  setCache(cacheKey, data, 15 * 60).then(() => {
2984
2956
  import_node_server_utils17.logger.info(`Cache set for key: ${cacheKey}`);
2985
2957
  }).catch((err) => {
@@ -2990,78 +2962,58 @@ function useUnitChecklistRepo() {
2990
2962
  throw error;
2991
2963
  }
2992
2964
  }
2993
- async function getUnitChecklistById(_id) {
2965
+ async function updateSupply(_id, value, session) {
2994
2966
  try {
2995
2967
  _id = new import_mongodb10.ObjectId(_id);
2996
2968
  } catch (error) {
2997
- throw new import_node_server_utils17.BadRequestError("Invalid unit checklist ID format.");
2969
+ throw new import_node_server_utils17.BadRequestError("Invalid supply ID format.");
2998
2970
  }
2999
2971
  try {
3000
- return await collection.findOne({ _id });
2972
+ const updateValue = { ...value, updatedAt: /* @__PURE__ */ new Date() };
2973
+ const res = await collection.updateOne(
2974
+ { _id },
2975
+ { $set: updateValue },
2976
+ { session }
2977
+ );
2978
+ if (res.modifiedCount === 0) {
2979
+ throw new import_node_server_utils17.InternalServerError("Unable to update cleaning supply.");
2980
+ }
2981
+ delNamespace().then(() => {
2982
+ import_node_server_utils17.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
2983
+ }).catch((err) => {
2984
+ import_node_server_utils17.logger.error(
2985
+ `Failed to clear cache for namespace: ${namespace_collection}`,
2986
+ err
2987
+ );
2988
+ });
2989
+ return res.modifiedCount;
3001
2990
  } catch (error) {
2991
+ const isDuplicated = error.message.includes("duplicate");
2992
+ if (isDuplicated) {
2993
+ throw new import_node_server_utils17.BadRequestError("Area already exists.");
2994
+ }
3002
2995
  throw error;
3003
2996
  }
3004
2997
  }
3005
- async function updateUnitChecklist(_id, value, session) {
2998
+ async function deleteSupply(_id, session) {
3006
2999
  try {
3007
3000
  _id = new import_mongodb10.ObjectId(_id);
3008
3001
  } catch (error) {
3009
- throw new import_node_server_utils17.BadRequestError("Invalid unit checklist ID format.");
3010
- }
3011
- if (value.checkedBy && typeof value.checkedBy === "string") {
3012
- try {
3013
- value.checkedBy = new import_mongodb10.ObjectId(value.checkedBy);
3014
- } catch (error) {
3015
- throw new import_node_server_utils17.BadRequestError("Invalid checkedBy ID format.");
3016
- }
3017
- }
3018
- if ("metadata" in value && value.metadata?.workOrder) {
3019
- const workOrder = value.metadata.workOrder;
3020
- if (workOrder.category && typeof workOrder.category === "string") {
3021
- try {
3022
- workOrder.category = new import_mongodb10.ObjectId(workOrder.category);
3023
- } catch (error) {
3024
- throw new import_node_server_utils17.BadRequestError("Invalid category ID format.");
3025
- }
3026
- }
3027
- if (workOrder.createdBy && typeof workOrder.createdBy === "string") {
3028
- try {
3029
- workOrder.createdBy = new import_mongodb10.ObjectId(workOrder.createdBy);
3030
- } catch (error) {
3031
- throw new import_node_server_utils17.BadRequestError("Invalid createdBy ID format.");
3032
- }
3033
- }
3034
- if (workOrder.serviceProvider && typeof workOrder.serviceProvider === "string") {
3035
- try {
3036
- workOrder.serviceProvider = new import_mongodb10.ObjectId(workOrder.serviceProvider);
3037
- } catch (error) {
3038
- throw new import_node_server_utils17.BadRequestError("Invalid serviceProvider ID format.");
3039
- }
3040
- }
3041
- if (workOrder.organization && typeof workOrder.organization === "string") {
3042
- try {
3043
- workOrder.organization = new import_mongodb10.ObjectId(workOrder.organization);
3044
- } catch (error) {
3045
- throw new import_node_server_utils17.BadRequestError("Invalid organization ID format.");
3046
- }
3047
- }
3048
- if (workOrder.site && typeof workOrder.site === "string") {
3049
- try {
3050
- workOrder.site = new import_mongodb10.ObjectId(workOrder.site);
3051
- } catch (error) {
3052
- throw new import_node_server_utils17.BadRequestError("Invalid site ID format.");
3053
- }
3054
- }
3002
+ throw new import_node_server_utils17.BadRequestError("Invalid supply ID format.");
3055
3003
  }
3056
3004
  try {
3057
- const updateValue = { ...value, updatedAt: /* @__PURE__ */ new Date() };
3005
+ const updateValue = {
3006
+ status: "deleted",
3007
+ updatedAt: /* @__PURE__ */ new Date(),
3008
+ deletedAt: /* @__PURE__ */ new Date()
3009
+ };
3058
3010
  const res = await collection.updateOne(
3059
3011
  { _id },
3060
3012
  { $set: updateValue },
3061
3013
  { session }
3062
3014
  );
3063
3015
  if (res.modifiedCount === 0) {
3064
- throw new import_node_server_utils17.InternalServerError("Unable to update unit checklist.");
3016
+ throw new import_node_server_utils17.InternalServerError("Unable to delete supply.");
3065
3017
  }
3066
3018
  delNamespace().then(() => {
3067
3019
  import_node_server_utils17.logger.info(`Cache cleared for namespace: ${namespace_collection}`);
@@ -3079,236 +3031,126 @@ function useUnitChecklistRepo() {
3079
3031
  return {
3080
3032
  createIndex,
3081
3033
  createTextIndex,
3082
- createUnitChecklist,
3083
- getAllUnitChecklist,
3084
- getUnitChecklistById,
3085
- updateUnitChecklist
3034
+ createUniqueIndex,
3035
+ createSupply,
3036
+ getSupplies,
3037
+ updateSupply,
3038
+ deleteSupply
3086
3039
  };
3087
3040
  }
3088
3041
 
3089
- // src/controllers/hygiene-unit-checklist.controller.ts
3090
- var import_node_server_utils19 = require("@iservice365/node-server-utils");
3091
- var import_joi10 = __toESM(require("joi"));
3092
-
3093
- // src/services/hygiene-unit-checklist.service.ts
3042
+ // src/controllers/hygiene-supply.controller.ts
3094
3043
  var import_node_server_utils18 = require("@iservice365/node-server-utils");
3095
- var import_core = require("@iservice365/core");
3096
- function useUnitChecklistService() {
3097
- const {
3098
- getUnitChecklistById: _getUnitChecklistById,
3099
- updateUnitChecklist: _updateUnitChecklist
3100
- } = useUnitChecklistRepo();
3101
- const { getSiteById } = (0, import_core.useSiteRepo)();
3102
- const { createWorkOrder } = (0, import_core.useWorkOrderService)();
3103
- async function approveUnitChecklist(id, value) {
3104
- try {
3105
- value.approve = true;
3106
- value.reject = false;
3107
- const result = await _updateUnitChecklist(id, value);
3108
- return result;
3109
- } catch (error) {
3110
- import_node_server_utils18.logger.error(`Error updating unit checklist with id ${id}:`, error);
3111
- throw error;
3112
- }
3113
- }
3114
- async function rejectUnitChecklist(id, value, fullHost) {
3115
- try {
3116
- value.reject = true;
3117
- value.approve = false;
3118
- if (value.metadata?.workOrder) {
3119
- const existingChecklist = await _getUnitChecklistById(id);
3120
- if (!existingChecklist)
3121
- throw new import_node_server_utils18.NotFoundError("Unit checklist not found.");
3122
- const site = await getSiteById(
3123
- existingChecklist.site
3124
- );
3125
- if (!site)
3126
- throw new import_node_server_utils18.NotFoundError("Site not found.");
3127
- const workOrderData = {
3128
- ...value.metadata.workOrder,
3129
- attachments: value.metadata.attachments,
3130
- createdBy: value.checkedBy,
3131
- organization: site.orgId,
3132
- site: site._id
3133
- };
3134
- const workOrder = await createWorkOrder(
3135
- workOrderData,
3136
- fullHost
3137
- );
3138
- if (!workOrder)
3139
- throw new import_node_server_utils18.NotFoundError("Failed to create work order.");
3140
- }
3141
- const result = await _updateUnitChecklist(id, value);
3142
- return result;
3143
- } catch (error) {
3144
- import_node_server_utils18.logger.error(`Error updating unit checklist with id ${id}:`, error);
3145
- throw error;
3146
- }
3147
- }
3148
- return {
3149
- approveUnitChecklist,
3150
- rejectUnitChecklist
3151
- };
3152
- }
3153
-
3154
- // src/controllers/hygiene-unit-checklist.controller.ts
3155
- var import_core2 = require("@iservice365/core");
3156
- function useUnitChecklistController() {
3157
- const {
3158
- createUnitChecklist: _createUnitChecklist,
3159
- getAllUnitChecklist: _getAllUnitChecklist
3160
- } = useUnitChecklistRepo();
3044
+ var import_joi10 = __toESM(require("joi"));
3045
+ function useSupplyController() {
3161
3046
  const {
3162
- approveUnitChecklist: _approveUnitChecklist,
3163
- rejectUnitChecklist: _rejectUnitChecklist
3164
- } = useUnitChecklistService();
3165
- async function createUnitChecklist(req, res, next) {
3166
- const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
3167
- (acc, [key, value]) => ({ ...acc, [key]: value }),
3168
- {}
3169
- ) : {};
3170
- const createdBy = cookies["user"] || "";
3171
- const payload = { ...req.body, ...req.params, createdBy };
3172
- const { error } = unitChecklistSchema.validate(payload);
3047
+ createSupply: _createSupply,
3048
+ getSupplies: _getSupplies,
3049
+ updateSupply: _updateSupply,
3050
+ deleteSupply: _deleteSupply
3051
+ } = useSupplyRepository();
3052
+ async function createSupply(req, res, next) {
3053
+ const payload = { ...req.body, ...req.params };
3054
+ const { error } = supplySchema.validate(payload);
3173
3055
  if (error) {
3174
- import_node_server_utils19.logger.log({ level: "error", message: error.message });
3175
- next(new import_node_server_utils19.BadRequestError(error.message));
3056
+ import_node_server_utils18.logger.log({ level: "error", message: error.message });
3057
+ next(new import_node_server_utils18.BadRequestError(error.message));
3176
3058
  return;
3177
3059
  }
3178
3060
  try {
3179
- const id = await _createUnitChecklist(payload);
3180
- res.status(201).json({ message: "Unit checklist created successfully.", id });
3061
+ const id = await _createSupply(payload);
3062
+ res.status(201).json({ message: "Supply created successfully.", id });
3181
3063
  return;
3182
3064
  } catch (error2) {
3183
- import_node_server_utils19.logger.log({ level: "error", message: error2.message });
3065
+ import_node_server_utils18.logger.log({ level: "error", message: error2.message });
3184
3066
  next(error2);
3185
3067
  return;
3186
3068
  }
3187
3069
  }
3188
- async function getAllUnitChecklist(req, res, next) {
3070
+ async function getSupplies(req, res, next) {
3189
3071
  const query = { ...req.query, ...req.params };
3190
3072
  const validation = import_joi10.default.object({
3191
3073
  page: import_joi10.default.number().min(1).optional().allow("", null),
3192
3074
  limit: import_joi10.default.number().min(1).optional().allow("", null),
3193
3075
  search: import_joi10.default.string().optional().allow("", null),
3194
- site: import_joi10.default.string().hex().required(),
3195
- type: import_joi10.default.string().valid(...allowedTypes).required(),
3196
- parentChecklist: import_joi10.default.string().hex().required(),
3197
- areaChecklist: import_joi10.default.string().hex().required()
3076
+ site: import_joi10.default.string().hex().required()
3198
3077
  });
3199
3078
  const { error } = validation.validate(query);
3200
3079
  if (error) {
3201
- import_node_server_utils19.logger.log({ level: "error", message: error.message });
3202
- next(new import_node_server_utils19.BadRequestError(error.message));
3080
+ import_node_server_utils18.logger.log({ level: "error", message: error.message });
3081
+ next(new import_node_server_utils18.BadRequestError(error.message));
3203
3082
  return;
3204
3083
  }
3205
3084
  const page = parseInt(req.query.page) ?? 1;
3206
3085
  const limit = parseInt(req.query.limit) ?? 20;
3207
3086
  const search = req.query.search ?? "";
3208
3087
  const site = req.params.site ?? "";
3209
- const type = req.params.type ?? "";
3210
- const parentChecklist = req.params.parentChecklist ?? "";
3211
- const areaChecklist = req.params.areaChecklist ?? "";
3212
3088
  try {
3213
- const data = await _getAllUnitChecklist({
3089
+ const data = await _getSupplies({
3214
3090
  page,
3215
3091
  limit,
3216
3092
  search,
3217
- site,
3218
- type,
3219
- parentChecklist,
3220
- areaChecklist
3093
+ site
3221
3094
  });
3222
3095
  res.json(data);
3223
3096
  return;
3224
3097
  } catch (error2) {
3225
- import_node_server_utils19.logger.log({ level: "error", message: error2.message });
3098
+ import_node_server_utils18.logger.log({ level: "error", message: error2.message });
3226
3099
  next(error2);
3227
3100
  return;
3228
3101
  }
3229
3102
  }
3230
- async function approveUnitChecklist(req, res, next) {
3231
- const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
3232
- (acc, [key, value]) => ({ ...acc, [key]: value }),
3233
- {}
3234
- ) : {};
3235
- const checkedBy = cookies["user"] || "";
3236
- const payload = { id: req.params.id, checkedBy };
3103
+ async function updateSupply(req, res, next) {
3104
+ const payload = { id: req.params.id, ...req.body };
3237
3105
  const validation = import_joi10.default.object({
3238
3106
  id: import_joi10.default.string().hex().required(),
3239
- checkedBy: import_joi10.default.string().hex().required()
3107
+ name: import_joi10.default.string().optional().allow("", null),
3108
+ unitOfMeasurement: import_joi10.default.string().optional().allow("", null),
3109
+ qty: import_joi10.default.number().min(0).optional().allow("", null)
3240
3110
  });
3241
3111
  const { error } = validation.validate(payload);
3242
3112
  if (error) {
3243
- import_node_server_utils19.logger.log({ level: "error", message: error.message });
3244
- next(new import_node_server_utils19.BadRequestError(error.message));
3113
+ import_node_server_utils18.logger.log({ level: "error", message: error.message });
3114
+ next(new import_node_server_utils18.BadRequestError(error.message));
3245
3115
  return;
3246
3116
  }
3247
3117
  try {
3248
3118
  const { id, ...value } = payload;
3249
- await _approveUnitChecklist(id, value);
3250
- res.json({ message: "Unit checklist approved successfully." });
3119
+ await _updateSupply(id, value);
3120
+ res.json({ message: "Supply updated successfully." });
3251
3121
  return;
3252
3122
  } catch (error2) {
3253
- import_node_server_utils19.logger.log({ level: "error", message: error2.message });
3123
+ import_node_server_utils18.logger.log({ level: "error", message: error2.message });
3254
3124
  next(error2);
3255
3125
  return;
3256
3126
  }
3257
3127
  }
3258
- async function rejectUnitChecklist(req, res, next) {
3259
- const cookies = req.headers.cookie ? req.headers.cookie.split(";").map((cookie) => cookie.trim().split("=")).reduce(
3260
- (acc, [key, value]) => ({ ...acc, [key]: value }),
3261
- {}
3262
- ) : {};
3263
- const checkedBy = cookies["user"] || "";
3264
- if (req.body.workOrder) {
3265
- req.body.workOrder.createdBy = checkedBy;
3266
- }
3267
- const payload = { id: req.params.id, checkedBy, ...req.body };
3128
+ async function deleteSupply(req, res, next) {
3129
+ const id = req.params.id;
3268
3130
  const validation = import_joi10.default.object({
3269
- id: import_joi10.default.string().hex().required(),
3270
- attachments: import_joi10.default.array().items(import_joi10.default.string()).optional(),
3271
- remarks: import_joi10.default.string().required(),
3272
- workOrder: import_core2.workOrderSchema.optional(),
3273
- checkedBy: import_joi10.default.string().hex().required()
3131
+ id: import_joi10.default.string().hex().required()
3274
3132
  });
3275
- const { error } = validation.validate(payload);
3133
+ const { error } = validation.validate({ id });
3276
3134
  if (error) {
3277
- import_node_server_utils19.logger.log({ level: "error", message: error.message });
3278
- next(new import_node_server_utils19.BadRequestError(error.message));
3135
+ import_node_server_utils18.logger.log({ level: "error", message: error.message });
3136
+ next(new import_node_server_utils18.BadRequestError(error.message));
3279
3137
  return;
3280
3138
  }
3281
3139
  try {
3282
- const { id, attachments, remarks, workOrder, ...value } = payload;
3283
- value.metadata = {
3284
- attachments: attachments || [],
3285
- remarks: remarks || "",
3286
- workOrder
3287
- };
3288
- if (value.metadata.workOrder) {
3289
- if (value.metadata.workOrder.category) {
3290
- value.metadata.workOrder.category = value.metadata.workOrder.category;
3291
- }
3292
- if (value.metadata.workOrder.serviceProvider) {
3293
- value.metadata.workOrder.serviceProvider = value.metadata.workOrder.serviceProvider;
3294
- }
3295
- value.metadata.workOrder.createdBy = checkedBy;
3296
- }
3297
- const fullHost = req.headers.origin;
3298
- await _rejectUnitChecklist(id, value, fullHost);
3299
- res.json({ message: "Unit checklist rejected successfully." });
3140
+ await _deleteSupply(id);
3141
+ res.json({ message: "Supply deleted successfully." });
3300
3142
  return;
3301
3143
  } catch (error2) {
3302
- import_node_server_utils19.logger.log({ level: "error", message: error2.message });
3144
+ import_node_server_utils18.logger.log({ level: "error", message: error2.message });
3303
3145
  next(error2);
3304
3146
  return;
3305
3147
  }
3306
3148
  }
3307
3149
  return {
3308
- createUnitChecklist,
3309
- getAllUnitChecklist,
3310
- approveUnitChecklist,
3311
- rejectUnitChecklist
3150
+ createSupply,
3151
+ getSupplies,
3152
+ updateSupply,
3153
+ deleteSupply
3312
3154
  };
3313
3155
  }
3314
3156
  // Annotate the CommonJS export names for ESM import in node:
@@ -3316,23 +3158,26 @@ function useUnitChecklistController() {
3316
3158
  MArea,
3317
3159
  MAreaChecklist,
3318
3160
  MParentChecklist,
3161
+ MSupply,
3319
3162
  MUnit,
3320
- MUnitChecklist,
3321
3163
  allowedChecklistStatus,
3164
+ allowedStatus,
3165
+ allowedTypes,
3322
3166
  areaChecklistSchema,
3323
3167
  areaSchema,
3324
3168
  parentChecklistSchema,
3325
- unitChecklistSchema,
3169
+ supplySchema,
3326
3170
  unitSchema,
3327
3171
  useAreaChecklistController,
3328
3172
  useAreaChecklistRepo,
3173
+ useAreaChecklistService,
3329
3174
  useAreaController,
3330
3175
  useAreaRepo,
3331
3176
  useAreaService,
3332
3177
  useParentChecklistController,
3333
3178
  useParentChecklistRepo,
3334
- useUnitChecklistController,
3335
- useUnitChecklistRepo,
3179
+ useSupplyController,
3180
+ useSupplyRepository,
3336
3181
  useUnitController,
3337
3182
  useUnitRepository,
3338
3183
  useUnitService