From 175e95c3a3022818e8ad607aa1c4195cf61c8548 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 31 Mar 2024 15:04:11 +0800
Subject: [PATCH 01/15] some logs
---
src/helpers/userHelper.js | 703 ++++++++++++++------------------------
1 file changed, 263 insertions(+), 440 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 4f4c69397..5d125d5e0 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -1,68 +1,68 @@
/* eslint-disable quotes */
/* eslint-disable no-continue */
/* eslint-disable no-await-in-loop */
-const mongoose = require("mongoose");
-const moment = require("moment-timezone");
-const _ = require("lodash");
-const userProfile = require("../models/userProfile");
-const timeEntries = require("../models/timeentry");
-const badge = require("../models/badge");
-const myTeam = require("./helperModels/myTeam");
-const dashboardHelper = require("./dashboardhelper")();
-const reportHelper = require("./reporthelper")();
-const emailSender = require("../utilities/emailSender");
-const logger = require("../startup/logger");
-const Reason = require("../models/reason");
-const token = require("../models/profileInitialSetupToken");
-const cache = require("../utilities/nodeCache")();
-const timeOffRequest = require("../models/timeOffRequest");
+const mongoose = require('mongoose');
+const moment = require('moment-timezone');
+const _ = require('lodash');
+const userProfile = require('../models/userProfile');
+const timeEntries = require('../models/timeentry');
+const badge = require('../models/badge');
+const myTeam = require('./helperModels/myTeam');
+const dashboardHelper = require('./dashboardhelper')();
+const reportHelper = require('./reporthelper')();
+const emailSender = require('../utilities/emailSender');
+const logger = require('../startup/logger');
+const Reason = require('../models/reason');
+const token = require('../models/profileInitialSetupToken');
+const cache = require('../utilities/nodeCache')();
+const timeOffRequest = require('../models/timeOffRequest');
const userHelper = function () {
// Update format to "MMM-DD-YY" from "YYYY-MMM-DD" (Confirmed with Jae)
const earnedDateBadge = () => {
const currentDate = new Date(Date.now());
- return moment(currentDate).tz("America/Los_Angeles").format("MMM-DD-YY");
+ return moment(currentDate).tz('America/Los_Angeles').format('MMM-DD-YY');
};
const getTeamMembers = function (user) {
const userId = mongoose.Types.ObjectId(user._id);
// var teamid = userdetails.teamId;
return myTeam.findById(userId).select({
- "myTeam._id": 0,
- "myTeam.role": 0,
- "myTeam.fullName": 0,
+ 'myTeam._id': 0,
+ 'myTeam.role': 0,
+ 'myTeam.fullName': 0,
_id: 0,
});
};
const getUserName = async function (userId) {
const userid = mongoose.Types.ObjectId(userId);
- return userProfile.findById(userid, "firstName lastName");
+ return userProfile.findById(userid, 'firstName lastName');
};
const validateProfilePic = function (profilePic) {
// if it is a url
- if (typeof profilePic !== "string") {
+ if (typeof profilePic !== 'string') {
return {
result: false,
- errors: "Invalid image",
+ errors: 'Invalid image',
};
}
if (profilePic.startsWith('http') || profilePic.startsWith('https')) {
return {
result: true,
- errors: "Valid image",
+ errors: 'Valid image',
};
}
- const picParts = profilePic.split(",");
+ const picParts = profilePic.split(',');
let result = true;
const errors = [];
if (picParts.length < 2) {
return {
result: false,
- errors: "Invalid image",
+ errors: 'Invalid image',
};
}
@@ -70,13 +70,13 @@ const userHelper = function () {
const imageSize = picParts[1].length;
const sizeInBytes = (Math.ceil(imageSize / 4) * 3) / 1024;
if (sizeInBytes > 50) {
- errors.push("Image size should not exceed 50KB");
+ errors.push('Image size should not exceed 50KB');
result = false;
}
- const imageType = picParts[0].split("/")[1].split(";")[0];
- if (imageType !== "jpeg" && imageType !== "png") {
- errors.push("Image type shoud be either jpeg or png.");
+ const imageType = picParts[0].split('/')[1].split(';')[0];
+ if (imageType !== 'jpeg' && imageType !== 'png') {
+ errors.push('Image type shoud be either jpeg or png.');
result = false;
}
@@ -95,10 +95,11 @@ const userHelper = function () {
coreTeamExtraHour,
requestForTimeOffEmailBody,
) {
- let finalParagraph = "";
+ let finalParagraph = '';
if (timeRemaining === undefined) {
- finalParagraph = "Life happens and we understand that. That’s why we allow 5 of them before taking action. This action usually includes removal from our team though, so please let your direct supervisor know what happened and do your best to avoid future blue squares if you are getting close to 5 and wish to avoid termination. Each blue square drops off after a year.
";
+ finalParagraph =
+ 'Life happens and we understand that. That’s why we allow 5 of them before taking action. This action usually includes removal from our team though, so please let your direct supervisor know what happened and do your best to avoid future blue squares if you are getting close to 5 and wish to avoid termination. Each blue square drops off after a year.
';
} else {
finalParagraph = `Please complete ALL owed time this week (${
timeRemaining + coreTeamExtraHour
@@ -108,8 +109,7 @@ const userHelper = function () {
const text = `Dear ${firstName} ${lastName},
Oops, it looks like something happened and you’ve managed to get a blue square.
Date Assigned: ${infringement.date}
\
- Description: ${
- requestForTimeOffEmailBody || infringement.description }
+ Description: ${requestForTimeOffEmailBody || infringement.description}
Total Infringements: This is your ${moment
.localeData()
.ordinal(totalInfringements)} blue square of 5.
@@ -130,7 +130,7 @@ const userHelper = function () {
* @return {void}
*/
const emailWeeklySummariesForAllUsers = async (weekIndex = 1) => {
- const currentFormattedDate = moment().tz("America/Los_Angeles").format();
+ const currentFormattedDate = moment().tz('America/Los_Angeles').format();
logger.logInfo(
`Job for emailing all users' weekly summaries starting at ${currentFormattedDate}`,
@@ -142,26 +142,23 @@ const userHelper = function () {
try {
const results = await reportHelper.weeklySummaries(weekIndex, weekIndex);
// checks for userProfiles who are eligible to receive the weeklySummary Reports
- await userProfile
- .find({ getWeeklyReport: true }, { email: 1, _id: 0 })
- .then((results) => {
- mappedResults = results.map((ele) => ele.email);
- mappedResults.push(
- "onecommunityglobal@gmail.com",
- "onecommunityhospitality@gmail.com",
- );
- mappedResults = mappedResults.toString();
- });
+ await userProfile.find({ getWeeklyReport: true }, { email: 1, _id: 0 }).then((results) => {
+ mappedResults = results.map((ele) => ele.email);
+ mappedResults.push('onecommunityglobal@gmail.com', 'onecommunityhospitality@gmail.com');
+ mappedResults = mappedResults.toString();
+ });
- let emailBody = "Weekly Summaries for all active users:
";
+ let emailBody = 'Weekly Summaries for all active users:
';
- const weeklySummaryNotProvidedMessage = 'Weekly Summary: Not provided!
';
+ const weeklySummaryNotProvidedMessage =
+ 'Weekly Summary: Not provided!
';
- const weeklySummaryNotRequiredMessage = 'Weekly Summary: Not required for this user
';
+ const weeklySummaryNotRequiredMessage =
+ 'Weekly Summary: Not required for this user
';
- results.sort((a, b) => `${a.firstName} ${a.lastName}`.localeCompare(
- `${b.firstName} ${b.lastname}`,
- ));
+ results.sort((a, b) =>
+ `${a.firstName} ${a.lastName}`.localeCompare(`${b.firstName} ${b.lastname}`),
+ );
for (let i = 0; i < results.length; i += 1) {
const result = results[i];
@@ -186,13 +183,12 @@ const userHelper = function () {
// hence totalSeconds[0] should be used
const hoursLogged = result.totalSeconds[0] / 3600 || 0;
- const mediaUrlLink = mediaUrl
- ? `${mediaUrl}`
- : "Not provided!";
+ const mediaUrlLink = mediaUrl ? `${mediaUrl}` : 'Not provided!';
- const googleDocLinkValue = adminLinks?.length > 0
- ? adminLinks.find(link => link.Name === 'Google Doc' && link.Link)
- : null;
+ const googleDocLinkValue =
+ adminLinks?.length > 0
+ ? adminLinks.find((link) => link.Name === 'Google Doc' && link.Link)
+ : null;
const googleDocLink = googleDocLinkValue
? `${googleDocLinkValue.Link}`
@@ -201,14 +197,14 @@ const userHelper = function () {
let weeklySummaryMessage = weeklySummaryNotProvidedMessage;
const colorStyle = (() => {
switch (weeklySummaryOption) {
- case "Team":
+ case 'Team':
return 'style="color: magenta;"';
- case "Not Required":
+ case 'Not Required':
return 'style="color: green"';
- case "Required":
- return "";
+ case 'Required':
+ return '';
default:
- return result.weeklySummaryNotReq ? 'style="color: green"' : "";
+ return result.weeklySummaryNotReq ? 'style="color: green"' : '';
}
})();
// weeklySummaries array should only have one item if any, hence weeklySummaries[0] needs be used to access it.
@@ -219,16 +215,16 @@ const userHelper = function () {
Weekly Summary
(for the week ending on ${moment(dueDate)
- .tz("America/Los_Angeles")
- .format("YYYY-MMM-DD")}):
+ .tz('America/Los_Angeles')
+ .format('YYYY-MMM-DD')}):
${summary}
`;
} else if (
- weeklySummaryOption === "Not Required"
- || (!weeklySummaryOption && result.weeklySummaryNotReq)
+ weeklySummaryOption === 'Not Required' ||
+ (!weeklySummaryOption && result.weeklySummaryNotReq)
) {
weeklySummaryMessage = weeklySummaryNotRequiredMessage;
}
@@ -240,9 +236,7 @@ const userHelper = function () {
Name: ${firstName} ${lastName}
- Media URL: ${
- mediaUrlLink || 'Not provided!'
- }
+ Media URL: ${mediaUrlLink || 'Not provided!'}
@@ -256,14 +250,12 @@ const userHelper = function () {
weeklySummariesCount === 8
? `
Total Valid Weekly Summaries: ${weeklySummariesCount}
`
: `Total Valid Weekly Summaries: ${
- weeklySummariesCount || "No valid submissions yet!"
+ weeklySummariesCount || 'No valid submissions yet!'
}
`
}
${
hoursLogged >= weeklycommittedHours
- ? `Hours logged: ${hoursLogged.toFixed(
- 2,
- )} / ${weeklycommittedHours}
`
+ ? `Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}
`
: `Hours logged: ${hoursLogged.toFixed(
2,
)} / ${weeklycommittedHours}
`
@@ -275,11 +267,11 @@ const userHelper = function () {
// Necessary because our version of node is outdated
// and doesn't have String.prototype.replaceAll
let emailString = [...new Set(emails)].toString();
- while (emailString.includes(",")) {
- emailString = emailString.replace(",", "\n");
+ while (emailString.includes(',')) {
+ emailString = emailString.replace(',', '\n');
}
- while (emailString.includes("\n")) {
- emailString = emailString.replace("\n", ", ");
+ while (emailString.includes('\n')) {
+ emailString = emailString.replace('\n', ', ');
}
emailBody += `\n
@@ -295,7 +287,7 @@ const userHelper = function () {
emailSender(
mailList,
- "Weekly Summaries for all active users...",
+ 'Weekly Summaries for all active users...',
emailBody,
null,
null,
@@ -320,8 +312,8 @@ const userHelper = function () {
weeklySummaries: {
$each: [
{
- dueDate: moment().tz("America/Los_Angeles").endOf("week"),
- summary: "",
+ dueDate: moment().tz('America/Los_Angeles').endOf('week'),
+ summary: '',
},
],
$position: 0,
@@ -340,29 +332,23 @@ const userHelper = function () {
*/
const assignBlueSquareForTimeNotMet = async () => {
try {
- const currentFormattedDate = moment().tz("America/Los_Angeles").format();
- const currentUTCDate = moment
- .tz("America/Los_Angeles")
- .startOf("day")
- .toISOString();
+ const currentFormattedDate = moment().tz('America/Los_Angeles').format();
+ const currentUTCDate = moment.tz('America/Los_Angeles').startOf('day').toISOString();
logger.logInfo(
`Job for assigning blue square for commitment not met starting at ${currentFormattedDate}`,
);
const pdtStartOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .startOf("week")
- .subtract(1, "week");
+ .tz('America/Los_Angeles')
+ .startOf('week')
+ .subtract(1, 'week');
- const pdtEndOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .endOf("week")
- .subtract(1, "week");
+ const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
{ isActive: true },
- "_id weeklycommittedHours weeklySummaries missedHours",
+ '_id weeklycommittedHours weeklySummaries missedHours',
);
// this part is supposed to be a for, so it'll be slower when sending emails, so the emails will not be
@@ -377,10 +363,7 @@ const userHelper = function () {
let hasWeeklySummary = false;
- if (
- Array.isArray(user.weeklySummaries)
- && user.weeklySummaries.length
- ) {
+ if (Array.isArray(user.weeklySummaries) && user.weeklySummaries.length) {
const { summary } = user.weeklySummaries[0];
if (summary) {
hasWeeklySummary = true;
@@ -426,26 +409,26 @@ const userHelper = function () {
);
if (
- updateResult?.weeklySummaryOption === "Not Required"
- || updateResult?.weeklySummaryNotReq
+ updateResult?.weeklySummaryOption === 'Not Required' ||
+ updateResult?.weeklySummaryNotReq
) {
hasWeeklySummary = true;
}
- const cutOffDate = moment().subtract(1, "year");
+ const cutOffDate = moment().subtract(1, 'year');
const oldInfringements = [];
for (let k = 0; k < updateResult?.infringements.length; k += 1) {
if (
- updateResult?.infringements
- && moment(updateResult?.infringements[k].date).diff(cutOffDate) >= 0
+ updateResult?.infringements &&
+ moment(updateResult?.infringements[k].date).diff(cutOffDate) >= 0
) {
oldInfringements.push(updateResult.infringements[k]);
} else {
break;
}
}
-
+ const historyInfringements = 'No Previous Infringements.';
if (oldInfringements.length) {
userProfile.findByIdAndUpdate(
personId,
@@ -479,12 +462,12 @@ const userHelper = function () {
if (hasTimeOffRequest) {
requestForTimeOff = requestsForTimeOff[0];
- requestForTimeOffStartingDate = moment(
- requestForTimeOff.startingDate,
- ).format("dddd YYYY-MM-DD");
- requestForTimeOffEndingDate = moment(
- requestForTimeOff.endingDate,
- ).format("dddd YYYY-MM-DD");
+ requestForTimeOffStartingDate = moment(requestForTimeOff.startingDate).format(
+ 'dddd YYYY-MM-DD',
+ );
+ requestForTimeOffEndingDate = moment(requestForTimeOff.endingDate).format(
+ 'dddd YYYY-MM-DD',
+ );
requestForTimeOffreason = requestForTimeOff.reason;
requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, due to: ${requestForTimeOffreason}`;
}
@@ -493,14 +476,12 @@ const userHelper = function () {
if (hasTimeOffRequest) {
description = requestForTimeOffreason;
} else if (timeNotMet && !hasWeeklySummary) {
- if (person.role === "Core Team") {
+ if (person.role === 'Core Team') {
description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. In the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD",
+ 'dddd YYYY-MM-DD',
)} and ending ${pdtEndOfLastWeek.format(
- "dddd YYYY-MM-DD",
- )}, you logged ${timeSpent.toFixed(
- 2,
- )} hours against a committed effort of ${
+ 'dddd YYYY-MM-DD',
+ )}, you logged ${timeSpent.toFixed(2)} hours against a committed effort of ${
person.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
@@ -515,18 +496,16 @@ const userHelper = function () {
description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent.toFixed(
2,
)} hours against a committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD",
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
}
} else if (timeNotMet) {
- if (person.role === "Core Team") {
+ if (person.role === 'Core Team') {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. In the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD",
+ 'dddd YYYY-MM-DD',
)} and ending ${pdtEndOfLastWeek.format(
- "dddd YYYY-MM-DD",
- )}, you logged ${timeSpent.toFixed(
- 2,
- )} hours against a committed effort of ${
+ 'dddd YYYY-MM-DD',
+ )}, you logged ${timeSpent.toFixed(2)} hours against a committed effort of ${
user.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
@@ -541,19 +520,21 @@ const userHelper = function () {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed(
2,
)} hours against a committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD",
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
}
} else {
description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD",
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
}
const infringement = {
- date: moment().utc().format("YYYY-MM-DD"),
+ date: moment().utc().format('YYYY-MM-DD'),
description,
- createdDate: hasTimeOffRequest ? moment(requestForTimeOff.createdAt).format('YYYY-MM-DD') : null,
+ createdDate: hasTimeOffRequest
+ ? moment(requestForTimeOff.createdAt).format('YYYY-MM-DD')
+ : null,
};
const status = await userProfile.findByIdAndUpdate(
@@ -566,8 +547,8 @@ const userHelper = function () {
{ new: true },
);
- let emailBody = "";
- if (person.role === "Core Team" && timeRemaining > 0) {
+ let emailBody = '';
+ if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
status.lastName,
@@ -591,10 +572,10 @@ const userHelper = function () {
emailSender(
status.email,
- "New Infringement Assigned",
+ 'New Infringement Assigned',
emailBody,
null,
- "onecommunityglobal@gmail.com",
+ 'onecommunityglobal@gmail.com',
status.email,
null,
);
@@ -618,12 +599,12 @@ const userHelper = function () {
const elem = categories[j];
if (elem._id == null) {
- elem._id = "Other";
+ elem._id = 'Other';
}
const updateResult2 = await userProfile.findOneAndUpdate(
- { _id: personId, "categoryTangibleHrs.category": elem._id },
- { $inc: { "categoryTangibleHrs.$.hrs": elem.timeSpent_hrs } },
+ { _id: personId, 'categoryTangibleHrs.category': elem._id },
+ { $inc: { 'categoryTangibleHrs.$.hrs': elem.timeSpent_hrs } },
{ new: true },
);
@@ -631,7 +612,7 @@ const userHelper = function () {
await userProfile.findOneAndUpdate(
{
_id: personId,
- "categoryTangibleHrs.category": { $ne: elem._id },
+ 'categoryTangibleHrs.category': { $ne: elem._id },
},
{
$addToSet: {
@@ -653,14 +634,11 @@ const userHelper = function () {
// processWeeklySummaries for nonActive users
try {
- const inactiveUsers = await userProfile.find({ isActive: false }, "_id");
+ const inactiveUsers = await userProfile.find({ isActive: false }, '_id');
for (let i = 0; i < inactiveUsers.length; i += 1) {
const user = inactiveUsers[i];
- await processWeeklySummariesByUserId(
- mongoose.Types.ObjectId(user._id),
- false,
- );
+ await processWeeklySummariesByUserId(mongoose.Types.ObjectId(user._id), false);
}
} catch (err) {
logger.logException(err);
@@ -669,50 +647,50 @@ const userHelper = function () {
const applyMissedHourForCoreTeam = async () => {
try {
- const currentDate = moment().tz("America/Los_Angeles").format();
+ const currentDate = moment().tz('America/Los_Angeles').format();
logger.logInfo(
`Job for applying missed hours for Core Team members starting at ${currentDate}`,
);
const startOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .startOf("week")
- .subtract(1, "week")
- .format("YYYY-MM-DD");
+ .tz('America/Los_Angeles')
+ .startOf('week')
+ .subtract(1, 'week')
+ .format('YYYY-MM-DD');
const endOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .endOf("week")
- .subtract(1, "week")
- .format("YYYY-MM-DD");
+ .tz('America/Los_Angeles')
+ .endOf('week')
+ .subtract(1, 'week')
+ .format('YYYY-MM-DD');
const missedHours = await userProfile.aggregate([
{
$match: {
- role: "Core Team",
+ role: 'Core Team',
isActive: true,
},
},
{
$lookup: {
- from: "timeEntries",
- localField: "_id",
- foreignField: "personId",
+ from: 'timeEntries',
+ localField: '_id',
+ foreignField: 'personId',
pipeline: [
{
$match: {
$expr: {
$and: [
- { $eq: ["$isTangible", true] },
- { $gte: ["$dateOfWork", startOfLastWeek] },
- { $lte: ["$dateOfWork", endOfLastWeek] },
+ { $eq: ['$isTangible', true] },
+ { $gte: ['$dateOfWork', startOfLastWeek] },
+ { $lte: ['$dateOfWork', endOfLastWeek] },
],
},
},
},
],
- as: "timeEntries",
+ as: 'timeEntries',
},
},
{
@@ -723,18 +701,15 @@ const userHelper = function () {
{
$subtract: [
{
- $sum: [
- { $ifNull: ["$missedHours", 0] },
- "$weeklycommittedHours",
- ],
+ $sum: [{ $ifNull: ['$missedHours', 0] }, '$weeklycommittedHours'],
},
{
$divide: [
{
$sum: {
$map: {
- input: "$timeEntries",
- in: "$$this.totalSeconds",
+ input: '$timeEntries',
+ in: '$$this.totalSeconds',
},
},
},
@@ -768,13 +743,13 @@ const userHelper = function () {
};
const deleteBlueSquareAfterYear = async () => {
- const currentFormattedDate = moment().tz("America/Los_Angeles").format();
+ const currentFormattedDate = moment().tz('America/Los_Angeles').format();
logger.logInfo(
`Job for deleting blue squares older than 1 year starting at ${currentFormattedDate}`,
);
- const cutOffDate = moment().subtract(1, "year").format("YYYY-MM-DD");
+ const cutOffDate = moment().subtract(1, 'year').format('YYYY-MM-DD');
try {
const results = await userProfile.updateMany(
@@ -797,7 +772,7 @@ const userHelper = function () {
};
const reActivateUser = async () => {
- const currentFormattedDate = moment().tz("America/Los_Angeles").format();
+ const currentFormattedDate = moment().tz('America/Los_Angeles').format();
logger.logInfo(
`Job for activating users based on scheduled re-activation date starting at ${currentFormattedDate}`,
@@ -806,7 +781,7 @@ const userHelper = function () {
try {
const users = await userProfile.find(
{ isActive: false, reactivationDate: { $exists: true } },
- "_id isActive reactivationDate",
+ '_id isActive reactivationDate',
);
for (let i = 0; i < users.length; i += 1) {
const user = users[i];
@@ -825,18 +800,14 @@ const userHelper = function () {
);
logger.logInfo(
`User with id: ${user._id} was re-acticated at ${moment()
- .tz("America/Los_Angeles")
+ .tz('America/Los_Angeles')
.format()}.`,
);
const id = user._id;
const person = await userProfile.findById(id);
- const endDate = moment(person.endDate).format("YYYY-MM-DD");
- logger.logInfo(
- `User with id: ${
- user._id
- } was re-acticated at ${moment().format()}.`,
- );
+ const endDate = moment(person.endDate).format('YYYY-MM-DD');
+ logger.logInfo(`User with id: ${user._id} was re-acticated at ${moment().format()}.`);
const subject = `IMPORTANT:${person.firstName} ${person.lastName} has been RE-activated in the Highest Good Network`;
@@ -850,14 +821,7 @@ const userHelper = function () {
The HGN A.I. (and One Community)
`;
- emailSender(
- "onecommunityglobal@gmail.com",
- subject,
- emailBody,
- null,
- null,
- person.email,
- );
+ emailSender('onecommunityglobal@gmail.com', subject, emailBody, null, null, person.email);
}
}
} catch (err) {
@@ -865,37 +829,24 @@ const userHelper = function () {
}
};
- const notifyInfringements = function (
- original,
- current,
- firstName,
- lastName,
- emailAddress,
- ) {
+ const notifyInfringements = function (original, current, firstName, lastName, emailAddress) {
if (!current) return;
const newOriginal = original.toObject();
const newCurrent = current.toObject();
const totalInfringements = newCurrent.length;
let newInfringements = [];
- newInfringements = _.differenceWith(
- newCurrent,
- newOriginal,
- (arrVal, othVal) => arrVal._id.equals(othVal._id),
+ newInfringements = _.differenceWith(newCurrent, newOriginal, (arrVal, othVal) =>
+ arrVal._id.equals(othVal._id),
);
newInfringements.forEach((element) => {
emailSender(
emailAddress,
- "New Infringement Assigned",
- getInfringementEmailBody(
- firstName,
- lastName,
- element,
- totalInfringements,
- ),
+ 'New Infringement Assigned',
+ getInfringementEmailBody(firstName, lastName, element, totalInfringements),
null,
- "onecommunityglobal@gmail.com",
+ 'onecommunityglobal@gmail.com',
emailAddress,
);
});
@@ -903,13 +854,13 @@ const userHelper = function () {
const replaceBadge = async function (personId, oldBadgeId, newBadgeId) {
userProfile.updateOne(
- { _id: personId, "badgeCollection.badge": oldBadgeId },
+ { _id: personId, 'badgeCollection.badge': oldBadgeId },
{
$set: {
- "badgeCollection.$.badge": newBadgeId,
- "badgeCollection.$.lastModified": Date.now().toString(),
- "badgeCollection.$.count": 1,
- "badgeCollection.$.earnedDate": [earnedDateBadge()],
+ 'badgeCollection.$.badge': newBadgeId,
+ 'badgeCollection.$.lastModified': Date.now().toString(),
+ 'badgeCollection.$.count': 1,
+ 'badgeCollection.$.earnedDate': [earnedDateBadge()],
},
},
(err) => {
@@ -922,11 +873,11 @@ const userHelper = function () {
const increaseBadgeCount = async function (personId, badgeId) {
userProfile.updateOne(
- { _id: personId, "badgeCollection.badge": badgeId },
+ { _id: personId, 'badgeCollection.badge': badgeId },
{
- $inc: { "badgeCollection.$.count": 1 },
- $set: { "badgeCollection.$.lastModified": Date.now().toString() },
- $push: { "badgeCollection.$.earnedDate": earnedDateBadge() },
+ $inc: { 'badgeCollection.$.count': 1 },
+ $set: { 'badgeCollection.$.lastModified': Date.now().toString() },
+ $push: { 'badgeCollection.$.earnedDate': earnedDateBadge() },
},
(err) => {
if (err) {
@@ -936,12 +887,7 @@ const userHelper = function () {
);
};
- const addBadge = async function (
- personId,
- badgeId,
- count = 1,
- featured = false,
- ) {
+ const addBadge = async function (personId, badgeId, count = 1, featured = false) {
userProfile.findByIdAndUpdate(
personId,
{
@@ -992,7 +938,7 @@ const userHelper = function () {
(item) => item.badge._id.toString() === badgeId.toString(),
);
if (!recordToUpdate) {
- throw new Error("Badge not found");
+ throw new Error('Badge not found');
}
// If the count is the same, do nothing
if (recordToUpdate.count === count) {
@@ -1012,14 +958,13 @@ const userHelper = function () {
}
newEarnedDate = [...copyOfEarnedDate];
userProfile.updateOne(
- { _id: personId, "badgeCollection.badge": badgeId },
+ { _id: personId, 'badgeCollection.badge': badgeId },
{
$set: {
- "badgeCollection.$.count": count,
- "badgeCollection.$.lastModified": Date.now().toString(),
- "badgeCollection.$.earnedDate": newEarnedDate,
- "badgeCollection.$.hasBadgeDeletionImpact":
- recordToUpdate.count > count, // badge deletion impact set to true if the new count is less than the old count
+ 'badgeCollection.$.count': count,
+ 'badgeCollection.$.lastModified': Date.now().toString(),
+ 'badgeCollection.$.earnedDate': newEarnedDate,
+ 'badgeCollection.$.hasBadgeDeletionImpact': recordToUpdate.count > count, // badge deletion impact set to true if the new count is less than the old count
},
},
(err) => {
@@ -1036,13 +981,7 @@ const userHelper = function () {
// remove the last badge you earned on this streak(not including 1)
- const removePrevHrBadge = async function (
- personId,
- user,
- badgeCollection,
- hrs,
- weeks,
- ) {
+ const removePrevHrBadge = async function (personId, user, badgeCollection, hrs, weeks) {
// Check each Streak Greater than One to check if it works
if (weeks < 3) {
return;
@@ -1052,7 +991,7 @@ const userHelper = function () {
.aggregate([
{
$match: {
- type: "X Hours for X Week Streak",
+ type: 'X Hours for X Week Streak',
weeks: { $gt: 1, $lt: weeks },
totalHrs: hrs,
},
@@ -1060,9 +999,9 @@ const userHelper = function () {
{ $sort: { weeks: -1, totalHrs: -1 } },
{
$group: {
- _id: "$weeks",
+ _id: '$weeks',
badges: {
- $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" },
+ $push: { _id: '$_id', hrs: '$totalHrs', weeks: '$weeks' },
},
},
},
@@ -1072,11 +1011,10 @@ const userHelper = function () {
streak.badges.every((bdge) => {
for (let i = 0; i < badgeCollection.length; i += 1) {
if (
- badgeCollection[i].badge?.type
- === "X Hours for X Week Streak"
- && badgeCollection[i].badge?.weeks === bdge.weeks
- && bdge.hrs === hrs
- && !removed
+ badgeCollection[i].badge?.type === 'X Hours for X Week Streak' &&
+ badgeCollection[i].badge?.weeks === bdge.weeks &&
+ bdge.hrs === hrs &&
+ !removed
) {
changeBadgeCount(
personId,
@@ -1094,24 +1032,14 @@ const userHelper = function () {
};
// 'No Infringement Streak',
- const checkNoInfringementStreak = async function (
- personId,
- user,
- badgeCollection,
- ) {
+ const checkNoInfringementStreak = async function (personId, user, badgeCollection) {
let badgeOfType;
for (let i = 0; i < badgeCollection.length; i += 1) {
- if (badgeCollection[i].badge?.type === "No Infringement Streak") {
- if (
- badgeOfType
- && badgeOfType.months <= badgeCollection[i].badge.months
- ) {
+ if (badgeCollection[i].badge?.type === 'No Infringement Streak') {
+ if (badgeOfType && badgeOfType.months <= badgeCollection[i].badge.months) {
removeDupBadge(personId, badgeOfType._id);
badgeOfType = badgeCollection[i].badge;
- } else if (
- badgeOfType
- && badgeOfType.months > badgeCollection[i].badge.months
- ) {
+ } else if (badgeOfType && badgeOfType.months > badgeCollection[i].badge.months) {
removeDupBadge(personId, badgeCollection[i].badge._id);
} else if (!badgeOfType) {
badgeOfType = badgeCollection[i].badge;
@@ -1119,7 +1047,7 @@ const userHelper = function () {
}
}
await badge
- .find({ type: "No Infringement Streak" })
+ .find({ type: 'No Infringement Streak' })
.sort({ months: -1 })
.then((results) => {
if (!Array.isArray(results) || !results.length) {
@@ -1130,18 +1058,13 @@ const userHelper = function () {
// Cannot account for time paused yet
if (elem.months <= 12) {
- if (
- moment().diff(moment(user.createdDate), "months", true)
- >= elem.months
- ) {
+ if (moment().diff(moment(user.createdDate), 'months', true) >= elem.months) {
if (
- user.infringements.length === 0
- || Math.abs(
+ user.infringements.length === 0 ||
+ Math.abs(
moment().diff(
- moment(
- user.infringements[user.infringements?.length - 1].date,
- ),
- "months",
+ moment(user.infringements[user.infringements?.length - 1].date),
+ 'months',
true,
),
) >= elem.months
@@ -1161,23 +1084,17 @@ const userHelper = function () {
}
}
} else if (user?.infringements?.length === 0) {
- if (
- moment().diff(moment(user.createdDate), "months", true)
- >= elem.months
- ) {
+ if (moment().diff(moment(user.createdDate), 'months', true) >= elem.months) {
if (
- user.oldInfringements.length === 0
- || Math.abs(
+ user.oldInfringements.length === 0 ||
+ Math.abs(
moment().diff(
- moment(
- user.oldInfringements[user.oldInfringements?.length - 1]
- .date,
- ),
- "months",
+ moment(user.oldInfringements[user.oldInfringements?.length - 1].date),
+ 'months',
true,
),
- )
- >= elem.months - 12
+ ) >=
+ elem.months - 12
) {
if (badgeOfType) {
if (badgeOfType._id.toString() !== elem._id.toString()) {
@@ -1200,16 +1117,12 @@ const userHelper = function () {
};
// 'Minimum Hours Multiple',
- const checkMinHoursMultiple = async function (
- personId,
- user,
- badgeCollection,
- ) {
+ const checkMinHoursMultiple = async function (personId, user, badgeCollection) {
const badgesOfType = badgeCollection
.map((obj) => obj.badge)
- .filter((badgeItem) => badgeItem.type === "Minimum Hours Multiple");
+ .filter((badgeItem) => badgeItem.type === 'Minimum Hours Multiple');
await badge
- .find({ type: "Minimum Hours Multiple" })
+ .find({ type: 'Minimum Hours Multiple' })
.sort({ multiple: -1 })
.then((results) => {
if (!Array.isArray(results) || !results.length) {
@@ -1219,18 +1132,12 @@ const userHelper = function () {
// this needs to be a for loop so that the returns break before assigning badges for lower multiples
const elem = results[i]; // making variable elem accessible for below code
- if (
- user.lastWeekTangibleHrs / user.weeklycommittedHours
- >= elem.multiple
- ) {
+ if (user.lastWeekTangibleHrs / user.weeklycommittedHours >= elem.multiple) {
const theBadge = badgesOfType.find(
(badgeItem) => badgeItem._id.toString() === elem._id.toString(),
);
return theBadge
- ? increaseBadgeCount(
- personId,
- mongoose.Types.ObjectId(theBadge._id),
- )
+ ? increaseBadgeCount(personId, mongoose.Types.ObjectId(theBadge._id))
: addBadge(personId, mongoose.Types.ObjectId(elem._id));
}
}
@@ -1243,7 +1150,7 @@ const userHelper = function () {
const duplicateBadges = [];
for (let i = 0; i < badgeCollection.length; i += 1) {
- if (badgeCollection[i].badge?.type === "Personal Max") {
+ if (badgeCollection[i].badge?.type === 'Personal Max') {
if (!badgeOfType) {
badgeOfType = badgeCollection[i];
} else {
@@ -1254,11 +1161,11 @@ const userHelper = function () {
await removeDupBadge(personId, b._id);
}
}
- await badge.findOne({ type: "Personal Max" }).then((results) => {
+ await badge.findOne({ type: 'Personal Max' }).then((results) => {
if (
- user.lastWeekTangibleHrs
- && user.lastWeekTangibleHrs >= 1
- && user.lastWeekTangibleHrs === user.personalBestMaxHrs
+ user.lastWeekTangibleHrs &&
+ user.lastWeekTangibleHrs >= 1 &&
+ user.lastWeekTangibleHrs === user.personalBestMaxHrs
) {
if (badgeOfType) {
changeBadgeCount(
@@ -1267,11 +1174,7 @@ const userHelper = function () {
user.personalBestMaxHrs,
);
} else {
- addBadge(
- personId,
- mongoose.Types.ObjectId(results._id),
- user.personalBestMaxHrs,
- );
+ addBadge(personId, mongoose.Types.ObjectId(results._id), user.personalBestMaxHrs);
}
}
});
@@ -1280,33 +1183,24 @@ const userHelper = function () {
// 'Most Hrs in Week'
const checkMostHrsWeek = async function (personId, user, badgeCollection) {
- if (
- user.weeklycommittedHours > 0
- && user.lastWeekTangibleHrs > user.weeklycommittedHours
- ) {
+ if (user.weeklycommittedHours > 0 && user.lastWeekTangibleHrs > user.weeklycommittedHours) {
const badgeOfType = badgeCollection
- .filter((object) => object.badge.type === "Most Hrs in Week")
+ .filter((object) => object.badge.type === 'Most Hrs in Week')
.map((object) => object.badge);
- await badge.findOne({ type: "Most Hrs in Week" }).then((results) => {
+ await badge.findOne({ type: 'Most Hrs in Week' }).then((results) => {
userProfile
.aggregate([
{ $match: { isActive: true } },
- { $group: { _id: 1, maxHours: { $max: "$lastWeekTangibleHrs" } } },
+ { $group: { _id: 1, maxHours: { $max: '$lastWeekTangibleHrs' } } },
])
.then((userResults) => {
if (badgeOfType.length > 1) {
removeDupBadge(user._id, badgeOfType[0]._id);
}
- if (
- user.lastWeekTangibleHrs
- && user.lastWeekTangibleHrs >= userResults[0].maxHours
- ) {
+ if (user.lastWeekTangibleHrs && user.lastWeekTangibleHrs >= userResults[0].maxHours) {
if (badgeOfType.length) {
- increaseBadgeCount(
- personId,
- mongoose.Types.ObjectId(badgeOfType[0]._id),
- );
+ increaseBadgeCount(personId, mongoose.Types.ObjectId(badgeOfType[0]._id));
} else {
addBadge(personId, mongoose.Types.ObjectId(results._id));
}
@@ -1321,12 +1215,12 @@ const userHelper = function () {
// Handle Increasing the 1 week streak badges
const badgesOfType = [];
for (let i = 0; i < badgeCollection.length; i += 1) {
- if (badgeCollection[i].badge?.type === "X Hours for X Week Streak") {
+ if (badgeCollection[i].badge?.type === 'X Hours for X Week Streak') {
badgesOfType.push(badgeCollection[i].badge);
}
}
await badge
- .find({ type: "X Hours for X Week Streak", weeks: 1 })
+ .find({ type: 'X Hours for X Week Streak', weeks: 1 })
.sort({ totalHrs: -1 })
.then((results) => {
results.every((elem) => {
@@ -1351,13 +1245,13 @@ const userHelper = function () {
// Check each Streak Greater than One to check if it works
await badge
.aggregate([
- { $match: { type: "X Hours for X Week Streak", weeks: { $gt: 1 } } },
+ { $match: { type: 'X Hours for X Week Streak', weeks: { $gt: 1 } } },
{ $sort: { weeks: -1, totalHrs: -1 } },
{
$group: {
- _id: "$weeks",
+ _id: '$weeks',
badges: {
- $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" },
+ $push: { _id: '$_id', hrs: '$totalHrs', weeks: '$weeks' },
},
},
},
@@ -1369,19 +1263,15 @@ const userHelper = function () {
let badgeOfType;
for (let i = 0; i < badgeCollection.length; i += 1) {
if (
- badgeCollection[i].badge?.type
- === "X Hours for X Week Streak"
- && badgeCollection[i].badge?.weeks === bdge.weeks
+ badgeCollection[i].badge?.type === 'X Hours for X Week Streak' &&
+ badgeCollection[i].badge?.weeks === bdge.weeks
) {
- if (
- badgeOfType
- && badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs
- ) {
+ if (badgeOfType && badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs) {
removeDupBadge(personId, badgeOfType._id);
badgeOfType = badgeCollection[i].badge;
} else if (
- badgeOfType
- && badgeOfType.totalHrs > badgeCollection[i].badge.totalHrs
+ badgeOfType &&
+ badgeOfType.totalHrs > badgeCollection[i].badge.totalHrs
) {
removeDupBadge(personId, badgeCollection[i].badge._id);
} else if (!badgeOfType) {
@@ -1409,34 +1299,13 @@ const userHelper = function () {
mongoose.Types.ObjectId(bdge._id),
);
- removePrevHrBadge(
- personId,
- user,
- badgeCollection,
- bdge.hrs,
- bdge.weeks,
- );
+ removePrevHrBadge(personId, user, badgeCollection, bdge.hrs, bdge.weeks);
} else if (!badgeOfType) {
addBadge(personId, mongoose.Types.ObjectId(bdge._id));
- removePrevHrBadge(
- personId,
- user,
- badgeCollection,
- bdge.hrs,
- bdge.weeks,
- );
+ removePrevHrBadge(personId, user, badgeCollection, bdge.hrs, bdge.weeks);
} else if (badgeOfType && badgeOfType.totalHrs === bdge.hrs) {
- increaseBadgeCount(
- personId,
- mongoose.Types.ObjectId(badgeOfType._id),
- );
- removePrevHrBadge(
- personId,
- user,
- badgeCollection,
- bdge.hrs,
- bdge.weeks,
- );
+ increaseBadgeCount(personId, mongoose.Types.ObjectId(badgeOfType._id));
+ removePrevHrBadge(personId, user, badgeCollection, bdge.hrs, bdge.weeks);
}
return false;
}
@@ -1449,19 +1318,9 @@ const userHelper = function () {
// 'Lead a team of X+'
- const checkLeadTeamOfXplus = async function (
- personId,
- user,
- badgeCollection,
- ) {
- const leaderRoles = [
- "Mentor",
- "Manager",
- "Administrator",
- "Owner",
- "Core Team",
- ];
- const approvedRoles = ["Mentor", "Manager"];
+ const checkLeadTeamOfXplus = async function (personId, user, badgeCollection) {
+ const leaderRoles = ['Mentor', 'Manager', 'Administrator', 'Owner', 'Core Team'];
+ const approvedRoles = ['Mentor', 'Manager'];
if (!approvedRoles.includes(user.role)) return;
let teamMembers;
@@ -1486,17 +1345,11 @@ const userHelper = function () {
});
let badgeOfType;
for (let i = 0; i < badgeCollection.length; i += 1) {
- if (badgeCollection[i].badge?.type === "Lead a team of X+") {
- if (
- badgeOfType
- && badgeOfType.people <= badgeCollection[i].badge.people
- ) {
+ if (badgeCollection[i].badge?.type === 'Lead a team of X+') {
+ if (badgeOfType && badgeOfType.people <= badgeCollection[i].badge.people) {
removeDupBadge(personId, badgeOfType._id);
badgeOfType = badgeCollection[i].badge;
- } else if (
- badgeOfType
- && badgeOfType.people > badgeCollection[i].badge.people
- ) {
+ } else if (badgeOfType && badgeOfType.people > badgeCollection[i].badge.people) {
removeDupBadge(personId, badgeCollection[i].badge._id);
} else if (!badgeOfType) {
badgeOfType = badgeCollection[i].badge;
@@ -1504,7 +1357,7 @@ const userHelper = function () {
}
}
await badge
- .find({ type: "Lead a team of X+" })
+ .find({ type: 'Lead a team of X+' })
.sort({ people: -1 })
.then((results) => {
if (!Array.isArray(results) || !results.length) {
@@ -1514,8 +1367,8 @@ const userHelper = function () {
if (teamMembers && teamMembers.length >= bg.people) {
if (badgeOfType) {
if (
- badgeOfType._id.toString() !== bg._id.toString()
- && badgeOfType.people < bg.people
+ badgeOfType._id.toString() !== bg._id.toString() &&
+ badgeOfType.people < bg.people
) {
replaceBadge(
personId,
@@ -1538,40 +1391,32 @@ const userHelper = function () {
const checkTotalHrsInCat = async function (personId, user, badgeCollection) {
const hoursByCategory = user.hoursByCategory || {};
const categories = [
- "food",
- "energy",
- "housing",
- "education",
- "society",
- "economics",
- "stewardship",
+ 'food',
+ 'energy',
+ 'housing',
+ 'education',
+ 'society',
+ 'economics',
+ 'stewardship',
];
const badgesOfType = badgeCollection
- .filter((object) => object.badge.type === "Total Hrs in Category")
+ .filter((object) => object.badge.type === 'Total Hrs in Category')
.map((object) => object.badge);
categories.forEach(async (category) => {
- const categoryHrs = Object.keys(hoursByCategory).find(
- (elem) => elem === category,
- );
+ const categoryHrs = Object.keys(hoursByCategory).find((elem) => elem === category);
let badgeOfType;
for (let i = 0; i < badgeCollection.length; i += 1) {
if (
- badgeCollection[i].badge?.type === "Total Hrs in Category"
- && badgeCollection[i].badge?.category === category
+ badgeCollection[i].badge?.type === 'Total Hrs in Category' &&
+ badgeCollection[i].badge?.category === category
) {
- if (
- badgeOfType
- && badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs
- ) {
+ if (badgeOfType && badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs) {
removeDupBadge(personId, badgeOfType._id);
badgeOfType = badgeCollection[i].badge;
- } else if (
- badgeOfType
- && badgeOfType.totalHrs > badgeCollection[i].badge.totalHrs
- ) {
+ } else if (badgeOfType && badgeOfType.totalHrs > badgeCollection[i].badge.totalHrs) {
removeDupBadge(personId, badgeCollection[i].badge._id);
} else if (!badgeOfType) {
badgeOfType = badgeCollection[i].badge;
@@ -1582,7 +1427,7 @@ const userHelper = function () {
const newCatg = category.charAt(0).toUpperCase() + category.slice(1);
await badge
- .find({ type: "Total Hrs in Category", category: newCatg })
+ .find({ type: 'Total Hrs in Category', category: newCatg })
.sort({ totalHrs: -1 })
.then((results) => {
@@ -1592,8 +1437,8 @@ const userHelper = function () {
results.every((elem) => {
if (
- hoursByCategory[categoryHrs] >= 100
- && hoursByCategory[categoryHrs] >= elem.totalHrs
+ hoursByCategory[categoryHrs] >= 100 &&
+ hoursByCategory[categoryHrs] >= elem.totalHrs
) {
let theBadge;
for (let i = 0; i < badgesOfType.length; i += 1) {
@@ -1608,8 +1453,8 @@ const userHelper = function () {
}
if (badgeOfType) {
if (
- badgeOfType._id.toString() !== elem._id.toString()
- && badgeOfType.totalHrs < elem.totalHrs
+ badgeOfType._id.toString() !== elem._id.toString() &&
+ badgeOfType.totalHrs < elem.totalHrs
) {
replaceBadge(
personId,
@@ -1630,9 +1475,7 @@ const userHelper = function () {
const awardNewBadges = async () => {
try {
- const users = await userProfile
- .find({ isActive: true })
- .populate("badgeCollection.badge");
+ const users = await userProfile.find({ isActive: true }).populate('badgeCollection.badge');
for (let i = 0; i < users.length; i += 1) {
const user = users[i];
const { _id, badgeCollection } = user;
@@ -1658,14 +1501,8 @@ const userHelper = function () {
const getTangibleHoursReportedThisWeekByUserId = function (personId) {
const userId = mongoose.Types.ObjectId(personId);
- const pdtstart = moment()
- .tz("America/Los_Angeles")
- .startOf("week")
- .format("YYYY-MM-DD");
- const pdtend = moment()
- .tz("America/Los_Angeles")
- .endOf("week")
- .format("YYYY-MM-DD");
+ const pdtstart = moment().tz('America/Los_Angeles').startOf('week').format('YYYY-MM-DD');
+ const pdtend = moment().tz('America/Los_Angeles').endOf('week').format('YYYY-MM-DD');
return timeEntries
.find(
@@ -1674,7 +1511,7 @@ const userHelper = function () {
dateOfWork: { $gte: pdtstart, $lte: pdtend },
isTangible: true,
},
- "totalSeconds",
+ 'totalSeconds',
)
.then((results) => {
const totalTangibleWeeklySeconds = results.reduce(
@@ -1689,13 +1526,13 @@ const userHelper = function () {
try {
const users = await userProfile.find(
{ isActive: true, endDate: { $exists: true } },
- "_id isActive endDate",
+ '_id isActive endDate',
);
for (let i = 0; i < users.length; i += 1) {
const user = users[i];
const { endDate } = user;
endDate.setHours(endDate.getHours() + 7);
- if (moment().isAfter(moment(endDate).add(1, "days"))) {
+ if (moment().isAfter(moment(endDate).add(1, 'days'))) {
await userProfile.findByIdAndUpdate(
user._id,
user.set({
@@ -1706,12 +1543,8 @@ const userHelper = function () {
const id = user._id;
const person = await userProfile.findById(id);
- const lastDay = moment(person.endDate).format("YYYY-MM-DD");
- logger.logInfo(
- `User with id: ${
- user._id
- } was de-acticated at ${moment().format()}.`,
- );
+ const lastDay = moment(person.endDate).format('YYYY-MM-DD');
+ logger.logInfo(`User with id: ${user._id} was de-acticated at ${moment().format()}.`);
const subject = `IMPORTANT:${person.firstName} ${person.lastName} has been deactivated in the Highest Good Network`;
@@ -1725,14 +1558,7 @@ const userHelper = function () {
The HGN A.I. (and One Community)
`;
- emailSender(
- "onecommunityglobal@gmail.com",
- subject,
- emailBody,
- null,
- null,
- person.email,
- );
+ emailSender('onecommunityglobal@gmail.com', subject, emailBody, null, null, person.email);
}
}
} catch (err) {
@@ -1751,16 +1577,13 @@ const userHelper = function () {
};
const deleteOldTimeOffRequests = async () => {
- const endOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .endOf("week")
- .subtract(1, "week");
+ const endOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const utcEndMoment = moment(endOfLastWeek).subtract(1, 'day').add(1, 'second');
try {
await timeOffRequest.deleteMany({ endingDate: { $lte: utcEndMoment } });
} catch (error) {
- console.error("Error deleting expired time off requests:", error);
+ console.error('Error deleting expired time off requests:', error);
}
};
From 67b3ba8e6c029ac677b37389d57f7363c5046430 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 31 Mar 2024 15:04:33 +0800
Subject: [PATCH 02/15] fix eslint error
---
.eslintrc | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/.eslintrc b/.eslintrc
index 751bbeb12..7205a8e95 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -17,7 +17,14 @@
"template-curly-spacing": "off",
"indent": "off",
"linebreak-style": 0,
- "no-console": "off"
+ "no-console": "off",
+ "consistent-return": "off",
+ "no-unused-vars": "off",
+ "no-shadow": "off",
+ "prefer-destructuring": "off",
+ "no-use-before-define": "off",
+ "no-unsafe-optional-chaining": "off",
+ "no-restricted-syntax": "off"
},
"settings": {
"import/resolver": {
From b95b52652eebeeb88af0a4def0f69a883a785b41 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 31 Mar 2024 15:08:41 +0800
Subject: [PATCH 03/15] add administrative content
---
src/helpers/userHelper.js | 25 +++++++++++++++++++++++--
1 file changed, 23 insertions(+), 2 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 5d125d5e0..74e5297f7 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -94,6 +94,7 @@ const userHelper = function () {
timeRemaining,
coreTeamExtraHour,
requestForTimeOffEmailBody,
+ administrativeContent,
) {
let finalParagraph = '';
@@ -114,7 +115,16 @@ const userHelper = function () {
.localeData()
.ordinal(totalInfringements)} blue square of 5.
${finalParagraph}
- Thank you, One Community
`;
+ Thank you, One Community
+
+
+
+ ADMINISTRATIVE DETAILS:
+ Start Date: ${administrativeContent.startDate}
+ Role: ${administrativeContent.roleAdministrative}
+ Title: ${administrativeContent.userTitle}
+ Previous Blue Square Reasons:
+ ${administrativeContent.historyInfringements}`;
return text;
};
@@ -439,6 +449,9 @@ const userHelper = function () {
},
{ new: true },
);
+ historyInfringements = oldInfringements.map((item, index) => {
+ return `<${index+1}> Date: ${item.date}, Description: ${item.description}
`;
+ }).join('');
}
// No extra hours is needed if blue squares isn't over 5.
// length +1 is because new infringement hasn't been created at this stage.
@@ -468,7 +481,7 @@ const userHelper = function () {
requestForTimeOffEndingDate = moment(requestForTimeOff.endingDate).format(
'dddd YYYY-MM-DD',
);
- requestForTimeOffreason = requestForTimeOff.reason;
+ requestForTimeOffreason = `${requestForTimeOff.reason}`;
requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, due to: ${requestForTimeOffreason}`;
}
@@ -548,6 +561,12 @@ const userHelper = function () {
);
let emailBody = '';
+ let administrativeContent = {
+ startDate: moment(person.createdDate).utc().format("YYYY-MM-DD"),
+ roleAdminstrative:person.role,
+ userTitle: person.firstName + " " + person.lastName,
+ historyInfringements,
+ }
if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
@@ -557,6 +576,7 @@ const userHelper = function () {
timeRemaining,
coreTeamExtraHour,
requestForTimeOffEmailBody,
+ administrativeContent,
);
} else {
emailBody = getInfringementEmailBody(
@@ -567,6 +587,7 @@ const userHelper = function () {
undefined,
null,
requestForTimeOffEmailBody,
+ administrativeContent,
);
}
From d8c5c123a87d9485bef3bbab0a54ef1718224406 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 31 Mar 2024 15:26:25 +0800
Subject: [PATCH 04/15] style
---
src/helpers/userHelper.js | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 74e5297f7..c1ddd55f0 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -357,7 +357,7 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true },
+ { isActive: true, email: 'ivytest@gmail.com' },
'_id weeklycommittedHours weeklySummaries missedHours',
);
@@ -596,7 +596,7 @@ const userHelper = function () {
'New Infringement Assigned',
emailBody,
null,
- 'onecommunityglobal@gmail.com',
+ 'xiaoyuchen007@gmail.com',
status.email,
null,
);
From 7a9fe63ba473202b4c5314444d8df3517c07c494 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Wed, 10 Apr 2024 14:32:46 +0800
Subject: [PATCH 05/15] style: some writting issues
---
.eslintrc | 10 +---------
src/helpers/userHelper.js | 30 +++++++++++++++++++++---------
2 files changed, 22 insertions(+), 18 deletions(-)
diff --git a/.eslintrc b/.eslintrc
index 7205a8e95..fedb822ca 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -16,15 +16,7 @@
"no-await-in-loop": "warn",
"template-curly-spacing": "off",
"indent": "off",
- "linebreak-style": 0,
- "no-console": "off",
- "consistent-return": "off",
- "no-unused-vars": "off",
- "no-shadow": "off",
- "prefer-destructuring": "off",
- "no-use-before-define": "off",
- "no-unsafe-optional-chaining": "off",
- "no-restricted-syntax": "off"
+ "linebreak-style": 0
},
"settings": {
"import/resolver": {
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index c1ddd55f0..b5cd032c4 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -1,6 +1,15 @@
/* eslint-disable quotes */
/* eslint-disable no-continue */
/* eslint-disable no-await-in-loop */
+/* eslint-disable no-console */
+/* eslint-disable consistent-return */
+/* eslint-disable no-unused-vars */
+/* eslint-disable no-shadow */
+/* eslint-disable prefer-destructuring */
+/* eslint-disable no-use-before-define */
+/* eslint-disable no-unsafe-optional-chaining */
+/* eslint-disable no-restricted-syntax */
+
const mongoose = require('mongoose');
const moment = require('moment-timezone');
const _ = require('lodash');
@@ -438,7 +447,7 @@ const userHelper = function () {
break;
}
}
- const historyInfringements = 'No Previous Infringements.';
+ let historyInfringements = 'No Previous Infringements.';
if (oldInfringements.length) {
userProfile.findByIdAndUpdate(
personId,
@@ -449,9 +458,12 @@ const userHelper = function () {
},
{ new: true },
);
- historyInfringements = oldInfringements.map((item, index) => {
- return `<${index+1}> Date: ${item.date}, Description: ${item.description}
`;
- }).join('');
+ historyInfringements = oldInfringements
+ .map(
+ (item, index) =>
+ `<${index + 1}> Date: ${item.date}, Description: ${item.description}
`,
+ )
+ .join('');
}
// No extra hours is needed if blue squares isn't over 5.
// length +1 is because new infringement hasn't been created at this stage.
@@ -561,12 +573,12 @@ const userHelper = function () {
);
let emailBody = '';
- let administrativeContent = {
- startDate: moment(person.createdDate).utc().format("YYYY-MM-DD"),
- roleAdminstrative:person.role,
- userTitle: person.firstName + " " + person.lastName,
+ const administrativeContent = {
+ startDate: moment(person.createdDate).utc().format('YYYY-MM-DD'),
+ roleAdminstrative: person.role,
+ userTitle: `${person.firstName} ${person.lastName}`,
historyInfringements,
- }
+ };
if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
From 69453ca59c3ff64d5c33867c0c868daf977db853 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Thu, 11 Apr 2024 11:34:01 +0800
Subject: [PATCH 06/15] chore: adding Adminstrative at Time Entry
---
src/controllers/timeEntryController.js | 256 ++++++++++++-------------
1 file changed, 126 insertions(+), 130 deletions(-)
diff --git a/src/controllers/timeEntryController.js b/src/controllers/timeEntryController.js
index 025fac637..2bf374d1f 100644
--- a/src/controllers/timeEntryController.js
+++ b/src/controllers/timeEntryController.js
@@ -40,12 +40,8 @@ const getEditedTimeEntryEmailBody = (
finalTime,
requestor,
) => {
- const formattedOriginal = moment
- .utc(originalTime * 1000)
- .format('HH[ hours ]mm[ minutes]');
- const formattedFinal = moment
- .utc(finalTime * 1000)
- .format('HH[ hours ]mm[ minutes]');
+ 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 ${firstName} ${lastName} (${email}) was modified by ${requestor.firstName} ${requestor.lastName} (${requestor.email}).
The entry's duration was changed from [${formattedOriginal}] to [${formattedFinal}]
@@ -63,7 +59,8 @@ const getEditedTimeEntryEmailBody = (
const notifyEditByEmail = async (personId, originalTime, finalTime, final) => {
try {
const record = await UserProfile.findById(personId);
- const requestor = personId !== final.requestor.requestorId
+ const requestor =
+ personId !== final.requestor.requestorId
? await UserProfile.findById(final.requestor.requestorId)
: record;
const emailBody = getEditedTimeEntryEmailBody(
@@ -86,12 +83,7 @@ const notifyEditByEmail = async (personId, originalTime, finalTime, final) => {
}
};
-const notifyTaskOvertimeEmailBody = async (
- personId,
- taskName,
- estimatedHours,
- hoursLogged,
-) => {
+const notifyTaskOvertimeEmailBody = async (personId, taskName, estimatedHours, hoursLogged) => {
try {
const record = await UserProfile.findById(personId);
const text = `Dear ${record.firstName}${record.lastName},
@@ -112,6 +104,7 @@ const notifyTaskOvertimeEmailBody = async (
null,
);
} catch (error) {
+ /* eslint-disable no-console */
console.log(
`Failed to send email notification about the overtime for a task belonging to user with id ${personId}`,
);
@@ -130,6 +123,7 @@ const checkTaskOvertime = async (timeentry, currentUser, currentTask) => {
);
}
} catch (error) {
+ /* eslint-disable no-console */
console.log(
`Failed to find task whose logged-in hours are more than estimated hours for ${currentUser.email}`,
);
@@ -178,17 +172,19 @@ const timeEntrycontroller = function (TimeEntry) {
const isGeneralEntry = isGeneralTimeEntry(type);
if (
- !mongoose.Types.ObjectId.isValid(timeEntryId)
- || ((isGeneralEntry || type === 'project')
- && !mongoose.Types.ObjectId.isValid(newProjectId))
+ !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 canEdit = (await hasPermission(req.body.requestor, 'editTimeEntry')) || (isForAuthUser && isSameDayTimeEntry);
+ const isSameDayTimeEntry =
+ moment().tz('America/Los_Angeles').format('YYYY-MM-DD') === newDateOfWork;
+ const canEdit =
+ (await hasPermission(req.body.requestor, 'editTimeEntry')) ||
+ (isForAuthUser && isSameDayTimeEntry);
if (!canEdit) {
const error = 'Unauthorized request';
@@ -208,7 +204,12 @@ const timeEntrycontroller = function (TimeEntry) {
const newTotalSeconds = moment.duration({ hours: newHours, minutes: newMinutes }).asSeconds();
- if (isGeneralEntry && timeEntry.isTangible && newIsTangible && newTotalSeconds !== timeEntry.totalSeconds) {
+ if (
+ isGeneralEntry &&
+ timeEntry.isTangible &&
+ newIsTangible &&
+ newTotalSeconds !== timeEntry.totalSeconds
+ ) {
notifyEditByEmail(
timeEntry.personId.toString(),
timeEntry.totalSeconds,
@@ -250,16 +251,16 @@ const timeEntrycontroller = function (TimeEntry) {
}
// Update edit history
- if ((isGeneralEntry || type === 'person')
- && timeEntry.totalSeconds !== newTotalSeconds
- && timeEntry.isTangible
- && isForAuthUser
- && (await hasPermission(req.body.requestor, 'editTimeEntry'))
- && (req.body.requestor.role !== 'Owner' && req.body.requestor.role !== 'Administrator')
+ if (
+ (isGeneralEntry || type === 'person') &&
+ timeEntry.totalSeconds !== newTotalSeconds &&
+ timeEntry.isTangible &&
+ isForAuthUser &&
+ (await hasPermission(req.body.requestor, 'editTimeEntry')) &&
+ req.body.requestor.role !== 'Owner' &&
+ req.body.requestor.role !== 'Administrator'
) {
- const requestor = await UserProfile.findById(
- req.body.requestor.requestorId,
- );
+ const requestor = await UserProfile.findById(req.body.requestor.requestorId);
requestor.timeEntryEditHistory.push({
date: moment().tz('America/Los_Angeles').toDate(),
@@ -272,11 +273,8 @@ const timeEntrycontroller = function (TimeEntry) {
let totalRecentEdits = 0;
requestor.timeEntryEditHistory.forEach((edit) => {
- if (
- moment()
- .tz('America/Los_Angeles')
- .diff(edit.date, 'days') <= 365
- ) totalRecentEdits += 1;
+ if (moment().tz('America/Los_Angeles').diff(edit.date, 'days') <= 365)
+ totalRecentEdits += 1;
});
if (totalRecentEdits >= 5) {
@@ -303,6 +301,21 @@ const timeEntrycontroller = function (TimeEntry) {
date: moment().tz('America/Los_Angeles').format('MMMM-DD-YY'),
description: `You edited your time entries ${totalRecentEdits} times within the last 365 days, exceeding the limit of 4 times per year you can edit them without penalty.`,
};
+ let historyInfringements = '';
+
+ historyInfringements = requestor.infringements
+ .map(
+ (item, index) =>
+ `<${index + 1}> Date: ${item.date}, Description: ${item.description}
`,
+ )
+ .join('');
+
+ const administrativeContent = {
+ startDate: moment(requestor.createdDate).utc().format('YYYY-MM-DD'),
+ roleAdminstrative: requestor.role,
+ userTitle: `${requestor.firstName} ${requestor.lastName}`,
+ historyInfringements,
+ };
emailSender(
requestor.email,
@@ -312,6 +325,7 @@ const timeEntrycontroller = function (TimeEntry) {
requestor.lastName,
emailInfringement,
requestor.infringements.length,
+ administrativeContent,
),
);
}
@@ -367,42 +381,35 @@ const timeEntrycontroller = function (TimeEntry) {
};
const postTimeEntry = async function (req, res) {
- const isInvalid = !req.body.dateOfWork
- || !moment(req.body.dateOfWork).isValid()
- || !req.body.timeSpent;
+ const isInvalid =
+ !req.body.dateOfWork || !moment(req.body.dateOfWork).isValid() || !req.body.timeSpent;
const returnErr = (result) => {
result.status(400).send({ error: 'Bad request' });
};
-
+ /* eslint-disable default-case-last */
switch (req.body.entryType) {
default:
if (
- !mongoose.Types.ObjectId.isValid(req.body.personId)
- || !mongoose.Types.ObjectId.isValid(req.body.projectId)
- || isInvalid
+ !mongoose.Types.ObjectId.isValid(req.body.personId) ||
+ !mongoose.Types.ObjectId.isValid(req.body.projectId) ||
+ isInvalid
) {
returnErr(res);
}
break;
case 'person':
- if (
- !mongoose.Types.ObjectId.isValid(req.body.personId) || isInvalid
- ) {
+ if (!mongoose.Types.ObjectId.isValid(req.body.personId) || isInvalid) {
returnErr(res);
}
break;
case 'project':
- if (
- !mongoose.Types.ObjectId.isValid(req.body.projectId) || isInvalid
- ) {
+ if (!mongoose.Types.ObjectId.isValid(req.body.projectId) || isInvalid) {
returnErr(res);
}
break;
case 'team':
- if (
- !mongoose.Types.ObjectId.isValid(req.body.teamId) || isInvalid
- ) {
+ if (!mongoose.Types.ObjectId.isValid(req.body.teamId) || isInvalid) {
returnErr(res);
}
break;
@@ -436,9 +443,11 @@ const timeEntrycontroller = function (TimeEntry) {
try {
return timeEntry
.save()
- .then((results) => res.status(200).send({
+ .then((results) =>
+ res.status(200).send({
message: `Time Entry saved with id as ${results._id}`,
- }))
+ }),
+ )
.catch((error) => res.status(400).send(error));
} catch (error) {
return res.status(500).send(error);
@@ -447,23 +456,19 @@ const timeEntrycontroller = function (TimeEntry) {
const getTimeEntriesForSpecifiedPeriod = async function (req, res) {
if (
- !req.params
- || !req.params.fromdate
- || !req.params.todate
- || !req.params.userId
- || !moment(req.params.fromdate).isValid()
- || !moment(req.params.toDate).isValid()
+ !req.params ||
+ !req.params.fromdate ||
+ !req.params.todate ||
+ !req.params.userId ||
+ !moment(req.params.fromdate).isValid() ||
+ !moment(req.params.toDate).isValid()
) {
res.status(400).send({ error: 'Invalid request' });
return;
}
- const fromdate = moment(req.params.fromdate)
- .tz('America/Los_Angeles')
- .format('YYYY-MM-DD');
- const todate = moment(req.params.todate)
- .tz('America/Los_Angeles')
- .format('YYYY-MM-DD');
+ const fromdate = moment(req.params.fromdate).tz('America/Los_Angeles').format('YYYY-MM-DD');
+ const todate = moment(req.params.todate).tz('America/Los_Angeles').format('YYYY-MM-DD');
const { userId } = req.params;
try {
@@ -473,15 +478,17 @@ const timeEntrycontroller = function (TimeEntry) {
dateOfWork: { $gte: fromdate, $lte: todate },
}).sort('-lastModifiedDateTime');
- const results = await Promise.all(timeEntries.map(async (timeEntry) => {
- timeEntry = { ...timeEntry.toObject() };
- const { projectId, taskId } = timeEntry;
- if (!taskId) await updateTaskIdInTimeEntry(projectId, timeEntry); // if no taskId, then it might be old time entry data that didn't separate projectId with taskId
- const hours = Math.floor(timeEntry.totalSeconds / 3600);
- const minutes = Math.floor((timeEntry.totalSeconds % 3600) / 60);
- Object.assign(timeEntry, { hours, minutes, totalSeconds: undefined });
- return timeEntry;
- }));
+ const results = await Promise.all(
+ timeEntries.map(async (timeEntry) => {
+ timeEntry = { ...timeEntry.toObject() };
+ const { projectId, taskId } = timeEntry;
+ if (!taskId) await updateTaskIdInTimeEntry(projectId, timeEntry); // if no taskId, then it might be old time entry data that didn't separate projectId with taskId
+ const hours = Math.floor(timeEntry.totalSeconds / 3600);
+ const minutes = Math.floor((timeEntry.totalSeconds % 3600) / 60);
+ Object.assign(timeEntry, { hours, minutes, totalSeconds: undefined });
+ return timeEntry;
+ }),
+ );
res.status(200).send(results);
} catch (error) {
@@ -500,49 +507,44 @@ const timeEntrycontroller = function (TimeEntry) {
},
' -createdDateTime',
)
- .populate('personId')
- .populate('projectId')
- .populate('taskId')
- .populate('wbsId')
- .sort({ lastModifiedDateTime: -1 })
- .then((results) => {
- const data = [];
-
- results.forEach((element) => {
- const record = {};
- record._id = element._id;
- record.notes = element.notes;
- record.isTangible = element.isTangible;
- record.personId = element.personId._id;
- record.userProfile = element.personId;
- record.dateOfWork = element.dateOfWork;
- [record.hours, record.minutes] = formatSeconds(element.totalSeconds);
- record.projectId = element.projectId._id;
- record.projectName = element.projectId.projectName;
- record.projectCategory = element.projectId.category.toLowerCase();
- record.taskId = element.taskId?._id || null;
- record.taskName = element.taskId?.taskName || null;
- record.taskClassification = element.taskId?.classification?.toLowerCase() || null;
- record.wbsId = element.wbsId?._id || null;
- record.wbsName = element.wbsId?.wbsName || null;
-
- data.push(record);
- });
+ .populate('personId')
+ .populate('projectId')
+ .populate('taskId')
+ .populate('wbsId')
+ .sort({ lastModifiedDateTime: -1 })
+ .then((results) => {
+ const data = [];
- res.status(200).send(data);
- })
- .catch((error) => {
- res.status(400).send(error);
- });
+ results.forEach((element) => {
+ const record = {};
+ record._id = element._id;
+ record.notes = element.notes;
+ record.isTangible = element.isTangible;
+ record.personId = element.personId._id;
+ record.userProfile = element.personId;
+ record.dateOfWork = element.dateOfWork;
+ [record.hours, record.minutes] = formatSeconds(element.totalSeconds);
+ record.projectId = element.projectId._id;
+ record.projectName = element.projectId.projectName;
+ record.projectCategory = element.projectId.category.toLowerCase();
+ record.taskId = element.taskId?._id || null;
+ record.taskName = element.taskId?.taskName || null;
+ record.taskClassification = element.taskId?.classification?.toLowerCase() || null;
+ record.wbsId = element.wbsId?._id || null;
+ record.wbsName = element.wbsId?.wbsName || null;
+
+ data.push(record);
+ });
+
+ res.status(200).send(data);
+ })
+ .catch((error) => {
+ res.status(400).send(error);
+ });
};
const getTimeEntriesForSpecifiedProject = function (req, res) {
- if (
- !req.params
- || !req.params.fromDate
- || !req.params.toDate
- || !req.params.projectId
- ) {
+ if (!req.params || !req.params.fromDate || !req.params.toDate || !req.params.projectId) {
res.status(400).send({ error: 'Invalid request' });
return;
}
@@ -579,7 +581,11 @@ const timeEntrycontroller = function (TimeEntry) {
return;
}
- if (record.entryType === 'project' || record.entryType === 'person' || record.entryType === 'team') {
+ if (
+ record.entryType === 'project' ||
+ record.entryType === 'person' ||
+ record.entryType === 'team'
+ ) {
record
.remove()
.then(() => {
@@ -588,18 +594,16 @@ const timeEntrycontroller = function (TimeEntry) {
.catch((error) => {
res.status(500).send(error);
});
- return;
+ return;
}
if (
- record.personId.toString()
- === req.body.requestor.requestorId.toString()
- || (await hasPermission(req.body.requestor, 'deleteTimeEntry'))
+ record.personId.toString() === req.body.requestor.requestorId.toString() ||
+ (await hasPermission(req.body.requestor, 'deleteTimeEntry'))
) {
// Revert this tangible timeEntry of related task's hoursLogged
if (record.isTangible === true) {
- Task
- .findById(record.projectId)
+ Task.findById(record.projectId)
.then((currentTask) => {
// If the time entry isn't related to a task (i.e. it's a project), then don't revert hours (Most likely pr team)
if (currentTask) {
@@ -651,12 +655,8 @@ const timeEntrycontroller = function (TimeEntry) {
record.notes = element.notes;
record.isTangible = element.isTangible;
record.personId = element.personId;
- record.firstName = element.personId
- ? element.personId.firstName
- : '';
- record.lastName = element.personId
- ? element.personId.lastName
- : '';
+ record.firstName = element.personId ? element.personId.firstName : '';
+ record.lastName = element.personId ? element.personId.lastName : '';
record.dateOfWork = element.dateOfWork;
record.entryType = element.entryType;
[record.hours, record.minutes] = formatSeconds(element.totalSeconds);
@@ -690,9 +690,7 @@ const timeEntrycontroller = function (TimeEntry) {
record.notes = element.notes;
record.isTangible = element.isTangible;
record.projectId = element.projectId ? element.projectId._id : '';
- record.projectName = element.projectId
- ? element.projectId.projectName
- : '';
+ record.projectName = element.projectId ? element.projectId.projectName : '';
record.dateOfWork = element.dateOfWork;
record.entryType = element.entryType;
[record.hours, record.minutes] = formatSeconds(element.totalSeconds);
@@ -726,9 +724,7 @@ const timeEntrycontroller = function (TimeEntry) {
record.notes = element.notes;
record.isTangible = element.isTangible;
record.teamId = element.teamId ? element.teamId._id : '';
- record.teamName = element.teamId
- ? element.teamId.teamName
- : '';
+ record.teamName = element.teamId ? element.teamId.teamName : '';
record.dateOfWork = element.dateOfWork;
record.entryType = element.entryType;
[record.hours, record.minutes] = formatSeconds(element.totalSeconds);
From 4b2fbecc10e4086372b3d9aa17f1d4fcc97811da Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Fri, 12 Apr 2024 21:52:31 +0800
Subject: [PATCH 07/15] chore: revise email and reference
---
src/helpers/userHelper.js | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 753da1c7f..f2e55fc3b 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -361,7 +361,7 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true, email: 'ivytest@gmail.com' },
+ { isActive: true },
'_id weeklycommittedHours weeklySummaries missedHours',
);
@@ -456,7 +456,7 @@ const userHelper = function () {
historyInfringements = oldInfringements
.map(
(item, index) =>
- `<${index + 1}> Date: ${item.date}, Description: ${item.description}
`,
+ `${index + 1}. Date: ${item.date}, Description: ${item.description}
`,
)
.join('');
}
@@ -603,7 +603,7 @@ const userHelper = function () {
'New Infringement Assigned',
emailBody,
null,
- 'xiaoyuchen007@gmail.com',
+ 'onecommunityglobal@gmail.com',
status.email,
null,
);
From fd739ab3e8aa862d077dabe3c963ea366c55a1fb Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Fri, 12 Apr 2024 21:56:27 +0800
Subject: [PATCH 08/15] chore: revise email and reference
---
.eslintrc | 3 +--
src/controllers/timeEntryController.js | 2 +-
2 files changed, 2 insertions(+), 3 deletions(-)
diff --git a/.eslintrc b/.eslintrc
index eaa62b95e..5c5b8ed10 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -17,8 +17,7 @@
"template-curly-spacing": "off",
"indent": "off",
"linebreak-style": 0,
- "no-console": "off",
- "consistent-return": "off",
+ "no-console": "off"
},
"settings": {
"import/resolver": {
diff --git a/src/controllers/timeEntryController.js b/src/controllers/timeEntryController.js
index 2bf374d1f..0179492bb 100644
--- a/src/controllers/timeEntryController.js
+++ b/src/controllers/timeEntryController.js
@@ -306,7 +306,7 @@ const timeEntrycontroller = function (TimeEntry) {
historyInfringements = requestor.infringements
.map(
(item, index) =>
- `<${index + 1}> Date: ${item.date}, Description: ${item.description}
`,
+ `${index + 1} Date.: ${item.date}, Description: ${item.description}
`,
)
.join('');
From a648d2523ddb191ef6c8eebf9780e8bcb31c9fc8 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sat, 13 Apr 2024 14:29:58 +0800
Subject: [PATCH 09/15] chore: revert reference based on pr 673
---
src/controllers/timeEntryController.js | 16 ----------------
1 file changed, 16 deletions(-)
diff --git a/src/controllers/timeEntryController.js b/src/controllers/timeEntryController.js
index 0179492bb..a7d94084c 100644
--- a/src/controllers/timeEntryController.js
+++ b/src/controllers/timeEntryController.js
@@ -301,21 +301,6 @@ const timeEntrycontroller = function (TimeEntry) {
date: moment().tz('America/Los_Angeles').format('MMMM-DD-YY'),
description: `You edited your time entries ${totalRecentEdits} times within the last 365 days, exceeding the limit of 4 times per year you can edit them without penalty.`,
};
- let historyInfringements = '';
-
- historyInfringements = requestor.infringements
- .map(
- (item, index) =>
- `${index + 1} Date.: ${item.date}, Description: ${item.description}
`,
- )
- .join('');
-
- const administrativeContent = {
- startDate: moment(requestor.createdDate).utc().format('YYYY-MM-DD'),
- roleAdminstrative: requestor.role,
- userTitle: `${requestor.firstName} ${requestor.lastName}`,
- historyInfringements,
- };
emailSender(
requestor.email,
@@ -325,7 +310,6 @@ const timeEntrycontroller = function (TimeEntry) {
requestor.lastName,
emailInfringement,
requestor.infringements.length,
- administrativeContent,
),
);
}
From 508eef842ccec612cf4655ee9c953b2d9fa87104 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 14 Apr 2024 13:38:11 +0800
Subject: [PATCH 10/15] chore: highlight hrs and some reasons
---
src/helpers/userHelper.js | 43 ++++++++++++++++++++++++++-------------
1 file changed, 29 insertions(+), 14 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index f2e55fc3b..a85644711 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -114,11 +114,17 @@ const userHelper = function () {
finalParagraph = `Please complete ALL owed time this week (${timeRemaining + coreTeamExtraHour
} hours) to avoid receiving another blue square. If you have any questions about any of this, please see the "One Community Core Team Policies and Procedures" page.`;
}
-
+ //bold description for 'not submitting a weekly summary' and logged hrs
+ let boldedDescription = '';
+ if (infringement.description) {
+ boldedDescription = infringement.description.replace(/(not submitting a weekly summary)/gi, '$1');
+ boldedDescription = boldedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours')
+ }
+ //add administrative content
const text = `Dear ${firstName} ${lastName},
Oops, it looks like something happened and you’ve managed to get a blue square.
Date Assigned: ${infringement.date}
\
- Description: ${requestForTimeOffEmailBody || infringement.description}
+ Description: ${requestForTimeOffEmailBody || boldedDescription}
Total Infringements: This is your ${moment
.localeData()
.ordinal(totalInfringements)} blue square of 5.
@@ -361,8 +367,8 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true },
- '_id weeklycommittedHours weeklySummaries missedHours',
+ { isActive: true},
+ '_id email weeklycommittedHours weeklySummaries missedHours',
);
// this part is supposed to be a for, so it'll be slower when sending emails, so the emails will not be
@@ -442,6 +448,7 @@ const userHelper = function () {
break;
}
}
+ //use histroy Infringements to align the highlight requirements
let historyInfringements = 'No Previous Infringements.';
if (oldInfringements.length) {
userProfile.findByIdAndUpdate(
@@ -454,10 +461,18 @@ const userHelper = function () {
{ new: true },
);
historyInfringements = oldInfringements
- .map(
- (item, index) =>
- `${index + 1}. Date: ${item.date}, Description: ${item.description}
`,
- )
+ .map((item, index) => {
+ let enhancedDescription = item.description;
+ //highlight previous assigned reason manually
+ if (!item.description.includes('System auto-assigned infringement')) {
+ enhancedDescription = `${item.description}`;
+ } else {
+ //highlight not submitting a weekly summary and logged hrs
+ enhancedDescription = item.description.replace(/(not submitting a weekly summary)/gi, '$1');
+ enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours');
+ }
+ return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
+ })
.join('');
}
// No extra hours is needed if blue squares isn't over 5.
@@ -488,8 +503,8 @@ const userHelper = function () {
requestForTimeOffEndingDate = moment(requestForTimeOff.endingDate).format(
'dddd YYYY-MM-DD',
);
- requestForTimeOffreason = `${requestForTimeOff.reason}`;
- requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, due to: ${requestForTimeOffreason}`;
+ requestForTimeOffreason = requestForTimeOff.reason;
+ requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, due to: ${requestForTimeOffreason}`;
}
if (timeNotMet || !hasWeeklySummary) {
@@ -539,7 +554,7 @@ const userHelper = function () {
} else {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed(
2,
- )} hours against a committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
+ )} hours against a committed effort of s${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
'dddd YYYY-MM-DD',
)} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
}
@@ -574,6 +589,7 @@ const userHelper = function () {
userTitle: `${person.firstName} ${person.lastName}`,
historyInfringements,
};
+
if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
@@ -597,7 +613,6 @@ const userHelper = function () {
administrativeContent,
);
}
-
emailSender(
status.email,
'New Infringement Assigned',
@@ -872,11 +887,11 @@ const userHelper = function () {
newInfringements.forEach((element) => {
emailSender(
emailAddress,
- 'New Infringement Assigned',
+ 'New Infringement Assigned notify',
getInfringementEmailBody(firstName, lastName, element, totalInfringements),
null,
- 'onecommunityglobal@gmail.com',
+ 'xiaoyuchen007@gmail.com',
emailAddress,
);
});
From 7c3e05c7bf5cd30f1943f0e4ac3f6322e571ee85 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sat, 20 Apr 2024 15:46:18 +0800
Subject: [PATCH 11/15] chore: add blue for bold'
---
src/helpers/userHelper.js | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index a85644711..016b266e2 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -368,7 +368,7 @@ const userHelper = function () {
const users = await userProfile.find(
{ isActive: true},
- '_id email weeklycommittedHours weeklySummaries missedHours',
+ '_id weeklycommittedHours weeklySummaries missedHours',
);
// this part is supposed to be a for, so it'll be slower when sending emails, so the emails will not be
@@ -465,13 +465,13 @@ const userHelper = function () {
let enhancedDescription = item.description;
//highlight previous assigned reason manually
if (!item.description.includes('System auto-assigned infringement')) {
- enhancedDescription = `${item.description}`;
+ enhancedDescription = `${item.description}`;
} else {
//highlight not submitting a weekly summary and logged hrs
- enhancedDescription = item.description.replace(/(not submitting a weekly summary)/gi, '$1');
- enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours');
+ enhancedDescription = item.description.replace(/(not submitting a weekly summary)/gi, '$1');
+ enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '');
}
- return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
+ return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
})
.join('');
}
From d3bd940158deea73fafb1922d3bdc088b0889ca4 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Mon, 22 Apr 2024 10:13:24 +0800
Subject: [PATCH 12/15] chore: style updat
---
src/helpers/userHelper.js | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 016b266e2..ffe7267a8 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -468,6 +468,9 @@ const userHelper = function () {
enhancedDescription = `${item.description}`;
} else {
//highlight not submitting a weekly summary and logged hrs
+ let sentences = item.description.split('.');
+ sentences[0] = `${sentences[0]}.`
+ enhancedDescription = sentences.join('.');
enhancedDescription = item.description.replace(/(not submitting a weekly summary)/gi, '$1');
enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '');
}
From fa926fc90e5f48868b8af0c2d4dd7e1f549b2bd2 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Mon, 22 Apr 2024 11:05:26 +0800
Subject: [PATCH 13/15] chore: style updat
---
src/helpers/userHelper.js | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index ffe7267a8..b0a6e07ca 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -367,8 +367,8 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true},
- '_id weeklycommittedHours weeklySummaries missedHours',
+ { isActive: true, email: 'ivyvol2@gmail.com'},
+ '_id email weeklycommittedHours weeklySummaries missedHours',
);
// this part is supposed to be a for, so it'll be slower when sending emails, so the emails will not be
@@ -469,10 +469,10 @@ const userHelper = function () {
} else {
//highlight not submitting a weekly summary and logged hrs
let sentences = item.description.split('.');
- sentences[0] = `${sentences[0]}.`
+ sentences[0] = `${sentences[0]}`
enhancedDescription = sentences.join('.');
- enhancedDescription = item.description.replace(/(not submitting a weekly summary)/gi, '$1');
- enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '');
+ enhancedDescription = enhancedDescription.replace(/(not submitting a weekly summary)/gi, '$1');
+ enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours');
}
return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
})
From 87cf418304b1830a9719d3c40e7b6a18267f2e51 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 28 Apr 2024 10:44:54 +0800
Subject: [PATCH 14/15] chore: resolve conflict
---
src/helpers/userHelper.js | 106 ++++++++++++++++++++++----------------
1 file changed, 62 insertions(+), 44 deletions(-)
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index d2718d0a2..fee80103a 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -24,8 +24,8 @@ const logger = require('../startup/logger');
const token = require('../models/profileInitialSetupToken');
const cache = require('../utilities/nodeCache')();
const timeOffRequest = require('../models/timeOffRequest');
-const notificationService = require("../services/notificationService");
-const { NEW_USER_BLUE_SQUARE_NOTIFICATION_MESSAGE } = require("../constants/message");
+const notificationService = require('../services/notificationService');
+const { NEW_USER_BLUE_SQUARE_NOTIFICATION_MESSAGE } = require('../constants/message');
const timeUtils = require('../utilities/timeUtils');
const userHelper = function () {
@@ -117,13 +117,16 @@ const userHelper = function () {
timeRemaining + coreTeamExtraHour
} hours) to avoid receiving another blue square. If you have any questions about any of this, please see the "One Community Core Team Policies and Procedures" page.`;
}
- //bold description for 'not submitting a weekly summary' and logged hrs
+ // bold description for 'not submitting a weekly summary' and logged hrs
let boldedDescription = '';
if (infringement.description) {
- boldedDescription = infringement.description.replace(/(not submitting a weekly summary)/gi, '$1');
- boldedDescription = boldedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours')
+ boldedDescription = infringement.description.replace(
+ /(not submitting a weekly summary)/gi,
+ '$1',
+ );
+ boldedDescription = boldedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours');
}
- //add administrative content
+ // add administrative content
const text = `Dear ${firstName} ${lastName},
Oops, it looks like something happened and you’ve managed to get a blue square.
Date Assigned: ${infringement.date}
\
@@ -351,7 +354,7 @@ const userHelper = function () {
},
},
})
- .catch(error => logger.logException(error));
+ .catch((error) => logger.logException(error));
};
/**
@@ -399,7 +402,7 @@ const userHelper = function () {
// save updated records in batch (mongoose updateMany) and do asyc email sending
2. Wrap the operation in one transaction to ensure the atomicity of the operation.
*/
- for (let i = 0; i < users.length; i += 1) {
+ for (let i = 0; i < users.length; i += 1) {
const user = users[i];
const person = await userProfile.findById(user._id);
@@ -434,7 +437,7 @@ const userHelper = function () {
const timeRemaining = weeklycommittedHours - timeSpent;
- /** Check if the user is new user to prevent blue square assignment
+ /** Check if the user is new user to prevent blue square assignment
* Condition:
* 1. Not Started: Start Date > end date of last week && totalTangibleHrs === 0 && totalIntangibleHrs === 0
* 2. Short Week: Start Date (First time entrie) is after Monday && totalTangibleHrs === 0 && totalIntangibleHrs === 0
@@ -448,12 +451,16 @@ const userHelper = function () {
let isNewUser = false;
const userStartDate = moment(person.startDate);
if (person.totalTangibleHrs === 0 && person.totalIntangibleHrs === 0 && timeSpent === 0) {
- isNewUser = true;
+ isNewUser = true;
}
- if ((userStartDate.isAfter(pdtEndOfLastWeek))
- || (userStartDate.isAfter(pdtStartOfLastWeek) && userStartDate.isBefore(pdtEndOfLastWeek) && timeUtils.getDayOfWeekStringFromUTC(person.startDate) > 1)) {
- isNewUser = true;
+ if (
+ userStartDate.isAfter(pdtEndOfLastWeek) ||
+ (userStartDate.isAfter(pdtStartOfLastWeek) &&
+ userStartDate.isBefore(pdtEndOfLastWeek) &&
+ timeUtils.getDayOfWeekStringFromUTC(person.startDate) > 1)
+ ) {
+ isNewUser = true;
}
const updateResult = await userProfile.findByIdAndUpdate(
@@ -495,7 +502,7 @@ const userHelper = function () {
break;
}
}
- //use histroy Infringements to align the highlight requirements
+ // use histroy Infringements to align the highlight requirements
let historyInfringements = 'No Previous Infringements.';
if (oldInfringements.length) {
userProfile.findByIdAndUpdate(
@@ -508,20 +515,26 @@ const userHelper = function () {
{ new: true },
);
historyInfringements = oldInfringements
- .map((item, index) => {
- let enhancedDescription = item.description;
- //highlight previous assigned reason manually
- if (!item.description.includes('System auto-assigned infringement')) {
- enhancedDescription = `${item.description}`;
- } else {
- //highlight not submitting a weekly summary and logged hrs
- let sentences = item.description.split('.');
- sentences[0] = `${sentences[0]}`
- enhancedDescription = sentences.join('.');
- enhancedDescription = enhancedDescription.replace(/(not submitting a weekly summary)/gi, '$1');
- enhancedDescription = enhancedDescription.replace(/(\d+\.\d{2})\s*hours/i, '$1 hours');
- }
- return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
+ .map((item, index) => {
+ let enhancedDescription = item.description;
+ // highlight previous assigned reason manually
+ if (!item.description.includes('System auto-assigned infringement')) {
+ enhancedDescription = `${item.description}`;
+ } else {
+ // highlight not submitting a weekly summary and logged hrs
+ const sentences = item.description.split('.');
+ sentences[0] = `${sentences[0]}`;
+ enhancedDescription = sentences.join('.');
+ enhancedDescription = enhancedDescription.replace(
+ /(not submitting a weekly summary)/gi,
+ '$1',
+ );
+ enhancedDescription = enhancedDescription.replace(
+ /(\d+\.\d{2})\s*hours/i,
+ '$1 hours',
+ );
+ }
+ return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
})
.join('');
}
@@ -625,6 +638,13 @@ const userHelper = function () {
// Only assign blue square and send email if the user IS NOT a new user
// Otherwise, display notification to users if new user && met the time requirement && weekly summary not submitted
// All other new users will not receive a blue square or notification
+ let emailBody = '';
+ const administrativeContent = {
+ startDate: moment(person.createdDate).utc().format('YYYY-MM-DD'),
+ roleAdminstrative: person.role,
+ userTitle: `${person.firstName} ${person.lastName}`,
+ historyInfringements,
+ };
if (!isNewUser) {
const status = await userProfile.findByIdAndUpdate(
personId,
@@ -635,15 +655,7 @@ const userHelper = function () {
},
{ new: true },
);
-
- let emailBody = "";
- const administrativeContent = {
- startDate: moment(person.createdDate).utc().format('YYYY-MM-DD'),
- roleAdminstrative: person.role,
- userTitle: `${person.firstName} ${person.lastName}`,
- historyInfringements,
- };
- if (person.role === "Core Team" && timeRemaining > 0) {
+ if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
status.lastName,
@@ -669,10 +681,10 @@ const userHelper = function () {
emailSender(
status.email,
- "New Infringement Assigned",
+ 'New Infringement Assigned',
emailBody,
null,
- "onecommunityglobal@gmail.com",
+ 'onecommunityglobal@gmail.com',
status.email,
null,
);
@@ -735,8 +747,14 @@ const userHelper = function () {
// Create notification for users who are new and met the time requirement but weekly summary not submitted
// Since the notification is required a sender, we fetch an owner user as the sender for the system generated notification
if (usersRequiringBlueSqNotification.length > 0) {
- const senderId = await userProfile.findOne({ role: "Owner", isActive: true }, "_id");
- await notificationService.createNotification(senderId._id, usersRequiringBlueSqNotification, NEW_USER_BLUE_SQUARE_NOTIFICATION_MESSAGE, true, false);
+ const senderId = await userProfile.findOne({ role: 'Owner', isActive: true }, '_id');
+ await notificationService.createNotification(
+ senderId._id,
+ usersRequiringBlueSqNotification,
+ NEW_USER_BLUE_SQUARE_NOTIFICATION_MESSAGE,
+ true,
+ false,
+ );
}
} catch (err) {
logger.logException(err);
@@ -1045,7 +1063,7 @@ const userHelper = function () {
const userInfo = await userProfile.findById(personId);
let newEarnedDate = [];
const recordToUpdate = userInfo.badgeCollection.find(
- item => item.badge._id.toString() === badgeId.toString(),
+ (item) => item.badge._id.toString() === badgeId.toString(),
);
if (!recordToUpdate) {
throw new Error(
@@ -1252,7 +1270,7 @@ const userHelper = function () {
if (user.lastWeekTangibleHrs / user.weeklycommittedHours >= elem.multiple) {
const theBadge = badgesOfType.find(
- badgeItem => badgeItem._id.toString() === elem._id.toString(),
+ (badgeItem) => badgeItem._id.toString() === elem._id.toString(),
);
return theBadge
? increaseBadgeCount(personId, mongoose.Types.ObjectId(theBadge._id))
@@ -1360,7 +1378,7 @@ const userHelper = function () {
return true;
});
});
- }
+ };
// 'X Hours for X Week Streak',
const checkXHrsForXWeeks = async function (personId, user, badgeCollection) {
From fcfbc0895f1fc9565988a2cd5014f4a2b0467a32 Mon Sep 17 00:00:00 2001
From: 20chen-7
Date: Sun, 28 Apr 2024 13:21:47 +0800
Subject: [PATCH 15/15] chore: fix resolved and add ad cont in notify
---
src/controllers/userProfileController.js | 38 +++++++------
src/helpers/userHelper.js | 68 +++++++++++++++++++-----
2 files changed, 74 insertions(+), 32 deletions(-)
diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js
index 496719f6b..0ad2f9527 100644
--- a/src/controllers/userProfileController.js
+++ b/src/controllers/userProfileController.js
@@ -110,7 +110,7 @@ const userProfileController = function (UserProfile) {
cache.setCache('allusers', JSON.stringify(results));
res.status(200).send(results);
})
- .catch(error => res.status(404).send(error));
+ .catch((error) => res.status(404).send(error));
};
const getProjectMembers = async function (req, res) {
@@ -329,7 +329,6 @@ const userProfileController = function (UserProfile) {
};
const putUserProfile = async function (req, res) {
-
const userid = req.params.userId;
const isRequestorAuthorized = !!(
canRequestorUpdateUser(req.body.requestor.requestorId, userid) &&
@@ -422,7 +421,7 @@ const userProfileController = function (UserProfile) {
let userIdx;
if (isUserInCache) {
allUserData = JSON.parse(cache.getCache('allusers'));
- userIdx = allUserData.findIndex(users => users._id === userid);
+ userIdx = allUserData.findIndex((users) => users._id === userid);
userData = allUserData[userIdx];
}
if (await hasPermission(req.body.requestor, 'putUserProfileImportantInfo')) {
@@ -499,10 +498,7 @@ const userProfileController = function (UserProfile) {
record.weeklycommittedHoursHistory.push(newEntry);
}
- if (
- req.body.startDate !== undefined
- && record.startDate !== req.body.startDate
- ) {
+ if (req.body.startDate !== undefined && record.startDate !== req.body.startDate) {
record.startDate = moment(req.body.startDate).toDate();
// Make sure weeklycommittedHoursHistory isn't empty
if (record.weeklycommittedHoursHistory.length === 0) {
@@ -558,6 +554,8 @@ const userProfileController = function (UserProfile) {
results.firstName,
results.lastName,
results.email,
+ results.role,
+ results.startDate,
);
res.status(200).json({
_id: record._id,
@@ -569,7 +567,7 @@ const userProfileController = function (UserProfile) {
cache.setCache('allusers', JSON.stringify(allUserData));
}
})
- .catch(error => res.status(400).send(error));
+ .catch((error) => res.status(400).send(error));
});
};
@@ -710,7 +708,7 @@ const userProfileController = function (UserProfile) {
res.status(200).send(results);
});
})
- .catch(error => res.status(404).send(error));
+ .catch((error) => res.status(404).send(error));
};
const getUserByName = (req, res) => {
@@ -723,7 +721,7 @@ const userProfileController = function (UserProfile) {
.then((results) => {
res.status(200).send(results);
})
- .catch(error => res.status(404).send(error));
+ .catch((error) => res.status(404).send(error));
};
const updateOneProperty = function (req, res) {
@@ -759,9 +757,9 @@ const userProfileController = function (UserProfile) {
.then(() => {
res.status(200).send({ message: 'updated property' });
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
};
const updatepassword = async function (req, res) {
@@ -821,11 +819,11 @@ const userProfileController = function (UserProfile) {
return user
.save()
.then(() => res.status(200).send({ message: 'updated password' }))
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
};
const getreportees = async function (req, res) {
@@ -857,7 +855,7 @@ const userProfileController = function (UserProfile) {
});
res.status(200).send(teammembers);
})
- .catch(error => res.status(400).send(error));
+ .catch((error) => res.status(400).send(error));
};
const getTeamMembersofUser = function (req, res) {
@@ -874,7 +872,7 @@ const userProfileController = function (UserProfile) {
.then((results) => {
res.status(200).send(results);
})
- .catch(error => res.status(400).send(error));
+ .catch((error) => res.status(400).send(error));
};
const getUserName = function (req, res) {
@@ -1126,7 +1124,7 @@ const userProfileController = function (UserProfile) {
}
res.status(200).send(users);
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
};
function escapeRegExp(string) {
@@ -1158,7 +1156,7 @@ const userProfileController = function (UserProfile) {
}
res.status(200).send(users);
})
- .catch(error => res.status(500).send(error));
+ .catch((error) => res.status(500).send(error));
};
/**
@@ -1225,4 +1223,4 @@ const userProfileController = function (UserProfile) {
};
};
-module.exports = userProfileController;
\ No newline at end of file
+module.exports = userProfileController;
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index fee80103a..bab26ed66 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -380,8 +380,8 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true },
- '_id weeklycommittedHours weeklySummaries missedHours',
+ { isActive: true, email: 'ivyadmin2@gmail.com' },
+ '_id email weeklycommittedHours weeklySummaries missedHours',
);
const usersRequiringBlueSqNotification = [];
@@ -639,12 +639,6 @@ const userHelper = function () {
// Otherwise, display notification to users if new user && met the time requirement && weekly summary not submitted
// All other new users will not receive a blue square or notification
let emailBody = '';
- const administrativeContent = {
- startDate: moment(person.createdDate).utc().format('YYYY-MM-DD'),
- roleAdminstrative: person.role,
- userTitle: `${person.firstName} ${person.lastName}`,
- historyInfringements,
- };
if (!isNewUser) {
const status = await userProfile.findByIdAndUpdate(
personId,
@@ -655,6 +649,12 @@ const userHelper = function () {
},
{ new: true },
);
+ const administrativeContent = {
+ startDate: moment(person.createdDate).utc().format('YYYY-MM-DD'),
+ roleAdminstrative: person.role,
+ userTitle: `${person.firstName} ${person.lastName}`,
+ historyInfringements,
+ };
if (person.role === 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
@@ -957,13 +957,52 @@ const userHelper = function () {
}
};
- const notifyInfringements = function (original, current, firstName, lastName, emailAddress) {
+ const notifyInfringements = function (
+ original,
+ current,
+ firstName,
+ lastName,
+ emailAddress,
+ role,
+ startDate,
+ ) {
if (!current) return;
const newOriginal = original.toObject();
const newCurrent = current.toObject();
const totalInfringements = newCurrent.length;
let newInfringements = [];
-
+ let historyInfringements = 'No Previous Infringements.';
+ if (original.length) {
+ historyInfringements = original
+ .map((item, index) => {
+ let enhancedDescription = item.description;
+ // highlight previous assigned reason manually
+ if (!item.description.includes('System auto-assigned infringement')) {
+ enhancedDescription = `${item.description}`;
+ } else {
+ // highlight not submitting a weekly summary and logged hrs
+ const sentences = item.description.split('.');
+ sentences[0] = `${sentences[0]}`;
+ enhancedDescription = sentences.join('.');
+ enhancedDescription = enhancedDescription.replace(
+ /(not submitting a weekly summary)/gi,
+ '$1',
+ );
+ enhancedDescription = enhancedDescription.replace(
+ /(\d+\.\d{2})\s*hours/i,
+ '$1 hours',
+ );
+ }
+ return `${index + 1}. Date: ${item.date}, Description: ${enhancedDescription}
`;
+ })
+ .join('');
+ }
+ const administrativeContent = {
+ startDate: moment(startDate).utc().format('YYYY-MM-DD'),
+ roleAdminstrative: role,
+ userTitle: `${firstName} ${lastName}`,
+ historyInfringements,
+ };
newInfringements = _.differenceWith(newCurrent, newOriginal, (arrVal, othVal) =>
arrVal._id.equals(othVal._id),
);
@@ -971,8 +1010,13 @@ const userHelper = function () {
emailSender(
emailAddress,
'New Infringement Assigned',
- getInfringementEmailBody(firstName, lastName, element, totalInfringements),
-
+ getInfringementEmailBody(
+ firstName,
+ lastName,
+ element,
+ totalInfringements,
+ administrativeContent,
+ ),
null,
'onecommunityglobal@gmail.com',
emailAddress,