Skip to content

Commit 1825379

Browse files
committed
fix(analytics): add validation for date range filters in OPT status API
1 parent 0342647 commit 1825379

1 file changed

Lines changed: 51 additions & 8 deletions

File tree

src/controllers/optAnalyticsController.js

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,68 @@ module.exports = () => ({
55
try {
66
const { startDate, endDate, role } = req.query;
77
const query = {};
8-
if (startDate || endDate) {
8+
9+
let start;
10+
let end;
11+
12+
if (startDate) {
13+
start = new Date(startDate);
14+
if (Number.isNaN(start.getTime())) {
15+
return res.status(400).json({
16+
message: 'Invalid startDate. Use ISO format (YYYY-MM-DD).',
17+
});
18+
}
19+
}
20+
21+
if (endDate) {
22+
end = new Date(endDate);
23+
if (Number.isNaN(end.getTime())) {
24+
return res.status(400).json({
25+
message: 'Invalid endDate. Use ISO format (YYYY-MM-DD).',
26+
});
27+
}
28+
}
29+
30+
if (start && end && start > end) {
31+
return res.status(400).json({
32+
message: 'startDate cannot be greater than endDate.',
33+
});
34+
}
35+
36+
if (start || end) {
937
query.applicationDate = {};
10-
if (startDate) query.applicationDate.$gte = new Date(startDate);
11-
if (endDate) query.applicationDate.$lte = new Date(endDate);
38+
if (start) query.applicationDate.$gte = start;
39+
if (end) query.applicationDate.$lte = end;
1240
}
13-
if (role) query.role = role;
41+
42+
if (role) {
43+
query.role = role;
44+
}
45+
1446
const result = await CandidateOPTStatus.find(query);
47+
48+
if (!result.length) {
49+
return res.json({
50+
totalCandidates: 0,
51+
breakDown: [],
52+
message: 'No records found for the given filters.',
53+
});
54+
}
55+
1556
const totalCandidates = result.length;
1657
const breakDownMap = {};
17-
result.forEach((candidate) => {
18-
const { optStatus } = candidate;
58+
59+
result.forEach(({ optStatus }) => {
1960
breakDownMap[optStatus] = (breakDownMap[optStatus] || 0) + 1;
2061
});
62+
2163
const breakDown = Object.entries(breakDownMap).map(([optStatus, count]) => ({
2264
optStatus,
2365
count,
24-
percentage: parseFloat(((count / totalCandidates) * 100).toFixed(2)),
66+
percentage: Number(((count / totalCandidates) * 100).toFixed(2)),
2567
}));
26-
res.json({
68+
69+
return res.json({
2770
totalCandidates,
2871
breakDown,
2972
});

0 commit comments

Comments
 (0)