diff --git a/.DS_Store b/.DS_Store index 7c6c469a2..2f6603376 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/package-lock.json b/package-lock.json index 0c8f3ee0b..91423c0a2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4409,6 +4409,22 @@ } } }, + "express-validator": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.0.1.tgz", + "integrity": "sha512-oB+z9QOzQIE8FnlINqyIFA8eIckahC6qc8KtqLdLJcU3/phVyuhXH3bA4qzcrhme+1RYaCSwrq+TlZ/kAKIARA==", + "requires": { + "lodash": "^4.17.21", + "validator": "^13.9.0" + }, + "dependencies": { + "validator": { + "version": "13.11.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.11.0.tgz", + "integrity": "sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==" + } + } + }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", diff --git a/package.json b/package.json index 1c6b8a5d4..e7fbd6307 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "cron": "^1.8.2", "dotenv": "^5.0.1", "express": "^4.17.1", + "express-validator": "^7.0.1", "googleapis": "^100.0.0", "jsonwebtoken": "^9.0.0", "lodash": "^4.17.21", diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index addd2e2e4..d05490e44 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -14,16 +14,14 @@ const logger = require("../startup/logger"); const hasPermission = require("../utilities/permissions"); const Reason = require("../models/reason"); const token = require("../models/profileInitialSetupToken"); - - const userHelper = function () { 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, }); }; @@ -38,11 +36,11 @@ const userHelper = function () { 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) { - const picParts = profilePic.split("base64"); + const picParts = profilePic.split('base64'); let result = true; const errors = []; @@ -55,17 +53,16 @@ const userHelper = function () { // validate size const imageSize = picParts[1].length; - const sizeInBytes = - (4 * Math.ceil(imageSize / 3) * 0.5624896334383812) / 1024; + const sizeInBytes = (4 * Math.ceil(imageSize / 3) * 0.5624896334383812) / 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]; - if (imageType !== "jpeg;" && imageType !== "png;") { - errors.push("Image type shoud be either jpeg or png."); + const imageType = picParts[0].split('/')[1]; + if (imageType !== 'jpeg;' && imageType !== 'png;') { + errors.push('Image type shoud be either jpeg or png.'); result = false; } @@ -120,7 +117,7 @@ const userHelper = function () { const currentFormattedDate = moment().tz("America/Los_Angeles").format(); logger.logInfo( - `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}` + `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}`, ); const emails = []; @@ -128,13 +125,11 @@ const userHelper = function () { try { const results = await reportHelper.weeklySummaries(weekIndex, weekIndex); - 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( @@ -171,14 +166,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. @@ -238,10 +233,8 @@ 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("\n")) - emailString = emailString.replace("\n", ", "); + while (emailString.includes(',')) emailString = emailString.replace(',', '\n'); + while (emailString.includes('\n')) emailString = emailString.replace('\n', ', '); emailBody += `\n
@@ -253,8 +246,8 @@ const userHelper = function () { `; emailSender( - "onecommunityglobal@gmail.com, sangam.pravah@gmail.com, onecommunityhospitality@gmail.com", - "Weekly Summaries for all active users...", + 'onecommunityglobal@gmail.com, sangam.pravah@gmail.com, onecommunityhospitality@gmail.com', + 'Weekly Summaries for all active users...', emailBody, null, null, @@ -301,8 +294,8 @@ const userHelper = function () { try { const currentFormattedDate = moment().tz("America/Los_Angeles").format(); const currentUTCDate = moment - .tz("America/Los_Angeles") - .startOf("day") + .tz('America/Los_Angeles') + .startOf('day') .toISOString(); logger.logInfo( @@ -310,23 +303,23 @@ const userHelper = function () { ); 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"); + .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 - //targeted as spam - //There's no need to put Promise.all here + // this part is supposed to be a for, so it'll be slower when sending emails, so the emails will not be + // targeted as spam + // There's no need to put Promise.all here for (let i = 0; i < users.length; i += 1) { const user = users[i]; @@ -357,13 +350,12 @@ const userHelper = function () { const results = await dashboardHelper.laborthisweek( personId, pdtStartOfLastWeek, - pdtEndOfLastWeek + pdtEndOfLastWeek, ); const { timeSpent_hrs: timeSpent } = results[0]; - const weeklycommittedHours = - user.weeklycommittedHours + (user.missedHours ?? 0); + const weeklycommittedHours = user.weeklycommittedHours + (user.missedHours ?? 0); const timeNotMet = timeSpent < weeklycommittedHours; let description; @@ -386,7 +378,7 @@ const userHelper = function () { lastWeekTangibleHrs: timeSpent || 0, }, }, - { new: true } + { new: true }, ); if ( @@ -396,13 +388,13 @@ const userHelper = function () { 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 { @@ -418,7 +410,7 @@ const userHelper = function () { oldInfringements: { $each: oldInfringements, $slice: -10 }, }, }, - { new: true } + { new: true }, ); } @@ -440,10 +432,9 @@ const userHelper = function () { )} 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"), @@ -457,7 +448,7 @@ const userHelper = function () { infringements: infringement, }, }, - { new: true } + { new: true }, ); let emailBody = ""; @@ -491,13 +482,13 @@ const userHelper = function () { const categories = await dashboardHelper.laborThisWeekByCategory( personId, pdtStartOfLastWeek, - pdtEndOfLastWeek + pdtEndOfLastWeek, ); if (Array.isArray(categories) && categories.length > 0) { await userProfile.findOneAndUpdate( { _id: personId, categoryTangibleHrs: { $exists: false } }, - { $set: { categoryTangibleHrs: [] } } + { $set: { categoryTangibleHrs: [] } }, ); } else { continue; @@ -507,13 +498,13 @@ 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 } }, - { new: true } + { _id: personId, 'categoryTangibleHrs.category': elem._id }, + { $inc: { 'categoryTangibleHrs.$.hrs': elem.timeSpent_hrs } }, + { new: true }, ); if (!updateResult2) { @@ -541,7 +532,7 @@ 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]; @@ -560,20 +551,20 @@ const userHelper = function () { const currentDate = moment().tz("America/Los_Angeles").format(); logger.logInfo( - `Job for applying missed hours for Core Team members starting at ${currentDate}` + `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([ { @@ -584,9 +575,9 @@ const userHelper = function () { }, { $lookup: { - from: "timeEntries", - localField: "_id", - foreignField: "personId", + from: 'timeEntries', + localField: '_id', + foreignField: 'personId', pipeline: [ { $match: { @@ -659,7 +650,7 @@ const userHelper = function () { const currentFormattedDate = moment().tz("America/Los_Angeles").format(); logger.logInfo( - `Job for deleting blue squares older than 1 year starting at ${currentFormattedDate}` + `Job for deleting blue squares older than 1 year starting at ${currentFormattedDate}`, ); const cutOffDate = moment().subtract(1, "year").format("YYYY-MM-DD"); @@ -688,13 +679,13 @@ const userHelper = function () { const currentFormattedDate = moment().tz("America/Los_Angeles").format(); logger.logInfo( - `Job for activating users based on scheduled re-activation date starting at ${currentFormattedDate}` + `Job for activating users based on scheduled re-activation date starting at ${currentFormattedDate}`, ); 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]; @@ -709,12 +700,12 @@ const userHelper = function () { endDate: user.endDate, }, }, - { new: true } + { new: true }, ); logger.logInfo( `User with id: ${user._id} was re-acticated at ${moment() - .tz("America/Los_Angeles") - .format()}.` + .tz('America/Los_Angeles') + .format()}.`, ); const id = user._id; const person = await userProfile.findById(id); @@ -791,7 +782,7 @@ 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, @@ -803,14 +794,14 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); }; const increaseBadgeCount = async function (personId, badgeId) { - console.log("Increase Badge Count", personId, badgeId); + console.log('Increase Badge Count', personId, badgeId); userProfile.updateOne( - { _id: personId, "badgeCollection.badge": badgeId }, + { _id: personId, 'badgeCollection.badge': badgeId }, { $inc: { "badgeCollection.$.count": 1 }, $set: { "badgeCollection.$.lastModified": Date.now().toString() }, @@ -820,7 +811,7 @@ const userHelper = function () { if (err) { console.log(err); } - } + }, ); }; @@ -828,7 +819,7 @@ const userHelper = function () { personId, badgeId, count = 1, - featured = false + featured = false, ) { console.log("Adding Badge"); userProfile.findByIdAndUpdate( @@ -848,7 +839,7 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); }; @@ -864,7 +855,7 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); }; @@ -873,7 +864,7 @@ const userHelper = function () { removeDupBadge(personId, badgeId); } else if (count) { userProfile.updateOne( - { _id: personId, "badgeCollection.badge": badgeId }, + { _id: personId, 'badgeCollection.badge': badgeId }, { $set: { "badgeCollection.$.count": count, @@ -884,7 +875,7 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); } }; @@ -907,7 +898,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, }, @@ -915,7 +906,7 @@ const userHelper = function () { { $sort: { weeks: -1, totalHrs: -1 } }, { $group: { - _id: "$weeks", + _id: '$weeks', badges: { $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" }, }, @@ -936,7 +927,7 @@ const userHelper = function () { changeBadgeCount( personId, badgeCollection[i].badge._id, - badgeCollection[i].badge.count - 1 + badgeCollection[i].badge.count - 1, ); removed = true; return false; @@ -975,7 +966,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) { @@ -991,8 +982,8 @@ const userHelper = function () { 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 @@ -1007,7 +998,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -1022,8 +1013,8 @@ const userHelper = function () { elem.months ) { if ( - user.oldInfringements.length === 0 || - Math.abs( + user.oldInfringements.length === 0 + || Math.abs( moment().diff( moment( user.oldInfringements[user.oldInfringements?.length - 1] @@ -1040,7 +1031,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -1059,7 +1050,7 @@ const userHelper = function () { const checkMinHoursMultiple = async function ( personId, user, - badgeCollection + badgeCollection, ) { const badgesOfType = badgeCollection .map((obj) => obj.badge) @@ -1076,11 +1067,11 @@ const userHelper = function () { const elem = results[i]; // making variable elem accessible for below code if ( - user.lastWeekTangibleHrs / user.weeklycommittedHours >= - elem.multiple + user.lastWeekTangibleHrs / user.weeklycommittedHours + >= elem.multiple ) { const theBadge = badgesOfType.find( - (badge) => badge._id.toString() === elem._id.toString() + badge => badge._id.toString() === elem._id.toString(), ); return theBadge ? increaseBadgeCount( @@ -1097,23 +1088,24 @@ const userHelper = function () { const checkPersonalMax = async function (personId, user, badgeCollection) { let badgeOfType; 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) { removeDupBadge(personId, badgeOfType._id); } } } + 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( personId, mongoose.Types.ObjectId(badgeOfType._id), - user.personalBestMaxHrs + user.personalBestMaxHrs, ); } else { addBadge( @@ -1140,7 +1132,7 @@ const userHelper = function () { userProfile .aggregate([ { $match: { isActive: true } }, - { $group: { _id: 1, maxHours: { $max: "$lastWeekTangibleHrs" } } }, + { $group: { _id: 1, maxHours: { $max: '$lastWeekTangibleHrs' } } }, ]) .then((userResults) => { if (badgeOfType.length > 1) { @@ -1148,13 +1140,13 @@ const userHelper = function () { } if ( - user.lastWeekTangibleHrs && - user.lastWeekTangibleHrs >= userResults[0].maxHours + user.lastWeekTangibleHrs + && user.lastWeekTangibleHrs >= userResults[0].maxHours ) { if (badgeOfType.length) { increaseBadgeCount( personId, - mongoose.Types.ObjectId(badgeOfType[0]._id) + mongoose.Types.ObjectId(badgeOfType[0]._id), ); } else { addBadge(personId, mongoose.Types.ObjectId(results._id)); @@ -1170,12 +1162,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) => { @@ -1200,11 +1192,11 @@ 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" }, }, @@ -1229,8 +1221,8 @@ const userHelper = function () { 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) { @@ -1255,7 +1247,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(bdge._id) + mongoose.Types.ObjectId(bdge._id), ); removePrevHrBadge( @@ -1272,7 +1264,7 @@ const userHelper = function () { user, badgeCollection, bdge.hrs, - bdge.weeks + bdge.weeks, ); } else if (badgeOfType && badgeOfType.totalHrs === bdge.hrs) { increaseBadgeCount( @@ -1353,7 +1345,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) { @@ -1408,18 +1400,18 @@ const userHelper = function () { 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 + 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) { @@ -1441,8 +1433,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) { @@ -1457,13 +1449,13 @@ 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, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -1478,7 +1470,7 @@ const userHelper = function () { }; const awardNewBadges = async () => { - console.log("Awarding"); + console.log('Awarding'); try { const users = await userProfile .find({ isActive: true }) @@ -1520,12 +1512,12 @@ const userHelper = function () { dateOfWork: { $gte: pdtstart, $lte: pdtend }, isTangible: true, }, - "totalSeconds" + 'totalSeconds', ) .then((results) => { const totalTangibleWeeklySeconds = results.reduce( (acc, { totalSeconds }) => acc + totalSeconds, - 0 + 0, ); return (totalTangibleWeeklySeconds / 3600).toFixed(2); }); @@ -1535,19 +1527,19 @@ 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({ isActive: false, }), - { new: true } + { new: true }, ); const id = user._id; const person = await userProfile.findById(id); diff --git a/src/routes/userProfileRouter.js b/src/routes/userProfileRouter.js index 9032359a8..e508d6f82 100644 --- a/src/routes/userProfileRouter.js +++ b/src/routes/userProfileRouter.js @@ -1,53 +1,83 @@ -const express = require('express'); +import { body } from 'express-validator'; +const express = require('express'); const routes = function (userProfile) { - const controller = require('../controllers/userProfileController')(userProfile); + const controller = require('../controllers/userProfileController')( + userProfile, + ); const userProfileRouter = express.Router(); - userProfileRouter.route('/userProfile') + userProfileRouter + .route('/userProfile') .get(controller.getUserProfiles) - .post(controller.postUserProfile); - - userProfileRouter.route('/userProfile/:userId') + .post( + body('firstName').customSanitizer(value => value.trim()), + body('lastName').customSanitizer(value => value.trim()), + controller.postUserProfile, + ); + + userProfileRouter + .route('/userProfile/:userId') .get(controller.getUserById) - .put(controller.putUserProfile) + .put( + body('firstName').customSanitizer(value => value.trim()), + body('lastName').customSanitizer(value => value.trim()), + body('personalLinks').customSanitizer(value => value.map((link) => { + if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { + return { + ...link, + Name: link.Name.trim(), + Link: link.Link.replace(/\s/g, ''), + }; + } + throw new Error('Url not valid'); + })), + controller.putUserProfile, + ) .delete(controller.deleteUserProfile) .patch(controller.changeUserStatus); - userProfileRouter.route('/userProfile/name/:name') + userProfileRouter + .route('/userProfile/name/:name') .get(controller.getUserByName); - userProfileRouter.route('/refreshToken/:userId') - .get(controller.refreshToken); + userProfileRouter.route('/refreshToken/:userId').get(controller.refreshToken); - userProfileRouter.route('/userProfile/reportees/:userId') + userProfileRouter + .route('/userProfile/reportees/:userId') .get(controller.getreportees); - userProfileRouter.route('/userProfile/teammembers/:userId') + userProfileRouter + .route('/userProfile/teammembers/:userId') .get(controller.getTeamMembersofUser); - userProfileRouter.route('/userProfile/:userId/property') + userProfileRouter + .route('/userProfile/:userId/property') .patch(controller.updateOneProperty); - userProfileRouter.route('/userProfile/:userId/updatePassword') + userProfileRouter + .route('/userProfile/:userId/updatePassword') .patch(controller.updatepassword); - userProfileRouter.route('/userProfile/:userId/resetPassword') + userProfileRouter + .route('/userProfile/:userId/resetPassword') .patch(controller.resetPassword); - userProfileRouter.route('/userProfile/name/:userId') + userProfileRouter + .route('/userProfile/name/:userId') .get(controller.getUserName); - userProfileRouter.route('/userProfile/project/:projectId') + userProfileRouter + .route('/userProfile/project/:projectId') .get(controller.getProjectMembers); - userProfileRouter.route('/userProfile/socials/facebook') + userProfileRouter + .route('/userProfile/socials/facebook') .get(controller.getAllUsersWithFacebookLink); return userProfileRouter; }; - module.exports = routes;