-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbmFinancialController.js
More file actions
303 lines (257 loc) · 9.68 KB
/
bmFinancialController.js
File metadata and controls
303 lines (257 loc) · 9.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
const logger = require('../../startup/logger');
const bmFinancialController = function (BuildingProject, BuildingMaterial, BuildingTool) {
const mongoose = require('mongoose');
const calculateLaborCost = async (projectId, hourlyRate = 25) => {
try {
const project = await BuildingProject.findById(projectId);
if (!project || !Array.isArray(project.members)) {
return 0;
}
let totalLaborCost = 0;
project.members.forEach((member) => {
const hoursWorked = member.hours || 0;
totalLaborCost += hoursWorked * hourlyRate;
});
return totalLaborCost;
} catch (err) {
console.error('Error calculating labor cost:', err);
throw err;
}
};
const calculateMaterialsCost = async (projectId) => {
try {
const materials = await BuildingMaterial.find({ project: projectId });
let totalCost = 0;
if (!materials.length) {
console.log('No materials found for project:', projectId);
}
materials.forEach((material) => {
if (Array.isArray(material.purchaseRecord)) {
material.purchaseRecord.forEach((record) => {
const { quantity = 0, unitPrice = 0, status } = record;
if (status?.trim().toLowerCase() === 'approved') {
totalCost += quantity * unitPrice;
}
});
}
});
return totalCost;
} catch (err) {
console.error('Error calculating materials cost:', err);
throw err;
}
};
const calculateToolsCost = async (projectId) => {
try {
const tools = await BuildingTool.find({ project: projectId });
let totalCost = 0;
if (!tools.length) {
console.log(`No tools found for project: ${projectId}`);
}
tools.forEach((tool) => {
if (Array.isArray(tool.purchaseRecord)) {
tool.purchaseRecord.forEach((record) => {
const quantity = record.quantity ?? 0;
const unitPrice = record.unitPrice ?? 0;
const status = record.status ?? '';
if (status.trim().toLowerCase() === 'approved') {
totalCost += quantity * unitPrice;
}
});
}
});
console.log('Total tools cost:', totalCost);
return totalCost;
} catch (err) {
console.error('Error calculating tools cost:', err);
throw err;
}
};
const getMonthOverMonthChanges = async (req, res) => {
try {
const { projectId } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
return res.status(400).json({ message: 'Invalid project ID' });
}
const projectObjectId = new mongoose.Types.ObjectId(projectId);
const now = new Date();
const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const lastMonthStart = new Date(thisMonthStart);
lastMonthStart.setMonth(thisMonthStart.getMonth() - 1);
const monthEnd = (monthStart) => {
const end = new Date(monthStart);
end.setMonth(end.getMonth() + 1);
return end;
};
const [materialDocs, toolDocs] = await Promise.all([
BuildingMaterial.find({ project: projectObjectId }),
BuildingTool.find({ project: projectObjectId }),
]);
const calculateCost = (docs, monthStart) => {
let cost = 0;
const end = monthEnd(monthStart);
docs.forEach((doc) => {
if (!Array.isArray(doc.purchaseRecord)) return;
doc.purchaseRecord.forEach((record) => {
const rDate = new Date(record.date);
if (
record.status === 'Approved' &&
!Number.isNaN(rDate) &&
rDate >= monthStart &&
rDate < end
) {
cost += (record.quantity || 0) * (record.unitPrice || 0);
}
});
});
return cost;
};
const thisMonthMaterialCost = calculateCost(materialDocs, thisMonthStart);
const lastMonthMaterialCost = calculateCost(materialDocs, lastMonthStart);
const thisMonthToolCost = calculateCost(toolDocs, thisMonthStart);
const lastMonthToolCost = calculateCost(toolDocs, lastMonthStart);
const thisMonthLaborCost = await calculateLaborCost(projectObjectId);
const lastMonthLaborCost = thisMonthLaborCost; // Replace with actual last month logic if available
const calcMoMChange = (current, previous) => {
if (previous === 0) return current === 0 ? 0 : 100;
return ((current - previous) / previous) * 100;
};
res.status(200).json({
materialCostChange: parseFloat(
calcMoMChange(thisMonthMaterialCost, lastMonthMaterialCost).toFixed(2),
),
laborCostChange: parseFloat(
calcMoMChange(thisMonthLaborCost, lastMonthLaborCost).toFixed(2),
),
equipmentCostChange: parseFloat(
calcMoMChange(thisMonthToolCost, lastMonthToolCost).toFixed(2),
),
});
} catch (err) {
res.status(500).json({ message: 'Internal server error' });
}
};
const getProjectsFinancialsByType = async (req, res) => {
try {
const { projectType } = req.query;
const projects = await BuildingProject.find({ projectType });
const results = await Promise.all(
projects.map(async (project) => {
let materialsCost = 0;
let toolsCost = 0;
let laborCost = 0;
try {
materialsCost = await calculateMaterialsCost(project._id);
} catch (error) {
logger.logException(
`Materials cost error for project ${project._id}: ${error.message}`,
);
}
try {
toolsCost = await calculateToolsCost(project._id);
} catch (error) {
logger.logException(`Tools cost error for project ${project._id}: ${error.message}`);
}
try {
laborCost = await calculateLaborCost(project._id);
} catch (error) {
logger.logException(`Labor cost error for project ${project._id}: ${error.message}`);
}
return {
projectId: project._id,
totalCost: materialsCost + toolsCost + laborCost,
materialCost: materialsCost,
laborCost,
equipmentCost: toolsCost,
};
}),
);
res.status(200).json(results);
} catch (err) {
logger.logException(`Error fetching financial data by project type: ${err.message}`);
res.status(500).json({ message: 'Internal server error' });
}
};
const getProjectsFinancialsByDateRange = async (req, res) => {
try {
const { startDate, endDate } = req.query;
const start = new Date(startDate);
const end = new Date(endDate);
const projects = await BuildingProject.find({ dateCreated: { $gte: start, $lte: end } });
const results = await Promise.all(
projects.map(async (project) => {
const materialsCost = await calculateMaterialsCost(project._id);
const toolsCost = await calculateToolsCost(project._id);
const laborCost = await calculateLaborCost(project._id);
const totalCost = materialsCost + toolsCost + laborCost;
return {
projectId: project._id,
totalCost,
materialCost: materialsCost,
laborCost,
equipmentCost: toolsCost,
};
}),
);
res.status(200).json(results);
} catch (err) {
logger.logException(`Error fetching financial data by date range: ${err.message}`);
res.status(500).json({ message: 'Internal server error' });
}
};
const getTotalProjectCost = async (req, res) => {
try {
const { projectId } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
return res.status(400).json({ message: 'Invalid project ID' });
}
const project = await BuildingProject.findById(projectId);
if (!project) {
logger.logException(`Project with ID ${projectId} not found`);
return res.status(404).json({ message: 'Project not found' });
}
const materialsCost = await calculateMaterialsCost(project._id);
const toolsCost = await calculateToolsCost(project._id);
const laboorCost = await calculateLaborCost(project._id);
const totalCost = materialsCost + toolsCost + laboorCost;
res.status(200).json({
totalCost,
});
} catch (error) {
logger.logException(`Error fetching project cost: ${error.message}`);
res.status(500).json({ message: 'Internal server error' });
}
};
const getCostBreakdown = async (req, res) => {
try {
const { projectId } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
return res.status(400).json({ message: 'Invalid project ID' });
}
const project = await BuildingProject.findById(projectId);
if (!project) {
logger.logException(`Project with ID ${projectId} not found`);
return res.status(404).json({ message: 'Project not found' });
}
const materialsCost = await calculateMaterialsCost(project._id);
const toolsCost = await calculateToolsCost(project._id);
const laboorCost = await calculateLaborCost(project._id);
res.status(200).json({
materialsCost,
equipmentCost: toolsCost,
laborCost: laboorCost,
});
} catch (error) {
logger.logException(`Error fetching project cost breakdown: ${error.message}`);
res.status(500).json({ message: 'Internal server error' });
}
};
return {
getTotalProjectCost,
getCostBreakdown,
getMonthOverMonthChanges,
getProjectsFinancialsByType,
getProjectsFinancialsByDateRange,
};
};
module.exports = bmFinancialController;