|
| 1 | +const mongoose = require('mongoose'); |
| 2 | +const InjuryOverTime = require('../../models/bmdashboard/buildingInjuryOverTime'); |
| 3 | + |
| 4 | +const parseCommaSeparatedValues = (value, mapper = (item) => item) => |
| 5 | + value |
| 6 | + .split(',') |
| 7 | + .map((item) => item.trim()) |
| 8 | + .filter(Boolean) |
| 9 | + .map(mapper); |
| 10 | + |
| 11 | +exports.getInjuryOverTime = async (req, res) => { |
| 12 | + try { |
| 13 | + const { projectIds, startDate, endDate, types, departments, severities } = req.query; |
| 14 | + |
| 15 | + const query = {}; |
| 16 | + |
| 17 | + if (projectIds) { |
| 18 | + const projectIdArray = parseCommaSeparatedValues(projectIds); |
| 19 | + |
| 20 | + if (!projectIdArray.every((id) => mongoose.Types.ObjectId.isValid(id))) { |
| 21 | + return res.status(400).json({ error: 'One or more projectIds are invalid' }); |
| 22 | + } |
| 23 | + |
| 24 | + query.projectId = { |
| 25 | + $in: projectIdArray.map((id) => mongoose.Types.ObjectId(id)), |
| 26 | + }; |
| 27 | + } |
| 28 | + |
| 29 | + if (startDate && endDate) { |
| 30 | + query.date = { |
| 31 | + $gte: new Date(startDate), |
| 32 | + $lte: new Date(endDate), |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + if (types) { |
| 37 | + query.injuryType = { $in: parseCommaSeparatedValues(types) }; |
| 38 | + } |
| 39 | + |
| 40 | + if (departments) { |
| 41 | + query.department = { $in: parseCommaSeparatedValues(departments) }; |
| 42 | + } |
| 43 | + |
| 44 | + if (severities) { |
| 45 | + query.severity = { $in: parseCommaSeparatedValues(severities) }; |
| 46 | + } |
| 47 | + |
| 48 | + const injuries = await InjuryOverTime.aggregate([ |
| 49 | + { $match: query }, |
| 50 | + { |
| 51 | + $group: { |
| 52 | + _id: { |
| 53 | + projectId: '$projectId', |
| 54 | + severity: '$severity', |
| 55 | + injuryType: '$injuryType', |
| 56 | + department: '$department', |
| 57 | + month: { |
| 58 | + $dateToString: { |
| 59 | + format: '%Y-%m-01', |
| 60 | + date: '$date', |
| 61 | + }, |
| 62 | + }, |
| 63 | + }, |
| 64 | + count: { $sum: '$count' }, |
| 65 | + }, |
| 66 | + }, |
| 67 | + { |
| 68 | + $project: { |
| 69 | + _id: 0, |
| 70 | + projectId: '$_id.projectId', |
| 71 | + severity: '$_id.severity', |
| 72 | + injuryType: '$_id.injuryType', |
| 73 | + department: '$_id.department', |
| 74 | + date: { $toDate: '$_id.month' }, |
| 75 | + count: 1, |
| 76 | + }, |
| 77 | + }, |
| 78 | + { |
| 79 | + $sort: { |
| 80 | + date: 1, |
| 81 | + projectId: 1, |
| 82 | + severity: 1, |
| 83 | + injuryType: 1, |
| 84 | + department: 1, |
| 85 | + }, |
| 86 | + }, |
| 87 | + ]); |
| 88 | + |
| 89 | + res.status(200).json(injuries); |
| 90 | + } catch (err) { |
| 91 | + console.error(err); |
| 92 | + res.status(500).json({ error: 'Internal server error' }); |
| 93 | + } |
| 94 | +}; |
0 commit comments