diff --git a/src/controllers/dashBoardController.js b/src/controllers/dashBoardController.js index 1cf730a5a..3fdda9eb7 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -211,7 +211,7 @@ const dashboardcontroller = function () { null, null, email, - null, + null ); res.status(200).send('Success'); } catch { diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index c75dd7b45..8bf04eb5f 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -13,7 +13,7 @@ const emailSender = require("../utilities/emailSender"); const logger = require("../startup/logger"); const hasPermission = require("../utilities/permissions"); const Reason = require("../models/reason"); -const token = require("../models/profileInitialSetupToken") +const token = require("../models/profileInitialSetupToken"); const userHelper = function () { const getTeamMembers = function (user) { @@ -57,7 +57,7 @@ const userHelper = function () { if (picParts.length < 2) { return { result: false, - errors: "Invalid image" + errors: "Invalid image", }; } @@ -79,7 +79,7 @@ const userHelper = function () { return { result, - errors + errors, }; }; @@ -90,10 +90,11 @@ const userHelper = function () { totalInfringements, timeRemaining ) { - let final_paragraph = ''; + let final_paragraph = ""; if (timeRemaining == undefined) { - final_paragraph = '
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.
'; + final_paragraph = + "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 { final_paragraph = `Life happens and we understand that. Please make up the missed hours this following week though to avoid getting another blue square. So you know what’s needed, the missing/incomplete hours (${timeRemaining} hours) have been added to your current week and this new weekly total can be seen at the top of your dashboard.
Reminder also that each blue square is removed from your profile 1 year after it was issued.
`; @@ -104,8 +105,8 @@ const userHelper = function () {Date Assigned: ${infringement.date}
Description: ${infringement.description}
Total Infringements: This is your ${moment - .localeData() - .ordinal(totalInfringements)} blue square of 5.
+ .localeData() + .ordinal(totalInfringements)} blue square of 5. ${final_paragraph}Thank you,
One Community
- Media URL: ${mediaUrlLink || 'Not provided!'} + Media URL: ${ + mediaUrlLink || 'Not provided!' + }
- ${weeklySummariesCount === 8 - ? `Total Valid Weekly Summaries: ${weeklySummariesCount}
` - : `Total Valid Weekly Summaries: ${weeklySummariesCount || - "No valid submissions yet!"}
` + ${ + weeklySummariesCount === 8 + ? `Total Valid Weekly Summaries: ${weeklySummariesCount}
` + : `Total Valid Weekly Summaries: ${ + weeklySummariesCount || "No valid submissions yet!" + }
` } - ${hoursLogged >= weeklycommittedHours - - ? `Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}
` - - : `Hours logged: ${hoursLogged.toFixed( - 2 - )} / ${weeklycommittedHours}
` + ${ + hoursLogged >= weeklycommittedHours + ? `Hours logged: ${hoursLogged.toFixed( + 2 + )} / ${weeklycommittedHours}
` + : `Hours logged: ${hoursLogged.toFixed( + 2 + )} / ${weeklycommittedHours}
` } ${weeklySummaryMessage} `; @@ -254,7 +264,9 @@ const userHelper = function () { "onecommunityglobal@gmail.com, sangam.pravah@gmail.com, onecommunityhospitality@gmail.com", "Weekly Summaries for all active users...", emailBody, - null + null, + null, + emailString ); } catch (err) { logger.logException(err); @@ -275,18 +287,16 @@ 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, - $slice: 4 - } - } + $slice: 4, + }, + }, }) - .catch(error => logger.logException(error)); + .catch((error) => logger.logException(error)); }; /** @@ -297,18 +307,14 @@ const userHelper = function () { */ const assignBlueSquareForTimeNotMet = async () => { try { - const currentFormattedDate = moment() - .tz("America/Los_Angeles") - .format(); + 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}`, - + `Job for assigning blue square for commitment not met starting at ${currentFormattedDate}` ); const pdtStartOfLastWeek = moment() @@ -321,7 +327,6 @@ const userHelper = function () { .endOf("week") .subtract(1, "week"); - const users = await userProfile.find( { isActive: true }, "_id weeklycommittedHours weeklySummaries missedHours" @@ -344,8 +349,10 @@ 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; @@ -371,31 +378,28 @@ const userHelper = function () { const timeRemaining = weeklycommittedHours - timeSpent; - const updateResult = await userProfile.findByIdAndUpdate( personId, { $inc: { - totalTangibleHrs: timeSpent || 0 + totalTangibleHrs: timeSpent || 0, }, $max: { - personalBestMaxHrs: timeSpent || 0 + personalBestMaxHrs: timeSpent || 0, }, $push: { - savedTangibleHrs: { $each: [timeSpent || 0], $slice: -200 } + savedTangibleHrs: { $each: [timeSpent || 0], $slice: -200 }, }, $set: { - lastWeekTangibleHrs: timeSpent || 0 - } + lastWeekTangibleHrs: timeSpent || 0, + }, }, { new: true } ); if ( - - updateResult?.weeklySummaryOption === 'Not Required' - || updateResult?.weeklySummaryNotReq - + updateResult?.weeklySummaryOption === "Not Required" || + updateResult?.weeklySummaryNotReq ) { hasWeeklySummary = true; } @@ -419,8 +423,8 @@ const userHelper = function () { personId, { $push: { - oldInfringements: { $each: oldInfringements, $slice: -10 } - } + oldInfringements: { $each: oldInfringements, $slice: -10 }, + }, }, { new: true } ); @@ -431,11 +435,15 @@ const userHelper = function () { description = foundReason.reason; } else { if (timeNotMet && !hasWeeklySummary) { - 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 committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format( + 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 committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format( "dddd YYYY-MM-DD" )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`; } else if (timeNotMet) { - description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed(2)} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format( + description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed( + 2 + )} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format( "dddd YYYY-MM-DD" )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`; } else { @@ -446,46 +454,46 @@ const userHelper = function () { } const infringement = { - date: moment() - .utc() - .format("YYYY-MM-DD"), - description + date: moment().utc().format("YYYY-MM-DD"), + description, }; const status = await userProfile.findByIdAndUpdate( personId, { $push: { - infringements: infringement - } + infringements: infringement, + }, }, { 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, infringement, status.infringements.length, - timeRemaining, + timeRemaining ); } else { emailBody = getInfringementEmailBody( status.firstName, status.lastName, infringement, - status.infringements.length, + status.infringements.length ); } emailSender( status.email, - 'New Infringement Assigned', + "New Infringement Assigned", emailBody, null, - "onecommunityglobal@gmail.com" + "onecommunityglobal@gmail.com", + null, + status.email ); const categories = await dashboardHelper.laborThisWeekByCategory( @@ -520,15 +528,15 @@ const userHelper = function () { await userProfile.findOneAndUpdate( { _id: personId, - "categoryTangibleHrs.category": { $ne: elem._id } + "categoryTangibleHrs.category": { $ne: elem._id }, }, { $addToSet: { categoryTangibleHrs: { category: elem._id, - hrs: elem.timeSpent_hrs - } - } + hrs: elem.timeSpent_hrs, + }, + }, } ); } @@ -545,8 +553,10 @@ const userHelper = function () { 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); @@ -555,9 +565,7 @@ 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}` @@ -579,8 +587,8 @@ const userHelper = function () { { $match: { role: "Core Team", - isActive: true - } + isActive: true, + }, }, { $lookup: { @@ -594,14 +602,14 @@ const userHelper = function () { $and: [ { $eq: ["$isTangible", true] }, { $gte: ["$dateOfWork", startOfLastWeek] }, - { $lte: ["$dateOfWork", endOfLastWeek] } - ] - } - } - } + { $lte: ["$dateOfWork", endOfLastWeek] }, + ], + }, + }, + }, ], - as: "timeEntries" - } + as: "timeEntries", + }, }, { $project: { @@ -611,9 +619,10 @@ const userHelper = function () { { $subtract: [ { - - $sum: [{ $ifNull: ['$missedHours', 0] }, '$weeklycommittedHours'], - + $sum: [ + { $ifNull: ["$missedHours", 0] }, + "$weeklycommittedHours", + ], }, { $divide: [ @@ -621,30 +630,30 @@ const userHelper = function () { $sum: { $map: { input: "$timeEntries", - in: "$$this.totalSeconds" - } - } + in: "$$this.totalSeconds", + }, + }, }, - 3600 - ] - } - ] + 3600, + ], + }, + ], }, - 0 - ] - } - } - } + 0, + ], + }, + }, + }, ]); const bulkOps = []; - missedHours.forEach(obj => { + missedHours.forEach((obj) => { bulkOps.push({ updateOne: { filter: { _id: obj._id }, - update: { missedHours: obj.missedHours } - } + update: { missedHours: obj.missedHours }, + }, }); }); @@ -655,17 +664,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( @@ -674,10 +679,10 @@ const userHelper = function () { $pull: { infringements: { date: { - $lte: cutOffDate - } - } - } + $lte: cutOffDate, + }, + }, + }, } ); @@ -688,9 +693,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}` @@ -708,11 +711,11 @@ const userHelper = function () { user._id, { $set: { - isActive: true + isActive: true, }, $unset: { - endDate: user.endDate - } + endDate: user.endDate, + }, }, { new: true } ); @@ -724,8 +727,12 @@ const userHelper = function () { 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`; @@ -739,9 +746,14 @@ const userHelper = function () {The HGN A.I. (and One Community)
`; - - emailSender('onecommunityglobal@gmail.com', subject, emailBody, null, null); - + emailSender( + "onecommunityglobal@gmail.com", + subject, + emailBody, + null, + null, + person.email + ); } } } catch (err) { @@ -749,24 +761,38 @@ 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 ); }); }; @@ -778,10 +804,10 @@ const userHelper = function () { $set: { "badgeCollection.$.badge": newBadgeId, "badgeCollection.$.lastModified": Date.now().toString(), - "badgeCollection.$.count": 1 - } + "badgeCollection.$.count": 1, + }, }, - err => { + (err) => { if (err) { throw new Error(err); } @@ -796,9 +822,9 @@ const userHelper = function () { { $inc: { "badgeCollection.$.count": 1 }, $set: { "badgeCollection.$.lastModified": Date.now().toString() }, - $push: { "badgeCollection.$.earnedDate": earnedDateBadge() } + $push: { "badgeCollection.$.earnedDate": earnedDateBadge() }, }, - err => { + (err) => { if (err) { console.log(err); } @@ -812,17 +838,21 @@ const userHelper = function () { count = 1, featured = false ) { - console.log('Adding Badge'); + console.log("Adding Badge"); userProfile.findByIdAndUpdate( personId, { $push: { badgeCollection: { - badge: badgeId, count, earnedDate: [earnedDateBadge()], featured, lastModified: Date.now().toString(), + badge: badgeId, + count, + earnedDate: [earnedDateBadge()], + featured, + lastModified: Date.now().toString(), }, }, }, - err => { + (err) => { if (err) { throw new Error(err); } @@ -835,10 +865,10 @@ const userHelper = function () { personId, { $pull: { - badgeCollection: { badge: badgeId } - } + badgeCollection: { badge: badgeId }, + }, }, - err => { + (err) => { if (err) { throw new Error(err); } @@ -855,10 +885,10 @@ const userHelper = function () { { $set: { "badgeCollection.$.count": count, - "badgeCollection.$.lastModified": Date.now().toString() - } + "badgeCollection.$.lastModified": Date.now().toString(), + }, }, - err => { + (err) => { if (err) { throw new Error(err); } @@ -869,8 +899,13 @@ 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; @@ -882,30 +917,29 @@ const userHelper = function () { $match: { type: "X Hours for X Week Streak", weeks: { $gt: 1, $lt: weeks }, - totalHrs: hrs - } + totalHrs: hrs, + }, }, { $sort: { weeks: -1, totalHrs: -1 } }, { $group: { _id: "$weeks", badges: { - $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" } - } - } - } + $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" }, + }, + }, + }, ]) - .then(results => { - results.forEach(streak => { - streak.badges.every(bdge => { + .then((results) => { + results.forEach((streak) => { + 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, @@ -924,15 +958,24 @@ 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; @@ -942,28 +985,29 @@ const userHelper = function () { await badge .find({ type: "No Infringement Streak" }) .sort({ months: -1 }) - .then(results => { + .then((results) => { if (!Array.isArray(results) || !results.length) { return; } - results.every(elem => { + results.every((elem) => { // 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( moment().diff( - - moment(user.infringements[user.infringements?.length - 1].date), - 'months', - true, - ), - + moment( + user.infringements[user.infringements?.length - 1].date + ), + "months", + true + ) ) >= elem.months ) { if (badgeOfType) { @@ -981,21 +1025,23 @@ 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( moment().diff( - - moment(user.oldInfringements[user.oldInfringements?.length - 1].date), - 'months', - true, - ), - ) - >= elem.months - 12 - + moment( + user.oldInfringements[user.oldInfringements?.length - 1] + .date + ), + "months", + true + ) + ) >= + elem.months - 12 ) { if (badgeOfType) { if (badgeOfType._id.toString() !== elem._id.toString()) { @@ -1024,10 +1070,10 @@ const userHelper = function () { badgeCollection ) { const badgesOfType = badgeCollection - .map(obj => obj.badge) - .filter(badge => badge.type === 'Minimum Hours Multiple') + .map((obj) => obj.badge) + .filter((badge) => badge.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) { @@ -1046,13 +1092,13 @@ const userHelper = function () { ); return theBadge ? increaseBadgeCount( - personId, - mongoose.Types.ObjectId(theBadge._id) - ) + personId, + mongoose.Types.ObjectId(theBadge._id) + ) : addBadge(personId, mongoose.Types.ObjectId(elem._id)); } } - }) + }); }; // 'Personal Max', @@ -1065,7 +1111,7 @@ const userHelper = function () { } } } - await badge.findOne({ type: "Personal Max" }).then(results => { + await badge.findOne({ type: "Personal Max" }).then((results) => { if ( user.lastWeekTangibleHrs && user.lastWeekTangibleHrs >= 1 && @@ -1078,9 +1124,11 @@ const userHelper = function () { user.personalBestMaxHrs ); } else { - - addBadge(personId, mongoose.Types.ObjectId(results._id), user.personalBestMaxHrs); - + addBadge( + personId, + mongoose.Types.ObjectId(results._id), + user.personalBestMaxHrs + ); } } }); @@ -1090,13 +1138,13 @@ const userHelper = function () { const checkMostHrsWeek = async function (personId, user, badgeCollection) { if ( - user.weeklycommittedHours > 0 - && user.lastWeekTangibleHrs > user.weeklycommittedHours + user.weeklycommittedHours > 0 && + user.lastWeekTangibleHrs > user.weeklycommittedHours ) { const badgeOfType = badgeCollection - .filter(object => object.badge.type === 'Most Hrs in Week') - .map(object => object.badge); - await badge.findOne({ type: 'Most Hrs in Week' }).then((results) => { + .filter((object) => object.badge.type === "Most Hrs in Week") + .map((object) => object.badge); + await badge.findOne({ type: "Most Hrs in Week" }).then((results) => { userProfile .aggregate([ { $match: { isActive: true } }, @@ -1105,7 +1153,6 @@ const userHelper = function () { .then((userResults) => { if (badgeOfType.length > 1) { removeDupBadge(user._id, badgeOfType[0]._id); - } if ( @@ -1138,8 +1185,8 @@ const userHelper = function () { await badge .find({ type: "X Hours for X Week Streak", weeks: 1 }) .sort({ totalHrs: -1 }) - .then(results => { - results.every(elem => { + .then((results) => { + results.every((elem) => { if (elem.totalHrs <= user.lastWeekTangibleHrs) { let theBadge; for (let i = 0; i < badgesOfType.length; i += 1) { @@ -1167,24 +1214,26 @@ const userHelper = function () { $group: { _id: "$weeks", badges: { - $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" } - } - } - } + $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" }, + }, + }, + }, ]) - .then(results => { + .then((results) => { let lastHr = -1; - results.forEach(streak => { - streak.badges.every(bdge => { + results.forEach((streak) => { + streak.badges.every((bdge) => { 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 ( @@ -1217,7 +1266,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( @@ -1228,9 +1283,17 @@ const userHelper = function () { 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; } @@ -1243,16 +1306,25 @@ 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; await getTeamMembers({ - _id: personId - }).then(results => { + _id: personId, + }).then((results) => { if (results) { teamMembers = results.myteam; } else { @@ -1271,13 +1343,17 @@ 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; @@ -1287,7 +1363,7 @@ const userHelper = function () { await badge .find({ type: "Lead a team of X+" }) .sort({ people: -1 }) - .then(results => { + .then((results) => { if (!Array.isArray(results) || !results.length) { return; } @@ -1295,16 +1371,14 @@ const userHelper = function () { if (teamMembers && teamMembers.length >= badge.people) { if (badgeOfType) { if ( - badgeOfType._id.toString() !== badge._id.toString() - && badgeOfType.people < badge.people - + badgeOfType._id.toString() !== badge._id.toString() && + badgeOfType.people < badge.people ) { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(badge._id), - + mongoose.Types.ObjectId(badge._id) ); } return false; @@ -1327,19 +1401,18 @@ const userHelper = function () { "education", "society", "economics", - "stewardship" + "stewardship", ]; const badgesOfType = badgeCollection - .filter(object => object.badge.type === "Total Hrs in Category") - .map(object => object.badge); + .filter((object) => object.badge.type === "Total Hrs in Category") + .map((object) => object.badge); - categories.forEach(async category => { + categories.forEach(async (category) => { const categoryHrs = Object.keys(hoursByCategory).find( - elem => elem === category + (elem) => elem === category ); - let badgeOfType; for (let i = 0; i < badgeCollection.length; i += 1) { if ( @@ -1365,16 +1438,16 @@ const userHelper = function () { const newCatg = category.charAt(0).toUpperCase() + category.slice(1); - - await badge.find({ type: 'Total Hrs in Category', category: newCatg }) + await badge + .find({ type: "Total Hrs in Category", category: newCatg }) .sort({ totalHrs: -1 }) - .then(results => { + .then((results) => { if (!Array.isArray(results) || !results.length || !categoryHrs) { return; } - results.every(elem => { + results.every((elem) => { if ( hoursByCategory[categoryHrs] >= 100 && hoursByCategory[categoryHrs] >= elem.totalHrs @@ -1415,9 +1488,9 @@ const userHelper = function () { const awardNewBadges = async () => { console.log("Awarding"); 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]; @@ -1439,20 +1512,25 @@ 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( { personId: userId, dateOfWork: { $gte: pdtstart, $lte: pdtend }, - isTangible: true + isTangible: true, }, "totalSeconds" ) - .then(results => { + .then((results) => { const totalTangibleWeeklySeconds = results.reduce( (acc, { totalSeconds }) => acc + totalSeconds, 0 @@ -1475,15 +1553,19 @@ const userHelper = function () { await userProfile.findByIdAndUpdate( user._id, user.set({ - isActive: false + isActive: false, }), { new: true } ); 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`; @@ -1497,8 +1579,14 @@ const userHelper = function () {The HGN A.I. (and One Community)
`; - - emailSender('onecommunityglobal@gmail.com', subject, emailBody, null, null); + emailSender( + "onecommunityglobal@gmail.com", + subject, + emailBody, + null, + null, + person.email + ); } } } catch (err) { @@ -1514,8 +1602,7 @@ const userHelper = function () { } catch (error) { logger.logException(err); } - } - + }; return { getUserName, @@ -1531,7 +1618,7 @@ const userHelper = function () { emailWeeklySummariesForAllUsers, awardNewBadges, getTangibleHoursReportedThisWeekByUserId, - deleteExpiredTokens + deleteExpiredTokens, }; };