Skip to content

Commit c3766ca

Browse files
Merge pull request #2044 from OneCommunityGlobal/SaiKrishna_UpdateHistoryButtonBackend
SaiKrishna Update History Button Backend Changes
2 parents 3029168 + 9fd499a commit c3766ca

6 files changed

Lines changed: 148 additions & 1 deletion

File tree

src/controllers/bmdashboard/__tests__/bmConsumableController.test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
const mongoose = require('mongoose');
22
const bmConsumableController = require('../bmConsumableController');
33

4+
jest.mock('../../../models/bmdashboard/updateHistory', () => ({
5+
create: jest.fn().mockResolvedValue({}),
6+
}));
7+
8+
const flushPromises = () => new Promise(setImmediate);
9+
410
mongoose.Types.ObjectId = jest.fn((id) => id);
511

612
const mockBuildingConsumable = {
@@ -139,6 +145,7 @@ describe('Building Consumable Controller', () => {
139145
mockBuildingConsumable.updateOne.mockResolvedValue({});
140146

141147
await controller.bmPostConsumableUpdateRecord(mockRequest, mockResponse);
148+
await flushPromises();
142149

143150
expect(mockBuildingConsumable.updateOne).toHaveBeenCalledWith(
144151
{ _id: '123' },
@@ -175,6 +182,7 @@ describe('Building Consumable Controller', () => {
175182
mockBuildingConsumable.updateOne.mockResolvedValue({});
176183

177184
await controller.bmPostConsumableUpdateRecord(percentRequest, mockResponse);
185+
await flushPromises();
178186

179187
const expectedUsed = 10; // 10% of 100
180188
const expectedWasted = 5; // 5% of 100

src/controllers/bmdashboard/bmConsumableController.js

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const mongoose = require('mongoose');
2+
const UpdateHistory = require('../../models/bmdashboard/updateHistory');
23

34
const bmConsumableController = function (BuildingConsumable) {
45
const fetchBMConsumables = async (req, res) => {
@@ -138,7 +139,46 @@ const bmConsumableController = function (BuildingConsumable) {
138139
},
139140
},
140141
)
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+
142182
res.status(200).send(results);
143183
})
144184
.catch((error) => {
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const UpdateHistory = require('../../models/bmdashboard/updateHistory');
2+
3+
const bmUpdateHistoryController = function () {
4+
// GET /api/bm/consumables/updateHistory
5+
const getConsumablesUpdateHistory = async (req, res) => {
6+
try {
7+
const history = await UpdateHistory.find({ itemType: 'consumable' })
8+
.populate('modifiedBy', 'firstName lastName _id')
9+
.sort({ date: -1 })
10+
.limit(500);
11+
12+
// Format response for frontend display
13+
const formattedHistory = history.map((record) => ({
14+
_id: record._id,
15+
date: record.date,
16+
itemName: record.itemName,
17+
projectName: record.projectName,
18+
changes: record.changes,
19+
modifiedBy: record.modifiedBy,
20+
}));
21+
22+
res.status(200).json(formattedHistory);
23+
} catch (error) {
24+
res.status(500).json({ message: 'Error fetching update history', error: error.message });
25+
}
26+
};
27+
28+
return {
29+
getConsumablesUpdateHistory,
30+
};
31+
};
32+
33+
module.exports = bmUpdateHistoryController;
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const mongoose = require('mongoose');
2+
3+
/**
4+
* UpdateHistory Schema
5+
* Tracks all modifications made to consumables (1 entry per update action)
6+
*/
7+
const updateHistorySchema = new mongoose.Schema({
8+
itemType: {
9+
type: String,
10+
enum: ['consumable', 'material', 'reusable', 'equipment', 'tool'],
11+
required: true,
12+
},
13+
itemId: {
14+
type: mongoose.SchemaTypes.ObjectId,
15+
required: true,
16+
ref: 'smallItemBase',
17+
},
18+
itemName: {
19+
type: String,
20+
required: true,
21+
},
22+
projectId: {
23+
type: mongoose.SchemaTypes.ObjectId,
24+
ref: 'buildingProject',
25+
},
26+
projectName: {
27+
type: String,
28+
},
29+
changes: {
30+
type: mongoose.Schema.Types.Mixed, // { stockUsed: {old, new}, stockWasted: {old, new}, ... }
31+
required: true,
32+
},
33+
modifiedBy: {
34+
type: mongoose.SchemaTypes.ObjectId,
35+
ref: 'userProfile',
36+
required: true,
37+
},
38+
date: {
39+
type: Date,
40+
default: Date.now,
41+
},
42+
});
43+
44+
updateHistorySchema.index({ itemType: 1, date: -1 });
45+
updateHistorySchema.index({ itemId: 1, date: -1 });
46+
47+
const UpdateHistory = mongoose.model('UpdateHistory', updateHistorySchema, 'updateHistory');
48+
49+
module.exports = UpdateHistory;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const express = require('express');
2+
3+
const routes = function () {
4+
const updateHistoryRouter = express.Router();
5+
const controller = require('../../controllers/bmdashboard/bmUpdateHistoryController')();
6+
7+
// GET /api/bm/consumables/updateHistory
8+
updateHistoryRouter
9+
.route('/consumables/updateHistory')
10+
.get(controller.getConsumablesUpdateHistory);
11+
12+
return updateHistoryRouter;
13+
};
14+
15+
module.exports = routes;

src/startup/routes.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ const biddingRouter = require('../routes/lbdashboard/biddingRouter')(biddingHome
239239
const titleRouter = require('../routes/titleRouter')(title);
240240
const bmToolRouter = require('../routes/bmdashboard/bmToolRouter')(buildingTool, toolType);
241241
const bmEquipmentRouter = require('../routes/bmdashboard/bmEquipmentRouter')(buildingEquipment);
242+
const bmUpdateHistoryRouter = require('../routes/bmdashboard/bmUpdateHistoryRouter')();
242243
const buildingIssue = require('../models/bmdashboard/buildingIssue');
243244
const bmIssueRouter = require('../routes/bmdashboard/bmIssueRouter')(buildingIssue);
244245
const bmInjuryRouter = require('../routes/bmdashboard/bmInjuryRouter')(injujrySeverity);
@@ -472,6 +473,7 @@ module.exports = function (app) {
472473
app.use('/api/bm', bmToolRouter);
473474
app.use('/api/bm', bmEquipmentRouter);
474475
app.use('/api/bm', bmConsumablesRouter);
476+
app.use('/api/bm', bmUpdateHistoryRouter);
475477
app.use('/api/dropbox', dropboxRouter);
476478
app.use('/api/github', githubRouter);
477479
app.use('/api/sentry', sentryRouter);

0 commit comments

Comments
 (0)