-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathtimeEntryController.js
More file actions
1675 lines (1543 loc) · 60.6 KB
/
timeEntryController.js
File metadata and controls
1675 lines (1543 loc) · 60.6 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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const moment = require('moment-timezone');
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');
const logger = require('../startup/logger');
const UserProfile = require('../models/userProfile');
const Project = require('../models/project');
const Task = require('../models/task');
const WBS = require('../models/wbs');
const emailSender = require('../utilities/emailSender');
const { hasPermission } = require('../utilities/permissions');
const cacheClosure = require('../utilities/nodeCache');
const cacheModule = require('../utilities/nodeCache');
const cacheUtil = cacheModule();
const formatSeconds = function (seconds) {
const formattedseconds = parseInt(seconds, 10);
const values = `${Math.floor(
moment.duration(formattedseconds, 'seconds').asHours(),
)}:${moment.duration(formattedseconds, 'seconds').minutes()}`;
return values.split(':');
};
const isGeneralTimeEntry = function (type) {
if (type === undefined || type === 'default') {
return true;
}
return false;
};
/**
* Get the email body for a time entry that was edited
* @param {*} targetUser The user profile object of the user that owns the time entry
* @param {*} requestor The user profile object of the user that modified the time entry
* @param {*} originalTime The time (in seconds) of the original time entry
* @param {*} finalTime The time (in seconds) of the updated time entry
* @param {*} originalDateOfWork The original date of work for the time entry
* @param {*} finalDateOfWork The updated date of work for the time entry
* @returns {String} The email body
*/
const getEditedTimeEntryEmailBody = (
targetUser,
requestor,
originalTime,
finalTime,
originalDateOfWork = null,
finalDateOfWork = null,
) => {
const formattedOriginal = moment.utc(originalTime * 1000).format('HH[ hours ]mm[ minutes]');
const formattedFinal = moment.utc(finalTime * 1000).format('HH[ hours ]mm[ minutes]');
return `
A time entry belonging to ${targetUser.firstName} ${targetUser.lastName} (${targetUser.email}) was modified by ${requestor.firstName} ${requestor.lastName} (${requestor.email}).
The entry's duration was changed from [${formattedOriginal}] to [${formattedFinal}]
${originalDateOfWork ? `The entry's date of work was changed from ${originalDateOfWork} to ${finalDateOfWork}` : ''}`;
};
/**
* Sends an email notification indicating that a user modified one of their own time entries
* @param {*} userprofile The user profile object of the user that owns the time entry
* @param {*} requstorId The id of the user that modified the time entry
* @param {*} originalTime The time (in seconds) of the original time entry
* @param {*} finalTime The time (in seconds) of the updated time entry
* @param {*} originalDateOfWork The original date of work for the time entry
* @param {*} finalDateOfWork The updated date of work for the time entry
* @returns {Void}
*/
const notifyEditByEmail = async (
userprofile,
requstorId,
originalTime,
finalTime,
originalDateOfWork = null,
finalDateOfWork = null,
) => {
try {
const requestor =
requstorId === userprofile._id.toString()
? userprofile
: await UserProfile.findById(requstorId);
const emailBody = getEditedTimeEntryEmailBody(
userprofile,
requestor,
originalTime,
finalTime,
originalDateOfWork,
finalDateOfWork,
);
emailSender(
'onecommunityglobal@gmail.com',
`A Time Entry was Edited for ${userprofile.firstName} ${userprofile.lastName}`,
emailBody,
);
} catch (error) {
throw new Error(
`Failed to send email notification about the modification of time entry belonging to user with id ${userprofile._id.toString()}`,
);
}
};
/**
* Sends an email notification indicating that a user logged more hours than estimated for a task
* @param {*} userProfile The user profile object of the user that owns the time entry
* @param {*} task The task object that the user logged time for
* @returns {Void}
*/
const notifyTaskOvertimeEmailBody = async (userProfile, task) => {
const { taskName, estimatedHours, hoursLogged } = task;
try {
const text = `Dear <b>${userProfile.firstName}${userProfile.lastName}</b>,
<p>Oops, it looks like you have logged more hours than estimated for a task </p>
<p><b>Task Name : ${taskName}</b></p>
<p><b>Time Estimated : ${estimatedHours}</b></p>
<p><b>Hours Logged : ${hoursLogged.toFixed(2)}</b></p>
<p><b>Please connect with your manager to explain what happened and submit a new hours estimation for completion.</b></p>
<p>Thank you,</p>
<p>One Community</p>`;
emailSender(
userProfile.email,
'Logged more hours than estimated for a task',
text,
null,
null,
'onecommunityglobal@gmail.com',
);
} catch (error) {
throw new Error(
`Failed to send email notification about the modification of time entry belonging to user with id ${userProfile._id}`,
);
}
};
/**
* Update task hoursLogged for a time entry
* @param {*} fromTaskId The id of the task that the time entry is moving from
* @param {*} secondsToBeRemoved The total seconds of the time entry that is moving from
* @param {*} toTaskId The id of the task that the time entry is moving to
* @param {*} secondsToBeAdded The total seconds of the time entry that is moving to
* @param {*} userprofile The userprofile object
* @param {*} session The session object
* @param {*} pendingEmailCollection The collection of email functions to be executed after the transaction
* @returns {Void}
*/
const updateTaskLoggedHours = async (
fromTaskId,
secondsToBeRemoved,
toTaskId,
secondsToBeAdded,
userprofile,
session,
pendingEmailCollection = null,
) => {
// if both fromTaskId and toTaskId are null, then there is no need to update task hoursLogged
if (!fromTaskId && !toTaskId) return;
const hoursToBeRemoved = secondsToBeRemoved ? Number((secondsToBeRemoved / 3600).toFixed(2)) : 0;
const hoursToBeAdded = secondsToBeAdded ? Number((secondsToBeAdded / 3600).toFixed(2)) : 0;
if (fromTaskId && toTaskId && fromTaskId !== toTaskId) {
// update from one task to another
try {
await Task.findOneAndUpdate(
{ _id: fromTaskId },
{ $inc: { hoursLogged: -hoursToBeRemoved } },
{ new: true, session },
);
const toTask = await Task.findOneAndUpdate(
{ _id: toTaskId },
{ $inc: { hoursLogged: hoursToBeAdded } },
{ new: true, session },
);
if (toTask.hoursLogged > toTask.estimatedHours && pendingEmailCollection) {
pendingEmailCollection.push(notifyTaskOvertimeEmailBody.bind(null, userprofile, toTask));
}
} catch (error) {
throw new Error(
`Failed to update task hoursLogged from task with id ${fromTaskId} to task with id ${toTaskId}`,
);
}
} else if (fromTaskId === toTaskId) {
// update within the same task
const hoursDiff = hoursToBeAdded - hoursToBeRemoved;
try {
const updatedTask = await Task.findOneAndUpdate(
{ _id: toTaskId },
{ $inc: { hoursLogged: hoursDiff } },
{ new: true, session },
);
if (updatedTask.hoursLogged > updatedTask.estimatedHours && pendingEmailCollection) {
pendingEmailCollection.push(
notifyTaskOvertimeEmailBody.bind(null, userprofile, updatedTask),
);
}
} catch (error) {
throw new Error(`Failed to update task hoursLogged for task with id ${toTaskId}`);
}
} else {
// Handle cases where only one task is involved
// eslint-disable-next-line no-lonely-if
if (fromTaskId && !toTaskId) {
// Remove hours from old task only
await Task.findOneAndUpdate(
{ _id: fromTaskId },
{ $inc: { hoursLogged: -hoursToBeRemoved } },
{ new: true, session },
);
} else if (!fromTaskId && toTaskId) {
// Add hours to new task only (your case!)
const updatedTask = await Task.findOneAndUpdate(
{ _id: toTaskId },
{ $inc: { hoursLogged: hoursToBeAdded } }, // Only add, don't subtract
{ new: true, session },
);
if (updatedTask.hoursLogged > updatedTask.estimatedHours && pendingEmailCollection) {
pendingEmailCollection.push(
notifyTaskOvertimeEmailBody.bind(null, userprofile, updatedTask),
);
}
}
}
};
/**
* Update userprofile hoursByCategory due to project change or posting time entry
* @param {*} userprofile The userprofile object
* @param {*} fromProjectId The id of the project that the time entry is moving from
* @param {*} secondsToBeRemoved The total seconds of the time entry that is moving from
* @param {*} toProjectId The id of the project that the time entry is moving to
* @param {*} secondsToBeAdded The total seconds of the time entry that is moving to
* @returns {Void}
*/
const updateUserprofileCategoryHrs = async (
fromProjectId,
secondsToBeRemoved,
toProjectId,
secondsToBeAdded,
userprofile,
) => {
if (fromProjectId) {
const fromProject = await Project.findById(fromProjectId);
const hoursToBeRemoved = Number((secondsToBeRemoved / 3600).toFixed(2));
if (fromProject.category.toLowerCase() in userprofile.hoursByCategory) {
userprofile.hoursByCategory[fromProject.category.toLowerCase()] -= hoursToBeRemoved;
} else {
userprofile.hoursByCategory.unassigned -= hoursToBeRemoved;
}
}
if (toProjectId) {
const toProject = await Project.findById(toProjectId);
const hoursToBeAdded = Number((secondsToBeAdded / 3600).toFixed(2));
if (toProject.category.toLowerCase() in userprofile.hoursByCategory) {
userprofile.hoursByCategory[toProject.category.toLowerCase()] += hoursToBeAdded;
} else {
userprofile.hoursByCategory.unassigned += hoursToBeAdded;
}
}
};
/**
* Update userprofile tangible and intangible hours
* @param {*} tangibleSecondsChanged The total seconds of the tangible time entry that is moving
* @param {*} intangibleSecondsChanged The total seconds of the intangible time entry that is moving
* @param {*} userprofile The userprofile object
* @returns {Void}
*/
const updateUserprofileTangibleIntangibleHrs = (
tangibleSecondsChanged,
intangibleSecondsChanged,
userprofile,
) => {
const tangibleHoursChanged = Number((tangibleSecondsChanged / 3600).toFixed(2));
const intangibleHoursChanged = Number((intangibleSecondsChanged / 3600).toFixed(2));
userprofile.totalIntangibleHrs += intangibleHoursChanged;
userprofile.totalTangibleHrs += tangibleHoursChanged;
};
/**
* Remove outdated userprofile cache
* @param {*} userprofile The userprofile object
* @returns {Void}
*/
const removeOutdatedUserprofileCache = (userId) => {
const userprofileCache = cacheClosure();
userprofileCache.removeCache(`user-${userId}`);
};
/**
* Validate userprofile hours, including totalTangibleHrs, totalIntangibleHrs, and hoursByCategory
* @param {*} userprofile The userprofile object
* @returns {Void}
*/
const validateUserprofileHours = (userprofile) => {
if (userprofile.totalTangibleHrs < 0) userprofile.totalTangibleHrs = 0;
if (userprofile.totalIntangibleHrs < 0) userprofile.totalIntangibleHrs = 0;
Object.keys(userprofile.hoursByCategory).forEach((category) => {
if (userprofile.hoursByCategory[category] < 0) userprofile.hoursByCategory[category] = 0;
});
};
/**
* Add an edit history to the userprofile
* @param {*} userprofile The userprofile object
* @param {*} initialTotalSeconds The total seconds of the time entry before the edit
* @param {*} newTotalSeconds The total seconds of the time entry after the edit
* @param {*} originalDateOfWork The original date of work for the time entry
* @param {*} finalDateOfWork The updated date of work for the time entry
* @param {*} pendingEmailCollection The collection of email functions to be executed
* @returns {Void}
*/
const addEditHistory = async (
userprofile,
initialTotalSeconds,
newTotalSeconds,
originalDateOfWork,
finalDateOfWork,
pendingEmailCollection,
) => {
userprofile.timeEntryEditHistory.push({
date: moment().tz('America/Los_Angeles').toDate(),
initialSeconds: initialTotalSeconds,
newSeconds: newTotalSeconds,
originalDateOfWork,
finalDateOfWork,
});
// Issue infraction if edit history contains more than 5 edits in the last year
const totalRecentEdits = userprofile.timeEntryEditHistory.filter(
(edit) => moment().tz('America/Los_Angeles').diff(edit.date, 'days') <= 365,
).length;
if (totalRecentEdits >= 5) {
const cutOffDate = moment().subtract(1, 'year');
const recentInfringements = userprofile.infringements.filter((infringement) =>
moment(infringement.date).isAfter(cutOffDate),
);
let modifiedRecentInfringements = 'No Previous Infringements!';
if (recentInfringements.length) {
modifiedRecentInfringements = recentInfringements
.map((item, index) => {
let enhancedDescription;
if (item.description) {
let sentences = item.description.split('.');
const dateRegex =
/in the week starting Sunday (\d{4})-(\d{2})-(\d{2}) and ending Saturday (\d{4})-(\d{2})-(\d{2})/g;
sentences = sentences.map((sentence) =>
sentence.replace(dateRegex, (match, year1, month1, day1, year2, month2, day2) => {
const startDate = moment(`${year1}-${month1}-${day1}`, 'YYYY-MM-DD').format(
'M-D-YYYY',
);
const endDate = moment(`${year2}-${month2}-${day2}`, 'YYYY-MM-DD').format(
'M-D-YYYY',
);
return `in the week starting Sunday ${startDate} and ending Saturday ${endDate}`;
}),
);
if (sentences[0].includes('System auto-assigned infringement for two reasons')) {
sentences[0] = sentences[0].replace(
/(not meeting weekly volunteer time commitment as well as not submitting a weekly summary)/gi,
'<span style="color: blue;"><b>$1</b></span>',
);
enhancedDescription = sentences.join('.');
enhancedDescription = enhancedDescription.replace(
/logged (\d+(\.\d+)?\s*hours)/i,
'logged <span style="color: blue;"><b>$1</b></span>',
);
} else if (
sentences[0].includes(
'System auto-assigned infringement for editing your time entries',
)
) {
sentences[0] = sentences[0].replace(
/time entries <(\d+)>\s*times/i,
'time entries <span><b>$1 times</b></span>',
);
enhancedDescription = sentences.join('.');
} else if (sentences[0].includes('System auto-assigned infringement')) {
sentences[0] = sentences[0].replace(
/(not submitting a weekly summary)/gi,
'<span style="color: blue;"><b>$1</b></span>',
);
sentences[0] = sentences[0].replace(
/(not meeting weekly volunteer time commitment)/gi,
'<span style="color: blue;"><b>$1</b></span>',
);
enhancedDescription = sentences.join('.');
enhancedDescription = enhancedDescription.replace(
/logged (\d+(\.\d+)?\s*hours)/i,
'logged <span style="color: blue;"><b>$1</b></span>',
);
} else {
enhancedDescription = `<span style="color: blue;"><b>${item.description}</b></span>`;
}
}
return `<p>${index + 1}. Date: <span style="color: blue;"><b>${moment(item.date).format(
'M-D-YYYY',
)}</b></span>, Description: ${enhancedDescription}</p>`;
})
.join('');
}
userprofile.infringements.push({
date: moment().tz('America/Los_Angeles'),
description: `System auto-assigned infringement for editing your time entries <${totalRecentEdits}> times within the last 365 days, exceeding the limit of 4 times per year you can edit them without penalty.
time entry edits in the last calendar year`,
});
const infringementNotificationToAdminEmailBody = `
<p>
${userprofile.firstName} ${userprofile.lastName} (${userprofile.email}) was issued a blue square for editing their time entries ${totalRecentEdits} times
within the last calendar year.
</p>
<p>
This is the ${totalRecentEdits}th edit within the past 365 days.
</p>
`;
const infringementNotificationToUserEmailBody = `Dear <b>${userprofile.firstName} ${userprofile.lastName}</b>,
<p>Oops, it looks like you chose to edit your time entries too many times and you’ve managed to get a blue square.</p>
<p><b>Date Assigned:</b> ${moment().tz('America/Los_Angeles').format('M-D-YYYY')}</p>\
<p><b>Description:</b> System auto-assigned infringement for editing your time entries <b>${totalRecentEdits} times</b> within the last 365 days, exceeding the limit of 4 times per year you can edit them without penalty.</p>
<p><b>Total Infringements:</b> This is your <b>${moment
.localeData()
.ordinal(recentInfringements.length)}</b> blue square of 5.</p>
<p>Thank you,<p>
<p>One Community</p>
<!-- Adding multiple non-breaking spaces -->
<hr style="border-top: 1px dashed #000;"/>
<p><b>ADMINISTRATIVE DETAILS:</b></p>
<p><b>Start Date:</b> ${moment(userprofile.startDate).utc().format('M-D-YYYY')}</p>
<p><b>Role:</b> ${userprofile.role}</p>
<p><b>Title:</b> ${userprofile.userTitle || 'Volunteer'} </p>
<p><b>Previous Blue Square Reasons: </b></p>
${modifiedRecentInfringements}`;
pendingEmailCollection.push(
emailSender.bind(
null,
'onecommunityglobal@gmail.com',
`${userprofile.firstName} ${userprofile.lastName} was issued a blue square for for editing a time entry ${totalRecentEdits} times`,
infringementNotificationToAdminEmailBody,
),
emailSender.bind(
null,
userprofile.email,
'You’ve been issued a blue square for editing your time entries too many times',
infringementNotificationToUserEmailBody,
),
);
}
};
/**
* Update timeEntry with wbsId and taskId if projectId in the old timeentry is actually a taskId
* @param {*} id The id of the time entry
* @param {*} timeEntry The time entry object
* @returns {Void}
*/
const updateTaskIdInTimeEntry = async (id, timeEntry) => {
// if id is a taskId, then timeentry should have the parent wbsId and projectId for that task;
// if id is not a taskId, then it is a projectId, timeentry should have both wbsId and taskId to be null;
let taskId = null;
let wbsId = null;
let projectId = id;
const task = await Task.findById(id);
if (task) {
taskId = id;
({ wbsId } = task);
const wbs = await WBS.findById(wbsId);
({ projectId } = wbs);
}
Object.assign(timeEntry, { taskId, wbsId, projectId });
};
/**
* Controller for timeEntry
*/
const timeEntrycontroller = function (TimeEntry) {
const invalidateWeeklySummariesCache = (weekIndex) => {
const cacheKey = `weeklySummaries_${weekIndex}`;
cacheUtil.removeCache(cacheKey);
// Also invalidate the "all weeks" cache
cacheUtil.removeCache('weeklySummaries_all');
};
/**
* Helper func: Check if this is the first time entry for the given user id
*
* @param {Mongoose.ObjectId} personId
* @returns
*/
const checkIsUserFirstTimeEntry = async (personId) => {
try {
const timeEntry = await TimeEntry.findOne({
personId,
});
if (timeEntry) {
return false;
}
} catch (error) {
throw new Error(`Failed to check user with id ${personId} on time entry`);
}
return true;
};
/**
* Post a time entry
*/
const postTimeEntry = async function (req, res) {
const isInvalid =
!req.body.dateOfWork ||
!moment(req.body.dateOfWork).isValid() ||
!(req.body.hours || req.body.minutes);
const returnErr = (result) => {
result.status(400).send({ error: 'Bad request' });
};
const isPostingForSelf = req.body.personId === req.body.requestor.requestorId;
const canPostTimeEntriesForOthers = await hasPermission(req.body.requestor, 'postTimeEntry');
if (!isPostingForSelf && !canPostTimeEntriesForOthers) {
res.status(403).send({ error: 'You do not have permission to post time entries for others' });
return;
}
switch (req.body.entryType) {
case 'person':
if (!mongoose.Types.ObjectId.isValid(req.body.personId) || isInvalid) returnErr(res);
break;
case 'project':
if (!mongoose.Types.ObjectId.isValid(req.body.projectId) || isInvalid) returnErr(res);
break;
case 'team':
if (!mongoose.Types.ObjectId.isValid(req.body.teamId) || isInvalid) returnErr(res);
break;
default:
if (
!mongoose.Types.ObjectId.isValid(req.body.personId) ||
!mongoose.Types.ObjectId.isValid(req.body.projectId) ||
isInvalid
)
returnErr(res);
}
const session = await mongoose.startSession();
session.startTransaction();
const pendingEmailCollection = [];
try {
const timeEntry = new TimeEntry();
const now = moment().utc().toISOString();
timeEntry.personId = req.body.personId;
timeEntry.projectId = req.body.projectId;
timeEntry.wbsId = req.body.wbsId;
timeEntry.taskId = req.body.taskId;
timeEntry.teamId = req.body.teamId;
timeEntry.dateOfWork = moment(req.body.dateOfWork).format('YYYY-MM-DD');
timeEntry.totalSeconds = moment
.duration({ hours: req.body.hours, minutes: req.body.minutes })
.asSeconds();
timeEntry.notes = req.body.notes;
timeEntry.isTangible = req.body.isTangible;
timeEntry.createdDateTime = now;
timeEntry.lastModifiedDateTime = now;
timeEntry.entryType = req.body.entryType;
const userprofile = await UserProfile.findById(timeEntry.personId);
if (userprofile) {
// if the time entry is tangible, update the tangible hours in the user profile
if (timeEntry.isTangible) {
// update the total tangible hours in the user profile and the hours by category
updateUserprofileTangibleIntangibleHrs(timeEntry.totalSeconds, 0, userprofile);
await updateUserprofileCategoryHrs(
null,
null,
timeEntry.projectId,
timeEntry.totalSeconds,
userprofile,
);
// if the time entry is related to a task, update the task hoursLogged
if (timeEntry.taskId) {
await updateTaskLoggedHours(
timeEntry.taskId,
0,
timeEntry.taskId,
timeEntry.totalSeconds,
userprofile,
session,
pendingEmailCollection,
);
}
} else {
// if the time entry is intangible, just update the intangible hours in the userprofile
updateUserprofileTangibleIntangibleHrs(0, timeEntry.totalSeconds, userprofile);
}
}
// Replace the isFirstTimelog checking logic from the frontend to the backend
// Update the user start date to current date if this is the first time entry (Weekly blue square assignment related)
const isFirstTimeEntry = await checkIsUserFirstTimeEntry(timeEntry.personId);
if (isFirstTimeEntry) {
userprofile.isFirstTimelog = false;
userprofile.startDate = now;
}
await timeEntry.save({ session });
if (userprofile) {
await userprofile.save({ session, validateModifiedOnly: true });
// since userprofile is updated, need to remove the cache so that the updated userprofile is fetched next time
removeOutdatedUserprofileCache(userprofile._id.toString());
// Add cache invalidation for weekly summaries here
const dateOfWork = new Date(timeEntry.dateOfWork);
const today = new Date();
const diffTime = today - dateOfWork;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
// Calculate which week this entry belongs to (0 = this week, 1 = last week, etc.)
const weekIndex = Math.floor(diffDays / 7);
// Only invalidate cache for entries in the last 4 weeks
if (weekIndex >= 0 && weekIndex <= 3) {
// Call the invalidation function
invalidateWeeklySummariesCache(weekIndex);
}
}
await session.commitTransaction();
pendingEmailCollection.forEach((emailHandler) => emailHandler());
return res.status(200).send({
message: 'Time Entry saved successfully',
});
} catch (err) {
await session.abortTransaction();
logger.logException(err);
return res.status(500).send({ error: err.toString() });
} finally {
session.endSession();
}
};
/**
* Edit a time entry
*/
const editTimeEntry = async (req, res) => {
const { timeEntryId } = req.params;
if (!timeEntryId) {
const error = 'ObjectId in request param is not in correct format';
return res.status(400).send({ error });
}
const {
personId,
hours: newHours,
minutes: newMinutes,
notes: newNotes,
isTangible: newIsTangible,
projectId: newProjectId,
wbsId: newWbsId,
taskId: newTaskId,
dateOfWork: newDateOfWork,
entryType,
} = req.body;
const newTotalSeconds = newHours * 3600 + newMinutes * 60;
const type = req.body.entryType;
const isGeneralEntry = isGeneralTimeEntry(type);
if (
!mongoose.Types.ObjectId.isValid(timeEntryId) ||
((isGeneralEntry || type === 'project') && !mongoose.Types.ObjectId.isValid(newProjectId))
) {
const error = 'ObjectIds are not correctly formed';
return res.status(400).send({ error });
}
const isForAuthUser = personId === req.body.requestor.requestorId;
const isSameDayTimeEntry =
moment().tz('America/Los_Angeles').format('YYYY-MM-DD') === newDateOfWork;
const isSameDayAuthUserEdit = isForAuthUser && isSameDayTimeEntry;
const session = await mongoose.startSession();
session.startTransaction();
const pendingEmailCollection = [];
/**
* possible side effects of time entry edit:
* 1. note change => no side effect
* 2. task change => task logged hours change (for both old and new task)
* 3. project change => userprofile hoursByCategory change
* 4. tangibility change => task logged hours change (for old or new tasks)
* userporfile totalTangibleHrs/totalInTangibleHrs change
* userprofile hoursByCategory change
* 5. time change => task logged hours change
* userprofile totalTangibleHrs/totalInTangibleHrs change
* userprofile hoursByCategory change
* add to userprofile timeEntryEditHistory
* notifyEditByEmail
* 6. dateOfWork change => add to userprofile timeEntryEditHistory
* notifyEditByEmail
*/
try {
// Get initial timeEntry by timeEntryId
const timeEntry = await TimeEntry.findById(timeEntryId);
if (!timeEntry) {
const error = `No valid records found for ${timeEntryId}`;
return res.status(400).send({ error });
}
const {
totalSeconds: initialTotalSeconds,
isTangible: initialIsTangible,
projectId: initialProjectIdObject,
taskId: initialTaskIdObject,
dateOfWork: initialDateOfWork,
} = timeEntry;
const initialProjectId = initialProjectIdObject ? initialProjectIdObject.toString() : null;
const initialTaskId = initialTaskIdObject ? initialTaskIdObject.toString() : null;
// Check if any of the fields have changed
const projectChanged = initialProjectId !== newProjectId;
const tangibilityChanged = initialIsTangible !== newIsTangible;
const timeChanged = initialTotalSeconds !== newTotalSeconds;
const dateOfWorkChanged = initialDateOfWork !== newDateOfWork;
const isTimeModified = newTotalSeconds !== timeEntry.totalSeconds;
const isDescriptionModified = newNotes !== timeEntry.notes;
const canEditTimeEntryTime = await hasPermission(req.body.requestor, 'editTimeEntryTime');
const canEditTimeEntryDescription = await hasPermission(
req.body.requestor,
'editTimeEntryDescription',
);
const canEditTimeEntryDate = await hasPermission(req.body.requestor, 'editTimeEntryDate');
const canEditTimeEntryIsTangible = isForAuthUser
? await hasPermission(req.body.requestor, 'toggleTangibleTime')
: await hasPermission(req.body.requestor, 'editTimeEntryToggleTangible');
const isNotUsingAPermission =
(!canEditTimeEntryTime && isTimeModified) || (!canEditTimeEntryDate && dateOfWorkChanged);
// Time
if (!isSameDayAuthUserEdit && isTimeModified && !canEditTimeEntryTime) {
const error = `You do not have permission to edit the time entry time`;
return res.status(403).send({ error });
}
// Description
if (!isSameDayAuthUserEdit && isDescriptionModified && !canEditTimeEntryDescription) {
const error = `You do not have permission to edit the time entry description`;
return res.status(403).send({ error });
}
// Date
if (dateOfWorkChanged && !canEditTimeEntryDate) {
const error = `You do not have permission to edit the time entry date`;
return res.status(403).send({ error });
}
// Tangible Time
if (tangibilityChanged && !canEditTimeEntryIsTangible) {
const error = `You do not have permission to edit the time entry isTangible`;
return res.status(403).send({ error });
}
timeEntry.notes = newNotes;
timeEntry.totalSeconds = newTotalSeconds;
timeEntry.isTangible = newIsTangible;
timeEntry.lastModifiedDateTime = moment().utc().toISOString();
if (newProjectId) timeEntry.projectId = mongoose.Types.ObjectId(newProjectId);
timeEntry.wbsId = newWbsId ? mongoose.Types.ObjectId(newWbsId) : null;
timeEntry.taskId = newTaskId ? mongoose.Types.ObjectId(newTaskId) : null;
timeEntry.dateOfWork = moment(newDateOfWork).format('YYYY-MM-DD');
// now handle the side effects in task and userprofile if certain fields have changed
const userprofile = await UserProfile.findById(personId);
if (userprofile) {
if (tangibilityChanged) {
// if tangibility changed
// tangiblity change usually only happens by itself via tangibility checkbox,
// and it can't be changed by user directly (except for owner-like roles)
// but here the other changes are also considered here for completeness
// change from tangible to intangible
if (initialIsTangible) {
// subtract initial logged hours from old task (if not null)
await updateTaskLoggedHours(
initialTaskId,
initialTotalSeconds,
null,
null,
userprofile,
session,
pendingEmailCollection,
);
// subtract initial logged hours from userprofile totalTangibleHrs and add new logged hours to userprofile totalIntangibleHrs
updateUserprofileTangibleIntangibleHrs(
-initialTotalSeconds,
newTotalSeconds,
userprofile,
);
// when changing from tangible to intangible, the original time needs to be removed from hoursByCategory
await updateUserprofileCategoryHrs(
initialProjectIdObject,
initialTotalSeconds,
null,
null,
userprofile,
);
} else {
// from intangible to tangible
await updateTaskLoggedHours(
null,
null,
newTaskId,
newTotalSeconds,
userprofile,
session,
pendingEmailCollection,
);
updateUserprofileTangibleIntangibleHrs(
newTotalSeconds,
-initialTotalSeconds,
userprofile,
);
await updateUserprofileCategoryHrs(
null,
null,
newProjectId,
newTotalSeconds,
userprofile,
);
}
// make sure all hours are positive
validateUserprofileHours(userprofile);
} else if (initialIsTangible) {
// if tangibility is not changed,
// when timeentry remains tangible, this is usually when timeentry is edited by user in the same day or by owner-like roles
// it doesn't matter if task is changed or not, just update taskLoggedHours and userprofile totalTangibleHours with new and old task ids
await updateTaskLoggedHours(
initialTaskId,
initialTotalSeconds,
newTaskId,
newTotalSeconds,
userprofile,
session,
pendingEmailCollection,
);
// when project is also changed
if (projectChanged || timeChanged) {
await updateUserprofileCategoryHrs(
initialProjectIdObject,
initialTotalSeconds,
newProjectId,
newTotalSeconds,
userprofile,
);
validateUserprofileHours(userprofile);
}
// if time or dateOfWork is changed
if (timeChanged || dateOfWorkChanged) {
const timeDiffInSeconds = newTotalSeconds - initialTotalSeconds;
updateUserprofileTangibleIntangibleHrs(timeDiffInSeconds, 0, userprofile);
notifyEditByEmail(
userprofile,
req.body.requestor.requestorId,
initialTotalSeconds,
newTotalSeconds,
initialDateOfWork,
newDateOfWork,
);
// Update edit history
if (isNotUsingAPermission && isSameDayAuthUserEdit && isGeneralEntry) {
addEditHistory(
userprofile,
initialTotalSeconds,
newTotalSeconds,
initialDateOfWork,
newDateOfWork,
pendingEmailCollection,
);
}
}
} else {
// when timeentry is intangible before and after change,
// just update timeEntry and the intangible hours in userprofile,
// no need to update task/userprofile
const timeDiffInSeconds = newTotalSeconds - initialTotalSeconds;
updateUserprofileTangibleIntangibleHrs(0, timeDiffInSeconds, userprofile);
}
}
await timeEntry.save({ session });
if (userprofile) {
await userprofile.save({ session, validateModifiedOnly: true });
// since userprofile is updated, need to remove the cache so that the updated userprofile is fetched next time
removeOutdatedUserprofileCache(userprofile._id.toString());
}
pendingEmailCollection.forEach((emailHandler) => emailHandler());
if (entryType === 'team') {
const lostteamentryCache = cacheClosure();
lostteamentryCache.clearByPrefix('LostTeamEntry_');
}
await session.commitTransaction();
return res.status(200).send(timeEntry);
} catch (err) {
await session.abortTransaction();
logger.logException(err);
return res.status(400).send({ error: err.toString() });
} finally {
session.endSession();
}
};
/**
* Delete a time entry
*/
const deleteTimeEntry = async function (req, res) {
if (!req.params.timeEntryId) {
res.status(400).send({ error: 'Bad request' });
return;
}
const session = await mongoose.startSession();
session.startTransaction();
try {
const timeEntry = await TimeEntry.findById(req.params.timeEntryId);
if (!timeEntry) {
res.status(400).send({ message: 'No valid record found' });
return;
}
const { personId, totalSeconds, dateOfWork, projectId, taskId, isTangible } = timeEntry;
const isForAuthUser = personId
? personId.toString() === req.body.requestor.requestorId
: false;
const isSameDayTimeEntry =
moment().tz('America/Los_Angeles').format('YYYY-MM-DD') === dateOfWork;
const isSameDayAuthUserDelete = isForAuthUser && isSameDayTimeEntry;
const hasDeleteTimeEntryPermission = await hasPermission(
req.body.requestor,
'deleteTimeEntry',
);
const canDelete = isSameDayAuthUserDelete || hasDeleteTimeEntryPermission;
if (!canDelete) {
res.status(403).send({ error: 'Unauthorized request' });
return;
}
const userprofile = await UserProfile.findById(personId);
if (userprofile) {
// Revert this tangible timeEntry of related task's hoursLogged
if (isTangible) {
updateUserprofileTangibleIntangibleHrs(-totalSeconds, 0, userprofile);
await updateUserprofileCategoryHrs(projectId, totalSeconds, null, null, userprofile);
// if the time entry is related to a task, update the task hoursLogged
if (taskId) {
await updateTaskLoggedHours(taskId, totalSeconds, null, null, userprofile, session);
}
} else {
updateUserprofileTangibleIntangibleHrs(0, -totalSeconds, userprofile);
}
}
if (timeEntry?.entryType === 'team') {
const lostteamentryCache = cacheClosure();
lostteamentryCache.clearByPrefix('LostTeamEntry_');
}
await timeEntry.remove({ session });
if (userprofile) {
await userprofile.save({ session, validateModifiedOnly: true });
// since userprofile is updated, need to remove the cache so that the updated userprofile is fetched next time
removeOutdatedUserprofileCache(userprofile._id.toString());
}
await session.commitTransaction();
res.status(200).send({ message: 'Successfully deleted' });
} catch (error) {
await session.abortTransaction();
logger.logException(error);
res.status(500).send({ error: error.toString() });
} finally {
session.endSession();
}
};
/**
* Get time entries for a specified period
*/
const getTimeEntriesForSpecifiedPeriod = async function (req, res) {
if (
!req.params ||