-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbmIssueController.js
More file actions
169 lines (146 loc) · 5.23 KB
/
bmIssueController.js
File metadata and controls
169 lines (146 loc) · 5.23 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
const mongoose = require('mongoose');
// const BuildingIssue = require('../../models/bmdashboard/buildingIssue');
const BuildingProject = require('../../models/bmdashboard/buildingProject');
const bmIssueController = function (BuildingIssue) {
const bmGetIssue = async (req, res) => {
try {
BuildingIssue.find()
.populate()
.then((result) => res.status(200).send(result))
.catch((error) => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};
const bmGetIssueChart = async (req, res) => {
try {
const { issueType, year } = req.query;
const matchQuery = {}; // Initialize an empty match query object
// Apply filters if provided
if (issueType) {
matchQuery.issueType = issueType;
}
if (year) {
const startDate = new Date(`${year}-01-01T00:00:00Z`);
const endDate = new Date(`${year}-12-31T23:59:59Z`);
matchQuery.issueDate = { $gte: startDate, $lte: endDate }; // Filter based on issueDate
}
const aggregationPipeline = [
{ $match: matchQuery }, // Match the filtered data
{
$group: {
_id: { issueType: '$issueType', year: { $year: '$issueDate' } },
count: { $sum: 1 }, // Properly count occurrences
},
},
{
$group: {
_id: '$_id.issueType',
years: {
$push: {
year: '$_id.year',
count: '$count',
},
},
},
},
{ $sort: { _id: 1 } }, // Sort by issueType
];
const issues = await mongoose.model('buildingIssue').aggregate(aggregationPipeline); // Execute aggregation pipeline
// Format the result
const result = issues.reduce((acc, item) => {
const issueTypeKey = item._id;
acc[issueTypeKey] = {};
item.years.forEach((yearData) => {
acc[issueType][yearData.year] = yearData.count;
});
return acc;
}, {});
res.status(200).json(result); // Return the formatted result
} catch (error) {
console.error('Error fetching issues:', error);
res.status(500).json({ message: 'Server error', error });
}
};
const bmPostIssue = async (req, res) => {
try {
BuildingIssue.create(req.body)
.then((result) => res.status(201).send(result))
.catch((error) => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};
const getLongestOpenIssues = async (req, res) => {
try {
const { dates, projects } = req.query;
// dates = '2021-10-01,2023-11-03';
// projects = '654946c8bc5772e8caf7e963';
const query = { status: 'open' };
let filteredProjectIds = [];
// Parse project filter if provided
if (projects) {
filteredProjectIds = projects.split(',').map((id) => id.trim());
}
// Apply date filtering logic
if (dates) {
const [startDateStr, endDateStr] = dates.split(',').map((d) => d.trim());
const startDate = new Date(startDateStr);
const endDate = new Date(endDateStr);
const matchingProjects = await BuildingProject.find({
dateCreated: { $gte: startDate, $lte: endDate },
isActive: true,
})
.select('_id')
.lean();
const dateFilteredIds = matchingProjects.map((p) => p._id.toString());
if (filteredProjectIds.length > 0) {
// Intersection of project filters
filteredProjectIds = filteredProjectIds.filter((id) => dateFilteredIds.includes(id));
} else {
filteredProjectIds = dateFilteredIds;
}
}
// If no matching project IDs, return early
if (dates && filteredProjectIds.length === 0) {
return res.json([]); // No results to return
}
if (filteredProjectIds.length > 0) {
query.projectId = { $in: filteredProjectIds };
}
let issues = await BuildingIssue.find(query)
.select('issueTitle issueDate')
.populate('projectId')
.lean();
issues = issues.map((issue) => {
const durationInMonths = Math.ceil(
(new Date() - new Date(issue.issueDate)) / (1000 * 60 * 60 * 24 * 30.44),
);
const years = Math.floor(durationInMonths / 12);
const months = durationInMonths % 12;
const durationText =
years > 0
? `${years} year${years > 1 ? 's' : ''} ${months} month${months > 1 ? 's' : ''}`
: `${months} month${months > 1 ? 's' : ''}`;
return {
issueName: issue.issueTitle[0],
durationOpen: durationText,
durationInMonths,
};
});
const topIssues = issues
.sort((a, b) => b.durationInMonths - a.durationInMonths)
.slice(0, 7)
.map(({ issueName, durationInMonths }) => ({
issueName,
durationOpen: durationInMonths, // send number only
}));
res.json(topIssues);
} catch (error) {
console.error('Error fetching longest open issues:', error);
res.status(500).json({ message: 'Error fetching longest open issues' });
}
};
return { bmGetIssue, bmPostIssue, bmGetIssueChart, getLongestOpenIssues };
};
module.exports = bmIssueController;