|
1 | 1 | const mongoose = require('mongoose'); |
| 2 | +const UpdateHistory = require('../../models/bmdashboard/updateHistory'); |
2 | 3 |
|
3 | 4 | const bmConsumableController = function (BuildingConsumable) { |
4 | 5 | const fetchBMConsumables = async (req, res) => { |
@@ -138,7 +139,46 @@ const bmConsumableController = function (BuildingConsumable) { |
138 | 139 | }, |
139 | 140 | }, |
140 | 141 | ) |
141 | | - .then((results) => { |
| 142 | + .then(async (results) => { |
| 143 | + // Log update history - 1 entry per update action |
| 144 | + try { |
| 145 | + const itemName = consumable.itemType?.name || 'Unknown Consumable'; |
| 146 | + const projectName = consumable.project?.name || 'Unknown Project'; |
| 147 | + const changes = {}; |
| 148 | + |
| 149 | + if (consumable.stockUsed !== newStockUsed) { |
| 150 | + changes.stockUsed = { old: consumable.stockUsed, new: newStockUsed }; |
| 151 | + } |
| 152 | + if (consumable.stockWasted !== newStockWasted) { |
| 153 | + changes.stockWasted = { old: consumable.stockWasted, new: newStockWasted }; |
| 154 | + } |
| 155 | + if (stockAvailable !== newAvailable) { |
| 156 | + changes.stockAvailable = { old: stockAvailable, new: newAvailable }; |
| 157 | + } |
| 158 | + |
| 159 | + if (Object.keys(changes).length > 0) { |
| 160 | + console.log( |
| 161 | + '=== CREATING UPDATE HISTORY ===', |
| 162 | + new Date().toISOString(), |
| 163 | + itemName, |
| 164 | + projectName, |
| 165 | + ); |
| 166 | + await UpdateHistory.create({ |
| 167 | + itemType: 'consumable', |
| 168 | + itemId: consumable._id, |
| 169 | + itemName, |
| 170 | + projectId: consumable.project?._id || consumable.project, |
| 171 | + projectName, |
| 172 | + changes, |
| 173 | + modifiedBy: req.body.requestor.requestorId, |
| 174 | + date: new Date(), |
| 175 | + }); |
| 176 | + console.log('=== UPDATE HISTORY CREATED ==='); |
| 177 | + } |
| 178 | + } catch (historyError) { |
| 179 | + console.log('Error logging update history:', historyError); |
| 180 | + } |
| 181 | + |
142 | 182 | res.status(200).send(results); |
143 | 183 | }) |
144 | 184 | .catch((error) => { |
|
0 commit comments