From a700e600c162de38b5b256a749830d9be2577fe8 Mon Sep 17 00:00:00 2001 From: luisarevalo21 Date: Tue, 31 Oct 2023 09:53:23 -0700 Subject: [PATCH 1/4] removed caching code which prevent user profile from being updated correctly. --- .../bmdashboard/bmMaterialsController.js | 24 +- src/controllers/dashBoardController.js | 92 +-- src/controllers/isEmailExistsController.js | 22 +- .../profileInitialSetupController.js | 89 ++- src/controllers/projectController.js | 177 +++-- src/controllers/teamController.js | 2 +- src/controllers/userProfileController.js | 106 ++- src/helpers/dashboardhelper.js | 4 +- src/helpers/reporthelper.js | 94 +-- src/helpers/taskHelper.js | 4 +- src/helpers/userHelper.js | 603 +++++++++--------- src/models/badge.js | 2 +- src/models/inventoryItemMaterial.js | 6 +- src/models/inventoryItemType.js | 6 +- src/models/profileInitialSetupToken.js | 4 +- src/models/userProfile.js | 4 +- src/routes/bmdashboard/bmMaterialsRouter.js | 4 +- src/routes/isEmailExistsRouter.js | 14 +- src/routes/profileInitialSetupRouter.js | 6 +- 19 files changed, 644 insertions(+), 619 deletions(-) diff --git a/src/controllers/bmdashboard/bmMaterialsController.js b/src/controllers/bmdashboard/bmMaterialsController.js index a31ed460e..fb6003e90 100644 --- a/src/controllers/bmdashboard/bmMaterialsController.js +++ b/src/controllers/bmdashboard/bmMaterialsController.js @@ -1,4 +1,4 @@ -const mongoose = require('mongoose') +const mongoose = require('mongoose'); const bmMaterialsController = function (ItemMaterial) { const bmMaterialsList = async function _matsList(req, res) { @@ -7,37 +7,37 @@ const bmMaterialsController = function (ItemMaterial) { .populate([ { path: 'project', - select: '_id projectName' + select: '_id projectName', }, { path: 'inventoryItemType', - select: '_id name uom totalStock totalAvailable' + select: '_id name uom totalStock totalAvailable', }, { path: 'usageRecord', populate: { path: 'createdBy', - select: '_id firstName lastName' - } + select: '_id firstName lastName', + }, }, { path: 'updateRecord', populate: { path: 'createdBy', - select: '_id firstName lastName' - } + select: '_id firstName lastName', + }, }, { path: 'purchaseRecord', populate: { path: 'createdBy', - select: '_id firstName lastName' - } - } + select: '_id firstName lastName', + }, + }, ]) .exec() .then(results => res.status(200).send(results)) - .catch(error => res.status(500).send(error)) + .catch(error => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -45,4 +45,4 @@ const bmMaterialsController = function (ItemMaterial) { return { bmMaterialsList }; }; -module.exports = bmMaterialsController; \ No newline at end of file +module.exports = bmMaterialsController; diff --git a/src/controllers/dashBoardController.js b/src/controllers/dashBoardController.js index c9cdbd588..c7f9c3973 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -1,8 +1,8 @@ -const mongoose = require("mongoose"); -const path = require("path"); -const fs = require("fs/promises"); -const dashboardhelper = require("../helpers/dashboardhelper")(); -const emailSender = require("../utilities/emailSender"); +const path = require('path'); +const fs = require('fs/promises'); +const mongoose = require('mongoose'); +const dashboardhelper = require('../helpers/dashboardhelper')(); +const emailSender = require('../utilities/emailSender'); const dashboardcontroller = function () { const dashboarddata = function (req, res) { @@ -20,13 +20,13 @@ const dashboardcontroller = function () { const laborthismonth = dashboardhelper.laborthismonth( userId, req.params.fromDate, - req.params.toDate + req.params.toDate, ); laborthismonth.then((results) => { if (!results || results.length === 0) { const emptyresult = [ { - projectName: "", + projectName: '', timeSpent_hrs: 0, }, ]; @@ -42,7 +42,7 @@ const dashboardcontroller = function () { const laborthisweek = dashboardhelper.laborthisweek( userId, req.params.fromDate, - req.params.toDate + req.params.toDate, ); laborthisweek.then((results) => { res.send(results).status(200); @@ -63,7 +63,7 @@ const dashboardcontroller = function () { }); } }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const orgData = function (req, res) { @@ -73,7 +73,7 @@ const dashboardcontroller = function () { .then((results) => { res.status(200).send(results[0]); }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const getBugReportEmailBody = function ( @@ -85,7 +85,7 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ) { const text = `New Bug Report From ${firstName} ${lastName}:

[Feature Name] Bug Title:

@@ -130,32 +130,32 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ); try { emailSender( - "onecommunityglobal@gmail.com", + 'onecommunityglobal@gmail.com', `Bug Rport from ${firstName} ${lastName}`, emailBody, - email + email, ); - res.status(200).send("Success"); + res.status(200).send('Success'); } catch { - res.status(500).send("Failed"); + res.status(500).send('Failed'); } }; const suggestionData = { suggestion: [ - "Identify and remedy poor client and/or user service experiences", - "Identify bright spots and enhance positive service experiences", - "Make fundamental changes to our programs and/or operations", - "Inform the development of new programs/projects", - "Identify where we are less inclusive or equitable across demographic groups", - "Strengthen relationships with the people we serve", + 'Identify and remedy poor client and/or user service experiences', + 'Identify bright spots and enhance positive service experiences', + 'Make fundamental changes to our programs and/or operations', + 'Inform the development of new programs/projects', + 'Identify where we are less inclusive or equitable across demographic groups', + 'Strengthen relationships with the people we serve', "Understand people's needs and how we can help them achieve their goals", - "Other", + 'Other', ], field: [], }; @@ -164,8 +164,8 @@ const dashboardcontroller = function () { let fieldaaray = []; if (suggestionData.field.length) { fieldaaray = suggestionData.field.map( - (item) => `

${item}

-

${args[3][item]}

` + item => `

${item}

+

${args[3][item]}

`, ); } const text = `New Suggestion: @@ -173,7 +173,7 @@ const dashboardcontroller = function () {

${args[0]}

Suggestion:

${args[1]}

- ${fieldaaray.length > 0 ? fieldaaray : ""} + ${fieldaaray.length > 0 ? fieldaaray : ''}

Wants Feedback:

${args[2]}

Thank you,
@@ -184,22 +184,24 @@ const dashboardcontroller = function () { // send suggestion email const sendMakeSuggestion = async (req, res) => { - const { suggestioncate, suggestion, confirm, ...rest } = req.body; + const { + suggestioncate, suggestion, confirm, ...rest +} = req.body; const emailBody = await getsuggestionEmailBody( suggestioncate, suggestion, confirm, - rest + rest, ); try { emailSender( - "onecommunityglobal@gmail.com", - "A new suggestion", - emailBody + 'onecommunityglobal@gmail.com', + 'A new suggestion', + emailBody, ); - res.status(200).send("Success"); + res.status(200).send('Success'); } catch { - res.status(500).send("Failed"); + res.status(500).send('Failed'); } }; @@ -208,40 +210,40 @@ const dashboardcontroller = function () { if (suggestionData) { res.status(200).send(suggestionData); } else { - res.status(404).send("Suggestion data not found."); + res.status(404).send('Suggestion data not found.'); } } catch (error) { - console.error("Error getting suggestion data:", error); - res.status(500).send("Internal Server Error"); + console.error('Error getting suggestion data:', error); + res.status(500).send('Internal Server Error'); } }; const editSuggestionOption = async (req, res) => { try { if (req.body.suggestion) { - if (req.body.action === "add") { + if (req.body.action === 'add') { suggestionData.suggestion.unshift(req.body.newField); } - if (req.body.action === "delete") { + if (req.body.action === 'delete') { suggestionData.suggestion = suggestionData.suggestion.filter( - (item, index) => index + 1 !== +req.body.newField + (item, index) => index + 1 !== +req.body.newField, ); } } else { - if (req.body.action === "add") { + if (req.body.action === 'add') { suggestionData.field.unshift(req.body.newField); } - if (req.body.action === "delete") { + if (req.body.action === 'delete') { suggestionData.field = suggestionData.field.filter( - (item) => item !== req.body.newField + item => item !== req.body.newField, ); } } - res.status(200).send("success"); + res.status(200).send('success'); } catch (error) { - console.error("Error editing suggestion option:", error); - res.status(500).send("Internal Server Error"); + console.error('Error editing suggestion option:', error); + res.status(500).send('Internal Server Error'); } }; diff --git a/src/controllers/isEmailExistsController.js b/src/controllers/isEmailExistsController.js index 2c41efc33..f6009a3c5 100644 --- a/src/controllers/isEmailExistsController.js +++ b/src/controllers/isEmailExistsController.js @@ -1,25 +1,23 @@ const UserProfile = require('../models/userProfile'); const isEmailExistsController = function () { - const isEmailExists = async function (req, res) { - - try { - const userProfile = await UserProfile.findOne({ email: req.params.email }).lean().exec() + try { + const userProfile = await UserProfile.findOne({ email: req.params.email }).lean().exec(); if (userProfile) { - res.status(200).send(`Email, ${userProfile.email}, found.`) + res.status(200).send(`Email, ${userProfile.email}, found.`); } else { - res.status(403).send(`Email, ${req.params.email}, not found.`) + res.status(403).send(`Email, ${req.params.email}, not found.`); } } catch (err) { - console.log(err) + console.log(err); } - } + }; return { - isEmailExists - } -} + isEmailExists, + }; +}; -module.exports = isEmailExistsController +module.exports = isEmailExistsController; diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js index 18cf7376c..6914cf48a 100644 --- a/src/controllers/profileInitialSetupController.js +++ b/src/controllers/profileInitialSetupController.js @@ -1,9 +1,9 @@ -const mongoose = require("mongoose"); -const { v4: uuidv4 } = require("uuid"); -const moment = require("moment-timezone"); -const jwt = require("jsonwebtoken"); -const emailSender = require("../utilities/emailSender"); -const config = require("../config"); +const mongoose = require('mongoose'); +const { v4: uuidv4 } = require('uuid'); +const moment = require('moment-timezone'); +const jwt = require('jsonwebtoken'); +const emailSender = require('../utilities/emailSender'); +const config = require('../config'); const cache = require('../utilities/nodeCache')(); // returns the email body that includes the setup link for the recipient. @@ -79,7 +79,7 @@ function informManagerMessage(user) { const profileInitialSetupController = function ( ProfileInitialSetupToken, userProfile, - Project + Project, ) { const { JWT_SECRET } = config; @@ -91,16 +91,16 @@ const profileInitialSetupController = function ( - Generates a link using the token and emails it to the recipient. */ const getSetupToken = async (req, res) => { - let { email, baseUrl,weeklyCommittedHours } = req.body; + let { email, baseUrl, weeklyCommittedHours } = req.body; email = email.toLowerCase(); const token = uuidv4(); - const expiration = moment().tz("America/Los_Angeles").add(1, "week"); + const expiration = moment().tz('America/Los_Angeles').add(1, 'week'); try { const existingEmail = await userProfile.findOne({ - email: email, + email, }); if (existingEmail) { - res.status(400).send("email already in use"); + res.status(400).send('email already in use'); } else { await ProfileInitialSetupToken.findOneAndDelete({ email }); @@ -116,10 +116,10 @@ const profileInitialSetupController = function ( emailSender( email, - "NEEDED: Complete your One Community profile setup", + 'NEEDED: Complete your One Community profile setup', sendLinkMessage(link), null, - null + null, ); res.status(200).send(link); @@ -136,7 +136,7 @@ const profileInitialSetupController = function ( */ const validateSetupToken = async (req, res) => { const { token } = req.body; - const currentMoment = moment.tz("America/Los_Angeles"); + const currentMoment = moment.tz('America/Los_Angeles'); try { const foundToken = await ProfileInitialSetupToken.findOne({ token }); @@ -146,10 +146,10 @@ const profileInitialSetupController = function ( if (expirationMoment.isAfter(currentMoment)) { res.status(200).send(foundToken); } else { - res.status(400).send("Invalid token"); + res.status(400).send('Invalid token'); } } else { - res.status(404).send("Token not found"); + res.status(404).send('Token not found'); } } catch (error) { res.status(500).send(`Error finding token: ${error}`); @@ -167,31 +167,30 @@ const profileInitialSetupController = function ( */ const setUpNewUser = async (req, res) => { const { token } = req.body; - const currentMoment = moment.tz("America/Los_Angeles"); + const currentMoment = moment.tz('America/Los_Angeles'); try { const foundToken = await ProfileInitialSetupToken.findOne({ token }); const existingEmail = await userProfile.findOne({ email: foundToken.email, }); if (existingEmail) { - res.status(400).send("email already in use"); - } else { - if (foundToken) { + res.status(400).send('email already in use'); + } else if (foundToken) { const expirationMoment = moment(foundToken.expiration); if (expirationMoment.isAfter(currentMoment)) { const defaultProject = await Project.findOne({ - projectName: "Orientation and Initial Setup", + projectName: 'Orientation and Initial Setup', }); const newUser = new userProfile(); newUser.password = req.body.password; - newUser.role = "Volunteer"; + newUser.role = 'Volunteer'; newUser.firstName = req.body.firstName; newUser.lastName = req.body.lastName; newUser.jobTitle = req.body.jobTitle; newUser.phoneNumber = req.body.phoneNumber; - newUser.bio = ""; + newUser.bio = ''; newUser.weeklycommittedHours = foundToken.weeklyCommittedHours; newUser.weeklycommittedHoursHistory = [ { @@ -205,32 +204,31 @@ const profileInitialSetupController = function ( newUser.projects = Array.from(new Set([defaultProject])); newUser.createdDate = Date.now(); newUser.email = req.body.email; - newUser.weeklySummaries = [{ summary: "" }]; + newUser.weeklySummaries = [{ summary: '' }]; newUser.weeklySummariesCount = 0; - newUser.weeklySummaryOption = "Required"; - newUser.mediaUrl = ""; + newUser.weeklySummaryOption = 'Required'; + newUser.mediaUrl = ''; newUser.collaborationPreference = req.body.collaborationPreference; - newUser.timeZone = req.body.timeZone || "America/Los_Angeles"; + newUser.timeZone = req.body.timeZone || 'America/Los_Angeles'; newUser.location = req.body.location; newUser.permissions = { frontPermissions: [], - backPermissions: [] - } - newUser.bioPosted = "default"; + backPermissions: [], + }; + newUser.bioPosted = 'default'; newUser.privacySettings.email = req.body.privacySettings.email; - newUser.privacySettings.phoneNumber = - req.body.privacySettings.phoneNumber; - newUser.teamCode = ""; + newUser.privacySettings.phoneNumber = req.body.privacySettings.phoneNumber; + newUser.teamCode = ''; newUser.isFirstTimelog = true; const savedUser = await newUser.save(); emailSender( - process.env.MANAGER_EMAIL || "jae@onecommunityglobal.org", // "jae@onecommunityglobal.org" + process.env.MANAGER_EMAIL || 'jae@onecommunityglobal.org', // "jae@onecommunityglobal.org" `NEW USER REGISTERED: ${savedUser.firstName} ${savedUser.lastName}`, informManagerMessage(savedUser), null, - null + null, ); await ProfileInitialSetupToken.findByIdAndDelete(foundToken._id); @@ -240,14 +238,14 @@ const profileInitialSetupController = function ( permissions: savedUser.permissions, expiryTimestamp: moment().add( config.TOKEN.Lifetime, - config.TOKEN.Units + config.TOKEN.Units, ), }; const token = jwt.sign(jwtPayload, JWT_SECRET); res.send({ token }).status(200); - + const NewUserCache = { permissions: savedUser.permissions, isActive: true, @@ -260,18 +258,15 @@ const profileInitialSetupController = function ( email: savedUser.email, }; - const allUserCache = JSON.parse(cache.getCache("allusers")); + const allUserCache = JSON.parse(cache.getCache('allusers')); allUserCache.push(NewUserCache); - cache.setCache("allusers", JSON.stringify(allUserCache)); - - + cache.setCache('allusers', JSON.stringify(allUserCache)); } else { - res.status(400).send("Token is expired"); + res.status(400).send('Token is expired'); } } else { - res.status(400).send("Invalid token"); + res.status(400).send('Invalid token'); } - } } catch (error) { res.status(500).send(`Error: ${error}`); } @@ -283,17 +278,15 @@ const profileInitialSetupController = function ( - sends the API Key as response */ const getTimeZoneAPIKeyByToken = async (req, res) => { - const token = req.body.token; + const { token } = req.body; const premiumKey = process.env.TIMEZONE_PREMIUM_KEY; const foundToken = await ProfileInitialSetupToken.findOne({ token }); if (foundToken) { res.status(200).send({ userAPIKey: premiumKey }); - return; } else { - res.status(403).send("Unauthorized Request"); - return; + res.status(403).send('Unauthorized Request'); } }; diff --git a/src/controllers/projectController.js b/src/controllers/projectController.js index a88378985..73d7a07e9 100644 --- a/src/controllers/projectController.js +++ b/src/controllers/projectController.js @@ -4,7 +4,7 @@ const userProfile = require('../models/userProfile'); const userProject = require('../helpers/helperModels/userProjects'); const { hasPermission } = require('../utilities/permissions'); const escapeRegex = require('../utilities/escapeRegex'); - +const cache = require('../utilities/nodeCache')(); const projectController = function (Project) { const getAllProjects = function (req, res) { @@ -15,70 +15,93 @@ const projectController = function (Project) { }; const deleteProject = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'deleteProject')) { - res.status(403).send({ error: 'You are not authorized to delete projects.' }); + if (!(await hasPermission(req.body.requestor, 'deleteProject'))) { + res + .status(403) + .send({ error: 'You are not authorized to delete projects.' }); return; } const { projectId } = req.params; Project.findById(projectId, (error, record) => { - if (error || !record || (record === null) || (record.length === 0)) { + if (error || !record || record === null || record.length === 0) { res.status(400).send({ error: 'No valid records found' }); return; } // find if project has any time entries associated with it - timeentry.find({ projectId: record._id }, '_id') - .then((timeentries) => { - if (timeentries.length > 0) { - res.status(400).send({ error: 'This project has associated time entries and cannot be deleted. Consider inactivaing it instead.' }); - } else { - const removeprojectfromprofile = userProfile.updateMany({}, { $pull: { projects: record._id } }).exec(); - const removeproject = record.remove(); - - Promise.all([removeprojectfromprofile, removeproject]) - .then(res.status(200).send({ message: 'Project successfully deleted and user profiles updated.' })) - .catch((errors) => { res.status(400).send(errors); }); - } - }); - }) - .catch((errors) => { res.status(400).send(errors); }); + timeentry.find({ projectId: record._id }, '_id').then((timeentries) => { + if (timeentries.length > 0) { + res.status(400).send({ + error: + 'This project has associated time entries and cannot be deleted. Consider inactivaing it instead.', + }); + } else { + const removeprojectfromprofile = userProfile + .updateMany({}, { $pull: { projects: record._id } }) + .exec(); + const removeproject = record.remove(); + + Promise.all([removeprojectfromprofile, removeproject]) + .then( + res.status(200).send({ + message: + 'Project successfully deleted and user profiles updated.', + }), + ) + .catch((errors) => { + res.status(400).send(errors); + }); + } + }); + }).catch((errors) => { + res.status(400).send(errors); + }); }; const postProject = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'postProject')) { - res.status(403).send({ error: 'You are not authorized to create new projects.' }); + if (!(await hasPermission(req.body.requestor, 'postProject'))) { + res + .status(403) + .send({ error: 'You are not authorized to create new projects.' }); return; } if (!req.body.projectName || !req.body.isActive) { - res.status(400).send({ error: 'Project Name and active status are mandatory fields.' }); + res.status(400).send({ + error: 'Project Name and active status are mandatory fields.', + }); return; } - Project.find({ projectName: { $regex: escapeRegex(req.body.projectName), $options: 'i' } }) - .then((result) => { - if (result.length > 0) { - res.status(400).send({ error: `Project Name must be unique. Another project with name ${result.projectName} already exists. Please note that project names are case insensitive.` }); - return; - } - const _project = new Project(); - _project.projectName = req.body.projectName; - _project.category = req.body.projectCategory || 'Unspecified'; - _project.isActive = req.body.isActive; - _project.createdDatetime = Date.now(); - _project.modifiedDatetime = Date.now(); - - _project.save() - .then(results => res.status(201).send(results)) - .catch(error => res.status(500).send({ error })); - }); + Project.find({ + projectName: { $regex: escapeRegex(req.body.projectName), $options: 'i' }, + }).then((result) => { + if (result.length > 0) { + res.status(400).send({ + error: `Project Name must be unique. Another project with name ${result.projectName} already exists. Please note that project names are case insensitive.`, + }); + return; + } + const _project = new Project(); + _project.projectName = req.body.projectName; + _project.category = req.body.projectCategory || 'Unspecified'; + _project.isActive = req.body.isActive; + _project.createdDatetime = Date.now(); + _project.modifiedDatetime = Date.now(); + + _project + .save() + .then(results => res.status(201).send(results)) + .catch(error => res.status(500).send({ error })); + }); }; - const putProject = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'putProject')) { - res.status(403).send('You are not authorized to make changes in the projects.'); + if (!(await hasPermission(req.body.requestor, 'putProject'))) { + res + .status(403) + .send('You are not authorized to make changes in the projects.'); return; } @@ -94,13 +117,13 @@ const projectController = function (Project) { record.isActive = req.body.isActive; record.modifiedDatetime = Date.now(); - record.save() + record + .save() .then(results => res.status(201).send(results._id)) .catch(errors => res.status(400).send(errors)); }); }; - const getProjectById = function (req, res) { const { projectId } = req.params; @@ -112,7 +135,14 @@ const projectController = function (Project) { const getUserProjects = function (req, res) { const { userId } = req.params; - userProject.findById(userId) + // console.log("this is a test inside get user profiles"); + + // if (cache.hasCache(`user-${userId}`)) { + // cache.removeCache(`user-${userId}`); + // } + + userProject + .findById(userId) .then((results) => { res.status(200).send(results.projects); }) @@ -124,12 +154,19 @@ const projectController = function (Project) { const assignProjectToUsers = async function (req, res) { // verify requestor is administrator, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users - if (!await hasPermission(req.body.requestor, 'assignProjectToUsers')) { - res.status(403).send({ error: 'You are not authorized to perform this operation' }); + if (!(await hasPermission(req.body.requestor, 'assignProjectToUsers'))) { + res + .status(403) + .send({ error: 'You are not authorized to perform this operation' }); return; } - if (!req.params.projectId || !mongoose.Types.ObjectId.isValid(req.params.projectId) || !req.body.users || (req.body.users.length === 0)) { + if ( + !req.params.projectId + || !mongoose.Types.ObjectId.isValid(req.params.projectId) + || !req.body.users + || req.body.users.length === 0 + ) { res.status(400).send({ error: 'Invalid request' }); return; } @@ -138,7 +175,7 @@ const projectController = function (Project) { Project.findById(req.params.projectId) .then((project) => { - if (!project || (project.length === 0)) { + if (!project || project.length === 0) { res.status(400).send({ error: 'Invalid project' }); return; } @@ -148,11 +185,32 @@ const projectController = function (Project) { users.forEach((element) => { const { userId, operation } = element; - if (operation === 'Assign') { assignlist.push(userId); } else { unassignlist.push(userId); } + if (operation === 'Assign') { + assignlist.push(userId); + } else { + unassignlist.push(userId); + } }); - const assignPromise = userProfile.updateMany({ _id: { $in: assignlist } }, { $addToSet: { projects: project._id } }).exec(); - const unassignPromise = userProfile.updateMany({ _id: { $in: unassignlist } }, { $pull: { projects: project._id } }).exec(); + const userToBeAssigned = mongoose.Types.ObjectId(req.params.userId); + + console.log('user to be asigned', userToBeAssigned); + if (cache.hasCache(`user-${userToBeAssigned}`)) { + cache.removeCache(`user-${userToBeAssigned}`); + } + + const assignPromise = userProfile + .updateMany( + { _id: { $in: assignlist } }, + { $addToSet: { projects: project._id } }, + ) + .exec(); + const unassignPromise = userProfile + .updateMany( + { _id: { $in: unassignlist } }, + { $pull: { projects: project._id } }, + ) + .exec(); Promise.all([assignPromise, unassignPromise]) .then(() => { @@ -173,10 +231,18 @@ const projectController = function (Project) { res.status(400).send({ error: 'Invalid request' }); return; } - userProfile.find({ projects: projectId }, '_id firstName lastName isActive profilePic') + userProfile + .find( + { projects: projectId }, + '_id firstName lastName isActive profilePic', + ) .sort({ firstName: 1, lastName: 1 }) - .then((results) => { res.status(200).send(results); }) - .catch((error) => { res.status(500).send(error); }); + .then((results) => { + res.status(200).send(results); + }) + .catch((error) => { + res.status(500).send(error); + }); }; return { @@ -191,5 +257,4 @@ const projectController = function (Project) { }; }; - module.exports = projectController; diff --git a/src/controllers/teamController.js b/src/controllers/teamController.js index c82b9e5ce..756f386d5 100644 --- a/src/controllers/teamController.js +++ b/src/controllers/teamController.js @@ -115,7 +115,7 @@ const teamcontroller = function (Team) { users.forEach((element) => { const { userId, operation } = element; // if user's profile is stored in cache, clear it so when you visit their profile page it will be up to date - if(cache.hasCache(`user-${userId}`)) cache.removeCache(`user-${userId}`); + if (cache.hasCache(`user-${userId}`)) cache.removeCache(`user-${userId}`); if (operation === 'Assign') { assignlist.push(userId); diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index 6dc571b39..aed8f1788 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -59,27 +59,25 @@ const userProfileController = function (UserProfile) { UserProfile.find( {}, - "_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate" + '_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate', ) .sort({ lastName: 1, }) .then((results) => { if (!results) { - if (cache.getCache("allusers")) { - const getData = JSON.parse(cache.getCache("allusers")); + if (cache.getCache('allusers')) { + const getData = JSON.parse(cache.getCache('allusers')); res.status(200).send(getData); return; - }else{ - res.status(500).send({ error: "User result was invalid" }); - return; } + res.status(500).send({ error: 'User result was invalid' }); + return; } - cache.setCache("allusers", JSON.stringify(results)); + 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) { @@ -93,14 +91,14 @@ const userProfileController = function (UserProfile) { $in: [req.params.projectId], }, }, - "_id firstName email", + '_id firstName email', (err, profiles) => { if (err) { - res.status(404).send("Error finding user profiles"); + res.status(404).send('Error finding user profiles'); return; } res.json(profiles); - } + }, ); }; @@ -118,15 +116,15 @@ const userProfileController = function (UserProfile) { const userByEmail = await UserProfile.findOne({ email: { $regex: escapeRegex(req.body.email), - $options: "i", + $options: 'i', }, }); if (userByEmail) { res.status(400).send({ error: - "That email address is already in use. Please choose another email address.", - type: "email", + 'That email address is already in use. Please choose another email address.', + type: 'email', }); return; } @@ -145,8 +143,8 @@ const userProfileController = function (UserProfile) { if (userByPhoneNumber) { res.status(400).send({ error: - "That phone number is already in use. Please choose another number.", - type: "phoneNumber", + 'That phone number is already in use. Please choose another number.', + type: 'phoneNumber', }); return; } @@ -160,8 +158,8 @@ const userProfileController = function (UserProfile) { if (userDuplicateName && !req.body.allowsDuplicateName) { res.status(400).send({ error: - "That name is already in use. Please confirm if you want to use this name.", - type: "name", + 'That name is already in use. Please confirm if you want to use this name.', + type: 'name', }); return; } @@ -188,15 +186,15 @@ const userProfileController = function (UserProfile) { up.projects = Array.from(new Set(req.body.projects)); up.createdDate = req.body.createdDate; up.email = req.body.email; - up.weeklySummaries = req.body.weeklySummaries || [{ summary: "" }]; + up.weeklySummaries = req.body.weeklySummaries || [{ summary: '' }]; up.weeklySummariesCount = req.body.weeklySummariesCount || 0; up.weeklySummaryOption = req.body.weeklySummaryOption; - up.mediaUrl = req.body.mediaUrl || ""; - up.collaborationPreference = req.body.collaborationPreference || ""; - up.timeZone = req.body.timeZone || "America/Los_Angeles"; + up.mediaUrl = req.body.mediaUrl || ''; + up.collaborationPreference = req.body.collaborationPreference || ''; + up.timeZone = req.body.timeZone || 'America/Los_Angeles'; up.location = req.body.location; up.permissions = req.body.permissions; - up.bioPosted = req.body.bioPosted || "default"; + up.bioPosted = req.body.bioPosted || 'default'; up.isFirstTimelog = true; up.save() @@ -218,11 +216,11 @@ const userProfileController = function (UserProfile) { lastName: up.lastName, email: up.email, }; - const allUserCache = JSON.parse(cache.getCache("allusers")); + const allUserCache = JSON.parse(cache.getCache('allusers')); allUserCache.push(userCache); - cache.setCache("allusers", JSON.stringify(allUserCache)); + cache.setCache('allusers', JSON.stringify(allUserCache)); }) - .catch((error) => res.status(501).send(error)); + .catch(error => res.status(501).send(error)); }; const putUserProfile = async function (req, res) { @@ -233,12 +231,12 @@ const userProfileController = function (UserProfile) { || req.body.requestor.requestorId === userid ) ); - - const canEditTeamCode = req.body.requestor.role === "Owner" || - req.body.requestor.permissions?.frontPermissions.includes("editTeamCode"); + + const canEditTeamCode = req.body.requestor.role === 'Owner' + || req.body.requestor.permissions?.frontPermissions.includes('editTeamCode'); if (!isRequestorAuthorized) { - res.status(403).send("You are not authorized to update this user"); + res.status(403).send('You are not authorized to update this user'); return; } @@ -250,7 +248,7 @@ const userProfileController = function (UserProfile) { cache.removeCache(`user-${userid}`); UserProfile.findById(userid, async (err, record) => { if (err || !record) { - res.status(404).send("No valid records found"); + res.status(404).send('No valid records found'); return; } // validate userprofile pic @@ -269,8 +267,7 @@ const userProfileController = function (UserProfile) { : []; record.jobTitle = req.body.jobTitle; record.emailPubliclyAccessible = req.body.emailPubliclyAccessible; - record.phoneNumberPubliclyAccessible = - req.body.phoneNumberPubliclyAccessible; + record.phoneNumberPubliclyAccessible = req.body.phoneNumberPubliclyAccessible; record.profilePic = req.body.profilePic; record.firstName = req.body.firstName; @@ -292,24 +289,24 @@ const userProfileController = function (UserProfile) { record.isVisible = req.body.isVisible || false; record.isRehireable = req.body.isRehireable || false; record.totalIntangibleHrs = req.body.totalIntangibleHrs; - record.bioPosted = req.body.bioPosted || "default"; + record.bioPosted = req.body.bioPosted || 'default'; record.isFirstTimelog = req.body.isFirstTimelog; - if(!canEditTeamCode && record.teamCode !== req.body.teamCode){ - res.status(403).send("You are not authorized to edit team code."); + if (!canEditTeamCode && record.teamCode !== req.body.teamCode) { + res.status(403).send('You are not authorized to edit team code.'); return; } record.teamCode = req.body.teamCode; // find userData in cache - const isUserInCache = cache.hasCache("allusers"); + const isUserInCache = cache.hasCache('allusers'); let allUserData; let userData; let userIdx; if (isUserInCache) { - allUserData = JSON.parse(cache.getCache("allusers")); - userIdx = allUserData.findIndex((users) => users._id === userid); + allUserData = JSON.parse(cache.getCache('allusers')); + userIdx = allUserData.findIndex(users => users._id === userid); userData = allUserData[userIdx]; } if (await hasPermission(req.body.requestor, 'putUserProfileImportantInfo')) { @@ -324,11 +321,11 @@ const userProfileController = function (UserProfile) { // If their last update was made today, remove that const lasti = record.weeklycommittedHoursHistory.length - 1; const lastChangeDate = moment( - record.weeklycommittedHoursHistory[lasti].dateChanged + record.weeklycommittedHoursHistory[lasti].dateChanged, ); const now = moment(); - if (lastChangeDate.isSame(now, "day")) { + if (lastChangeDate.isSame(now, 'day')) { record.weeklycommittedHoursHistory.pop(); } @@ -341,8 +338,7 @@ const userProfileController = function (UserProfile) { record.weeklycommittedHoursHistory.push(newEntry); } - record.missedHours = - req.body.role === "Core Team" ? req.body?.missedHours ?? 0 : 0; + record.missedHours = req.body.role === 'Core Team' ? req.body?.missedHours ?? 0 : 0; record.adminLinks = req.body.adminLinks; record.teams = Array.from(new Set(req.body.teams)); record.projects = Array.from(new Set(req.body.projects)); @@ -374,8 +370,7 @@ const userProfileController = function (UserProfile) { record.weeklycommittedHoursHistory.push(newEntry); } // then also change the first committed history (index 0) - record.weeklycommittedHoursHistory[0].dateChanged = - record.createdDate; + record.weeklycommittedHoursHistory[0].dateChanged = record.createdDate; } record.bioPosted = req.body.bioPosted || 'default'; @@ -390,7 +385,7 @@ const userProfileController = function (UserProfile) { userData.endDate = record.endDate.toISOString(); } } else { - record.set("endDate", undefined, { strict: false }); + record.set('endDate', undefined, { strict: false }); } if (isUserInCache) { userData.role = record.role; @@ -412,7 +407,7 @@ const userProfileController = function (UserProfile) { results.infringements, results.firstName, results.lastName, - results.email + results.email, ); res.status(200).json({ _id: record._id, @@ -421,10 +416,10 @@ const userProfileController = function (UserProfile) { // update alluser cache if we have cache if (isUserInCache) { allUserData.splice(userIdx, 1, userData); - cache.setCache("allusers", JSON.stringify(allUserData)); + cache.setCache('allusers', JSON.stringify(allUserData)); } }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }); }; @@ -569,15 +564,14 @@ const userProfileController = function (UserProfile) { const { userId } = req.params; const { key, value } = req.body; - if (key === "teamCode") { - const canEditTeamCode = req.body.requestor.role === "Owner" || - req.body.requestor.permissions?.frontPermissions.includes("editTeamCode"); + if (key === 'teamCode') { + const canEditTeamCode = req.body.requestor.role === 'Owner' + || req.body.requestor.permissions?.frontPermissions.includes('editTeamCode'); - if(!canEditTeamCode){ - res.status(403).send("You are not authorized to edit team code."); + if (!canEditTeamCode) { + res.status(403).send('You are not authorized to edit team code.'); return; } - } // remove user from cache, it should be loaded next time diff --git a/src/helpers/dashboardhelper.js b/src/helpers/dashboardhelper.js index 34d464583..fe2007281 100644 --- a/src/helpers/dashboardhelper.js +++ b/src/helpers/dashboardhelper.js @@ -192,7 +192,7 @@ const dashboardhelper = function () { // leaderboard user roles hierarchy $or: [ { - role: { $in: ['Owner', 'Core Team'] }, + role: { $in: ['Owner', 'Core Team'] }, }, { $and: [ @@ -200,7 +200,7 @@ const dashboardhelper = function () { role: 'Administrator', }, { 'persondata.0.role': { $nin: ['Owner', 'Administrator'] } }, - ] + ], }, { $and: [ diff --git a/src/helpers/reporthelper.js b/src/helpers/reporthelper.js index 0c2a8104d..3826aa8ed 100644 --- a/src/helpers/reporthelper.js +++ b/src/helpers/reporthelper.js @@ -1,5 +1,5 @@ -const moment = require("moment-timezone"); -const userProfile = require("../models/userProfile"); +const moment = require('moment-timezone'); +const userProfile = require('../models/userProfile'); /** * @@ -8,9 +8,9 @@ const userProfile = require("../models/userProfile"); * @returns The absolute value of the difference in weeks between the two input dates. */ const absoluteDifferenceInWeeks = (dateOfWork, pstEnd) => { - dateOfWork = moment(dateOfWork).endOf("week"); - pstEnd = moment(pstEnd).tz("America/Los_Angeles").endOf("week"); - return Math.abs(dateOfWork.diff(pstEnd, "weeks")); + dateOfWork = moment(dateOfWork).endOf('week'); + pstEnd = moment(pstEnd).tz('America/Los_Angeles').endOf('week'); + return Math.abs(dateOfWork.diff(pstEnd, 'weeks')); }; const reporthelper = function () { @@ -23,14 +23,14 @@ const reporthelper = function () { */ const weeklySummaries = async (startWeekIndex, endWeekIndex) => { const pstStart = moment() - .tz("America/Los_Angeles") - .startOf("week") - .subtract(startWeekIndex, "week") + .tz('America/Los_Angeles') + .startOf('week') + .subtract(startWeekIndex, 'week') .toDate(); const pstEnd = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(endWeekIndex, "week") + .tz('America/Los_Angeles') + .endOf('week') + .subtract(endWeekIndex, 'week') .toDate(); const results = await userProfile.aggregate([ @@ -39,33 +39,33 @@ const reporthelper = function () { }, { $lookup: { - from: "timeEntries", - localField: "_id", - foreignField: "personId", - as: "timeEntries", + from: 'timeEntries', + localField: '_id', + foreignField: 'personId', + as: 'timeEntries', }, }, { - $set: { totalTangibleHrs: { $objectToArray: "$hoursByCategory" } }, + $set: { totalTangibleHrs: { $objectToArray: '$hoursByCategory' } }, }, { $project: { timeEntries: { $filter: { - input: "$timeEntries", - as: "timeEntry", + input: '$timeEntries', + as: 'timeEntry', cond: { $and: [ { $gte: [ - "$$timeEntry.dateOfWork", - moment(pstStart).format("YYYY-MM-DD"), + '$$timeEntry.dateOfWork', + moment(pstStart).format('YYYY-MM-DD'), ], }, { $lte: [ - "$$timeEntry.dateOfWork", - moment(pstEnd).format("YYYY-MM-DD"), + '$$timeEntry.dateOfWork', + moment(pstEnd).format('YYYY-MM-DD'), ], }, ], @@ -86,22 +86,22 @@ const reporthelper = function () { bioPosted: 1, badgeCollection: { $filter: { - input: "$badgeCollection", - as: "badge", + input: '$badgeCollection', + as: 'badge', cond: { $or: [ { $and: [ { $gte: [ - "$$badge.earnedDate", - moment(pstStart).format("YYYY-MM-DD"), + '$$badge.earnedDate', + moment(pstStart).format('YYYY-MM-DD'), ], }, { $lte: [ - "$$badge.earnedDate", - moment(pstEnd).format("YYYY-MM-DD"), + '$$badge.earnedDate', + moment(pstEnd).format('YYYY-MM-DD'), ], }, ], @@ -109,10 +109,10 @@ const reporthelper = function () { { $and: [ { - $gte: ["$$badge.lastModified", pstStart], + $gte: ['$$badge.lastModified', pstStart], }, { - $lte: ["$$badge.lastModified", pstEnd], + $lte: ['$$badge.lastModified', pstEnd], }, ], }, @@ -126,15 +126,15 @@ const reporthelper = function () { role: 1, weeklySummaries: { $filter: { - input: "$weeklySummaries", - as: "ws", + input: '$weeklySummaries', + as: 'ws', cond: { $and: [ { - $gte: ["$$ws.dueDate", pstStart], + $gte: ['$$ws.dueDate', pstStart], }, { - $lte: ["$$ws.dueDate", pstEnd], + $lte: ['$$ws.dueDate', pstEnd], }, ], }, @@ -142,13 +142,13 @@ const reporthelper = function () { }, weeklySummariesCount: 1, isTangible: 1, - totalTangibleHrs: { $sum: "$totalTangibleHrs.v" }, + totalTangibleHrs: { $sum: '$totalTangibleHrs.v' }, daysInTeam: { $dateDiff: { - startDate: "$createdDate", + startDate: '$createdDate', endDate: new Date(), - unit: "day", - timezone: "America/Los_Angeles", + unit: 'day', + timezone: 'America/Los_Angeles', }, }, }, @@ -162,8 +162,8 @@ const reporthelper = function () { result.timeEntries.forEach((entry) => { const index = absoluteDifferenceInWeeks(entry.dateOfWork, pstEnd); if ( - result.totalSeconds[index] === undefined || - result.totalSeconds[index] === null + result.totalSeconds[index] === undefined + || result.totalSeconds[index] === null ) { result.totalSeconds[index] = 0; } @@ -189,16 +189,16 @@ const reporthelper = function () { */ const doesDateBelongToWeek = function (dueDate, weekIndex) { const pstStartOfWeek = moment() - .tz("America/Los_Angeles") - .startOf("week") - .subtract(weekIndex, "week"); + .tz('America/Los_Angeles') + .startOf('week') + .subtract(weekIndex, 'week'); const pstEndOfWeek = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(weekIndex, "week"); + .tz('America/Los_Angeles') + .endOf('week') + .subtract(weekIndex, 'week'); const fromDate = moment(pstStartOfWeek).toDate(); const toDate = moment(pstEndOfWeek).toDate(); - return moment(dueDate).isBetween(fromDate, toDate, undefined, "[]"); + return moment(dueDate).isBetween(fromDate, toDate, undefined, '[]'); }; /** diff --git a/src/helpers/taskHelper.js b/src/helpers/taskHelper.js index a94aaee94..f59dedcbc 100644 --- a/src/helpers/taskHelper.js +++ b/src/helpers/taskHelper.js @@ -43,7 +43,7 @@ const taskHelper = function () { // dashboard tasks user roles hierarchy $or: [ { - role: { $in: ['Owner', 'Core Team'] }, + role: { $in: ['Owner', 'Core Team'] }, }, { $and: [ @@ -51,7 +51,7 @@ const taskHelper = function () { role: 'Administrator', }, { 'persondata.0.role': { $nin: ['Owner', 'Administrator'] } }, - ] + ], }, { $and: [ diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index af416f1a7..a1fd6265a 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -1,28 +1,28 @@ /* 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 hasPermission = require("../utilities/permissions"); -const Reason = require("../models/reason"); -const token = require("../models/profileInitialSetupToken") +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 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, }); }; @@ -46,40 +46,39 @@ 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 = []; if (picParts.length < 2) { return { result: false, - errors: "Invalid image" + errors: 'Invalid image', }; } // 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; } return { result, - errors + errors, }; }; @@ -87,7 +86,7 @@ const userHelper = function () { firstName, lastName, infringement, - totalInfringements + totalInfringements, ) { const text = `Dear ${firstName} ${lastName},

Oops, it looks like something happened and you’ve managed to get a blue square.

@@ -114,11 +113,11 @@ const userHelper = function () { */ const emailWeeklySummariesForAllUsers = async (weekIndex = 1) => { const currentFormattedDate = moment() - .tz("America/Los_Angeles") + .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 = []; @@ -126,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(`${b.firstName} ${b.lastname}`)); @@ -146,7 +143,7 @@ const userHelper = function () { mediaUrl, weeklySummariesCount, weeklycommittedHours, - weeklySummaryOption + weeklySummaryOption, } = result; if (email !== undefined && email !== null) { @@ -163,14 +160,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. @@ -181,8 +178,8 @@ 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} @@ -207,15 +204,15 @@ const userHelper = function () {

${weeklySummariesCount === 8 ? `

Total Valid Weekly Summaries: ${weeklySummariesCount}

` - : `

Total Valid Weekly Summaries: ${weeklySummariesCount || - "No valid submissions yet!"}

` + : `

Total Valid Weekly Summaries: ${weeklySummariesCount + || 'No valid submissions yet!'}

` } ${hoursLogged >= weeklycommittedHours ? `

Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}

` : `

Hours logged: ${hoursLogged.toFixed( - 2 + 2, )} / ${weeklycommittedHours}

` } ${weeklySummaryMessage} @@ -225,10 +222,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
@@ -240,10 +235,10 @@ 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, ); } catch (err) { logger.logException(err); @@ -265,15 +260,15 @@ const userHelper = function () { $each: [ { dueDate: moment() - .tz("America/Los_Angeles") - .endOf("week"), - summary: "" - } + .tz('America/Los_Angeles') + .endOf('week'), + summary: '', + }, ], $position: 0, - $slice: 4 - } - } + $slice: 4, + }, + }, }) .catch(error => logger.logException(error)); }; @@ -287,11 +282,11 @@ const userHelper = function () { const assignBlueSquareForTimeNotMet = async () => { try { const currentFormattedDate = moment() - .tz("America/Los_Angeles") + .tz('America/Los_Angeles') .format(); const currentUTCDate = moment - .tz("America/Los_Angeles") - .startOf("day") + .tz('America/Los_Angeles') + .startOf('day') .toISOString(); logger.logInfo( @@ -301,24 +296,24 @@ 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]; @@ -345,13 +340,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; @@ -360,19 +354,19 @@ const userHelper = function () { 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 } + { new: true }, ); if ( @@ -384,13 +378,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 { @@ -403,72 +397,70 @@ const userHelper = function () { personId, { $push: { - oldInfringements: { $each: oldInfringements, $slice: -10 } - } + oldInfringements: { $each: oldInfringements, $slice: -10 }, + }, }, - { new: true } + { new: true }, ); } if (timeNotMet || !hasWeeklySummary) { if (foundReason) { description = foundReason.reason; - } else { - if (timeNotMet && !hasWeeklySummary) { + } 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( - "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) { 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")}.`; + '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"), - description + .format('YYYY-MM-DD'), + description, }; const status = await userProfile.findByIdAndUpdate( personId, { $push: { - infringements: infringement - } + infringements: infringement, + }, }, - { new: true } + { new: true }, ); emailSender( status.email, - "New Infringement Assigned", + 'New Infringement Assigned', getInfringementEmailBody( status.firstName, status.lastName, infringement, - status.infringements.length + status.infringements.length, ), null, - "onecommunityglobal@gmail.com" + 'onecommunityglobal@gmail.com', ); 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; @@ -478,29 +470,29 @@ 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) { 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, + }, + }, + }, ); } } @@ -512,12 +504,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); - } } catch (err) { logger.logException(err); @@ -527,52 +518,52 @@ const userHelper = function () { const applyMissedHourForCoreTeam = async () => { try { const currentDate = moment() - .tz("America/Los_Angeles") + .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([ { $match: { - role: "Core Team", - isActive: true - } + 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', + }, }, { $project: { @@ -591,31 +582,31 @@ const userHelper = function () { { $sum: { $map: { - input: "$timeEntries", - in: "$$this.totalSeconds" - } - } + input: '$timeEntries', + 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 }, + }, }); }); @@ -627,16 +618,16 @@ const userHelper = function () { const deleteBlueSquareAfterYear = async () => { const currentFormattedDate = moment() - .tz("America/Los_Angeles") + .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"); + .subtract(1, 'year') + .format('YYYY-MM-DD'); try { const results = await userProfile.updateMany( @@ -645,11 +636,11 @@ const userHelper = function () { $pull: { infringements: { date: { - $lte: cutOffDate - } - } - } - } + $lte: cutOffDate, + }, + }, + }, + }, ); logger.logInfo(results); @@ -660,17 +651,17 @@ const userHelper = function () { const reActivateUser = async () => { const currentFormattedDate = moment() - .tz("America/Los_Angeles") + .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]; @@ -679,18 +670,18 @@ const userHelper = function () { user._id, { $set: { - isActive: true + isActive: true, }, $unset: { - endDate: user.endDate - } + 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); @@ -712,7 +703,6 @@ const userHelper = function () { emailSender('onecommunityglobal@gmail.com', subject, emailBody, null, null); - } } } catch (err) { @@ -722,7 +712,6 @@ const userHelper = function () { const notifyInfringements = function (original, current, firstName, lastName, emailAddress) { - if (!current) return; const newOriginal = original.toObject(); const newCurrent = current.toObject(); @@ -737,43 +726,43 @@ const userHelper = function () { getInfringementEmailBody(firstName, lastName, element, totalInfringements), null, - "onecommunityglobal@gmail.com" + 'onecommunityglobal@gmail.com', ); }); }; 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.$.badge': newBadgeId, + 'badgeCollection.$.lastModified': Date.now().toString(), + 'badgeCollection.$.count': 1, + }, }, - err => { + (err) => { 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() }, - $push: { "badgeCollection.$.earnedDate": earnedDateBadge() } + $inc: { 'badgeCollection.$.count': 1 }, + $set: { 'badgeCollection.$.lastModified': Date.now().toString() }, + $push: { 'badgeCollection.$.earnedDate': earnedDateBadge() }, }, - err => { + (err) => { if (err) { console.log(err); } - } + }, ); }; @@ -781,7 +770,7 @@ const userHelper = function () { personId, badgeId, count = 1, - featured = false + featured = false, ) { console.log('Adding Badge'); userProfile.findByIdAndUpdate( @@ -793,11 +782,11 @@ const userHelper = function () { }, }, }, - err => { + (err) => { if (err) { throw new Error(err); } - } + }, ); }; @@ -806,14 +795,14 @@ const userHelper = function () { personId, { $pull: { - badgeCollection: { badge: badgeId } - } + badgeCollection: { badge: badgeId }, + }, }, - err => { + (err) => { if (err) { throw new Error(err); } - } + }, ); }; @@ -822,18 +811,18 @@ 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, - "badgeCollection.$.lastModified": Date.now().toString() - } + 'badgeCollection.$.count': count, + 'badgeCollection.$.lastModified': Date.now().toString(), + }, }, - err => { + (err) => { if (err) { throw new Error(err); } - } + }, ); } }; @@ -841,7 +830,6 @@ const userHelper = function () { // remove the last badge you earned on this streak(not including 1) const removePrevHrBadge = async function (personId, user, badgeCollection, hrs, weeks) { - // Check each Streak Greater than One to check if it works if (weeks < 3) { return; @@ -851,24 +839,24 @@ 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 - } + totalHrs: hrs, + }, }, { $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' }, + }, + }, + }, ]) - .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 ( @@ -881,7 +869,7 @@ const userHelper = function () { changeBadgeCount( personId, badgeCollection[i].badge._id, - badgeCollection[i].badge.count - 1 + badgeCollection[i].badge.count - 1, ); removed = true; return false; @@ -903,7 +891,6 @@ const userHelper = function () { removeDupBadge(personId, badgeOfType._id); badgeOfType = badgeCollection[i].badge; } else if (badgeOfType && badgeOfType.months > badgeCollection[i].badge.months) { - removeDupBadge(personId, badgeCollection[i].badge._id); } else if (!badgeOfType) { badgeOfType = badgeCollection[i].badge; @@ -911,23 +898,21 @@ const userHelper = function () { } } await badge - .find({ type: "No Infringement Streak" }) + .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 ( - user.infringements.length === 0 || - Math.abs( + user.infringements.length === 0 + || Math.abs( moment().diff( moment(user.infringements[user.infringements?.length - 1].date), @@ -942,7 +927,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -952,12 +937,10 @@ const userHelper = function () { } } } else if (user?.infringements?.length === 0) { - 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), @@ -973,7 +956,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -992,11 +975,11 @@ const userHelper = function () { const checkMinHoursMultiple = async function ( personId, user, - badgeCollection + badgeCollection, ) { const badgesOfType = badgeCollection .map(obj => obj.badge) - .filter(badge => badge.type === 'Minimum Hours Multiple') + .filter(badge => badge.type === 'Minimum Hours Multiple'); await badge .find({ type: 'Minimum Hours Multiple' }) .sort({ multiple: -1 }) @@ -1009,49 +992,47 @@ 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( personId, - mongoose.Types.ObjectId(theBadge._id) + mongoose.Types.ObjectId(theBadge._id), ) : addBadge(personId, mongoose.Types.ObjectId(elem._id)); } } - }) + }); }; // 'Personal Max', 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 => { + 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(personId, mongoose.Types.ObjectId(results._id), user.personalBestMaxHrs); - } } }); @@ -1071,22 +1052,21 @@ 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) { removeDupBadge(user._id, badgeOfType[0]._id); - } 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)); @@ -1102,15 +1082,15 @@ 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 => { + .then((results) => { + results.every((elem) => { if (elem.totalHrs <= user.lastWeekTangibleHrs) { let theBadge; for (let i = 0; i < badgesOfType.length; i += 1) { @@ -1132,21 +1112,21 @@ 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' }, + }, + }, + }, ]) - .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 ( @@ -1155,12 +1135,11 @@ const userHelper = function () { && badgeCollection[i].badge?.weeks === bdge.weeks ) { 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) { @@ -1185,7 +1164,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(bdge._id) + mongoose.Types.ObjectId(bdge._id), ); removePrevHrBadge(personId, user, badgeCollection, bdge.hrs, bdge.weeks); @@ -1196,12 +1175,11 @@ const userHelper = function () { user, badgeCollection, bdge.hrs, - bdge.weeks + bdge.weeks, ); } else if (badgeOfType && badgeOfType.totalHrs === bdge.hrs) { increaseBadgeCount(personId, mongoose.Types.ObjectId(badgeOfType._id)); removePrevHrBadge(personId, user, badgeCollection, bdge.hrs, bdge.weeks); - } return false; } @@ -1222,8 +1200,8 @@ const userHelper = function () { let teamMembers; await getTeamMembers({ - _id: personId - }).then(results => { + _id: personId, + }).then((results) => { if (results) { teamMembers = results.myteam; } else { @@ -1242,13 +1220,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) { removeDupBadge(personId, badgeOfType._id); badgeOfType = badgeCollection[i].badge; } else if (badgeOfType && badgeOfType.people > badgeCollection[i].badge.people) { - removeDupBadge(personId, badgeCollection[i].badge._id); } else if (!badgeOfType) { badgeOfType = badgeCollection[i].badge; @@ -1256,9 +1232,9 @@ const userHelper = function () { } } await badge - .find({ type: "Lead a team of X+" }) + .find({ type: 'Lead a team of X+' }) .sort({ people: -1 }) - .then(results => { + .then((results) => { if (!Array.isArray(results) || !results.length) { return; } @@ -1292,40 +1268,40 @@ 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 => { + 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 ( - 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) { @@ -1340,15 +1316,15 @@ const userHelper = function () { 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 + hoursByCategory[categoryHrs] >= 100 + && hoursByCategory[categoryHrs] >= elem.totalHrs ) { let theBadge; for (let i = 0; i < badgesOfType.length; i += 1) { @@ -1363,13 +1339,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; @@ -1384,9 +1360,8 @@ const userHelper = function () { }; const awardNewBadges = async () => { - console.log("Awarding"); + console.log('Awarding'); try { - const users = await userProfile.find({ isActive: true }).populate('badgeCollection.badge'); @@ -1419,14 +1394,14 @@ const userHelper = function () { { personId: userId, dateOfWork: { $gte: pdtstart, $lte: pdtend }, - isTangible: true + isTangible: true, }, - "totalSeconds" + 'totalSeconds', ) - .then(results => { + .then((results) => { const totalTangibleWeeklySeconds = results.reduce( (acc, { totalSeconds }) => acc + totalSeconds, - 0 + 0, ); return (totalTangibleWeeklySeconds / 3600).toFixed(2); }); @@ -1436,19 +1411,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 + isActive: false, }), - { new: true } + { new: true }, ); const id = user._id; const person = await userProfile.findById(id); @@ -1485,7 +1460,7 @@ const userHelper = function () { } catch (error) { logger.logException(err); } - } + }; return { @@ -1502,7 +1477,7 @@ const userHelper = function () { emailWeeklySummariesForAllUsers, awardNewBadges, getTangibleHoursReportedThisWeekByUserId, - deleteExpiredTokens + deleteExpiredTokens, }; }; diff --git a/src/models/badge.js b/src/models/badge.js index 8b2c754e7..e3e93eaaf 100644 --- a/src/models/badge.js +++ b/src/models/badge.js @@ -19,7 +19,7 @@ const Badge = new Schema({ imageUrl: { type: String }, ranking: { type: Number }, description: { type: String }, - showReport: {type: Boolean}, + showReport: { type: Boolean }, }); module.exports = mongoose.model('badge', Badge, 'badges'); diff --git a/src/models/inventoryItemMaterial.js b/src/models/inventoryItemMaterial.js index e6153af45..8460ecd6e 100644 --- a/src/models/inventoryItemMaterial.js +++ b/src/models/inventoryItemMaterial.js @@ -29,12 +29,12 @@ const InventoryItemMaterial = new Schema({ poId: { type: String, required: true }, sellerId: { type: String, required: true }, quantity: { type: Number, required: true }, // adds to stockBought - unitPrice: {type: Number, required: true}, + unitPrice: { type: Number, required: true }, currency: { type: String, required: true }, subtotal: { type: Number, required: true }, tax: { type: Number, required: true }, shipping: { type: Number, required: true }, - }] -}) + }], +}); module.exports = mongoose.model('inventoryItemMaterial', InventoryItemMaterial, 'inventoryMaterial'); diff --git a/src/models/inventoryItemType.js b/src/models/inventoryItemType.js index 321038a84..b7b3ec46f 100644 --- a/src/models/inventoryItemType.js +++ b/src/models/inventoryItemType.js @@ -9,11 +9,9 @@ const InventoryItemType = new Schema({ // creates an item, tracks total amount i uom: { type: String, required: true }, // unit of measurement totalStock: { type: Number, required: true }, // total amount of all stock acquired totalAvailable: { type: Number, required: true }, - projectsUsing: [ {type: mongoose.SchemaTypes.ObjectId, ref: 'project'} ], + projectsUsing: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'project' }], imageUrl: { type: String }, - link: { type: String} + link: { type: String }, }); module.exports = mongoose.model('inventoryItemType', InventoryItemType, 'inventoryItemType'); - - diff --git a/src/models/profileInitialSetupToken.js b/src/models/profileInitialSetupToken.js index 48413fb77..77b830229 100644 --- a/src/models/profileInitialSetupToken.js +++ b/src/models/profileInitialSetupToken.js @@ -10,7 +10,7 @@ const profileInitialSetupTokenSchema = new mongoose.Schema({ type: String, required: true, }, - weeklyCommittedHours : { + weeklyCommittedHours: { type: Number, required: true, default: 10, @@ -21,4 +21,4 @@ const profileInitialSetupTokenSchema = new mongoose.Schema({ }, }); -module.exports = mongoose.model('profileInitialSetupToken', profileInitialSetupTokenSchema, 'profileInitialSetupToken'); \ No newline at end of file +module.exports = mongoose.model('profileInitialSetupToken', profileInitialSetupTokenSchema, 'profileInitialSetupToken'); diff --git a/src/models/userProfile.js b/src/models/userProfile.js index a58d1d293..1a29ec3e0 100644 --- a/src/models/userProfile.js +++ b/src/models/userProfile.js @@ -7,7 +7,7 @@ const bcrypt = require('bcryptjs'); const SALT_ROUNDS = 10; const nextDay = new Date(); -nextDay.setDate(nextDay.getDate()+1); +nextDay.setDate(nextDay.getDate() + 1); const userProfileSchema = new Schema({ password: { @@ -153,7 +153,7 @@ const userProfileSchema = new Schema({ isVisible: { type: Boolean, default: false }, weeklySummaryOption: { type: String }, bioPosted: { type: String, default: 'default' }, - isFirstTimelog: { type: Boolean, default: true}, + isFirstTimelog: { type: Boolean, default: true }, teamCode: { type: String, default: '' }, infoCollections: [ { diff --git a/src/routes/bmdashboard/bmMaterialsRouter.js b/src/routes/bmdashboard/bmMaterialsRouter.js index ab8a67388..1188acf9d 100644 --- a/src/routes/bmdashboard/bmMaterialsRouter.js +++ b/src/routes/bmdashboard/bmMaterialsRouter.js @@ -8,6 +8,6 @@ materialsRouter.route('/materials') .get(controller.bmMaterialsList); return materialsRouter; -} +}; -module.exports = routes; \ No newline at end of file +module.exports = routes; diff --git a/src/routes/isEmailExistsRouter.js b/src/routes/isEmailExistsRouter.js index cfb4e6033..d19b14fe2 100644 --- a/src/routes/isEmailExistsRouter.js +++ b/src/routes/isEmailExistsRouter.js @@ -2,14 +2,14 @@ const express = require('express'); const routes = function () { - const controller = require('../controllers/isEmailExistsController')() + const controller = require('../controllers/isEmailExistsController')(); - const isEmailExistsRouter = express.Router() + const isEmailExistsRouter = express.Router(); - isEmailExistsRouter.route("/is-email-exists/:email") - .get(controller.isEmailExists) + isEmailExistsRouter.route('/is-email-exists/:email') + .get(controller.isEmailExists); - return isEmailExistsRouter -} + return isEmailExistsRouter; +}; -module.exports = routes +module.exports = routes; diff --git a/src/routes/profileInitialSetupRouter.js b/src/routes/profileInitialSetupRouter.js index a23c6a868..2091afcad 100644 --- a/src/routes/profileInitialSetupRouter.js +++ b/src/routes/profileInitialSetupRouter.js @@ -5,9 +5,9 @@ const routes = function (ProfileInitialSetupToken, userProfile, Project) { const controller = require('../controllers/profileInitialSetupController')(ProfileInitialSetupToken, userProfile, Project); ProfileInitialSetup.route('/getInitialSetuptoken') .post(controller.getSetupToken); - ProfileInitialSetup.route('/ProfileInitialSetup').post(controller.setUpNewUser) - ProfileInitialSetup.route('/validateToken').post(controller.validateSetupToken) - ProfileInitialSetup.route('/getTimeZoneAPIKeyByToken').post(controller.getTimeZoneAPIKeyByToken) + ProfileInitialSetup.route('/ProfileInitialSetup').post(controller.setUpNewUser); + ProfileInitialSetup.route('/validateToken').post(controller.validateSetupToken); + ProfileInitialSetup.route('/getTimeZoneAPIKeyByToken').post(controller.getTimeZoneAPIKeyByToken); return ProfileInitialSetup; }; From b010a7cfa4004d31906c1f5141d20714d33a13a6 Mon Sep 17 00:00:00 2001 From: luisarevalo21 Date: Wed, 1 Nov 2023 20:53:18 -0700 Subject: [PATCH 2/4] resolved cachcing issue which delayed the projects from being updated --- src/controllers/projectController.js | 108 +++---- src/controllers/userProfileController.js | 383 +++++++++++++---------- 2 files changed, 264 insertions(+), 227 deletions(-) diff --git a/src/controllers/projectController.js b/src/controllers/projectController.js index 73d7a07e9..53cb5c421 100644 --- a/src/controllers/projectController.js +++ b/src/controllers/projectController.js @@ -1,40 +1,40 @@ -const mongoose = require('mongoose'); -const timeentry = require('../models/timeentry'); -const userProfile = require('../models/userProfile'); -const userProject = require('../helpers/helperModels/userProjects'); -const { hasPermission } = require('../utilities/permissions'); -const escapeRegex = require('../utilities/escapeRegex'); -const cache = require('../utilities/nodeCache')(); +const mongoose = require("mongoose"); +const timeentry = require("../models/timeentry"); +const userProfile = require("../models/userProfile"); +const userProject = require("../helpers/helperModels/userProjects"); +const { hasPermission } = require("../utilities/permissions"); +const escapeRegex = require("../utilities/escapeRegex"); +const cache = require("../utilities/nodeCache")(); const projectController = function (Project) { const getAllProjects = function (req, res) { - Project.find({}, 'projectName isActive category') + Project.find({}, "projectName isActive category") .sort({ projectName: 1 }) - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send(error)); + .then((results) => res.status(200).send(results)) + .catch((error) => res.status(404).send(error)); }; const deleteProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, 'deleteProject'))) { + if (!(await hasPermission(req.body.requestor, "deleteProject"))) { res .status(403) - .send({ error: 'You are not authorized to delete projects.' }); + .send({ error: "You are not authorized to delete projects." }); return; } const { projectId } = req.params; Project.findById(projectId, (error, record) => { if (error || !record || record === null || record.length === 0) { - res.status(400).send({ error: 'No valid records found' }); + res.status(400).send({ error: "No valid records found" }); return; } // find if project has any time entries associated with it - timeentry.find({ projectId: record._id }, '_id').then((timeentries) => { + timeentry.find({ projectId: record._id }, "_id").then((timeentries) => { if (timeentries.length > 0) { res.status(400).send({ error: - 'This project has associated time entries and cannot be deleted. Consider inactivaing it instead.', + "This project has associated time entries and cannot be deleted. Consider inactivaing it instead.", }); } else { const removeprojectfromprofile = userProfile @@ -46,8 +46,8 @@ const projectController = function (Project) { .then( res.status(200).send({ message: - 'Project successfully deleted and user profiles updated.', - }), + "Project successfully deleted and user profiles updated.", + }) ) .catch((errors) => { res.status(400).send(errors); @@ -60,22 +60,22 @@ const projectController = function (Project) { }; const postProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, 'postProject'))) { + if (!(await hasPermission(req.body.requestor, "postProject"))) { res .status(403) - .send({ error: 'You are not authorized to create new projects.' }); + .send({ error: "You are not authorized to create new projects." }); return; } if (!req.body.projectName || !req.body.isActive) { res.status(400).send({ - error: 'Project Name and active status are mandatory fields.', + error: "Project Name and active status are mandatory fields.", }); return; } Project.find({ - projectName: { $regex: escapeRegex(req.body.projectName), $options: 'i' }, + projectName: { $regex: escapeRegex(req.body.projectName), $options: "i" }, }).then((result) => { if (result.length > 0) { res.status(400).send({ @@ -85,30 +85,30 @@ const projectController = function (Project) { } const _project = new Project(); _project.projectName = req.body.projectName; - _project.category = req.body.projectCategory || 'Unspecified'; + _project.category = req.body.projectCategory || "Unspecified"; _project.isActive = req.body.isActive; _project.createdDatetime = Date.now(); _project.modifiedDatetime = Date.now(); _project .save() - .then(results => res.status(201).send(results)) - .catch(error => res.status(500).send({ error })); + .then((results) => res.status(201).send(results)) + .catch((error) => res.status(500).send({ error })); }); }; const putProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, 'putProject'))) { + if (!(await hasPermission(req.body.requestor, "putProject"))) { res .status(403) - .send('You are not authorized to make changes in the projects.'); + .send("You are not authorized to make changes in the projects."); return; } const { projectId } = req.params; Project.findById(projectId, (error, record) => { if (error || record === null) { - res.status(400).send('No valid records found'); + res.status(400).send("No valid records found"); return; } @@ -119,28 +119,22 @@ const projectController = function (Project) { record .save() - .then(results => res.status(201).send(results._id)) - .catch(errors => res.status(400).send(errors)); + .then((results) => res.status(201).send(results._id)) + .catch((errors) => res.status(400).send(errors)); }); }; const getProjectById = function (req, res) { const { projectId } = req.params; - Project.findById(projectId, '-__v -createdDatetime -modifiedDatetime') - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send(error)); + Project.findById(projectId, "-__v -createdDatetime -modifiedDatetime") + .then((results) => res.status(200).send(results)) + .catch((error) => res.status(404).send(error)); }; const getUserProjects = function (req, res) { const { userId } = req.params; - // console.log("this is a test inside get user profiles"); - - // if (cache.hasCache(`user-${userId}`)) { - // cache.removeCache(`user-${userId}`); - // } - userProject .findById(userId) .then((results) => { @@ -154,20 +148,20 @@ const projectController = function (Project) { const assignProjectToUsers = async function (req, res) { // verify requestor is administrator, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users - if (!(await hasPermission(req.body.requestor, 'assignProjectToUsers'))) { + if (!(await hasPermission(req.body.requestor, "assignProjectToUsers"))) { res .status(403) - .send({ error: 'You are not authorized to perform this operation' }); + .send({ error: "You are not authorized to perform this operation" }); return; } if ( - !req.params.projectId - || !mongoose.Types.ObjectId.isValid(req.params.projectId) - || !req.body.users - || req.body.users.length === 0 + !req.params.projectId || + !mongoose.Types.ObjectId.isValid(req.params.projectId) || + !req.body.users || + req.body.users.length === 0 ) { - res.status(400).send({ error: 'Invalid request' }); + res.status(400).send({ error: "Invalid request" }); return; } @@ -176,7 +170,7 @@ const projectController = function (Project) { Project.findById(req.params.projectId) .then((project) => { if (!project || project.length === 0) { - res.status(400).send({ error: 'Invalid project' }); + res.status(400).send({ error: "Invalid project" }); return; } const { users } = req.body; @@ -185,36 +179,32 @@ const projectController = function (Project) { users.forEach((element) => { const { userId, operation } = element; - if (operation === 'Assign') { + if (cache.hasCache(`user-${userId}`)) { + cache.removeCache(`user-${userId}`); + } + if (operation === "Assign") { assignlist.push(userId); } else { unassignlist.push(userId); } }); - const userToBeAssigned = mongoose.Types.ObjectId(req.params.userId); - - console.log('user to be asigned', userToBeAssigned); - if (cache.hasCache(`user-${userToBeAssigned}`)) { - cache.removeCache(`user-${userToBeAssigned}`); - } - const assignPromise = userProfile .updateMany( { _id: { $in: assignlist } }, - { $addToSet: { projects: project._id } }, + { $addToSet: { projects: project._id } } ) .exec(); const unassignPromise = userProfile .updateMany( { _id: { $in: unassignlist } }, - { $pull: { projects: project._id } }, + { $pull: { projects: project._id } } ) .exec(); Promise.all([assignPromise, unassignPromise]) .then(() => { - res.status(200).send({ result: 'Done' }); + res.status(200).send({ result: "Done" }); }) .catch((error) => { res.status(500).send({ error }); @@ -228,13 +218,13 @@ const projectController = function (Project) { const getprojectMembership = function (req, res) { const { projectId } = req.params; if (!mongoose.Types.ObjectId.isValid(projectId)) { - res.status(400).send({ error: 'Invalid request' }); + res.status(400).send({ error: "Invalid request" }); return; } userProfile .find( { projects: projectId }, - '_id firstName lastName isActive profilePic', + "_id firstName lastName isActive profilePic" ) .sort({ firstName: 1, lastName: 1 }) .then((results) => { diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index aed8f1788..5c181a549 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -1,20 +1,23 @@ -const moment = require('moment-timezone'); - -const mongoose = require('mongoose'); -const bcrypt = require('bcryptjs'); - -const moment_ = require('moment'); -const jwt = require('jsonwebtoken'); -const userHelper = require('../helpers/userHelper')(); -const TimeEntry = require('../models/timeentry'); -const logger = require('../startup/logger'); -const Badge = require('../models/badge'); -const userProfile = require('../models/userProfile'); -const yearMonthDayDateValidator = require('../utilities/yearMonthDayDateValidator'); -const cache = require('../utilities/nodeCache')(); -const { hasPermission, canRequestorUpdateUser } = require('../utilities/permissions'); -const escapeRegex = require('../utilities/escapeRegex'); -const config = require('../config'); +const moment = require("moment-timezone"); + +const mongoose = require("mongoose"); +const bcrypt = require("bcryptjs"); + +const moment_ = require("moment"); +const jwt = require("jsonwebtoken"); +const userHelper = require("../helpers/userHelper")(); +const TimeEntry = require("../models/timeentry"); +const logger = require("../startup/logger"); +const Badge = require("../models/badge"); +const userProfile = require("../models/userProfile"); +const yearMonthDayDateValidator = require("../utilities/yearMonthDayDateValidator"); +const cache = require("../utilities/nodeCache")(); +const { + hasPermission, + canRequestorUpdateUser, +} = require("../utilities/permissions"); +const escapeRegex = require("../utilities/escapeRegex"); +const config = require("../config"); async function ValidatePassword(req, res) { const { userId } = req.params; @@ -22,7 +25,7 @@ async function ValidatePassword(req, res) { if (!mongoose.Types.ObjectId.isValid(userId)) { res.status(400).send({ - error: 'Bad Request', + error: "Bad Request", }); return; } @@ -30,12 +33,15 @@ async function ValidatePassword(req, res) { // Verify correct params in body if (!req.body.newpassword || !req.body.confirmnewpassword) { res.status(400).send({ - error: 'One of more required fields are missing', + error: "One of more required fields are missing", }); return; } // Verify request is authorized by self or adminsitrator - if (!userId === requestor.requestorId && !await hasPermission(req.body.requestor, 'updatePassword')) { + if ( + !userId === requestor.requestorId && + !(await hasPermission(req.body.requestor, "updatePassword")) + ) { res.status(403).send({ error: "You are unauthorized to update this user's password", }); @@ -45,44 +51,44 @@ async function ValidatePassword(req, res) { // Verify new and confirm new password are correct if (req.body.newpassword !== req.body.confirmnewpassword) { res.status(400).send({ - error: 'New and confirm new passwords are not same', + error: "New and confirm new passwords are not same", }); } } const userProfileController = function (UserProfile) { const getUserProfiles = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'getUserProfiles')) { - res.status(403).send('You are not authorized to view all users'); + if (!(await hasPermission(req.body.requestor, "getUserProfiles"))) { + res.status(403).send("You are not authorized to view all users"); return; } UserProfile.find( {}, - '_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate', + "_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate" ) .sort({ lastName: 1, }) .then((results) => { if (!results) { - if (cache.getCache('allusers')) { - const getData = JSON.parse(cache.getCache('allusers')); + if (cache.getCache("allusers")) { + const getData = JSON.parse(cache.getCache("allusers")); res.status(200).send(getData); return; } - res.status(500).send({ error: 'User result was invalid' }); - return; + res.status(500).send({ error: "User result was invalid" }); + return; } - cache.setCache('allusers', JSON.stringify(results)); + 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) { - if (!await hasPermission(req.body.requestor, 'getProjectMembers')) { - res.status(403).send('You are not authorized to view all users'); + if (!(await hasPermission(req.body.requestor, "getProjectMembers"))) { + res.status(403).send("You are not authorized to view all users"); return; } UserProfile.find( @@ -91,40 +97,43 @@ const userProfileController = function (UserProfile) { $in: [req.params.projectId], }, }, - '_id firstName email', + "_id firstName email", (err, profiles) => { if (err) { - res.status(404).send('Error finding user profiles'); + res.status(404).send("Error finding user profiles"); return; } res.json(profiles); - }, + } ); }; const postUserProfile = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'postUserProfile')) { - res.status(403).send('You are not authorized to create new users'); + if (!(await hasPermission(req.body.requestor, "postUserProfile"))) { + res.status(403).send("You are not authorized to create new users"); return; } - if (req.body.role === 'Owner' && !await hasPermission(req.body.requestor, 'addDeleteEditOwners')) { - res.status(403).send('You are not authorized to create new owners'); + if ( + req.body.role === "Owner" && + !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + ) { + res.status(403).send("You are not authorized to create new owners"); return; } const userByEmail = await UserProfile.findOne({ email: { $regex: escapeRegex(req.body.email), - $options: 'i', + $options: "i", }, }); if (userByEmail) { res.status(400).send({ error: - 'That email address is already in use. Please choose another email address.', - type: 'email', + "That email address is already in use. Please choose another email address.", + type: "email", }); return; } @@ -143,8 +152,8 @@ const userProfileController = function (UserProfile) { if (userByPhoneNumber) { res.status(400).send({ error: - 'That phone number is already in use. Please choose another number.', - type: 'phoneNumber', + "That phone number is already in use. Please choose another number.", + type: "phoneNumber", }); return; } @@ -158,8 +167,8 @@ const userProfileController = function (UserProfile) { if (userDuplicateName && !req.body.allowsDuplicateName) { res.status(400).send({ error: - 'That name is already in use. Please confirm if you want to use this name.', - type: 'name', + "That name is already in use. Please confirm if you want to use this name.", + type: "name", }); return; } @@ -186,15 +195,15 @@ const userProfileController = function (UserProfile) { up.projects = Array.from(new Set(req.body.projects)); up.createdDate = req.body.createdDate; up.email = req.body.email; - up.weeklySummaries = req.body.weeklySummaries || [{ summary: '' }]; + up.weeklySummaries = req.body.weeklySummaries || [{ summary: "" }]; up.weeklySummariesCount = req.body.weeklySummariesCount || 0; up.weeklySummaryOption = req.body.weeklySummaryOption; - up.mediaUrl = req.body.mediaUrl || ''; - up.collaborationPreference = req.body.collaborationPreference || ''; - up.timeZone = req.body.timeZone || 'America/Los_Angeles'; + up.mediaUrl = req.body.mediaUrl || ""; + up.collaborationPreference = req.body.collaborationPreference || ""; + up.timeZone = req.body.timeZone || "America/Los_Angeles"; up.location = req.body.location; up.permissions = req.body.permissions; - up.bioPosted = req.body.bioPosted || 'default'; + up.bioPosted = req.body.bioPosted || "default"; up.isFirstTimelog = true; up.save() @@ -216,39 +225,42 @@ const userProfileController = function (UserProfile) { lastName: up.lastName, email: up.email, }; - const allUserCache = JSON.parse(cache.getCache('allusers')); + const allUserCache = JSON.parse(cache.getCache("allusers")); allUserCache.push(userCache); - cache.setCache('allusers', JSON.stringify(allUserCache)); + cache.setCache("allusers", JSON.stringify(allUserCache)); }) - .catch(error => res.status(501).send(error)); + .catch((error) => res.status(501).send(error)); }; const putUserProfile = async function (req, res) { const userid = req.params.userId; const isRequestorAuthorized = !!( - canRequestorUpdateUser(req.body.requestor.requestorId, userid) && ( - await hasPermission(req.body.requestor, 'putUserProfile') - || req.body.requestor.requestorId === userid - ) + canRequestorUpdateUser(req.body.requestor.requestorId, userid) && + ((await hasPermission(req.body.requestor, "putUserProfile")) || + req.body.requestor.requestorId === userid) ); - const canEditTeamCode = req.body.requestor.role === 'Owner' - || req.body.requestor.permissions?.frontPermissions.includes('editTeamCode'); + const canEditTeamCode = + req.body.requestor.role === "Owner" || + req.body.requestor.permissions?.frontPermissions.includes("editTeamCode"); if (!isRequestorAuthorized) { - res.status(403).send('You are not authorized to update this user'); + res.status(403).send("You are not authorized to update this user"); return; } - if (req.body.role === 'Owner' && !await hasPermission(req.body.requestor, 'addDeleteEditOwners')) { - res.status(403).send('You are not authorized to update this user'); + if ( + req.body.role === "Owner" && + !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + ) { + res.status(403).send("You are not authorized to update this user"); return; } cache.removeCache(`user-${userid}`); UserProfile.findById(userid, async (err, record) => { if (err || !record) { - res.status(404).send('No valid records found'); + res.status(404).send("No valid records found"); return; } // validate userprofile pic @@ -267,7 +279,8 @@ const userProfileController = function (UserProfile) { : []; record.jobTitle = req.body.jobTitle; record.emailPubliclyAccessible = req.body.emailPubliclyAccessible; - record.phoneNumberPubliclyAccessible = req.body.phoneNumberPubliclyAccessible; + record.phoneNumberPubliclyAccessible = + req.body.phoneNumberPubliclyAccessible; record.profilePic = req.body.profilePic; record.firstName = req.body.firstName; @@ -289,27 +302,29 @@ const userProfileController = function (UserProfile) { record.isVisible = req.body.isVisible || false; record.isRehireable = req.body.isRehireable || false; record.totalIntangibleHrs = req.body.totalIntangibleHrs; - record.bioPosted = req.body.bioPosted || 'default'; + record.bioPosted = req.body.bioPosted || "default"; record.isFirstTimelog = req.body.isFirstTimelog; if (!canEditTeamCode && record.teamCode !== req.body.teamCode) { - res.status(403).send('You are not authorized to edit team code.'); + res.status(403).send("You are not authorized to edit team code."); return; } record.teamCode = req.body.teamCode; // find userData in cache - const isUserInCache = cache.hasCache('allusers'); + const isUserInCache = cache.hasCache("allusers"); let allUserData; let userData; let userIdx; if (isUserInCache) { - allUserData = JSON.parse(cache.getCache('allusers')); - userIdx = allUserData.findIndex(users => users._id === userid); + allUserData = JSON.parse(cache.getCache("allusers")); + userIdx = allUserData.findIndex((users) => users._id === userid); userData = allUserData[userIdx]; } - if (await hasPermission(req.body.requestor, 'putUserProfileImportantInfo')) { + if ( + await hasPermission(req.body.requestor, "putUserProfileImportantInfo") + ) { record.role = req.body.role; record.isRehireable = req.body.isRehireable; record.isActive = req.body.isActive; @@ -321,11 +336,11 @@ const userProfileController = function (UserProfile) { // If their last update was made today, remove that const lasti = record.weeklycommittedHoursHistory.length - 1; const lastChangeDate = moment( - record.weeklycommittedHoursHistory[lasti].dateChanged, + record.weeklycommittedHoursHistory[lasti].dateChanged ); const now = moment(); - if (lastChangeDate.isSame(now, 'day')) { + if (lastChangeDate.isSame(now, "day")) { record.weeklycommittedHoursHistory.pop(); } @@ -337,8 +352,8 @@ const userProfileController = function (UserProfile) { }; record.weeklycommittedHoursHistory.push(newEntry); } - - record.missedHours = req.body.role === 'Core Team' ? req.body?.missedHours ?? 0 : 0; + record.missedHours = + req.body.role === "Core Team" ? req.body?.missedHours ?? 0 : 0; record.adminLinks = req.body.adminLinks; record.teams = Array.from(new Set(req.body.teams)); record.projects = Array.from(new Set(req.body.projects)); @@ -370,12 +385,15 @@ const userProfileController = function (UserProfile) { record.weeklycommittedHoursHistory.push(newEntry); } // then also change the first committed history (index 0) - record.weeklycommittedHoursHistory[0].dateChanged = record.createdDate; + record.weeklycommittedHoursHistory[0].dateChanged = + record.createdDate; } - record.bioPosted = req.body.bioPosted || 'default'; + record.bioPosted = req.body.bioPosted || "default"; - if (await hasPermission(req.body.requestor, 'putUserProfilePermissions')) { + if ( + await hasPermission(req.body.requestor, "putUserProfilePermissions") + ) { record.permissions = req.body.permissions; } @@ -385,7 +403,7 @@ const userProfileController = function (UserProfile) { userData.endDate = record.endDate.toISOString(); } } else { - record.set('endDate', undefined, { strict: false }); + record.set("endDate", undefined, { strict: false }); } if (isUserInCache) { userData.role = record.role; @@ -395,7 +413,7 @@ const userProfileController = function (UserProfile) { userData.createdDate = record.createdDate.toISOString(); } } - if (await hasPermission(req.body.requestor, 'infringementAuthorizer')) { + if (await hasPermission(req.body.requestor, "infringementAuthorizer")) { record.infringements = req.body.infringements; } @@ -407,7 +425,7 @@ const userProfileController = function (UserProfile) { results.infringements, results.firstName, results.lastName, - results.email, + results.email ); res.status(200).json({ _id: record._id, @@ -416,32 +434,31 @@ const userProfileController = function (UserProfile) { // update alluser cache if we have cache if (isUserInCache) { allUserData.splice(userIdx, 1, userData); - cache.setCache('allusers', JSON.stringify(allUserData)); + cache.setCache("allusers", JSON.stringify(allUserData)); } }) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }); }; const deleteUserProfile = async function (req, res) { const { option, userId } = req.body; - if (!await hasPermission(req.body.requestor, 'deleteUserProfile')) { - res.status(403).send('You are not authorized to delete users'); + if (!(await hasPermission(req.body.requestor, "deleteUserProfile"))) { + res.status(403).send("You are not authorized to delete users"); return; } - if (req.body.role === 'Owner' && !await hasPermission(req.body.requestor, 'addDeleteEditOwners')) { - res.status(403).send('You are not authorized to delete this user'); + if ( + req.body.role === "Owner" && + !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + ) { + res.status(403).send("You are not authorized to delete this user"); return; } - if ( - !userId - || !option - || (option !== 'delete' && option !== 'archive') - ) { + if (!userId || !option || (option !== "delete" && option !== "archive")) { res.status(400).send({ - error: 'Bad request', + error: "Bad request", }); return; } @@ -449,25 +466,27 @@ const userProfileController = function (UserProfile) { if (!user) { res.status(400).send({ - error: 'Invalid user', + error: "Invalid user", }); return; } - if (option === 'archive') { + if (option === "archive") { const timeArchiveUser = await UserProfile.findOne( { firstName: process.env.TIME_ARCHIVE_FIRST_NAME, lastName: process.env.TIME_ARCHIVE_LAST_NAME, }, - '_id', + "_id" ); if (!timeArchiveUser) { - logger.logException('Time Archive user was not found. Please check the database'); + logger.logException( + "Time Archive user was not found. Please check the database" + ); res.status(500).send({ error: - 'Time Archive User not found. Please contact your developement team on why that happened', + "Time Archive User not found. Please contact your developement team on why that happened", }); return; } @@ -480,35 +499,39 @@ const userProfileController = function (UserProfile) { $set: { personId: mongoose.Types.ObjectId(timeArchiveUser._id), }, - }, + } ); } cache.removeCache(`user-${userId}`); - const allUserData = JSON.parse(cache.getCache('allusers')); - const userIdx = allUserData.findIndex(users => users._id === userId); + const allUserData = JSON.parse(cache.getCache("allusers")); + const userIdx = allUserData.findIndex((users) => users._id === userId); allUserData.splice(userIdx, 1); - cache.setCache('allusers', JSON.stringify(allUserData)); + cache.setCache("allusers", JSON.stringify(allUserData)); await UserProfile.deleteOne({ _id: userId, }); - res.status(200).send({ message: 'Executed Successfully' }); + res.status(200).send({ message: "Executed Successfully" }); }; const getUserById = function (req, res) { const userid = req.params.userId; + if (cache.getCache(`user-${userid}`)) { const getData = JSON.parse(cache.getCache(`user-${userid}`)); res.status(200).send(getData); return; } - UserProfile.findById(userid, '-password -refreshTokens -lastModifiedDate -__v') + UserProfile.findById( + userid, + "-password -refreshTokens -lastModifiedDate -__v" + ) .populate([ { - path: 'teams', - select: '_id teamName', + path: "teams", + select: "_id teamName", options: { sort: { teamName: 1, @@ -516,8 +539,8 @@ const userProfileController = function (UserProfile) { }, }, { - path: 'projects', - select: '_id projectName category', + path: "projects", + select: "_id projectName category", options: { sort: { projectName: 1, @@ -525,59 +548,67 @@ const userProfileController = function (UserProfile) { }, }, { - path: 'badgeCollection', + path: "badgeCollection", populate: { - path: 'badge', + path: "badge", model: Badge, - select: '_id badgeName type imageUrl description ranking showReport', + select: + "_id badgeName type imageUrl description ranking showReport", }, }, ]) .exec() .then((results) => { if (!results) { - res.status(400).send({ error: 'This is not a valid user' }); + res.status(400).send({ error: "This is not a valid user" }); return; } - userHelper.getTangibleHoursReportedThisWeekByUserId(userid).then((hours) => { - results.set('tangibleHoursReportedThisWeek', hours, { - strict: false, + userHelper + .getTangibleHoursReportedThisWeekByUserId(userid) + .then((hours) => { + results.set("tangibleHoursReportedThisWeek", hours, { + strict: false, + }); + cache.setCache(`user-${userid}`, JSON.stringify(results)); + res.status(200).send(results); }); - cache.setCache(`user-${userid}`, JSON.stringify(results)); - res.status(200).send(results); - }); }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; const getUserByName = (req, res) => { const { name } = req.params; UserProfile.find( - { firstName: name.split(' ')[0], lastName: name.split(' ')[1] }, - '_id, profilePic, badgeCollection', + { firstName: name.split(" ")[0], lastName: name.split(" ")[1] }, + "_id, profilePic, badgeCollection" ) - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send(error)); + .then((results) => res.status(200).send(results)) + .catch((error) => res.status(404).send(error)); }; const updateOneProperty = function (req, res) { const { userId } = req.params; const { key, value } = req.body; - if (key === 'teamCode') { - const canEditTeamCode = req.body.requestor.role === 'Owner' - || req.body.requestor.permissions?.frontPermissions.includes('editTeamCode'); + if (key === "teamCode") { + const canEditTeamCode = + req.body.requestor.role === "Owner" || + req.body.requestor.permissions?.frontPermissions.includes( + "editTeamCode" + ); if (!canEditTeamCode) { - res.status(403).send('You are not authorized to edit team code.'); + res.status(403).send("You are not authorized to edit team code."); return; } } // remove user from cache, it should be loaded next time cache.removeCache(`user-${userId}`); - if (!key || value === undefined) return res.status(400).send({ error: 'Missing property or value' }); - if (!key || value === undefined) return res.status(400).send({ error: 'Missing property or value' }); + if (!key || value === undefined) + return res.status(400).send({ error: "Missing property or value" }); + if (!key || value === undefined) + return res.status(400).send({ error: "Missing property or value" }); return UserProfile.findById(userId) .then((user) => { @@ -588,11 +619,11 @@ const userProfileController = function (UserProfile) { return user .save() .then(() => { - res.status(200).send({ message: 'updated property' }); + 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) { @@ -600,18 +631,25 @@ const userProfileController = function (UserProfile) { const { requestor } = req.body; if (!mongoose.Types.ObjectId.isValid(userId)) { return res.status(400).send({ - error: 'Bad Request', + error: "Bad Request", }); } // Verify correct params in body - if (!req.body.currentpassword || !req.body.newpassword || !req.body.confirmnewpassword) { + if ( + !req.body.currentpassword || + !req.body.newpassword || + !req.body.confirmnewpassword + ) { return res.status(400).send({ - error: 'One of more required fields are missing', + error: "One of more required fields are missing", }); } // Verify request is authorized by self or adminsitrator - if (!userId === requestor.requestorId && !await hasPermission(req.body.requestor, 'updatePassword')) { + if ( + !userId === requestor.requestorId && + !(await hasPermission(req.body.requestor, "updatePassword")) + ) { return res.status(403).send({ error: "You are unauthorized to update this user's password", }); @@ -627,25 +665,25 @@ const userProfileController = function (UserProfile) { if (req.body.newpassword !== req.body.confirmnewpassword) { res.status(400).send({ - error: 'New and confirm new passwords are not same', + error: "New and confirm new passwords are not same", }); } // Verify old and new passwords are not same if (req.body.currentpassword === req.body.newpassword) { res.status(400).send({ - error: 'Old and new passwords should not be same', + error: "Old and new passwords should not be same", }); } - return UserProfile.findById(userId, 'password') + return UserProfile.findById(userId, "password") .then((user) => { bcrypt .compare(req.body.currentpassword, user.password) .then((passwordMatch) => { if (!passwordMatch) { return res.status(400).send({ - error: 'Incorrect current password', + error: "Incorrect current password", }); } @@ -655,28 +693,35 @@ const userProfileController = function (UserProfile) { }); return user .save() - .then(() => res.status(200).send({ message: 'updated password' })) - .catch(error => res.status(500).send(error)); + .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)); }; const getreportees = async function (req, res) { if (!mongoose.Types.ObjectId.isValid(req.params.userId)) { res.status(400).send({ - error: 'Bad request', + error: "Bad request", }); return; } const userid = mongoose.Types.ObjectId(req.params.userId); - let validroles = ['Volunteer', 'Manager', 'Administrator', 'Core Team', 'Owner', 'Mentor']; + let validroles = [ + "Volunteer", + "Manager", + "Administrator", + "Core Team", + "Owner", + "Mentor", + ]; - if (await hasPermission(req.body.requestor, 'getReporteesLimitRoles')) { - validroles = ['Volunteer', 'Manager']; + if (await hasPermission(req.body.requestor, "getReporteesLimitRoles")) { + validroles = ["Volunteer", "Manager"]; } userHelper @@ -692,13 +737,13 @@ 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) { if (!mongoose.Types.ObjectId.isValid(req.params.userId)) { res.status(400).send({ - error: 'Bad request', + error: "Bad request", }); return; } @@ -709,14 +754,14 @@ 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) { const { userId } = req.params; if (mongoose.Types.ObjectId.isValid(userId)) { - UserProfile.findById(userId, 'firstName lastName') + UserProfile.findById(userId, "firstName lastName") .then((result) => { const name = `${result.firstName} ${result.lastName}`; res.status(200).send({ @@ -728,30 +773,30 @@ const userProfileController = function (UserProfile) { }); } else { res.status(400).send({ - error: 'Bad request', + error: "Bad request", }); } }; const changeUserStatus = async function (req, res) { const { userId } = req.params; - const status = req.body.status === 'Active'; + const status = req.body.status === "Active"; const activationDate = req.body.reactivationDate; const { endDate } = req.body; - const isSet = req.body.isSet === 'FinalDay'; + const isSet = req.body.isSet === "FinalDay"; if (!mongoose.Types.ObjectId.isValid(userId)) { res.status(400).send({ - error: 'Bad Request', + error: "Bad Request", }); return; } - if (!await hasPermission(req.body.requestor, 'changeUserStatus')) { - res.status(403).send('You are not authorized to change user status'); + if (!(await hasPermission(req.body.requestor, "changeUserStatus"))) { + res.status(403).send("You are not authorized to change user status"); return; } cache.removeCache(`user-${userId}`); - UserProfile.findById(userId, 'isActive') + UserProfile.findById(userId, "isActive") .then((user) => { user.set({ isActive: status, @@ -762,20 +807,22 @@ const userProfileController = function (UserProfile) { user .save() .then(() => { - const isUserInCache = cache.hasCache('allusers'); + const isUserInCache = cache.hasCache("allusers"); if (isUserInCache) { - const allUserData = JSON.parse(cache.getCache('allusers')); - const userIdx = allUserData.findIndex(users => users._id === userId); + const allUserData = JSON.parse(cache.getCache("allusers")); + const userIdx = allUserData.findIndex( + (users) => users._id === userId + ); const userData = allUserData[userIdx]; if (!status) { userData.endDate = user.endDate.toISOString(); } userData.isActive = user.isActive; allUserData.splice(userIdx, 1, userData); - cache.setCache('allusers', JSON.stringify(allUserData)); + cache.setCache("allusers", JSON.stringify(allUserData)); } res.status(200).send({ - message: 'status updated', + message: "status updated", }); }) .catch((error) => { @@ -790,7 +837,7 @@ const userProfileController = function (UserProfile) { const resetPassword = function (req, res) { ValidatePassword(req); - UserProfile.findById(req.params.userId, 'password') + UserProfile.findById(req.params.userId, "password") .then((user) => { user.set({ password: req.body.newpassword, @@ -799,7 +846,7 @@ const userProfileController = function (UserProfile) { .save() .then(() => { res.status(200).send({ - message: ' password Reset', + message: " password Reset", }); }) .catch((error) => { @@ -813,7 +860,7 @@ const userProfileController = function (UserProfile) { const getAllUsersWithFacebookLink = function (req, res) { try { - UserProfile.find({ 'personalLinks.Name': 'Facebook' }).then((results) => { + UserProfile.find({ "personalLinks.Name": "Facebook" }).then((results) => { res.status(200).send(results); }); } catch (error) { @@ -825,7 +872,7 @@ const userProfileController = function (UserProfile) { const user = await UserProfile.findById(req.params.userId); if (!user) { - res.status(403).send({ message: 'User does not exist' }); + res.status(403).send({ message: "User does not exist" }); return; } From 355ed4cc2ca3cb5a3b7716d54b567973fe2c4eb9 Mon Sep 17 00:00:00 2001 From: luisarevalo21 Date: Sun, 5 Nov 2023 19:11:09 -0800 Subject: [PATCH 3/4] fixed projects not appearing when adding via the projects tab. Projects added appear in the user's profile --- src/controllers/projectController.js | 92 +++--- src/controllers/rolePresetsController.js | 59 ++-- src/controllers/rolesController.js | 107 +++---- src/controllers/userProfileController.js | 345 +++++++++++------------ 4 files changed, 309 insertions(+), 294 deletions(-) diff --git a/src/controllers/projectController.js b/src/controllers/projectController.js index 53cb5c421..550a4dcee 100644 --- a/src/controllers/projectController.js +++ b/src/controllers/projectController.js @@ -1,40 +1,40 @@ -const mongoose = require("mongoose"); -const timeentry = require("../models/timeentry"); -const userProfile = require("../models/userProfile"); -const userProject = require("../helpers/helperModels/userProjects"); -const { hasPermission } = require("../utilities/permissions"); -const escapeRegex = require("../utilities/escapeRegex"); -const cache = require("../utilities/nodeCache")(); +const mongoose = require('mongoose'); +const timeentry = require('../models/timeentry'); +const userProfile = require('../models/userProfile'); +const userProject = require('../helpers/helperModels/userProjects'); +const { hasPermission } = require('../utilities/permissions'); +const escapeRegex = require('../utilities/escapeRegex'); +const cache = require('../utilities/nodeCache')(); const projectController = function (Project) { const getAllProjects = function (req, res) { - Project.find({}, "projectName isActive category") + Project.find({}, 'projectName isActive category') .sort({ projectName: 1 }) - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }; const deleteProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "deleteProject"))) { + if (!(await hasPermission(req.body.requestor, 'deleteProject'))) { res .status(403) - .send({ error: "You are not authorized to delete projects." }); + .send({ error: 'You are not authorized to delete projects.' }); return; } const { projectId } = req.params; Project.findById(projectId, (error, record) => { if (error || !record || record === null || record.length === 0) { - res.status(400).send({ error: "No valid records found" }); + res.status(400).send({ error: 'No valid records found' }); return; } // find if project has any time entries associated with it - timeentry.find({ projectId: record._id }, "_id").then((timeentries) => { + timeentry.find({ projectId: record._id }, '_id').then((timeentries) => { if (timeentries.length > 0) { res.status(400).send({ error: - "This project has associated time entries and cannot be deleted. Consider inactivaing it instead.", + 'This project has associated time entries and cannot be deleted. Consider inactivaing it instead.', }); } else { const removeprojectfromprofile = userProfile @@ -46,8 +46,8 @@ const projectController = function (Project) { .then( res.status(200).send({ message: - "Project successfully deleted and user profiles updated.", - }) + 'Project successfully deleted and user profiles updated.', + }), ) .catch((errors) => { res.status(400).send(errors); @@ -60,22 +60,22 @@ const projectController = function (Project) { }; const postProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "postProject"))) { + if (!(await hasPermission(req.body.requestor, 'postProject'))) { res .status(403) - .send({ error: "You are not authorized to create new projects." }); + .send({ error: 'You are not authorized to create new projects.' }); return; } if (!req.body.projectName || !req.body.isActive) { res.status(400).send({ - error: "Project Name and active status are mandatory fields.", + error: 'Project Name and active status are mandatory fields.', }); return; } Project.find({ - projectName: { $regex: escapeRegex(req.body.projectName), $options: "i" }, + projectName: { $regex: escapeRegex(req.body.projectName), $options: 'i' }, }).then((result) => { if (result.length > 0) { res.status(400).send({ @@ -85,30 +85,30 @@ const projectController = function (Project) { } const _project = new Project(); _project.projectName = req.body.projectName; - _project.category = req.body.projectCategory || "Unspecified"; + _project.category = req.body.projectCategory || 'Unspecified'; _project.isActive = req.body.isActive; _project.createdDatetime = Date.now(); _project.modifiedDatetime = Date.now(); _project .save() - .then((results) => res.status(201).send(results)) - .catch((error) => res.status(500).send({ error })); + .then(results => res.status(201).send(results)) + .catch(error => res.status(500).send({ error })); }); }; const putProject = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "putProject"))) { + if (!(await hasPermission(req.body.requestor, 'putProject'))) { res .status(403) - .send("You are not authorized to make changes in the projects."); + .send('You are not authorized to make changes in the projects.'); return; } const { projectId } = req.params; Project.findById(projectId, (error, record) => { if (error || record === null) { - res.status(400).send("No valid records found"); + res.status(400).send('No valid records found'); return; } @@ -119,17 +119,17 @@ const projectController = function (Project) { record .save() - .then((results) => res.status(201).send(results._id)) - .catch((errors) => res.status(400).send(errors)); + .then(results => res.status(201).send(results._id)) + .catch(errors => res.status(400).send(errors)); }); }; const getProjectById = function (req, res) { const { projectId } = req.params; - Project.findById(projectId, "-__v -createdDatetime -modifiedDatetime") - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + Project.findById(projectId, '-__v -createdDatetime -modifiedDatetime') + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }; const getUserProjects = function (req, res) { @@ -148,20 +148,20 @@ const projectController = function (Project) { const assignProjectToUsers = async function (req, res) { // verify requestor is administrator, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users - if (!(await hasPermission(req.body.requestor, "assignProjectToUsers"))) { + if (!(await hasPermission(req.body.requestor, 'assignProjectToUsers'))) { res .status(403) - .send({ error: "You are not authorized to perform this operation" }); + .send({ error: 'You are not authorized to perform this operation' }); return; } if ( - !req.params.projectId || - !mongoose.Types.ObjectId.isValid(req.params.projectId) || - !req.body.users || - req.body.users.length === 0 + !req.params.projectId + || !mongoose.Types.ObjectId.isValid(req.params.projectId) + || !req.body.users + || req.body.users.length === 0 ) { - res.status(400).send({ error: "Invalid request" }); + res.status(400).send({ error: 'Invalid request' }); return; } @@ -170,7 +170,7 @@ const projectController = function (Project) { Project.findById(req.params.projectId) .then((project) => { if (!project || project.length === 0) { - res.status(400).send({ error: "Invalid project" }); + res.status(400).send({ error: 'Invalid project' }); return; } const { users } = req.body; @@ -182,7 +182,7 @@ const projectController = function (Project) { if (cache.hasCache(`user-${userId}`)) { cache.removeCache(`user-${userId}`); } - if (operation === "Assign") { + if (operation === 'Assign') { assignlist.push(userId); } else { unassignlist.push(userId); @@ -192,19 +192,19 @@ const projectController = function (Project) { const assignPromise = userProfile .updateMany( { _id: { $in: assignlist } }, - { $addToSet: { projects: project._id } } + { $addToSet: { projects: project._id } }, ) .exec(); const unassignPromise = userProfile .updateMany( { _id: { $in: unassignlist } }, - { $pull: { projects: project._id } } + { $pull: { projects: project._id } }, ) .exec(); Promise.all([assignPromise, unassignPromise]) .then(() => { - res.status(200).send({ result: "Done" }); + res.status(200).send({ result: 'Done' }); }) .catch((error) => { res.status(500).send({ error }); @@ -218,13 +218,13 @@ const projectController = function (Project) { const getprojectMembership = function (req, res) { const { projectId } = req.params; if (!mongoose.Types.ObjectId.isValid(projectId)) { - res.status(400).send({ error: "Invalid request" }); + res.status(400).send({ error: 'Invalid request' }); return; } userProfile .find( { projects: projectId }, - "_id firstName lastName isActive profilePic" + '_id firstName lastName isActive profilePic', ) .sort({ firstName: 1, lastName: 1 }) .then((results) => { diff --git a/src/controllers/rolePresetsController.js b/src/controllers/rolePresetsController.js index 3642627f7..58377e7df 100644 --- a/src/controllers/rolePresetsController.js +++ b/src/controllers/rolePresetsController.js @@ -1,26 +1,32 @@ -const { hasPermission } = require('../utilities/permissions'); +const { hasPermission } = require("../utilities/permissions"); const rolePresetsController = function (Preset) { const getPresetsByRole = async function (req, res) { - if (!await hasPermission(req.body.requestor.role, 'putRole')) { - res.status(403).send('You are not authorized to make changes to roles.'); + if (!(await hasPermission(req.body.requestor.role, "putRole"))) { + res.status(403).send("You are not authorized to make changes to roles."); return; } const { roleName } = req.params; Preset.find({ roleName }) - .then((results) => { res.status(200).send(results); }) - .catch((error) => { res.status(400).send(error); }); + .then((results) => { + res.status(200).send(results); + }) + .catch((error) => { + res.status(400).send(error); + }); }; const createNewPreset = async function (req, res) { - if (!await hasPermission(req.body.requestor.role, 'putRole')) { - res.status(403).send('You are not authorized to make changes to roles.'); + if (!(await hasPermission(req.body.requestor.role, "putRole"))) { + res.status(403).send("You are not authorized to make changes to roles."); return; } if (!req.body.roleName || !req.body.presetName || !req.body.permissions) { - res.status(400).send({ error: 'roleName, presetName, and permissions are mandatory fields.' }); + res.status(400).send({ + error: "roleName, presetName, and permissions are mandatory fields.", + }); return; } @@ -28,14 +34,19 @@ const rolePresetsController = function (Preset) { preset.roleName = req.body.roleName; preset.presetName = req.body.presetName; preset.permissions = req.body.permissions; - preset.save() - .then(result => res.status(201).send({ newPreset: result, message: 'New preset created' })) - .catch(error => res.status(400).send({ error })); + preset + .save() + .then((result) => + res + .status(201) + .send({ newPreset: result, message: "New preset created" }) + ) + .catch((error) => res.status(400).send({ error })); }; const updatePresetById = async function (req, res) { - if (!await hasPermission(req.body.requestor.role, 'putRole')) { - res.status(403).send('You are not authorized to make changes to roles.'); + if (!(await hasPermission(req.body.requestor.role, "putRole"))) { + res.status(403).send("You are not authorized to make changes to roles."); return; } @@ -45,27 +56,29 @@ const rolePresetsController = function (Preset) { record.roleName = req.body.roleName; record.presetName = req.body.presetName; record.permissions = req.body.permissions; - record.save() - .then(results => res.status(200).send(results)) - .catch(errors => res.status(400).send(errors)); + record + .save() + .then((results) => res.status(200).send(results)) + .catch((errors) => res.status(400).send(errors)); }) - .catch(error => res.status(400).send({ error })); + .catch((error) => res.status(400).send({ error })); }; const deletePresetById = async function (req, res) { - if (!await hasPermission(req.body.requestor.role, 'putRole')) { - res.status(403).send('You are not authorized to make changes to roles.'); + if (!(await hasPermission(req.body.requestor.role, "putRole"))) { + res.status(403).send("You are not authorized to make changes to roles."); return; } const { presetId } = req.params; Preset.findById(presetId) .then((result) => { - result.remove() - .then(res.status(200).send({ message: 'Deleted preset' })) - .catch(error => res.status(400).send({ error })); + result + .remove() + .then(res.status(200).send({ message: "Deleted preset" })) + .catch((error) => res.status(400).send({ error })); }) - .catch(error => res.status(400).send({ error })); + .catch((error) => res.status(400).send({ error })); }; return { diff --git a/src/controllers/rolesController.js b/src/controllers/rolesController.js index d3d9f8310..3f3dd0555 100644 --- a/src/controllers/rolesController.js +++ b/src/controllers/rolesController.js @@ -1,22 +1,24 @@ -const UserProfile = require('../models/userProfile'); -const cache = require('../utilities/nodeCache')(); -const { hasPermission } = require('../utilities/permissions'); +const UserProfile = require("../models/userProfile"); +const cache = require("../utilities/nodeCache")(); +const { hasPermission } = require("../utilities/permissions"); const rolesController = function (Role) { const getAllRoles = function (req, res) { Role.find({}) - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send({ error })); + .then((results) => res.status(200).send(results)) + .catch((error) => res.status(404).send({ error })); }; const createNewRole = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'postRole')) { - res.status(403).send('You are not authorized to create new roles.'); + if (!(await hasPermission(req.body.requestor, "postRole"))) { + res.status(403).send("You are not authorized to create new roles."); return; } if (!req.body.roleName || !req.body.permissions) { - res.status(400).send({ error: 'roleName and permissions are mandatory fields.' }); + res + .status(400) + .send({ error: "roleName and permissions are mandatory fields." }); return; } @@ -25,81 +27,88 @@ const rolesController = function (Role) { role.permissions = req.body.permissions; role.permissionsBackEnd = req.body.permissionsBackEnd; - role.save().then(results => res.status(201).send(results)).catch(err => res.status(500).send({ err })); + role + .save() + .then((results) => res.status(201).send(results)) + .catch((err) => res.status(500).send({ err })); }; const getRoleById = function (req, res) { - const { roleId } = req.params; - Role.findById( - roleId, - ) - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send({ error })); -}; - + const { roleId } = req.params; + Role.findById(roleId) + .then((results) => { + return res.status(200).send(results); + }) + .catch((error) => res.status(404).send({ error })); + }; const updateRoleById = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'putRole')) { - res.status(403).send('You are not authorized to make changes to roles.'); + if (!(await hasPermission(req.body.requestor, "putRole"))) { + res.status(403).send("You are not authorized to make changes to roles."); return; } const { roleId } = req.params; if (!req.body.permissions) { - res.status(400).send({ error: 'Permissions is a mandatory field' }); + res.status(400).send({ error: "Permissions is a mandatory field" }); return; - } + } Role.findById(roleId, (error, record) => { if (error || record === null) { - res.status(400).send('No valid records found'); + res.status(400).send("No valid records found"); return; } + record.roleName = req.body.roleName; record.permissions = req.body.permissions; record.permissionsBackEnd = req.body.permissionsBackEnd; - record.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(400).send(errors)); + record + .save() + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(400).send(errors)); }); }; const deleteRoleById = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'deleteRole')) { - res.status(403).send('You are not authorized to delete roles.'); + if (!(await hasPermission(req.body.requestor, "deleteRole"))) { + res.status(403).send("You are not authorized to delete roles."); return; } const { roleId } = req.params; Role.findById(roleId) - .then(result => ( + .then((result) => result .remove() - .then(UserProfile - .updateMany({ role: result.roleName }, { role: 'Volunteer' }) - .then(() => { - const isUserInCache = cache.hasCache('allusers'); - if (isUserInCache) { - const allUserData = JSON.parse(cache.getCache('allusers')); - allUserData.forEach((user) => { - if (user.role === result.roleName) { - user.role = 'Volunteer'; - cache.removeCache(`user-${user._id}`); - } - }); - cache.setCache('allusers', JSON.stringify(allUserData)); - } - res.status(200).send({ message: 'Deleted role' }); - }) - .catch(error => res.status(400).send({ error }))) - .catch(error => res.status(400).send({ error })) - )) - .catch(error => res.status(400).send({ error })); + .then( + UserProfile.updateMany( + { role: result.roleName }, + { role: "Volunteer" } + ) + .then(() => { + const isUserInCache = cache.hasCache("allusers"); + if (isUserInCache) { + const allUserData = JSON.parse(cache.getCache("allusers")); + allUserData.forEach((user) => { + if (user.role === result.roleName) { + user.role = "Volunteer"; + cache.removeCache(`user-${user._id}`); + } + }); + cache.setCache("allusers", JSON.stringify(allUserData)); + } + res.status(200).send({ message: "Deleted role" }); + }) + .catch((error) => res.status(400).send({ error })) + ) + .catch((error) => res.status(400).send({ error })) + ) + .catch((error) => res.status(400).send({ error })); }; - return { getAllRoles, createNewRole, diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index 5c181a549..f4513aac4 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -1,23 +1,23 @@ -const moment = require("moment-timezone"); - -const mongoose = require("mongoose"); -const bcrypt = require("bcryptjs"); - -const moment_ = require("moment"); -const jwt = require("jsonwebtoken"); -const userHelper = require("../helpers/userHelper")(); -const TimeEntry = require("../models/timeentry"); -const logger = require("../startup/logger"); -const Badge = require("../models/badge"); -const userProfile = require("../models/userProfile"); -const yearMonthDayDateValidator = require("../utilities/yearMonthDayDateValidator"); -const cache = require("../utilities/nodeCache")(); +const moment = require('moment-timezone'); + +const mongoose = require('mongoose'); +const bcrypt = require('bcryptjs'); + +const moment_ = require('moment'); +const jwt = require('jsonwebtoken'); +const userHelper = require('../helpers/userHelper')(); +const TimeEntry = require('../models/timeentry'); +const logger = require('../startup/logger'); +const Badge = require('../models/badge'); +const userProfile = require('../models/userProfile'); +const yearMonthDayDateValidator = require('../utilities/yearMonthDayDateValidator'); +const cache = require('../utilities/nodeCache')(); const { hasPermission, canRequestorUpdateUser, -} = require("../utilities/permissions"); -const escapeRegex = require("../utilities/escapeRegex"); -const config = require("../config"); +} = require('../utilities/permissions'); +const escapeRegex = require('../utilities/escapeRegex'); +const config = require('../config'); async function ValidatePassword(req, res) { const { userId } = req.params; @@ -25,7 +25,7 @@ async function ValidatePassword(req, res) { if (!mongoose.Types.ObjectId.isValid(userId)) { res.status(400).send({ - error: "Bad Request", + error: 'Bad Request', }); return; } @@ -33,14 +33,14 @@ async function ValidatePassword(req, res) { // Verify correct params in body if (!req.body.newpassword || !req.body.confirmnewpassword) { res.status(400).send({ - error: "One of more required fields are missing", + error: 'One of more required fields are missing', }); return; } // Verify request is authorized by self or adminsitrator if ( - !userId === requestor.requestorId && - !(await hasPermission(req.body.requestor, "updatePassword")) + !userId === requestor.requestorId + && !(await hasPermission(req.body.requestor, 'updatePassword')) ) { res.status(403).send({ error: "You are unauthorized to update this user's password", @@ -51,44 +51,44 @@ async function ValidatePassword(req, res) { // Verify new and confirm new password are correct if (req.body.newpassword !== req.body.confirmnewpassword) { res.status(400).send({ - error: "New and confirm new passwords are not same", + error: 'New and confirm new passwords are not same', }); } } const userProfileController = function (UserProfile) { const getUserProfiles = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "getUserProfiles"))) { - res.status(403).send("You are not authorized to view all users"); + if (!(await hasPermission(req.body.requestor, 'getUserProfiles'))) { + res.status(403).send('You are not authorized to view all users'); return; } UserProfile.find( {}, - "_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate" + '_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate', ) .sort({ lastName: 1, }) .then((results) => { if (!results) { - if (cache.getCache("allusers")) { - const getData = JSON.parse(cache.getCache("allusers")); + if (cache.getCache('allusers')) { + const getData = JSON.parse(cache.getCache('allusers')); res.status(200).send(getData); return; } - res.status(500).send({ error: "User result was invalid" }); + res.status(500).send({ error: 'User result was invalid' }); return; } - cache.setCache("allusers", JSON.stringify(results)); + 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) { - if (!(await hasPermission(req.body.requestor, "getProjectMembers"))) { - res.status(403).send("You are not authorized to view all users"); + if (!(await hasPermission(req.body.requestor, 'getProjectMembers'))) { + res.status(403).send('You are not authorized to view all users'); return; } UserProfile.find( @@ -97,43 +97,43 @@ const userProfileController = function (UserProfile) { $in: [req.params.projectId], }, }, - "_id firstName email", + '_id firstName email', (err, profiles) => { if (err) { - res.status(404).send("Error finding user profiles"); + res.status(404).send('Error finding user profiles'); return; } res.json(profiles); - } + }, ); }; const postUserProfile = async function (req, res) { - if (!(await hasPermission(req.body.requestor, "postUserProfile"))) { - res.status(403).send("You are not authorized to create new users"); + if (!(await hasPermission(req.body.requestor, 'postUserProfile'))) { + res.status(403).send('You are not authorized to create new users'); return; } if ( - req.body.role === "Owner" && - !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + req.body.role === 'Owner' + && !(await hasPermission(req.body.requestor, 'addDeleteEditOwners')) ) { - res.status(403).send("You are not authorized to create new owners"); + res.status(403).send('You are not authorized to create new owners'); return; } const userByEmail = await UserProfile.findOne({ email: { $regex: escapeRegex(req.body.email), - $options: "i", + $options: 'i', }, }); if (userByEmail) { res.status(400).send({ error: - "That email address is already in use. Please choose another email address.", - type: "email", + 'That email address is already in use. Please choose another email address.', + type: 'email', }); return; } @@ -152,8 +152,8 @@ const userProfileController = function (UserProfile) { if (userByPhoneNumber) { res.status(400).send({ error: - "That phone number is already in use. Please choose another number.", - type: "phoneNumber", + 'That phone number is already in use. Please choose another number.', + type: 'phoneNumber', }); return; } @@ -167,8 +167,8 @@ const userProfileController = function (UserProfile) { if (userDuplicateName && !req.body.allowsDuplicateName) { res.status(400).send({ error: - "That name is already in use. Please confirm if you want to use this name.", - type: "name", + 'That name is already in use. Please confirm if you want to use this name.', + type: 'name', }); return; } @@ -195,15 +195,15 @@ const userProfileController = function (UserProfile) { up.projects = Array.from(new Set(req.body.projects)); up.createdDate = req.body.createdDate; up.email = req.body.email; - up.weeklySummaries = req.body.weeklySummaries || [{ summary: "" }]; + up.weeklySummaries = req.body.weeklySummaries || [{ summary: '' }]; up.weeklySummariesCount = req.body.weeklySummariesCount || 0; up.weeklySummaryOption = req.body.weeklySummaryOption; - up.mediaUrl = req.body.mediaUrl || ""; - up.collaborationPreference = req.body.collaborationPreference || ""; - up.timeZone = req.body.timeZone || "America/Los_Angeles"; + up.mediaUrl = req.body.mediaUrl || ''; + up.collaborationPreference = req.body.collaborationPreference || ''; + up.timeZone = req.body.timeZone || 'America/Los_Angeles'; up.location = req.body.location; up.permissions = req.body.permissions; - up.bioPosted = req.body.bioPosted || "default"; + up.bioPosted = req.body.bioPosted || 'default'; up.isFirstTimelog = true; up.save() @@ -225,42 +225,41 @@ const userProfileController = function (UserProfile) { lastName: up.lastName, email: up.email, }; - const allUserCache = JSON.parse(cache.getCache("allusers")); + const allUserCache = JSON.parse(cache.getCache('allusers')); allUserCache.push(userCache); - cache.setCache("allusers", JSON.stringify(allUserCache)); + cache.setCache('allusers', JSON.stringify(allUserCache)); }) - .catch((error) => res.status(501).send(error)); + .catch(error => res.status(501).send(error)); }; const putUserProfile = async function (req, res) { const userid = req.params.userId; const isRequestorAuthorized = !!( - canRequestorUpdateUser(req.body.requestor.requestorId, userid) && - ((await hasPermission(req.body.requestor, "putUserProfile")) || - req.body.requestor.requestorId === userid) + canRequestorUpdateUser(req.body.requestor.requestorId, userid) + && ((await hasPermission(req.body.requestor, 'putUserProfile')) + || req.body.requestor.requestorId === userid) ); - const canEditTeamCode = - req.body.requestor.role === "Owner" || - req.body.requestor.permissions?.frontPermissions.includes("editTeamCode"); + const canEditTeamCode = req.body.requestor.role === 'Owner' + || req.body.requestor.permissions?.frontPermissions.includes('editTeamCode'); if (!isRequestorAuthorized) { - res.status(403).send("You are not authorized to update this user"); + res.status(403).send('You are not authorized to update this user'); return; } if ( - req.body.role === "Owner" && - !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + req.body.role === 'Owner' + && !(await hasPermission(req.body.requestor, 'addDeleteEditOwners')) ) { - res.status(403).send("You are not authorized to update this user"); + res.status(403).send('You are not authorized to update this user'); return; } cache.removeCache(`user-${userid}`); UserProfile.findById(userid, async (err, record) => { if (err || !record) { - res.status(404).send("No valid records found"); + res.status(404).send('No valid records found'); return; } // validate userprofile pic @@ -279,8 +278,7 @@ const userProfileController = function (UserProfile) { : []; record.jobTitle = req.body.jobTitle; record.emailPubliclyAccessible = req.body.emailPubliclyAccessible; - record.phoneNumberPubliclyAccessible = - req.body.phoneNumberPubliclyAccessible; + record.phoneNumberPubliclyAccessible = req.body.phoneNumberPubliclyAccessible; record.profilePic = req.body.profilePic; record.firstName = req.body.firstName; @@ -302,28 +300,28 @@ const userProfileController = function (UserProfile) { record.isVisible = req.body.isVisible || false; record.isRehireable = req.body.isRehireable || false; record.totalIntangibleHrs = req.body.totalIntangibleHrs; - record.bioPosted = req.body.bioPosted || "default"; + record.bioPosted = req.body.bioPosted || 'default'; record.isFirstTimelog = req.body.isFirstTimelog; if (!canEditTeamCode && record.teamCode !== req.body.teamCode) { - res.status(403).send("You are not authorized to edit team code."); + res.status(403).send('You are not authorized to edit team code.'); return; } record.teamCode = req.body.teamCode; // find userData in cache - const isUserInCache = cache.hasCache("allusers"); + const isUserInCache = cache.hasCache('allusers'); let allUserData; let userData; let userIdx; if (isUserInCache) { - allUserData = JSON.parse(cache.getCache("allusers")); - userIdx = allUserData.findIndex((users) => users._id === userid); + allUserData = JSON.parse(cache.getCache('allusers')); + userIdx = allUserData.findIndex(users => users._id === userid); userData = allUserData[userIdx]; } if ( - await hasPermission(req.body.requestor, "putUserProfileImportantInfo") + await hasPermission(req.body.requestor, 'putUserProfileImportantInfo') ) { record.role = req.body.role; record.isRehireable = req.body.isRehireable; @@ -336,11 +334,11 @@ const userProfileController = function (UserProfile) { // If their last update was made today, remove that const lasti = record.weeklycommittedHoursHistory.length - 1; const lastChangeDate = moment( - record.weeklycommittedHoursHistory[lasti].dateChanged + record.weeklycommittedHoursHistory[lasti].dateChanged, ); const now = moment(); - if (lastChangeDate.isSame(now, "day")) { + if (lastChangeDate.isSame(now, 'day')) { record.weeklycommittedHoursHistory.pop(); } @@ -352,8 +350,7 @@ const userProfileController = function (UserProfile) { }; record.weeklycommittedHoursHistory.push(newEntry); } - record.missedHours = - req.body.role === "Core Team" ? req.body?.missedHours ?? 0 : 0; + record.missedHours = req.body.role === 'Core Team' ? req.body?.missedHours ?? 0 : 0; record.adminLinks = req.body.adminLinks; record.teams = Array.from(new Set(req.body.teams)); record.projects = Array.from(new Set(req.body.projects)); @@ -385,14 +382,13 @@ const userProfileController = function (UserProfile) { record.weeklycommittedHoursHistory.push(newEntry); } // then also change the first committed history (index 0) - record.weeklycommittedHoursHistory[0].dateChanged = - record.createdDate; + record.weeklycommittedHoursHistory[0].dateChanged = record.createdDate; } - record.bioPosted = req.body.bioPosted || "default"; + record.bioPosted = req.body.bioPosted || 'default'; if ( - await hasPermission(req.body.requestor, "putUserProfilePermissions") + await hasPermission(req.body.requestor, 'putUserProfilePermissions') ) { record.permissions = req.body.permissions; } @@ -403,7 +399,7 @@ const userProfileController = function (UserProfile) { userData.endDate = record.endDate.toISOString(); } } else { - record.set("endDate", undefined, { strict: false }); + record.set('endDate', undefined, { strict: false }); } if (isUserInCache) { userData.role = record.role; @@ -413,7 +409,7 @@ const userProfileController = function (UserProfile) { userData.createdDate = record.createdDate.toISOString(); } } - if (await hasPermission(req.body.requestor, "infringementAuthorizer")) { + if (await hasPermission(req.body.requestor, 'infringementAuthorizer')) { record.infringements = req.body.infringements; } @@ -425,7 +421,7 @@ const userProfileController = function (UserProfile) { results.infringements, results.firstName, results.lastName, - results.email + results.email, ); res.status(200).json({ _id: record._id, @@ -434,31 +430,31 @@ const userProfileController = function (UserProfile) { // update alluser cache if we have cache if (isUserInCache) { allUserData.splice(userIdx, 1, userData); - cache.setCache("allusers", JSON.stringify(allUserData)); + cache.setCache('allusers', JSON.stringify(allUserData)); } }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }); }; const deleteUserProfile = async function (req, res) { const { option, userId } = req.body; - if (!(await hasPermission(req.body.requestor, "deleteUserProfile"))) { - res.status(403).send("You are not authorized to delete users"); + if (!(await hasPermission(req.body.requestor, 'deleteUserProfile'))) { + res.status(403).send('You are not authorized to delete users'); return; } if ( - req.body.role === "Owner" && - !(await hasPermission(req.body.requestor, "addDeleteEditOwners")) + req.body.role === 'Owner' + && !(await hasPermission(req.body.requestor, 'addDeleteEditOwners')) ) { - res.status(403).send("You are not authorized to delete this user"); + res.status(403).send('You are not authorized to delete this user'); return; } - if (!userId || !option || (option !== "delete" && option !== "archive")) { + if (!userId || !option || (option !== 'delete' && option !== 'archive')) { res.status(400).send({ - error: "Bad request", + error: 'Bad request', }); return; } @@ -466,27 +462,27 @@ const userProfileController = function (UserProfile) { if (!user) { res.status(400).send({ - error: "Invalid user", + error: 'Invalid user', }); return; } - if (option === "archive") { + if (option === 'archive') { const timeArchiveUser = await UserProfile.findOne( { firstName: process.env.TIME_ARCHIVE_FIRST_NAME, lastName: process.env.TIME_ARCHIVE_LAST_NAME, }, - "_id" + '_id', ); if (!timeArchiveUser) { logger.logException( - "Time Archive user was not found. Please check the database" + 'Time Archive user was not found. Please check the database', ); res.status(500).send({ error: - "Time Archive User not found. Please contact your developement team on why that happened", + 'Time Archive User not found. Please contact your developement team on why that happened', }); return; } @@ -499,20 +495,20 @@ const userProfileController = function (UserProfile) { $set: { personId: mongoose.Types.ObjectId(timeArchiveUser._id), }, - } + }, ); } cache.removeCache(`user-${userId}`); - const allUserData = JSON.parse(cache.getCache("allusers")); - const userIdx = allUserData.findIndex((users) => users._id === userId); + const allUserData = JSON.parse(cache.getCache('allusers')); + const userIdx = allUserData.findIndex(users => users._id === userId); allUserData.splice(userIdx, 1); - cache.setCache("allusers", JSON.stringify(allUserData)); + cache.setCache('allusers', JSON.stringify(allUserData)); await UserProfile.deleteOne({ _id: userId, }); - res.status(200).send({ message: "Executed Successfully" }); + res.status(200).send({ message: 'Executed Successfully' }); }; const getUserById = function (req, res) { @@ -526,12 +522,12 @@ const userProfileController = function (UserProfile) { UserProfile.findById( userid, - "-password -refreshTokens -lastModifiedDate -__v" + '-password -refreshTokens -lastModifiedDate -__v', ) .populate([ { - path: "teams", - select: "_id teamName", + path: 'teams', + select: '_id teamName', options: { sort: { teamName: 1, @@ -539,8 +535,8 @@ const userProfileController = function (UserProfile) { }, }, { - path: "projects", - select: "_id projectName category", + path: 'projects', + select: '_id projectName category', options: { sort: { projectName: 1, @@ -548,67 +544,64 @@ const userProfileController = function (UserProfile) { }, }, { - path: "badgeCollection", + path: 'badgeCollection', populate: { - path: "badge", + path: 'badge', model: Badge, select: - "_id badgeName type imageUrl description ranking showReport", + '_id badgeName type imageUrl description ranking showReport', }, }, ]) .exec() .then((results) => { if (!results) { - res.status(400).send({ error: "This is not a valid user" }); + res.status(400).send({ error: 'This is not a valid user' }); return; } userHelper .getTangibleHoursReportedThisWeekByUserId(userid) .then((hours) => { - results.set("tangibleHoursReportedThisWeek", hours, { + results.set('tangibleHoursReportedThisWeek', hours, { strict: false, }); cache.setCache(`user-${userid}`, JSON.stringify(results)); res.status(200).send(results); }); }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const getUserByName = (req, res) => { const { name } = req.params; UserProfile.find( - { firstName: name.split(" ")[0], lastName: name.split(" ")[1] }, - "_id, profilePic, badgeCollection" + { firstName: name.split(' ')[0], lastName: name.split(' ')[1] }, + '_id, profilePic, badgeCollection', ) - .then((results) => res.status(200).send(results)) - .catch((error) => res.status(404).send(error)); + .then(results => res.status(200).send(results)) + .catch(error => res.status(404).send(error)); }; const updateOneProperty = function (req, res) { const { userId } = req.params; const { key, value } = req.body; - if (key === "teamCode") { - const canEditTeamCode = - req.body.requestor.role === "Owner" || - req.body.requestor.permissions?.frontPermissions.includes( - "editTeamCode" + if (key === 'teamCode') { + const canEditTeamCode = req.body.requestor.role === 'Owner' + || req.body.requestor.permissions?.frontPermissions.includes( + 'editTeamCode', ); if (!canEditTeamCode) { - res.status(403).send("You are not authorized to edit team code."); + res.status(403).send('You are not authorized to edit team code.'); return; } } // remove user from cache, it should be loaded next time cache.removeCache(`user-${userId}`); - if (!key || value === undefined) - return res.status(400).send({ error: "Missing property or value" }); - if (!key || value === undefined) - return res.status(400).send({ error: "Missing property or value" }); + if (!key || value === undefined) return res.status(400).send({ error: 'Missing property or value' }); + if (!key || value === undefined) return res.status(400).send({ error: 'Missing property or value' }); return UserProfile.findById(userId) .then((user) => { @@ -619,11 +612,11 @@ const userProfileController = function (UserProfile) { return user .save() .then(() => { - res.status(200).send({ message: "updated property" }); + 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) { @@ -631,24 +624,24 @@ const userProfileController = function (UserProfile) { const { requestor } = req.body; if (!mongoose.Types.ObjectId.isValid(userId)) { return res.status(400).send({ - error: "Bad Request", + error: 'Bad Request', }); } // Verify correct params in body if ( - !req.body.currentpassword || - !req.body.newpassword || - !req.body.confirmnewpassword + !req.body.currentpassword + || !req.body.newpassword + || !req.body.confirmnewpassword ) { return res.status(400).send({ - error: "One of more required fields are missing", + error: 'One of more required fields are missing', }); } // Verify request is authorized by self or adminsitrator if ( - !userId === requestor.requestorId && - !(await hasPermission(req.body.requestor, "updatePassword")) + !userId === requestor.requestorId + && !(await hasPermission(req.body.requestor, 'updatePassword')) ) { return res.status(403).send({ error: "You are unauthorized to update this user's password", @@ -665,25 +658,25 @@ const userProfileController = function (UserProfile) { if (req.body.newpassword !== req.body.confirmnewpassword) { res.status(400).send({ - error: "New and confirm new passwords are not same", + error: 'New and confirm new passwords are not same', }); } // Verify old and new passwords are not same if (req.body.currentpassword === req.body.newpassword) { res.status(400).send({ - error: "Old and new passwords should not be same", + error: 'Old and new passwords should not be same', }); } - return UserProfile.findById(userId, "password") + return UserProfile.findById(userId, 'password') .then((user) => { bcrypt .compare(req.body.currentpassword, user.password) .then((passwordMatch) => { if (!passwordMatch) { return res.status(400).send({ - error: "Incorrect current password", + error: 'Incorrect current password', }); } @@ -693,18 +686,18 @@ const userProfileController = function (UserProfile) { }); return user .save() - .then(() => res.status(200).send({ message: "updated password" })) - .catch((error) => res.status(500).send(error)); + .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)); }; const getreportees = async function (req, res) { if (!mongoose.Types.ObjectId.isValid(req.params.userId)) { res.status(400).send({ - error: "Bad request", + error: 'Bad request', }); return; } @@ -712,16 +705,16 @@ const userProfileController = function (UserProfile) { const userid = mongoose.Types.ObjectId(req.params.userId); let validroles = [ - "Volunteer", - "Manager", - "Administrator", - "Core Team", - "Owner", - "Mentor", + 'Volunteer', + 'Manager', + 'Administrator', + 'Core Team', + 'Owner', + 'Mentor', ]; - if (await hasPermission(req.body.requestor, "getReporteesLimitRoles")) { - validroles = ["Volunteer", "Manager"]; + if (await hasPermission(req.body.requestor, 'getReporteesLimitRoles')) { + validroles = ['Volunteer', 'Manager']; } userHelper @@ -737,13 +730,13 @@ 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) { if (!mongoose.Types.ObjectId.isValid(req.params.userId)) { res.status(400).send({ - error: "Bad request", + error: 'Bad request', }); return; } @@ -754,14 +747,14 @@ 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) { const { userId } = req.params; if (mongoose.Types.ObjectId.isValid(userId)) { - UserProfile.findById(userId, "firstName lastName") + UserProfile.findById(userId, 'firstName lastName') .then((result) => { const name = `${result.firstName} ${result.lastName}`; res.status(200).send({ @@ -773,30 +766,30 @@ const userProfileController = function (UserProfile) { }); } else { res.status(400).send({ - error: "Bad request", + error: 'Bad request', }); } }; const changeUserStatus = async function (req, res) { const { userId } = req.params; - const status = req.body.status === "Active"; + const status = req.body.status === 'Active'; const activationDate = req.body.reactivationDate; const { endDate } = req.body; - const isSet = req.body.isSet === "FinalDay"; + const isSet = req.body.isSet === 'FinalDay'; if (!mongoose.Types.ObjectId.isValid(userId)) { res.status(400).send({ - error: "Bad Request", + error: 'Bad Request', }); return; } - if (!(await hasPermission(req.body.requestor, "changeUserStatus"))) { - res.status(403).send("You are not authorized to change user status"); + if (!(await hasPermission(req.body.requestor, 'changeUserStatus'))) { + res.status(403).send('You are not authorized to change user status'); return; } cache.removeCache(`user-${userId}`); - UserProfile.findById(userId, "isActive") + UserProfile.findById(userId, 'isActive') .then((user) => { user.set({ isActive: status, @@ -807,11 +800,11 @@ const userProfileController = function (UserProfile) { user .save() .then(() => { - const isUserInCache = cache.hasCache("allusers"); + const isUserInCache = cache.hasCache('allusers'); if (isUserInCache) { - const allUserData = JSON.parse(cache.getCache("allusers")); + const allUserData = JSON.parse(cache.getCache('allusers')); const userIdx = allUserData.findIndex( - (users) => users._id === userId + users => users._id === userId, ); const userData = allUserData[userIdx]; if (!status) { @@ -819,10 +812,10 @@ const userProfileController = function (UserProfile) { } userData.isActive = user.isActive; allUserData.splice(userIdx, 1, userData); - cache.setCache("allusers", JSON.stringify(allUserData)); + cache.setCache('allusers', JSON.stringify(allUserData)); } res.status(200).send({ - message: "status updated", + message: 'status updated', }); }) .catch((error) => { @@ -837,7 +830,7 @@ const userProfileController = function (UserProfile) { const resetPassword = function (req, res) { ValidatePassword(req); - UserProfile.findById(req.params.userId, "password") + UserProfile.findById(req.params.userId, 'password') .then((user) => { user.set({ password: req.body.newpassword, @@ -846,7 +839,7 @@ const userProfileController = function (UserProfile) { .save() .then(() => { res.status(200).send({ - message: " password Reset", + message: ' password Reset', }); }) .catch((error) => { @@ -860,7 +853,7 @@ const userProfileController = function (UserProfile) { const getAllUsersWithFacebookLink = function (req, res) { try { - UserProfile.find({ "personalLinks.Name": "Facebook" }).then((results) => { + UserProfile.find({ 'personalLinks.Name': 'Facebook' }).then((results) => { res.status(200).send(results); }); } catch (error) { @@ -872,7 +865,7 @@ const userProfileController = function (UserProfile) { const user = await UserProfile.findById(req.params.userId); if (!user) { - res.status(403).send({ message: "User does not exist" }); + res.status(403).send({ message: 'User does not exist' }); return; } From 03686ad637011d3702f0c7668b77f7074a83febd Mon Sep 17 00:00:00 2001 From: luisarevalo21 Date: Thu, 9 Nov 2023 20:49:51 -0800 Subject: [PATCH 4/4] resolved merge conflict --- package-lock.json | 2 +- src/models/userProfile.js | 99 ++++++++++++++++++++++----------------- 2 files changed, 58 insertions(+), 43 deletions(-) diff --git a/package-lock.json b/package-lock.json index 3fcc98986..97de1f352 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5536,7 +5536,7 @@ "lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==" + "integrity": "sha1-gteb/zCmfEAF/9XiUVMArZyk168=" }, "lodash.merge": { "version": "4.6.2", diff --git a/src/models/userProfile.js b/src/models/userProfile.js index d1bd7db88..7fc388e98 100644 --- a/src/models/userProfile.js +++ b/src/models/userProfile.js @@ -1,9 +1,9 @@ -const mongoose = require('mongoose'); -const moment = require('moment-timezone'); +const mongoose = require("mongoose"); +const moment = require("moment-timezone"); const { Schema } = mongoose; -const validate = require('mongoose-validator'); -const bcrypt = require('bcryptjs'); +const validate = require("mongoose-validator"); +const bcrypt = require("bcryptjs"); const SALT_ROUNDS = 10; const nextDay = new Date(); @@ -15,11 +15,12 @@ const userProfileSchema = new Schema({ required: true, validate: { validator(v) { - const passwordregex = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/; + const passwordregex = + /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/; return passwordregex.test(v); }, message: - '{VALUE} is not a valid password!password should be at least 8 charcaters long with uppercase, lowercase and number/special char.', + "{VALUE} is not a valid password!password should be at least 8 charcaters long with uppercase, lowercase and number/special char.", }, }, isActive: { type: Boolean, required: true, default: true }, @@ -47,7 +48,9 @@ const userProfileSchema = new Schema({ type: String, required: true, unique: true, - validate: [validate({ validator: 'isEmail', message: 'Email address is invalid' })], + validate: [ + validate({ validator: "isEmail", message: "Email address is invalid" }), + ], }, weeklycommittedHours: { type: Number, default: 10 }, weeklycommittedHoursHistory: [ @@ -60,13 +63,15 @@ const userProfileSchema = new Schema({ createdDate: { type: Date, required: true, default: nextDay }, lastModifiedDate: { type: Date, required: true, default: Date.now() }, reactivationDate: { type: Date }, - personalLinks: [{ _id: Schema.Types.ObjectId, Name: String, Link: { type: String } }], + personalLinks: [ + { _id: Schema.Types.ObjectId, Name: String, Link: { type: String } }, + ], adminLinks: [{ _id: Schema.Types.ObjectId, Name: String, Link: String }], - teams: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'team' }], - projects: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'project' }], + teams: [{ type: mongoose.SchemaTypes.ObjectId, ref: "team" }], + projects: [{ type: mongoose.SchemaTypes.ObjectId, ref: "project" }], badgeCollection: [ { - badge: { type: mongoose.SchemaTypes.ObjectId, ref: 'badge' }, + badge: { type: mongoose.SchemaTypes.ObjectId, ref: "badge" }, count: { type: Number, default: 0 }, earnedDate: { type: Array, default: [] }, lastModified: { type: Date, required: true, default: Date.now() }, @@ -79,11 +84,17 @@ const userProfileSchema = new Schema({ ], profilePic: { type: String }, infringements: [ - { date: { type: String, required: true }, description: { type: String, required: true } }, + { + date: { type: String, required: true }, + description: { type: String, required: true }, + }, ], - location: { type: String, default: '' }, + location: { type: String, default: "" }, oldInfringements: [ - { date: { type: String, required: true }, description: { type: String, required: true } }, + { + date: { type: String, required: true }, + description: { type: String, required: true }, + }, ], privacySettings: { blueSquares: { type: Boolean, default: true }, @@ -95,7 +106,7 @@ const userProfileSchema = new Schema({ dueDate: { type: Date, required: true, - default: moment().tz('America/Los_Angeles').endOf('week'), + default: moment().tz("America/Los_Angeles").endOf("week"), }, summary: { type: String }, uploadDate: { type: Date }, @@ -125,17 +136,17 @@ const userProfileSchema = new Schema({ category: { type: String, enum: [ - 'Food', - 'Energy', - 'Housing', - 'Education', - 'Society', - 'Economics', - 'Stewardship', - 'Other', - 'Unspecified', + "Food", + "Energy", + "Housing", + "Education", + "Society", + "Economics", + "Stewardship", + "Other", + "Unspecified", ], - default: 'Other', + default: "Other", }, hrs: { type: Number, default: 0 }, }, @@ -143,52 +154,56 @@ const userProfileSchema = new Schema({ savedTangibleHrs: [Number], timeEntryEditHistory: [ { - date: { type: Date, required: true, default: moment().tz('America/Los_Angeles').toDate() }, + date: { + type: Date, + required: true, + default: moment().tz("America/Los_Angeles").toDate(), + }, initialSeconds: { type: Number, required: true }, newSeconds: { type: Number, required: true }, }, ], weeklySummaryNotReq: { type: Boolean, default: false }, - timeZone: { type: String, required: true, default: 'America/Los_Angeles' }, + timeZone: { type: String, required: true, default: "America/Los_Angeles" }, isVisible: { type: Boolean, default: false }, weeklySummaryOption: { type: String }, - bioPosted: { type: String, default: 'default' }, + bioPosted: { type: String, default: "default" }, isFirstTimelog: { type: Boolean, default: true }, -<<<<<<< HEAD - teamCode: { type: String, default: '' }, -======= teamCode: { type: String, - default: '', + default: "", validate: { validator(v) { const teamCoderegex = /^([a-zA-Z]-[a-zA-Z]{3}|[a-zA-Z]{5})$|^$/; return teamCoderegex.test(v); }, - message: - 'Please enter a code in the format of A-AAA or AAAAA', + message: "Please enter a code in the format of A-AAA or AAAAA", }, }, ->>>>>>> development infoCollections: [ { - areaName: { type: String }, + areaName: { type: String }, areaContent: { type: String }, - }], + }, + ], }); -userProfileSchema.pre('save', function (next) { +userProfileSchema.pre("save", function (next) { const user = this; - if (!user.isModified('password')) return next(); + if (!user.isModified("password")) return next(); return bcrypt .genSalt(SALT_ROUNDS) - .then(result => bcrypt.hash(user.password, result)) + .then((result) => bcrypt.hash(user.password, result)) .then((hash) => { user.password = hash; return next(); }) - .catch(error => next(error)); + .catch((error) => next(error)); }); -module.exports = mongoose.model('userProfile', userProfileSchema, 'userProfiles'); +module.exports = mongoose.model( + "userProfile", + userProfileSchema, + "userProfiles" +);