-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathprojectController.js
More file actions
741 lines (662 loc) · 26.4 KB
/
Copy pathprojectController.js
File metadata and controls
741 lines (662 loc) · 26.4 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/* eslint-disable quotes */
/* eslint-disable arrow-parens */
const mongoose = require('mongoose');
const timeentry = require('../models/timeentry');
const task = require('../models/task');
const wbs = require('../models/wbs');
const userProfile = require('../models/userProfile');
// const { hasPermission } = require('../utilities/permissions');
const helper = require('../utilities/permissions');
const escapeRegex = require('../utilities/escapeRegex');
const logger = require('../startup/logger');
const cache = require('../utilities/nodeCache')();
// Shit code included.
const projectController = function (Project) {
const getAllProjects = async function (req, res) {
try {
const projects = await Project.find(
{ isArchived: { $ne: true } },
'projectName isActive category modifiedDatetime membersModifiedDatetime inventoryModifiedDatetime',
).sort({ modifiedDatetime: -1 });
res.status(200).send(projects);
} catch (error) {
logger.logException(error);
res.status(404).send('Error fetching projects. Please try again.');
}
};
const getProjectsCommittedHours = async function (req, res) {
try {
const { fromDate, toDate } = req.body;
logger.logInfo(
`Fetching projects with committed hours. Date filter: ${JSON.stringify({ fromDate, toDate })}`,
);
const taskDateFilter = {};
if (fromDate && toDate) {
const start = new Date(fromDate);
const end = new Date(toDate);
end.setHours(23, 59, 59, 999);
taskDateFilter.$or = [
{
startedDatetime: { $lte: end },
dueDatetime: { $gte: start },
},
{
startedDatetime: { $gte: start, $lte: end },
},
{
dueDatetime: { $gte: start, $lte: end },
},
];
}
logger.logInfo(
`Fetching projects with committed hours. Date filter: ${JSON.stringify(taskDateFilter)}`,
);
const projects = await Project.find({ isArchived: { $ne: true } }, '_id projectName');
const result = await Promise.all(
projects.map(async (project) => {
const wbsList = await wbs.find({ projectId: project._id }, '_id');
const wbsIds = wbsList.map((wbsItem) => wbsItem._id);
const tasks = await task.find(
{
wbsId: { $in: wbsIds },
...taskDateFilter,
},
'estimatedHours',
);
const committedHours = tasks.reduce(
(total, taskItem) => total + Number(taskItem.estimatedHours || 0),
0,
);
return {
projectId: project._id,
projectName: project.projectName,
committedHours,
};
}),
);
res.status(200).send(result);
} catch (error) {
logger.logException(error);
res.status(500).send('Error fetching project committed hours.');
}
};
const getArchivedProjects = async function (req, res) {
try {
const archivedProjects = await Project.find(
{ isArchived: true },
'projectName isActive category modifiedDatetime membersModifiedDatetime isArchived',
).sort({ modifiedDatetime: -1 });
res.status(200).send(archivedProjects);
} catch (error) {
logger.logException(error);
res.status(404).send('Error fetching archived projects. Please try again.');
}
};
const deleteProject = async function (req, res) {
if (!(await helper.hasPermission(req.body.requestor, 'deleteProject'))) {
res.status(403).send({ error: 'You are not authorized to delete projects.' });
return;
}
const { projectId } = req.params;
Project.findById(projectId, (error, record) => {
if (error || !record || record === null || record.length === 0) {
res.status(400).send({ error: 'No valid records found' });
return;
}
// find if project has any time entries associated with it
timeentry
.find({ projectId: record._id }, '_id')
.then((timeentries) => {
if (timeentries.length > 0) {
res.status(400).send({
error:
'This project has associated time entries and cannot be deleted. Consider inactivaing it instead.',
});
} else {
const removeprojectfromprofile = userProfile
.updateMany({}, { $pull: { projects: record._id } })
.exec();
const removeproject = record.remove();
Promise.all([removeprojectfromprofile, removeproject])
.then(() => {
res.status(200).send({
message: 'Project successfully deleted and user profiles updated.',
});
})
.catch((errors) => {
res.status(400).send(errors);
});
}
})
.catch((errors) => {
res.status(400).send(errors);
});
});
// .catch((errors) => {
// res.status(400).send(errors);
// });
};
const postProject = async function (req, res) {
if (!(await helper.hasPermission(req.body.requestor, 'postProject'))) {
return res.status(401).send('You are not authorized to create new projects.');
}
if (!req.body.projectName) {
return res.status(400).send('Project Name is mandatory fields.');
}
try {
const projectWithRepeatedName = await Project.find({
projectName: {
$regex: escapeRegex(req.body.projectName),
$options: 'i',
},
});
if (projectWithRepeatedName.length > 0) {
return res
.status(400)
.send(
`Project Name must be unique. Another project with name ${req.body.projectName} already exists. Please note that project names are case insensitive.`,
);
}
const _project = new Project();
const now = new Date();
_project.projectName = req.body.projectName;
_project.category = req.body.projectCategory;
_project.isActive = true;
_project.createdDatetime = now;
_project.modifiedDatetime = now;
const savedProject = await _project.save();
return res.status(200).send(savedProject);
} catch (error) {
res.status(400).send('Error creating project. Please try again.');
}
};
const putProject = async function (req, res) {
// console.log("PUT body:", req.body);
if (!(await helper.hasPermission(req.body.requestor, 'editProject'))) {
if (!(await helper.hasPermission(req.body.requestor, 'putProject'))) {
res.status(403).send('You are not authorized to make changes in the projects.');
return;
}
}
const {
projectName,
category,
isActive,
_id: projectId,
isArchived,
inventoryModifiedDatetime,
} = req.body;
const sameNameProejct = await Project.find({
projectName,
_id: { $ne: projectId },
});
if (sameNameProejct.length > 0) {
res.status(400).send('This project name is already taken');
return;
}
const session = await mongoose.startSession();
session.startTransaction();
try {
const targetProject = await Project.findById(projectId);
if (!targetProject) {
res.status(400).send('No valid records found');
await session.abortTransaction();
return;
}
// STORE ORIGINAL CATEGORY BEFORE UPDATE
const originalCategory = targetProject.category;
logger.logInfo(
`[Category Cascade] Project ${projectId} update started. Original category: ${originalCategory}, New category: ${category}`,
);
targetProject.projectName = projectName ?? targetProject.projectName;
targetProject.category = category ?? targetProject.category;
targetProject.isActive = isActive !== undefined ? isActive : targetProject.isActive;
targetProject.modifiedDatetime = Date.now();
targetProject.isArchived = isArchived !== undefined ? isArchived : targetProject.isArchived;
targetProject.inventoryModifiedDatetime =
inventoryModifiedDatetime ?? targetProject.inventoryModifiedDatetime;
// IF CATEGORY CHANGED, CASCADE TO NON-OVERRIDDEN TASKS
if (category && originalCategory !== category) {
logger.logInfo(
`[Category Cascade] Category changed from "${originalCategory}" to "${category}". Starting cascade...`,
);
// Get all WBS for this project
const projectWBSIds = await wbs.find({ projectId }, '_id', { session });
const wbsIds = projectWBSIds.map((w) => w._id);
logger.logInfo(`[Category Cascade] Found ${wbsIds.length} WBS for project ${projectId}`);
logger.logInfo(`[Category Cascade] WBS IDs: ${JSON.stringify(wbsIds)}`);
if (wbsIds.length > 0) {
// First, let's see ALL tasks for these WBS
const allTasks = await task.find(
{ wbsId: { $in: wbsIds } },
{
taskName: 1,
category: 1,
categoryOverride: 1,
categoryLocked: 1,
wbsId: 1,
},
{ session },
);
logger.logInfo(`[Category Cascade] Total tasks found in WBS: ${allTasks.length}`);
allTasks.forEach((t) => {
logger.logInfo(
`[Category Cascade] Task: "${t.taskName}", Category: "${t.category}", Override: ${t.categoryOverride}, Locked: ${t.categoryLocked}, WBS: ${t.wbsId}`,
);
});
// Count tasks by lock status (this is what determines cascade behavior)
const lockedTrue = allTasks.filter((t) => t.categoryLocked === true).length;
const lockedFalse = allTasks.filter((t) => t.categoryLocked === false).length;
const lockedUndefined = allTasks.filter((t) => t.categoryLocked === undefined).length;
logger.logInfo(
`[Category Cascade] Lock stats - Locked: ${lockedTrue}, Unlocked: ${lockedFalse}, Undefined: ${lockedUndefined}`,
);
// Update all tasks that are NOT locked (categoryLocked = false or undefined)
// Also update categoryOverride to false since they now match project category
const updateResult = await task.updateMany(
{
wbsId: { $in: wbsIds },
$or: [
{ categoryLocked: { $exists: false } }, // Old tasks without the field
{ categoryLocked: false }, // Tasks explicitly unlocked
],
},
{
category,
categoryOverride: false, // These tasks now match project category
modifiedDatetime: Date.now(),
},
{ session },
);
logger.logInfo(`[Category Cascade] updateMany result: ${JSON.stringify(updateResult)}`);
logger.logInfo(
`[Category Cascade] Updated ${updateResult.modifiedCount} tasks with new category "${category}"`,
);
logger.logInfo(
`[Category Cascade] Matched ${updateResult.matchedCount} tasks (unlocked), Modified ${updateResult.modifiedCount} tasks`,
);
// Verify the update by checking tasks again
const updatedTasks = await task.find(
{
wbsId: { $in: wbsIds },
$or: [{ categoryLocked: { $exists: false } }, { categoryLocked: false }],
},
{
taskName: 1,
category: 1,
categoryOverride: 1,
categoryLocked: 1,
},
{ session },
);
logger.logInfo(
`[Category Cascade] After update verification - ${updatedTasks.length} unlocked tasks:`,
);
updatedTasks.forEach((t) => {
logger.logInfo(
`[Category Cascade] Task: "${t.taskName}", Category NOW: "${t.category}", Override: ${t.categoryOverride}, Locked: ${t.categoryLocked}`,
);
});
} else {
logger.logInfo(`[Category Cascade] No WBS found, skipping task updates`);
}
} else {
logger.logInfo(
`[Category Cascade] Category unchanged or empty, skipping cascade. Category: "${category}", Original: "${originalCategory}"`,
);
}
// if (isArchived) {
// logger.logInfo(`[Category Cascade] Project ${projectId} is being archived`);
// targetProject.isArchived = isArchived;
// // deactivate wbs within target project
// await wbs.updateMany({ projectId }, { isActive: false }, { session });
// // deactivate tasks within affected wbs
// const deactivatedwbsIds = await wbs.find({ projectId }, '_id');
// await task.updateMany(
// { wbsId: { $in: deactivatedwbsIds } },
// { isActive: false },
// { session },
// );
// // remove project from userprofiles.projects array
// await userProfile.updateMany(
// { projects: projectId },
// { $pull: { projects: projectId } },
// { session },
// );
// // deactivate timeentry for affected tasks
// await timeentry.updateMany({ projectId }, { isActive: false }, { session });
// } else {
// // reactivate wbs within target project
// await wbs.updateMany({ projectId }, { isActive: true }, { session });
// // reactivate tasks within affected wbs
// const activatedwbsIds = await wbs.find({ projectId }, '_id');
// await task.updateMany({ wbsId: { $in: activatedwbsIds } }, { isActive: true }, { session });
// // readd project from userprofiles.projects array
// await userProfile.updateMany(
// { projects: { $ne: projectId } },
// { $addToSet: { projects: projectId } },
// { session },
// );
// // activate timeentry for affected tasks
// await timeentry.updateMany({ projectId }, { isActive: true }, { session });
// }
// 🔹 Run archive/unarchive logic only when the archive status actually changes
if (typeof isArchived !== 'undefined' && targetProject.isArchived !== isArchived) {
logger.logInfo(
`[Category Cascade] Project ${projectId} is being ${isArchived ? 'archived' : 'unarchived'}`,
);
targetProject.isArchived = isArchived;
if (isArchived) {
// deactivate wbs within target project
await wbs.updateMany({ projectId }, { isActive: false }, { session });
// deactivate tasks within affected wbs
const deactivatedWbsIds = await wbs.find({ projectId }, '_id');
await task.updateMany(
{ wbsId: { $in: deactivatedWbsIds } },
{ isActive: false },
{ session },
);
// remove project from userprofiles.projects array
await userProfile.updateMany(
{ projects: projectId },
{ $pull: { projects: projectId } },
{ session },
);
// deactivate timeentry for affected tasks
await timeentry.updateMany({ projectId }, { isActive: false }, { session });
logger.logInfo(`[Category Cascade] Project ${projectId} archived successfully.`);
} else {
// reactivate wbs within target project
await wbs.updateMany({ projectId }, { isActive: true }, { session });
// reactivate tasks within affected wbs
const activatedWbsIds = await wbs.find({ projectId }, '_id');
await task.updateMany(
{ wbsId: { $in: activatedWbsIds } },
{ isActive: true },
{ session },
);
// readd project to userprofiles.projects array
await userProfile.updateMany(
{ projects: { $ne: projectId } },
{ $addToSet: { projects: projectId } },
{ session },
);
// activate timeentry for affected tasks
await timeentry.updateMany({ projectId }, { isActive: true }, { session });
logger.logInfo(`[Category Cascade] Project ${projectId} unarchived successfully.`);
}
} else {
logger.logInfo(
`[Category Cascade] Archive status unchanged for project ${projectId}, skipping archive/unarchive cascade.`,
);
}
await targetProject.save({ session });
await session.commitTransaction();
logger.logInfo(`[Category Cascade] Project ${projectId} update completed successfully`);
res.status(200).send(targetProject);
} catch (error) {
await session.abortTransaction();
logger.logException(error);
res.status(400).send('Error updating project. Please try again.');
} finally {
session.endSession();
}
};
const getProjectById = function (req, res) {
const { projectId } = req.params;
Project.findById(projectId, '-__v -createdDatetime -modifiedDatetime')
.then((results) => res.status(200).send(results))
.catch((err) => {
logger.logException(err);
res.status(404).send('Error fetching project. Please try again.');
});
};
const getUserProjects = async function (req, res) {
try {
const { userId } = req.params;
const user = await userProfile.findById(userId, 'projects');
if (!user) {
res.status(400).send('Invalid user');
return;
}
const { projects } = user;
const projectList = await Project.find(
{ _id: { $in: projects }, isActive: { $ne: false } },
'_id projectName category',
);
const result = projectList
.map((p) => {
p = p.toObject();
p.projectId = p._id;
delete p._id;
return p;
})
.sort((p1, p2) => {
if (p1.projectName.toLowerCase() < p2.projectName.toLowerCase()) return -1;
if (p1.projectName.toLowerCase() > p2.projectName.toLowerCase()) return 1;
return 0;
});
res.status(200).send(result);
} catch (error) {
logger.logException(error);
res.status(400).send('Error fetching projects. Please try again.');
}
};
const assignProjectToUsers = async function (req, res) {
// verify requestor is administrator, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users
if (!(await helper.hasPermission(req.body.requestor, 'assignProjectToUsers'))) {
res.status(403).send('You are not authorized to perform this operation');
return;
}
if (
!req.params.projectId ||
!mongoose.Types.ObjectId.isValid(req.params.projectId) ||
!req.body.users ||
req.body.users.length === 0
) {
res.status(400).send('Invalid request');
return;
}
// verify project exists
Project.findById(req.params.projectId)
.then((project) => {
if (!project || project.length === 0) {
res.status(400).send('Invalid project');
return;
}
const { users } = req.body;
const assignlist = [];
const unassignlist = [];
users.forEach((element) => {
const { userId, operation } = element;
if (cache.hasCache(`user-${userId}`)) {
cache.removeCache(`user-${userId}`);
}
if (operation === 'Assign') {
assignlist.push(userId);
} else {
unassignlist.push(userId);
}
});
const assignPromise = userProfile
.updateMany({ _id: { $in: assignlist } }, { $addToSet: { projects: project._id } })
.exec();
const unassignPromise = userProfile
.updateMany({ _id: { $in: unassignlist } }, { $pull: { projects: project._id } })
.exec();
Promise.all([assignPromise, unassignPromise])
.then(() => {
res.status(200).send({ result: 'Done' });
})
.catch((error) => {
res.status(500).send({ error });
});
})
.catch((err) => {
logger.logException(err);
res.status(500).send('Error fetching project. Please try again.');
});
};
/**
* Get project members with profile pictures
* @route GET /api/project/:projectId/users
* @returns {Array} Users with profilePic field - can be slow for large lists
* @see getprojectMembershipSummary for faster alternative without profile pics
*/
const getprojectMembership = async function (req, res) {
try {
// GETs usually have no body; prefer req.user populated by your auth middleware.
const requestor =
(req.user && (req.user._id || req.user.id)) || req.query?.requestor || req.body?.requestor;
// Allow users who can fetch members OR who can create/update/suggest tasks
const canGet =
(await helper.hasPermission(requestor, 'getProjectMembers')) ||
(await helper.hasPermission(requestor, 'postTask')) ||
(await helper.hasPermission(requestor, 'updateTask')) ||
(await helper.hasPermission(requestor, 'suggestTask'));
if (!canGet) {
return res.status(403).send('You are not authorized to perform this operation');
}
const { projectId } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
return res.status(400).send('Invalid request');
}
const results = await userProfile
.find(
{ projects: projectId },
{ firstName: 1, lastName: 1, profilePic: 1, _id: 1, isActive: 1 },
)
.sort({ firstName: 1, lastName: 1 });
return res.status(200).send(results);
} catch (error) {
logger?.logException?.(error);
return res.status(500).send('Error fetching project members');
}
};
/**
* Get project members summary (fast version)
* @route GET /api/project/:projectId/users/summary
* @returns {Array} Users without profilePic field - optimized for large lists
* @performance 2-5 seconds vs 2+ minutes for full endpoint
*/
const getprojectMembershipSummary = async function (req, res) {
// Check permissions - same as full endpoint
if (!(await helper.hasPermission(req.body.requestor, 'getProjectMembers'))) {
res.status(403).send('You are not authorized to perform this operation');
return;
}
const { projectId } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
res.status(400).send('Invalid request');
return;
}
userProfile
.find(
{ projects: projectId },
{ firstName: 1, lastName: 1, isActive: 1 }, // Excludes profilePic for performance
)
.then((results) => {
res.status(200).json(results);
})
.catch((error) => {
console.error('Summary query error:', error);
res.status(500).send(error);
});
};
function escapeRegExp(str) {
return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
const searchProjectMembers = async function (req, res) {
const { projectId, query } = req.params;
if (!mongoose.Types.ObjectId.isValid(projectId)) {
// if (!mongoose.Types.ObjectId.isValid(projectId)) {
// res.status(400).send('Invalid request');
// return;
// }
const getProjMembers = await helper.hasPermission(req.body.requestor, 'getProjectMembers');
// // If a user has permission to post, edit, or suggest tasks, they also have the ability to assign resources to those tasks.
// // Therefore, the _id field must be included when retrieving the user profile for project members (resources).
const postTask = await helper.hasPermission(req.body.requestor, 'postTask');
const updateTask = await helper.hasPermission(req.body.requestor, 'updateTask');
const suggestTask = await helper.hasPermission(req.body.requestor, 'suggestTask');
// eslint-disable-next-line no-unused-vars
const getId = getProjMembers || postTask || updateTask || suggestTask;
// userProfile
// .find(
// { projects: projectId },
// { firstName: 1, lastName: 1, isActive: 1, profilePic: 1, _id: getId },
// )
// .sort({ firstName: 1, lastName: 1 })
// .then((results) => {
// res.status(200).send(results);
// })
// .catch((error) => {
// res.status(500).send(error);
// });
return res.status(400).send('Invalid project ID');
}
// Sanitize user input and escape special characters
const sanitizedQuery = escapeRegExp(query.trim());
// case-insensitive search
const searchRegex = new RegExp(sanitizedQuery, 'i');
try {
const getProjMembers = await helper.hasPermission(req.body.requestor, 'getProjectMembers');
const postTask = await helper.hasPermission(req.body.requestor, 'postTask');
const updateTask = await helper.hasPermission(req.body.requestor, 'updateTask');
const suggestTask = await helper.hasPermission(req.body.requestor, 'suggestTask');
const canGetId = getProjMembers || postTask || updateTask || suggestTask;
const results = await userProfile
.find({
projects: projectId,
$or: [{ firstName: { $regex: searchRegex } }, { lastName: { $regex: searchRegex } }],
})
.select(`firstName lastName isActive ${canGetId ? '_id' : ''}`)
.sort({ firstName: 1, lastName: 1 })
.limit(30);
res.status(200).send(results);
} catch (error) {
res.status(500).send(error);
}
};
const getProjectsWithActiveUserCounts = async function (req, res) {
try {
const projects = await Project.find({ isArchived: { $ne: true } }, '_id');
const projectIds = projects.map((project) => project._id);
const userCounts = await userProfile.aggregate([
{ $match: { projects: { $in: projectIds }, isActive: true } },
{ $unwind: '$projects' },
{ $match: { projects: { $in: projectIds } } },
{
$group: {
_id: '$projects',
activeUserCount: { $sum: 1 },
},
},
]);
const result = userCounts.reduce((acc, curr) => {
acc[curr._id.toString()] = curr.activeUserCount;
return acc;
}, {});
res.status(200).send(result);
} catch (error) {
console.error(error);
res.status(500).send('Error fetching active member counts');
}
};
return {
getAllProjects,
postProject,
getProjectById,
putProject,
deleteProject,
getUserProjects,
assignProjectToUsers,
getprojectMembership,
getArchivedProjects,
getprojectMembershipSummary,
searchProjectMembers,
getProjectsWithActiveUserCounts,
getProjectsCommittedHours,
};
};
module.exports = projectController;