diff --git a/package-lock.json b/package-lock.json index af31874d5..442b76f5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3580,14 +3580,23 @@ } }, "eslint-config-airbnb-base": { - "version": "13.2.0", - "resolved": "https://registry.npmjs.org/eslint-config-airbnb-base/-/eslint-config-airbnb-base-13.2.0.tgz", - "integrity": "sha512-1mg/7eoB4AUeB0X1c/ho4vb2gYkNH8Trr/EgCT/aGmKhhG+F6vF5s8+iRBlWAzFIAphxIdp3YfEKgEl0f9Xg+w==", + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/eslint-config-airbnb-base/-/eslint-config-airbnb-base-15.0.0.tgz", + "integrity": "sha512-xaX3z4ZZIcFLvh2oUNvcX5oEofXda7giYmuplVxoOg5A7EXJMrUyqRgR+mhDhPK8LZ4PttFOBvCYDbX3sUoUig==", "dev": true, "requires": { - "confusing-browser-globals": "^1.0.5", - "object.assign": "^4.1.0", - "object.entries": "^1.1.0" + "confusing-browser-globals": "^1.0.10", + "object.assign": "^4.1.2", + "object.entries": "^1.1.5", + "semver": "^6.3.0" + }, + "dependencies": { + "semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true + } } }, "eslint-import-resolver-babel-module": { diff --git a/package.json b/package.json index e7fbd6307..cf8c708f2 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@types/node": "^8.10.61", "eslint": "^8.47.0", "eslint-config-airbnb": "^19.0.4", - "eslint-config-airbnb-base": "^13.1.0", + "eslint-config-airbnb-base": "^15.0.0", "eslint-import-resolver-babel-module": "^5.3.1", "eslint-plugin-import": "^2.28.0", "eslint-plugin-jsx-a11y": "^6.7.1", diff --git a/src/controllers/actionItemController.js b/src/controllers/actionItemController.js index 42777cfad..f694013d4 100644 --- a/src/controllers/actionItemController.js +++ b/src/controllers/actionItemController.js @@ -36,7 +36,6 @@ const actionItemController = function (ActionItem) { _actionItem.assignedTo = req.body.assignedTo; _actionItem.createdBy = req.body.requestor.requestorId; - _actionItem.save() .then((result) => { notificationhelper.notificationcreated(requestorId, assignedTo, _actionItem.description); @@ -58,7 +57,6 @@ const actionItemController = function (ActionItem) { const deleteactionItem = async function (req, res) { const actionItemId = mongoose.Types.ObjectId(req.params.actionItemId); - const _actionItem = await ActionItem.findById(actionItemId) .catch((error) => { res.status(400).send(error); @@ -109,10 +107,9 @@ const actionItemController = function (ActionItem) { _actionItem.save() .then(res.status(200).send('Saved')) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }; - return { getactionItem, postactionItem, diff --git a/src/controllers/badgeController.js b/src/controllers/badgeController.js index eae0039c9..316230ccb 100644 --- a/src/controllers/badgeController.js +++ b/src/controllers/badgeController.js @@ -7,11 +7,21 @@ const cache = require('../utilities/nodeCache')(); const logger = require('../startup/logger'); const badgeController = function (Badge) { + /** + * getAllBadges handles badges retrieval. + * @param {Object} req - Request object. + * @returns {Array} List containing badge records. + */ const getAllBadges = async function (req, res) { if (!(await hasPermission(req.body.requestor, 'seeBadges'))) { res.status(403).send('You are not authorized to view all badge data.'); return; } + // Add cache to reduce database query and optimize performance + if (cache.hasCache('allBadges')) { + res.status(200).send(cache.getCache('allBadges')); + return; + } Badge.find( {}, @@ -25,16 +35,19 @@ const badgeController = function (Badge) { ranking: 1, badgeName: 1, }) - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send(error)); + .then((results) => { + cache.setCache('allBadges', results); + res.status(200).send(results); + }) + .catch((error) => res.status(500).send(error)); }; /** - * Updated Date: 12/06/2023 + * Updated Date: 01/12/2024 * Updated By: Shengwei * Function added: * - Added data validation for earned date and badge count mismatch. - * - Added fillEarnedDateToMatchCount function to resolve earned date and badge count mismatch. + * - Added fillEarnedDateToMatchCount function to resolve earned date and badge count mismatch. (Deleted due to new requirement) * - Refactored data validation for duplicate badge id. * - Added data validation for badge count should greater than 0. * - Added formatDate function to format date to MMM-DD-YY. @@ -45,14 +58,6 @@ const badgeController = function (Badge) { return moment(currentDate).tz('America/Los_Angeles').format('MMM-DD-YY'); }; - const fillEarnedDateToMatchCount = (earnedDate, count) => { - const result = [...earnedDate]; - while (result.length < count) { - result.push(formatDate()); - } - return result; - }; - const assignBadges = async function (req, res) { if (!(await hasPermission(req.body.requestor, 'assignBadges'))) { res.status(403).send('You are not authorized to assign badges.'); @@ -75,32 +80,16 @@ const badgeController = function (Badge) { newBadgeCollection = req.body.badgeCollection.map((element) => { if (badgeCounts[element.badge]) { throw new Error('Duplicate badges sent in.'); - // res.status(500).send('Duplicate badges sent in.'); - // return; } badgeCounts[element.badge] = element.count; // Validation: count should be greater than 0 if (element.count < 1) { throw new Error('Badge count should be greater than 0.'); } - if (element.count !== element.earnedDate.length) { - element.earnedDate = fillEarnedDateToMatchCount( - element.earnedDate, - element.count, - ); - element.lastModified = Date.now(); - logger.logInfo( - `Badge count and earned dates mismatched found. ${Date.now()} was generated for user ${userToBeAssigned}. Badge record ID ${ - element._id - }; Badge Type ID ${element.badge}`, - ); - } - return element; }); } catch (err) { - res - .status(500) - .send(`Internal Error: Badge Collection. ${err.message}`); + logger.logException(`Internal Error: Badge Collection. ${err.message} User ID: ${userToBeAssigned} Badge Collection: ${JSON.stringify(req.body.badgeCollection)}`); + res.status(500).send(`Internal Error: Badge Collection. ${ err.message}`); return; } record.badgeCollection = newBadgeCollection; @@ -158,8 +147,14 @@ const badgeController = function (Badge) { badge .save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(500).send(errors)); + .then((results) => { + // remove cache after new badge is saved + if (cache.getCache('allBadges')) { + cache.removeCache('allBadges'); + } + res.status(201).send(results); + }) + .catch((errors) => res.status(500).send(errors)); }); }; @@ -183,11 +178,15 @@ const badgeController = function (Badge) { const deleteRecord = record.remove(); Promise.all([removeBadgeFromProfile, deleteRecord]) - .then( + .then(() => { + // remove cache after new badge is deleted + if (cache.getCache('allBadges')) { + cache.removeCache('allBadges'); + } res.status(200).send({ message: 'Badge successfully deleted and user profiles updated', - }), - ) + }); + }) .catch((errors) => { res.status(500).send(errors); }); @@ -234,6 +233,10 @@ const badgeController = function (Badge) { res.status(400).send({ error: 'No valid records found' }); return; } + // remove cache after new badge is updated + if (cache.getCache('allBadges')) { + cache.removeCache('allBadges'); + } res.status(200).send({ message: 'Badge successfully updated' }); }); }; diff --git a/src/controllers/bmdashboard/bmConsumableController.js b/src/controllers/bmdashboard/bmConsumableController.js index 40d87fcdc..4125cfb2d 100644 --- a/src/controllers/bmdashboard/bmConsumableController.js +++ b/src/controllers/bmdashboard/bmConsumableController.js @@ -31,7 +31,7 @@ const bmConsumableController = function (BuildingConsumable) { .then((result) => { res.status(200).send(result); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } diff --git a/src/controllers/bmdashboard/bmInventoryTypeController.js b/src/controllers/bmdashboard/bmInventoryTypeController.js index 1a5755d59..81ac38146 100644 --- a/src/controllers/bmdashboard/bmInventoryTypeController.js +++ b/src/controllers/bmdashboard/bmInventoryTypeController.js @@ -14,8 +14,8 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp MatType .find() .exec() - .then(result => res.status(200).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(200).send(result)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -26,8 +26,8 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp ToolType .find() .exec() - .then(result => res.status(200).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(200).send(result)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -55,7 +55,6 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp } }; - async function addMaterialType(req, res) { const { name, @@ -118,7 +117,7 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp }); } }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (error) { res.status(500).send(error); } @@ -142,8 +141,8 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp SelectedType .find() .exec() - .then(result => res.status(200).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(200).send(result)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -182,7 +181,7 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp }); } }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (error) { res.status(500).send(error); } diff --git a/src/controllers/bmdashboard/bmMaterialsController.js b/src/controllers/bmdashboard/bmMaterialsController.js index 207e2428a..1757ab8dd 100644 --- a/src/controllers/bmdashboard/bmMaterialsController.js +++ b/src/controllers/bmdashboard/bmMaterialsController.js @@ -29,8 +29,8 @@ const bmMaterialsController = function (BuildingMaterial) { }, ]) .exec() - .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)); } catch (err) { res.json(err); } @@ -74,7 +74,7 @@ const bmMaterialsController = function (BuildingMaterial) { BuildingMaterial .create(newDoc) .then(() => res.status(201).send()) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); return; } BuildingMaterial @@ -84,7 +84,7 @@ const bmMaterialsController = function (BuildingMaterial) { ) .exec() .then(() => res.status(201).send()) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (error) { res.status(500).send(error); } @@ -132,7 +132,7 @@ const bmMaterialsController = function (BuildingMaterial) { ) .then((results) => { res.status(200).send(results); }) - .catch(error => res.status(500).send({ message: error })); + .catch((error) => res.status(500).send({ message: error })); } }; @@ -183,7 +183,7 @@ const bmMaterialsController = function (BuildingMaterial) { res.status(500).send('Stock quantities submitted seems to be invalid'); return; } - const updatePromises = updateRecordsToBeAdded.map(updateItem => BuildingMaterial.updateOne( + const updatePromises = updateRecordsToBeAdded.map((updateItem) => BuildingMaterial.updateOne( { _id: updateItem.updateId }, { $set: updateItem.set, @@ -194,7 +194,7 @@ const bmMaterialsController = function (BuildingMaterial) { .then((results) => { res.status(200).send({ result: `Successfully posted log for ${results.length} Material records.` }); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } diff --git a/src/controllers/bmdashboard/bmNewLessonController.js b/src/controllers/bmdashboard/bmNewLessonController.js index 526e467f1..c2e24f286 100644 --- a/src/controllers/bmdashboard/bmNewLessonController.js +++ b/src/controllers/bmdashboard/bmNewLessonController.js @@ -8,8 +8,8 @@ const bmNewLessonController = function (BuildingNewLesson) { BuildingNewLesson .find() .populate() - .then(result => res.status(200).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(200).send(result)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -17,8 +17,8 @@ const bmNewLessonController = function (BuildingNewLesson) { const bmPostLessonList = async (req, res) => { try { const newLesson = BuildingNewLesson.create(req.body) - .then(result => res.status(201).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(201).send(result)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -47,7 +47,7 @@ const bmNewLessonController = function (BuildingNewLesson) { // Extract only allowed fields (content, tag, relatedProject and title) const allowedFields = ['content', 'tags', 'relatedProject', 'title', 'allowedRoles', 'files']; const filteredUpdateData = Object.keys(updateData) - .filter(key => allowedFields.includes(key)) + .filter((key) => allowedFields.includes(key)) .reduce((obj, key) => { obj[key] = updateData[key]; return obj; @@ -87,7 +87,6 @@ const bmNewLessonController = function (BuildingNewLesson) { // return; // } - try { const deletedLesson = await BuildingNewLesson.findByIdAndDelete(lessonId); @@ -104,30 +103,30 @@ const bmNewLessonController = function (BuildingNewLesson) { const likeLesson = async (req, res) => { const { lessonId } = req.params; const { userId } = req.body; - + try { const existingLike = await Like.findOne({ user: userId, lesson: lessonId }); - + if (existingLike) { // User has already liked the lesson, handle unlike await Like.findByIdAndDelete(existingLike._id); await BuildingNewLesson.findByIdAndUpdate(lessonId, { $pull: { likes: existingLike._id } }); - + // Decrement total likes count await BuildingNewLesson.findByIdAndUpdate(lessonId, { $inc: { totalLikes: -1 } }); - + return res.status(200).json({ status: 'success', message: 'Lesson unliked successfully' }); } - + // User has not liked the lesson, handle like const newLike = new Like({ user: userId, lesson: lessonId }); await newLike.save(); - + await BuildingNewLesson.findByIdAndUpdate(lessonId, { $push: { likes: newLike._id } }); - + // Increment total likes count await BuildingNewLesson.findByIdAndUpdate(lessonId, { $inc: { totalLikes: 1 } }); - + return res.status(200).json({ status: 'success', message: 'Lesson liked successfully' }); } catch (error) { console.error('Error liking/unliking lesson:', error); @@ -135,7 +134,7 @@ const bmNewLessonController = function (BuildingNewLesson) { } }; return { - bmPostLessonList, bmGetLessonList, bmGetSingleLesson, bmDeleteSingleLesson, bmEditSingleLesson, likeLesson + bmPostLessonList, bmGetLessonList, bmGetSingleLesson, bmDeleteSingleLesson, bmEditSingleLesson, likeLesson, }; }; diff --git a/src/controllers/bmdashboard/bmProjectController.js b/src/controllers/bmdashboard/bmProjectController.js index a4f6712e0..1b9237c44 100644 --- a/src/controllers/bmdashboard/bmProjectController.js +++ b/src/controllers/bmdashboard/bmProjectController.js @@ -78,7 +78,7 @@ const bmMProjectController = function (BuildingProject) { }); res.status(200).send(results); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (err) { res.status(500).send(err); } @@ -105,7 +105,7 @@ const bmMProjectController = function (BuildingProject) { }, ]) .exec() - .then(project => res.status(200).send(project)) + .then((project) => res.status(200).send(project)) // TODO: uncomment this block to execute the auth check // authenticate request by comparing userId param with buildingManager id field // Note: _id has type object and must be converted to string @@ -117,7 +117,7 @@ const bmMProjectController = function (BuildingProject) { // } // return res.status(200).send(project); // }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } diff --git a/src/controllers/bmdashboard/bmToolController.js b/src/controllers/bmdashboard/bmToolController.js index c620255b7..e62153875 100644 --- a/src/controllers/bmdashboard/bmToolController.js +++ b/src/controllers/bmdashboard/bmToolController.js @@ -46,8 +46,8 @@ const bmToolController = (BuildingTool) => { }, ]) .exec() - .then(tool => res.status(200).send(tool)) - .catch(error => res.status(500).send(error)); + .then((tool) => res.status(200).send(tool)) + .catch((error) => res.status(500).send(error)); } catch (err) { res.json(err); } @@ -84,7 +84,7 @@ const bmToolController = (BuildingTool) => { BuildingTool .create(newDoc) .then(() => res.status(201).send()) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); return; } @@ -95,7 +95,7 @@ const bmToolController = (BuildingTool) => { ) .exec() .then(() => res.status(201).send()) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); } catch (error) { res.status(500).send(error); } diff --git a/src/controllers/dashBoardController.js b/src/controllers/dashBoardController.js index 2ad0065ad..660922e07 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -23,7 +23,7 @@ const dashboardcontroller = function () { return User.findOneAndUpdate( { _id: req.params.userId }, { copiedAiPrompt: Date.now() }, - { new: true } + { new: true }, ) .then((user) => { if (user) { @@ -51,7 +51,7 @@ const dashboardcontroller = function () { ...req.body, aIPromptText: req.body.aIPromptText, modifiedDatetime: Date.now(), - } + }, ) .then(() => { res.status(200).send("Successfully saved AI prompt."); @@ -90,7 +90,7 @@ 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) { @@ -112,7 +112,7 @@ const dashboardcontroller = function () { const laborthisweek = dashboardhelper.laborthisweek( userId, req.params.fromDate, - req.params.toDate + req.params.toDate, ); laborthisweek.then((results) => { res.status(200).send(results); @@ -155,7 +155,7 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ) { const text = `New Bug Report From ${firstName} ${lastName}:

[Feature Name] Bug Title:

@@ -200,7 +200,7 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ); try { @@ -208,7 +208,7 @@ const dashboardcontroller = function () { "onecommunityglobal@gmail.com", `Bug Rport from ${firstName} ${lastName}`, emailBody, - email + email, ); res.status(200).send("Success"); } catch { @@ -235,7 +235,7 @@ const dashboardcontroller = function () { if (suggestionData.field.length) { fieldaaray = suggestionData.field.map( (item) => `

${item}

-

${args[3][item]}

` +

${args[3][item]}

`, ); } const text = `New Suggestion From ${args[3].firstName} ${ @@ -263,13 +263,15 @@ const dashboardcontroller = function () { // send suggestion email const sendMakeSuggestion = async (req, res) => { - const { suggestioncate, suggestion, confirm, email, ...rest } = req.body; + const { + suggestioncate, suggestion, confirm, email, ...rest +} = req.body; const emailBody = await getsuggestionEmailBody( suggestioncate, suggestion, confirm, rest, - email + email, ); try { emailSender( @@ -279,7 +281,7 @@ const dashboardcontroller = function () { null, null, email, - null + null, ); res.status(200).send("Success"); } catch { @@ -308,7 +310,7 @@ const dashboardcontroller = function () { } 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 { @@ -317,7 +319,7 @@ const dashboardcontroller = function () { } if (req.body.action === "delete") { suggestionData.field = suggestionData.field.filter( - (item) => item !== req.body.newField + (item) => item !== req.body.newField, ); } } diff --git a/src/controllers/forgotPwdcontroller.js b/src/controllers/forgotPwdcontroller.js index 056974afb..a7a252784 100644 --- a/src/controllers/forgotPwdcontroller.js +++ b/src/controllers/forgotPwdcontroller.js @@ -3,7 +3,6 @@ const emailSender = require('../utilities/emailSender'); const logger = require('../startup/logger'); const escapeRegex = require('../utilities/escapeRegex'); - function getEmailMessageForForgotPassword(user, ranPwd) { const message = ` Hello ${user.firstName} ${user.lastName},

Congratulations on successfully completing the Highest Good Network 3-question Change My Password Challenge. Your reward is this NEW PASSWORD!

diff --git a/src/controllers/informationController.js b/src/controllers/informationController.js index a0462ee31..92c0a7855 100644 --- a/src/controllers/informationController.js +++ b/src/controllers/informationController.js @@ -2,16 +2,25 @@ const mongoose = require('mongoose'); // const userProfile = require('../models/userProfile'); // const hasPermission = require('../utilities/permissions'); const escapeRegex = require('../utilities/escapeRegex'); - +const cache = require('../utilities/nodeCache')(); const informationController = function (Information) { const getInformations = function (req, res) { + // return all informations if cache is available + if (cache.hasCache('informations')) { + res.status(200).send(cache.getCache('informations')); + return; + } + Information.find({}, 'infoName infoContent visibility') - .then(results => res.status(200).send(results)) - .catch(error => res.status(404).send(error)); + .then((results) => { + // cache results + cache.setCache('informations', results); + res.status(200).send(results); + }) + .catch((error) => res.status(404).send(error)); }; - const addInformation = function (req, res) { Information.find({ infoName: { $regex: escapeRegex(req.body.infoName), $options: 'i' } }) .then((result) => { @@ -24,22 +33,44 @@ const informationController = function (Information) { _info.infoContent = req.body.infoContent || 'Unspecified'; _info.visibility = req.body.visibility || '0'; _info.save() - .then(newInformation => res.status(201).send(newInformation)) - .catch(error => res.status(400).send(error)); + .then((newInformation) => { + // remove cache if cache is available + if (cache.hasCache('informations')) { + cache.removeCache('informations'); + return; + } + res.status(201).send(newInformation); + }) + .catch((error) => res.status(400).send(error)); }) - .catch(error => res.status(500).send({ error })); + .catch((error) => res.status(500).send({ error })); }; + const deleteInformation = function (req, res) { Information.findOneAndDelete({ _id: req.params.id }) - .then(deletedInformation => res.status(200).send(deletedInformation)) - .catch(error => res.status(400).send(error)); + .then((deletedInformation) => { + // remove cache if cache is available + if (cache.hasCache('informations')) { + cache.removeCache('informations'); + return; + } + res.status(200).send(deletedInformation); + }) + .catch((error) => res.status(400).send(error)); }; // Update existing information by id const updateInformation = function (req, res) { Information.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true }) - .then(updatedInformation => res.status(200).send(updatedInformation)) - .catch(error => res.status(400).send(error)); + .then((updatedInformation) => { + // remove cache if cache is available + if (cache.hasCache('informations')) { + cache.removeCache('informations'); + return; + } + res.status(200).send(updatedInformation); + }) + .catch((error) => res.status(400).send(error)); }; return { @@ -50,5 +81,4 @@ const informationController = function (Information) { }; }; - module.exports = informationController; diff --git a/src/controllers/inventoryController.js b/src/controllers/inventoryController.js index 10ec43785..02aedf578 100644 --- a/src/controllers/inventoryController.js +++ b/src/controllers/inventoryController.js @@ -35,8 +35,8 @@ const inventoryController = function (Item, ItemType) { .sort({ wasted: 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 postInvInProjectWBS = async function (req, res) { @@ -80,10 +80,11 @@ const inventoryController = function (Item, ItemType) { const inventoryItem = new Item(data); return inventoryItem.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(500).send(errors)); } - return Item.findOneAndUpdate({ + return Item.findOneAndUpdate( +{ project: mongoose.Types.ObjectId(req.params.projectId), wbs: req.params.wbsId && req.params.wbsId !== 'Unassigned' ? mongoose.Types.ObjectId(req.params.wbsId) @@ -97,16 +98,17 @@ const inventoryController = function (Item, ItemType) { notes: { quantity: req.body.quantity, typeOfMovement: 'Purchased', message: `Created ${req.body.quantity} on ${moment(Date.now()).format('MM/DD/YYYY')} note: ${req.body.notes}` }, poNums: req.body.poNum, }, - }, { new: true }) + }, +{ new: true }, +) .then((results) => { Item.findByIdAndUpdate(results._id, { costPer: results.quantity !== 0 ? results.cost / results.quantity : 0 }, { new: true }) - .then(result => res.status(201).send(result)); + .then((result) => res.status(201).send(result)); }); } return res.status(400).send('Valid Project, Quantity and Type Id are necessary as well as valid wbs if sent in and not Unassigned'); }; - const getAllInvInProject = async function (req, res) { if (!await hasPermission(req.body.requestor, 'getAllInvInProject')) { return res.status(403).send('You are not authorized to view inventory data.'); @@ -135,8 +137,8 @@ const inventoryController = function (Item, ItemType) { .sort({ wasted: 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 postInvInProject = async function (req, res) { @@ -169,11 +171,12 @@ const inventoryController = function (Item, ItemType) { const inventoryItem = new Item(data); return inventoryItem.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(500).send(errors)); } // if item does exist we will update it - return Item.findOneAndUpdate({ + return Item.findOneAndUpdate( +{ project: mongoose.Types.ObjectId(req.params.projectId), wbs: null, inventoryItemType: req.body.typeId || req.body.typeID, wasted: false, }, { @@ -182,12 +185,14 @@ const inventoryController = function (Item, ItemType) { notes: { quantity: req.body.quantity, typeOfMovement: 'Purchased', message: `Created ${req.body.quantity} on ${moment(Date.now()).format('MM/DD/YYYY')} note: ${req.body.notes}` }, poNums: req.body.poNum, }, - }, { new: true }) + }, +{ new: true }, +) .then((results) => { // new call to update the costPer using the new quantities and cost Item.findByIdAndUpdate(results._id, { costPer: results.quantity !== 0 ? results.cost / results.quantity : 0 }, { new: true }) - .then(result => res.status(201).send(result)) - .catch(errors => res.status(500).send(errors)); + .then((result) => res.status(201).send(result)) + .catch((errors) => res.status(500).send(errors)); }); } return res.status(400).send('Valid Project, Quantity and Type Id are necessary'); @@ -251,9 +256,9 @@ const inventoryController = function (Item, ItemType) { }, }, { new: true }).then((results) => { Item.findByIdAndUpdate(results._id, { costPer: results.quantity !== 0 ? results.cost / results.quantity : 0 }, { new: true }) - .then(result => res.status(201).send(result)) - .catch(errors => res.status(500).send(errors)); - }).catch(errors => res.status(500).send(errors)); + .then((result) => res.status(201).send(result)) + .catch((errors) => res.status(500).send(errors)); + }).catch((errors) => res.status(500).send(errors)); } const data = { quantity: req.body.quantity, @@ -271,17 +276,16 @@ const inventoryController = function (Item, ItemType) { const inventoryItem = new Item(data); return inventoryItem.save() - .then(results => res.status(201).send({ from: prevResults, to: results })) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send({ from: prevResults, to: results })) + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); } return res.status(400).send('Valid Project, Quantity and Type Id are necessary as well as valid wbs if sent in and not Unassigned'); }; - const delInvById = async function (req, res) { if (!await hasPermission(req.body.requestor, 'delInvById')) { return res.status(403).send('You are not authorized to waste inventory.'); @@ -341,9 +345,9 @@ const inventoryController = function (Item, ItemType) { }, }, { new: true }).then((results) => { Item.findByIdAndUpdate(results._id, { costPer: results.quantity !== 0 ? results.cost / results.quantity : 0 }, { new: true }) - .then(result => res.status(201).send(result)) - .catch(errors => res.status(500).send(errors)); - }).catch(errors => res.status(500).send(errors)); + .then((result) => res.status(201).send(result)) + .catch((errors) => res.status(500).send(errors)); + }).catch((errors) => res.status(500).send(errors)); } const data = { quantity: req.body.quantity, @@ -361,12 +365,12 @@ const inventoryController = function (Item, ItemType) { const inventoryItem = new Item(data); return inventoryItem.save() - .then(results => res.status(201).send({ from: prevResults, to: results })) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send({ from: prevResults, to: results })) + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); } return res.status(400).send('Valid Project, Quantity and Type Id are necessary as well as valid wbs if sent in and not Unassigned'); }; @@ -422,9 +426,9 @@ const inventoryController = function (Item, ItemType) { }, }, { new: true }).then((results) => { Item.findByIdAndUpdate(results._id, { costPer: results.quantity !== 0 ? results.cost / results.quantity : 0 }, { new: true }) - .then(result => res.status(201).send(result)) - .catch(errors => res.status(500).send(errors)); - }).catch(errors => res.status(500).send(errors)); + .then((result) => res.status(201).send(result)) + .catch((errors) => res.status(500).send(errors)); + }).catch((errors) => res.status(500).send(errors)); } const data = { quantity: req.body.quantity, @@ -442,12 +446,12 @@ const inventoryController = function (Item, ItemType) { const inventoryItem = new Item(data); return inventoryItem.save() - .then(results => res.status(201).send({ from: prevResults, to: results })) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send({ from: prevResults, to: results })) + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); }) - .catch(errors => res.status(500).send(errors)); + .catch((errors) => res.status(500).send(errors)); } return res.status(400).send('Valid Project, Quantity and Type Id are necessary as well as valid wbs if sent in and not Unassigned'); }; @@ -460,8 +464,8 @@ const inventoryController = function (Item, ItemType) { // Look up an inventory item by id and send back the info as jsong // send result just sending something now to have it work and not break anything return Item.findById({ _id: req.params.invId }) - .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 putInvById = async function (req, res) { @@ -499,8 +503,8 @@ const inventoryController = function (Item, ItemType) { // send result just sending something now to have it work and not break anything // Use model ItemType and return the find by Id return ItemType.findById({ _id: req.params.typeId }) - .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 putInvType = async function (req, res) { @@ -532,8 +536,8 @@ const inventoryController = function (Item, ItemType) { } // send result just sending something now to have it work and not break anything return ItemType.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 postInvType = async function (req, res) { @@ -559,8 +563,8 @@ const inventoryController = function (Item, ItemType) { itemType.link = req.body.link; itemType.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(500).send(errors)); + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(500).send(errors)); }); // send result just sending something now to have it work and not break anything // create an inventory type req.body.name, req.body.description, req.body.imageUrl, req.body.quantifier diff --git a/src/controllers/logincontroller.js b/src/controllers/logincontroller.js index b6da4cf8b..a2765e1c5 100644 --- a/src/controllers/logincontroller.js +++ b/src/controllers/logincontroller.js @@ -70,7 +70,6 @@ const logincontroller = function () { } }; - const getUser = function (req, res) { const { requestor } = req.body; diff --git a/src/controllers/mapLocationsController.js b/src/controllers/mapLocationsController.js index 76fad59f9..dee7f2684 100644 --- a/src/controllers/mapLocationsController.js +++ b/src/controllers/mapLocationsController.js @@ -1,13 +1,14 @@ const UserProfile = require('../models/userProfile'); const cache = require('../utilities/nodeCache')(); - const mapLocationsController = function (MapLocation) { const getAllLocations = async function (req, res) { try { const users = []; - const results = await UserProfile.find({}, - '_id firstName lastName isActive location jobTitle totalTangibleHrs hoursByCategory'); + const results = await UserProfile.find( +{}, + '_id firstName lastName isActive location jobTitle totalTangibleHrs hoursByCategory', +); results.forEach((item) => { if ( @@ -17,7 +18,7 @@ const mapLocationsController = function (MapLocation) { users.push(item); } }); - const modifiedUsers = users.map(item => ({ + const modifiedUsers = users.map((item) => ({ location: item.location, isActive: item.isActive, jobTitle: item.jobTitle[0], @@ -41,7 +42,7 @@ const mapLocationsController = function (MapLocation) { MapLocation.findOneAndDelete({ _id: locationId }) .then(() => res.status(200).send({ message: 'The location was successfully removed!' })) - .catch(error => res.status(500).send({ message: error || "Couldn't remove the location" })); + .catch((error) => res.status(500).send({ message: error || "Couldn't remove the location" })); }; const putUserLocation = async function (req, res) { if (!req.body.requestor.role === 'Owner') { diff --git a/src/controllers/mouseoverTextController.js b/src/controllers/mouseoverTextController.js index 5187e0ee4..bb96aa3ca 100644 --- a/src/controllers/mouseoverTextController.js +++ b/src/controllers/mouseoverTextController.js @@ -1,4 +1,3 @@ - const mouseoverTextController = (function (MouseoverText) { const createMouseoverText = function (req, res) { const newMouseoverText = new MouseoverText(); @@ -6,13 +5,13 @@ const mouseoverTextController = (function (MouseoverText) { newMouseoverText.save().then(() => res.status(201).json({ _serverMessage: 'MouseoverText succesfuly created!', mouseoverText: newMouseoverText, - })).catch(err => res.status(500).send({ err })); + })).catch((err) => res.status(500).send({ err })); }; const getMouseoverText = function (req, res) { MouseoverText.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 updateMouseoverText = function (req, res) { @@ -29,8 +28,8 @@ const mouseoverTextController = (function (MouseoverText) { mouseoverText.mouseoverText = req.body.newMouseoverText; mouseoverText.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(400).send(errors)); + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(400).send(errors)); }); }; diff --git a/src/controllers/notificationController.js b/src/controllers/notificationController.js index be42d6e65..12cad126b 100644 --- a/src/controllers/notificationController.js +++ b/src/controllers/notificationController.js @@ -37,7 +37,6 @@ const notificationController = function (Notification) { .catch((error) => { res.status(400).send(error); }); }; - return { getUserNotifications, deleteUserNotification, diff --git a/src/controllers/popupEditorBackupController.js b/src/controllers/popupEditorBackupController.js index 21eccaf8f..9e12545cc 100644 --- a/src/controllers/popupEditorBackupController.js +++ b/src/controllers/popupEditorBackupController.js @@ -3,8 +3,8 @@ const { hasPermission } = require('../utilities/permissions'); const popupEditorBackupController = function (PopupEditorBackups) { const getAllPopupEditorBackups = function (req, res) { PopupEditorBackups.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 getPopupEditorBackupById = function (req, res) { @@ -18,7 +18,6 @@ const popupEditorBackupController = function (PopupEditorBackups) { } }; - const createPopupEditorBackup = async function (req, res) { if (!await hasPermission(req.body.requestor, 'createPopup')) { res @@ -34,15 +33,14 @@ const popupEditorBackupController = function (PopupEditorBackups) { return; } - const popup = new PopupEditorBackups(); popup.popupId = req.body.popupId; popup.popupName = req.body.popupName; popup.popupContent = req.body.popupContent; popup.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 updatePopupEditorBackup = async function (req, res) { @@ -66,15 +64,15 @@ const popupEditorBackupController = function (PopupEditorBackups) { PopupEditorBackups.find({ popupId: { $in: popupId } }, (error, popupBackup) => { if (popupBackup.length > 0) { popupBackup[0].popupContent = req.body.popupContent; - popupBackup[0].save().then(results => res.status(201).send(results)); + popupBackup[0].save().then((results) => res.status(201).send(results)); } else { const popup = new PopupEditorBackups(); popup.popupId = req.params.id; popup.popupContent = req.body.popupContent; popup.popupName = req.body.popupName; popup.save() - .then(results => res.status(201).send(results)) - .catch(err => res.status(500).send({ err })); + .then((results) => res.status(201).send(results)) + .catch((err) => res.status(500).send({ err })); } }); } catch (error) { @@ -82,7 +80,6 @@ const popupEditorBackupController = function (PopupEditorBackups) { } }; - return { createPopupEditorBackup, getAllPopupEditorBackups, @@ -91,5 +88,4 @@ const popupEditorBackupController = function (PopupEditorBackups) { }; }; - module.exports = popupEditorBackupController; diff --git a/src/controllers/popupEditorController.js b/src/controllers/popupEditorController.js index 71dcb7b69..1c62dd6b1 100644 --- a/src/controllers/popupEditorController.js +++ b/src/controllers/popupEditorController.js @@ -3,17 +3,16 @@ const { hasPermission } = require('../utilities/permissions'); const popupEditorController = function (PopupEditors) { const getAllPopupEditors = function (req, res) { PopupEditors.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 getPopupEditorById = function (req, res) { PopupEditors.findById(req.params.id) - .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 createPopupEditor = async function (req, res) { if (!await hasPermission(req.body.requestor, 'createPopup')) { res @@ -33,8 +32,8 @@ const popupEditorController = function (PopupEditors) { popup.popupContent = req.body.popupContent; popup.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 updatePopupEditor = async function (req, res) { @@ -56,12 +55,11 @@ const popupEditorController = function (PopupEditors) { PopupEditors.findById(popupId, (error, popup) => { popup.popupContent = req.body.popupContent; - popup.save().then(results => res.status(201).send(results)) - .catch(err => res.status(500).send({ err })); + popup.save().then((results) => res.status(201).send(results)) + .catch((err) => res.status(500).send({ err })); }); }; - return { createPopupEditor, getAllPopupEditors, @@ -70,5 +68,4 @@ const popupEditorController = function (PopupEditors) { }; }; - module.exports = popupEditorController; diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js index 435002fa9..cd40e356c 100644 --- a/src/controllers/profileInitialSetupController.js +++ b/src/controllers/profileInitialSetupController.js @@ -1,10 +1,10 @@ -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")(); +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. function sendLinkMessage(Link) { @@ -76,8 +76,7 @@ function informManagerMessage(user) { return message; } -const sendEmailWithAcknowledgment = (email, subject, message) => - new Promise((resolve, reject) => { +const sendEmailWithAcknowledgment = (email, subject, message) => new Promise((resolve, reject) => { emailSender(email, subject, message, null, null, null, (error, result) => { if (result) resolve(result); if (error) reject(result); @@ -88,7 +87,7 @@ const profileInitialSetupController = function ( ProfileInitialSetupToken, userProfile, Project, - MapLocation + MapLocation, ) { const { JWT_SECRET } = config; @@ -100,8 +99,8 @@ const profileInitialSetupController = function ( return response; } catch (err) { return { - type: "Error", - message: err.message || "An error occurred while saving the location", + type: 'Error', + message: err.message || 'An error occurred while saving the location', }; } }; @@ -117,13 +116,13 @@ const profileInitialSetupController = function ( let { email, baseUrl, weeklyCommittedHours } = req.body; email = email.toLowerCase(); const token = uuidv4(); - const expiration = moment().tz("America/Los_Angeles").add(3, "week"); + const expiration = moment().tz('America/Los_Angeles').add(3, 'week'); try { const existingEmail = await userProfile.findOne({ email, }); if (existingEmail) { - res.status(400).send("email already in use"); + res.status(400).send('email already in use'); } else { await ProfileInitialSetupToken.findOneAndDelete({ email }); @@ -139,8 +138,8 @@ const profileInitialSetupController = function ( const acknowledgment = await sendEmailWithAcknowledgment( email, - "NEEDED: Complete your One Community profile setup", - sendLinkMessage(link) + 'NEEDED: Complete your One Community profile setup', + sendLinkMessage(link), ); res.status(200).send(acknowledgment); @@ -157,7 +156,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 }); @@ -167,10 +166,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}`); @@ -188,30 +187,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"); + 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 = [ { @@ -225,33 +224,32 @@ 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.profilePic = req.body.profilePicture; newUser.permissions = { frontPermissions: [], backPermissions: [], }; - newUser.bioPosted = "default"; + 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); @@ -261,14 +259,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); const locationData = { - title: "", + title: '', firstName: req.body.firstName, lastName: req.body.lastName, jobTitle: req.body.jobTitle, @@ -279,7 +277,7 @@ const profileInitialSetupController = function ( res.send({ token }).status(200); const mapEntryResult = await setMapLocation(locationData); - if (mapEntryResult.type === "Error") { + if (mapEntryResult.type === 'Error') { console.log(mapEntryResult.message); } @@ -295,14 +293,14 @@ 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}`); @@ -323,7 +321,7 @@ const profileInitialSetupController = function ( if (foundToken) { res.status(200).send({ userAPIKey: premiumKey }); } else { - res.status(403).send("Unauthorized Request"); + res.status(403).send('Unauthorized Request'); } }; @@ -332,17 +330,17 @@ const profileInitialSetupController = function ( const users = []; const results = await userProfile.find( {}, - "location totalTangibleHrs hoursByCategory" + 'location totalTangibleHrs hoursByCategory', ); results.forEach((item) => { if ( - (item.location?.coords.lat && - item.location?.coords.lng && - item.totalTangibleHrs >= 10) || - (item.location?.coords.lat && - item.location?.coords.lng && - calculateTotalHours(item.hoursByCategory) >= 10) + (item.location?.coords.lat + && item.location?.coords.lng + && item.totalTangibleHrs >= 10) + || (item.location?.coords.lat + && item.location?.coords.lng + && calculateTotalHours(item.hoursByCategory) >= 10) ) { users.push(item); } diff --git a/src/controllers/reportsController.js b/src/controllers/reportsController.js index 8f4aba87b..c5f678586 100644 --- a/src/controllers/reportsController.js +++ b/src/controllers/reportsController.js @@ -14,7 +14,7 @@ const reportsController = function () { const summaries = reporthelper.formatSummaries(results); res.status(200).send(summaries); }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; return { diff --git a/src/controllers/rolePresetsController.js b/src/controllers/rolePresetsController.js index 3a7dc18c8..454275126 100644 --- a/src/controllers/rolePresetsController.js +++ b/src/controllers/rolePresetsController.js @@ -29,8 +29,8 @@ const rolePresetsController = function (Preset) { 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 })); + .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) { @@ -46,10 +46,10 @@ const rolePresetsController = function (Preset) { 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)); + .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) { @@ -63,9 +63,9 @@ const rolePresetsController = function (Preset) { .then((result) => { 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 })); + .catch((error) => res.status(400).send({ error })); }; return { diff --git a/src/controllers/rolesController.js b/src/controllers/rolesController.js index d3d9f8310..a69343520 100644 --- a/src/controllers/rolesController.js +++ b/src/controllers/rolesController.js @@ -5,8 +5,8 @@ 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) { @@ -25,7 +25,7 @@ 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) { @@ -33,11 +33,10 @@ const rolesController = function (Role) { Role.findById( roleId, ) - .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 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.'); @@ -61,8 +60,8 @@ const rolesController = function (Role) { record.permissionsBackEnd = req.body.permissionsBackEnd; record.save() - .then(results => res.status(201).send(results)) - .catch(errors => res.status(400).send(errors)); + .then((results) => res.status(201).send(results)) + .catch((errors) => res.status(400).send(errors)); }); }; @@ -74,7 +73,7 @@ const rolesController = function (Role) { const { roleId } = req.params; Role.findById(roleId) - .then(result => ( + .then((result) => ( result .remove() .then(UserProfile @@ -93,13 +92,12 @@ const rolesController = function (Role) { } 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 }))) + .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/taskController.js b/src/controllers/taskController.js index 47aff4d02..ac6053269 100644 --- a/src/controllers/taskController.js +++ b/src/controllers/taskController.js @@ -26,16 +26,16 @@ const taskController = function (Task) { } Task.find(query) - .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 getWBSId = (req, res) => { const { wbsId } = req.params; WBS.findById(wbsId) - .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 updateSumUp = ( @@ -81,10 +81,10 @@ const taskController = function (Task) { }; const calculateSubTasks = (level, tasks) => { - const parentTasks = tasks.filter(task => task.level === level); + const parentTasks = tasks.filter((task) => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - taskChild => taskChild.level === level + 1, + (taskChild) => taskChild.level === level + 1, ); let sumHoursBest = 0; let sumHoursWorst = 0; @@ -144,10 +144,10 @@ const taskController = function (Task) { }; const setDatesSubTasks = (level, tasks) => { - const parentTasks = tasks.filter(task => task.level === level); + const parentTasks = tasks.filter((task) => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - taskChild => taskChild.level === level + 1, + (taskChild) => taskChild.level === level + 1, ); let minStartedDate = task.startedDatetime; let maxDueDatetime = task.dueDatetime; @@ -178,10 +178,10 @@ const taskController = function (Task) { }; const calculatePriority = (level, tasks) => { - const parentTasks = tasks.filter(task => task.level === level); + const parentTasks = tasks.filter((task) => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - taskChild => taskChild.level === level + 1, + (taskChild) => taskChild.level === level + 1, ); let totalNumberPriority = 0; let totalChild = 0; @@ -222,10 +222,10 @@ const taskController = function (Task) { }; const setAssigned = (level, tasks) => { - const parentTasks = tasks.filter(task => task.level === level); + const parentTasks = tasks.filter((task) => task.level === level); parentTasks.forEach((task) => { const childTasks = tasks.filter( - taskChild => taskChild.level === level + 1, + (taskChild) => taskChild.level === level + 1, ); let isAssigned = false; let hasChild = false; @@ -259,7 +259,7 @@ const taskController = function (Task) { { wbsId: { $in: [wbsId] } }, ], }).then((tasks) => { - tasks = [...new Set(tasks.map(item => item))]; + tasks = [...new Set(tasks.map((item) => item))]; for (let lv = 3; lv > 0; lv -= 1) { calculateSubTasks(lv, tasks); setDatesSubTasks(lv, tasks); @@ -308,7 +308,7 @@ const taskController = function (Task) { break; case 2: // task.num is x.x, only has one level of parent (x) task.parentId1 = tasksWithId.find( - pTask => pTask.num === taskNumArr[0], + (pTask) => pTask.num === taskNumArr[0], )._id; // task of parentId1 has num prop of x task.parentId2 = null; task.parentId3 = null; @@ -316,23 +316,23 @@ const taskController = function (Task) { break; case 3: // task.num is x.x.x, has two levels of parent (parent: x.x and grandparent: x) task.parentId1 = tasksWithId.find( - pTask => pTask.num === taskNumArr[0], + (pTask) => pTask.num === taskNumArr[0], )._id; // task of parentId1 has num prop of x task.parentId2 = tasksWithId.find( - pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, + (pTask) => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, )._id; // task of parentId2 has num prop of x.x task.parentId3 = null; task.mother = task.parentId2; // parent task num prop is x.x break; case 4: // task.num is x.x.x.x, has three levels of parent (x.x.x, x.x and x) task.parentId1 = tasksWithId.find( - pTask => pTask.num === taskNumArr[0], + (pTask) => pTask.num === taskNumArr[0], )._id; // x task.parentId2 = tasksWithId.find( - pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, + (pTask) => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}`, )._id; // x.x task.parentId3 = tasksWithId.find( - pTask => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}.${taskNumArr[2]}`, + (pTask) => pTask.num === `${taskNumArr[0]}.${taskNumArr[1]}.${taskNumArr[2]}`, )._id; // x.x.x task.mother = task.parentId3; // parent task num prop is x.x.x break; @@ -388,7 +388,7 @@ const taskController = function (Task) { (resources, childTaskMember) => { if ( task.resources.every( - member => member.name !== childTaskMember.name, + (member) => member.name !== childTaskMember.name, ) ) return [...resources, childTaskMember]; return resources; @@ -494,7 +494,7 @@ const taskController = function (Task) { }); Promise.all([saveTask, saveWbs, saveProject]) - .then(results => res.status(201).send(results[0])) + .then((results) => res.status(201).send(results[0])) .catch((errors) => { res.status(400).send(errors); }); @@ -520,7 +520,7 @@ const taskController = function (Task) { task .save() .then() - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); }); // level 2 @@ -536,7 +536,7 @@ const taskController = function (Task) { childTask1 .save() .then(true) - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); // level 3 Task.find({ parentId: { $in: [childTask1._id] } }) @@ -551,7 +551,7 @@ const taskController = function (Task) { childTask2 .save() .then(true) - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); // level 4 Task.find({ parentId: { $in: [childTask2._id] } }) @@ -569,19 +569,19 @@ const taskController = function (Task) { childTask3 .save() .then(true) - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); }); } }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }); } }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }); } }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }); res.status(200).send(true); @@ -642,7 +642,7 @@ const taskController = function (Task) { Promise.all(queries) .then(() => res.status(200).send('Success!')) - .catch(err => res.status(400).send(err)); + .catch((err) => res.status(400).send(err)); }); }; @@ -664,7 +664,7 @@ const taskController = function (Task) { ], }).then((record) => { if (!record || record === null || record.length === 0) return res.status(400).send({ error: 'No valid records found' }); - const removeTasks = record.map(rec => rec.remove()); + const removeTasks = record.map((rec) => rec.remove()); return removeTasks; }); @@ -686,7 +686,7 @@ const taskController = function (Task) { Promise.all([removeChildTasks, updateMotherChildrenQty]) .then(() => res.status(200).send({ message: 'Task successfully deleted' })) // no need to resetNum(taskId, mother); - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); }; const deleteTaskByWBS = async (req, res) => { @@ -747,7 +747,7 @@ const taskController = function (Task) { { ...req.body, modifiedDatetime: Date.now() }, ) .then(() => res.status(201).send()) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; const swap = async function (req, res) { @@ -792,18 +792,18 @@ const taskController = function (Task) { task1 .save() .then() - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); task2 .save() .then() - .catch(errors => res.status(400).send(errors)); + .catch((errors) => res.status(400).send(errors)); Task.find({ wbsId: { $in: [task1.wbsId] }, }) - .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)); }); }); }; @@ -827,7 +827,7 @@ const taskController = function (Task) { } // Fetch the resource names for all resources - const resourceNamesPromises = task.resources.map(resource => taskHelper.getUserProfileFirstAndLastName(resource.userID)); + const resourceNamesPromises = task.resources.map((resource) => taskHelper.getUserProfileFirstAndLastName(resource.userID)); const resourceNames = await Promise.all(resourceNamesPromises); // Update the task's resources with the fetched names @@ -847,7 +847,7 @@ const taskController = function (Task) { try { Task.find({ wbsId: { $in: [wbsId] } }).then((tasks) => { - tasks = tasks.filter(task => task.level === 1); + tasks = tasks.filter((task) => task.level === 1); tasks.forEach((task) => { updateParents(task.wbsId, task.taskId.toString()); }); @@ -873,12 +873,12 @@ const taskController = function (Task) { '-resources.profilePic', ).then((results) => { WBS.find({ - _id: { $in: results.map(item => item.wbsId) }, + _id: { $in: results.map((item) => item.wbsId) }, }).then((WBSs) => { const resultsWithProjectsIds = results.map((item) => { item.set( 'projectId', - WBSs?.find(wbs => wbs._id.toString() === item.wbsId.toString()) + WBSs?.find((wbs) => wbs._id.toString() === item.wbsId.toString()) ?.projectId, { strict: false }, ); @@ -933,7 +933,7 @@ const taskController = function (Task) { { ...req.body, modifiedDatetime: Date.now() }, ) .then(() => res.status(201).send()) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; const getReviewReqEmailBody = function (name, taskName) { @@ -953,7 +953,7 @@ const taskController = function (Task) { role: { $in: ['Administrator', 'Manager', 'Mentor'] }, }); membership.forEach((member) => { - if (member.teams.some(team => user.teams.includes(team))) { + if (member.teams.some((team) => user.teams.includes(team))) { recipients.push(member.email); } }); diff --git a/src/controllers/taskNotificationController.js b/src/controllers/taskNotificationController.js index 256c5249e..5d999b800 100644 --- a/src/controllers/taskNotificationController.js +++ b/src/controllers/taskNotificationController.js @@ -20,7 +20,7 @@ const taskNotificationController = function (TaskNotification) { // If task notification with taskId and userId exists, don't do anything. // Else, create new task notification.image.png await Promise.all( - userIds.map(async userId => TaskNotification.updateOne( + userIds.map(async (userId) => TaskNotification.updateOne( { $and: [{ taskId }, { userId: mongoose.Types.ObjectId(userId) }], }, @@ -93,13 +93,13 @@ const taskNotificationController = function (TaskNotification) { result.dateRead = Date.now(); result .save() - .then(notification => res.status(200).send(notification)) - .catch(error => res.status(400).send(error)); + .then((notification) => res.status(200).send(notification)) + .catch((error) => res.status(400).send(error)); } else { res.status(404).send('TaskNotification not found.'); } }) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }; return { diff --git a/src/controllers/teamController.js b/src/controllers/teamController.js index 9cd98036e..4a90aea99 100644 --- a/src/controllers/teamController.js +++ b/src/controllers/teamController.js @@ -7,15 +7,15 @@ const teamcontroller = function (Team) { const getAllTeams = function (req, res) { Team.find({}) .sort({ teamName: 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 getTeamById = function (req, res) { const { teamId } = req.params; Team.findById(teamId) - .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 postTeam = async function (req, res) { if (!await hasPermission(req.body.requestor, 'postTeam')) { @@ -43,11 +43,11 @@ const teamcontroller = function (Team) { } else { // If no team with the same name exists, save the new team team.save() - .then(results => res.send(results).status(200)) - .catch(error => res.send(error).status(404)); + .then((results) => res.send(results).status(200)) + .catch((error) => res.send(error).status(404)); } }) - .catch(error => res.send(error).status(404)); + .catch((error) => res.send(error).status(404)); }; const deleteTeam = async function (req, res) { if (!await hasPermission(req.body.requestor, 'deleteTeam')) { @@ -102,8 +102,8 @@ const teamcontroller = function (Team) { record .save() - .then(results => res.status(200).send(results._id)) - .catch(errors => res.status(400).send(errors)); + .then((results) => res.status(200).send(results._id)) + .catch((errors) => res.status(400).send(errors)); }); }; @@ -136,7 +136,6 @@ const teamcontroller = function (Team) { // 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 (operation === 'Assign') { await Team.findOneAndUpdate({ _id: teamId }, { $addToSet: { members: { userId } }, $set: { modifiedDatetime: Date.now() } }, { new: true }); const newMember = await userProfile.findOneAndUpdate({ _id: userId }, { $addToSet: { teams: teamId } }, { new: true }); @@ -179,8 +178,8 @@ const teamcontroller = function (Team) { }, }, ]) - .then(result => res.status(200).send(result)) - .catch(error => res.status(500).send(error)); + .then((result) => res.status(200).send(result)) + .catch((error) => res.status(500).send(error)); }; return { diff --git a/src/controllers/timeEntryController.js b/src/controllers/timeEntryController.js index 597a9f3eb..b99fe3bd4 100644 --- a/src/controllers/timeEntryController.js +++ b/src/controllers/timeEntryController.js @@ -435,10 +435,10 @@ const timeEntrycontroller = function (TimeEntry) { try { return timeEntry .save() - .then(results => res.status(200).send({ + .then((results) => res.status(200).send({ message: `Time Entry saved with id as ${results._id}`, })) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); } catch (error) { return res.status(500).send(error); } diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js index db61532e7..3144a4f52 100644 --- a/src/controllers/timeOffRequestController.js +++ b/src/controllers/timeOffRequestController.js @@ -3,9 +3,8 @@ const moment = require('moment-timezone'); const { hasPermission } = require('../utilities/permissions'); const timeOffRequestController = function (TimeOffRequest) { - const setTimeOffRequest = async (req, res) => { - const hasRolePermission = [ "Owner" , "Administrator" ].includes(req.body.requestor.role) + const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission) { res.status(403).send('You are not authorized to set time off requests.'); return; @@ -22,7 +21,6 @@ const timeOffRequestController = function (TimeOffRequest) { const startDate = moment(startingDate); const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, 'second'); - const newTimeOffRequest = new TimeOffRequest(); newTimeOffRequest.requestFor = mongoose.Types.ObjectId(requestFor); @@ -89,7 +87,7 @@ const timeOffRequestController = function (TimeOffRequest) { }; const updateTimeOffRequestById = async (req, res) => { - const hasRolePermission = [ "Owner" , "Administrator" ].includes(req.body.requestor.role) + const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission) { res.status(403).send('You are not authorized to set time off requests.'); return; @@ -133,7 +131,7 @@ const timeOffRequestController = function (TimeOffRequest) { }; const deleteTimeOffRequestById = async (req, res) => { - const hasRolePermission = [ "Owner" , "Administrator" ].includes(req.body.requestor.role) + const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission) { res.status(403).send('You are not authorized to set time off requests.'); return; diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index e5d5b105f..461b98898 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -94,7 +94,7 @@ const userProfileController = function (UserProfile) { cache.setCache('allusers', JSON.stringify(results)); res.status(200).send(results); }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; const getProjectMembers = async function (req, res) { @@ -270,7 +270,7 @@ const userProfileController = function (UserProfile) { allUserCache.push(userCache); 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) { @@ -367,7 +367,7 @@ const userProfileController = function (UserProfile) { let userIdx; if (isUserInCache) { allUserData = JSON.parse(cache.getCache('allusers')); - userIdx = allUserData.findIndex(users => users._id === userid); + userIdx = allUserData.findIndex((users) => users._id === userid); userData = allUserData[userIdx]; } if ( @@ -496,7 +496,7 @@ const userProfileController = function (UserProfile) { cache.setCache('allusers', JSON.stringify(allUserData)); } }) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }); }; @@ -564,7 +564,7 @@ const userProfileController = function (UserProfile) { cache.removeCache(`user-${userId}`); const allUserData = JSON.parse(cache.getCache('allusers')); - const userIdx = allUserData.findIndex(users => users._id === userId); + const userIdx = allUserData.findIndex((users) => users._id === userId); allUserData.splice(userIdx, 1); cache.setCache('allusers', JSON.stringify(allUserData)); @@ -631,7 +631,7 @@ const userProfileController = function (UserProfile) { res.status(200).send(results); }); }) - .catch(error => res.status(404).send(error)); + .catch((error) => res.status(404).send(error)); }; const getUserByName = (req, res) => { @@ -640,8 +640,10 @@ const userProfileController = function (UserProfile) { { 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) { @@ -678,9 +680,9 @@ const userProfileController = function (UserProfile) { .then(() => { res.status(200).send({ message: 'updated property' }); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); }; const updatepassword = async function (req, res) { @@ -754,11 +756,11 @@ const userProfileController = function (UserProfile) { return user .save() .then(() => res.status(200).send({ message: 'updated password' })) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); }) - .catch(error => res.status(500).send(error)); + .catch((error) => res.status(500).send(error)); }; const getreportees = async function (req, res) { @@ -797,7 +799,7 @@ const userProfileController = function (UserProfile) { }); res.status(200).send(teammembers); }) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }; const getTeamMembersofUser = function (req, res) { @@ -814,7 +816,7 @@ const userProfileController = function (UserProfile) { .then((results) => { res.status(200).send(results); }) - .catch(error => res.status(400).send(error)); + .catch((error) => res.status(400).send(error)); }; const getUserName = function (req, res) { @@ -871,7 +873,7 @@ const userProfileController = function (UserProfile) { if (isUserInCache) { 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) { @@ -949,6 +951,64 @@ const userProfileController = function (UserProfile) { res.status(200).send({ refreshToken: currentRefreshToken }); }; + // Search for user by first name + const getUserBySingleName = (req, res) => { + const pattern = new RegExp(`^${ req.params.singleName}`, 'i'); + + // Searches for first or last name + UserProfile.find({ + $or: [ + { firstName: { $regex: pattern } }, + { lastName: { $regex: pattern } }, + ], + }) + .select('firstName lastName') + .then((users) => { + if (users.length === 0) { + return res.status(404).send({ error: 'Users Not Found' }); + } + res.status(200).send(users); + }) + .catch((error) => res.status(500).send(error)); + }; + + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + + // Search for user by full name (first and last) + const getUserByFullName = (req, res) => { + // Creates an array containing the first and last name and filters out whitespace + const fullName = req.params.fullName + .split(' ') + .filter((name) => name !== ''); + // Creates a partial match regex for both first and last name + const firstNameRegex = new RegExp(`^${ escapeRegExp(fullName[0])}`, 'i'); + const lastNameRegex = new RegExp(`^${ escapeRegExp(fullName[1])}`, 'i'); + + // Verfies both the first and last name are present + if (fullName.length < 2) { + return res + .status(400) + .send({ error: 'Both first name and last name are required.' }); + } + + UserProfile.find({ + $and: [ + { firstName: { $regex: firstNameRegex } }, + { lastName: { $regex: lastNameRegex } }, + ], + }) + .select('firstName lastName') + .then((users) => { + if (users.length === 0) { + return res.status(404).send({ error: 'Users Not Found' }); + } + res.status(200).send(users); + }) + .catch((error) => res.status(500).send(error)); + }; + return { postUserProfile, getUserProfiles, @@ -966,6 +1026,8 @@ const userProfileController = function (UserProfile) { getUserByName, getAllUsersWithFacebookLink, refreshToken, + getUserBySingleName, + getUserByFullName, }; }; diff --git a/src/controllers/wbsController.js b/src/controllers/wbsController.js index d74ea01ac..3fdb1392c 100644 --- a/src/controllers/wbsController.js +++ b/src/controllers/wbsController.js @@ -9,7 +9,7 @@ const wbsController = function (WBS) { const getAllWBS = function (req, res) { WBS.find( { projectId: { $in: [req.params.projectId] } }, - "wbsName isActive modifiedDatetime" + "wbsName isActive modifiedDatetime", ) .sort({ modifiedDatetime: -1 }) .then((results) => res.status(200).send(results)) diff --git a/src/helpers/dashboardhelper.js b/src/helpers/dashboardhelper.js index 8d5ebab3c..2652c8587 100644 --- a/src/helpers/dashboardhelper.js +++ b/src/helpers/dashboardhelper.js @@ -2,7 +2,7 @@ const moment = require('moment-timezone'); const mongoose = require('mongoose'); const userProfile = require('../models/userProfile'); const timeentry = require('../models/timeentry'); -const myTeam = require('../helpers/helperModels/myTeam'); +const myTeam = require('./helperModels/myTeam'); const team = require('../models/team'); const dashboardhelper = function () { @@ -233,7 +233,7 @@ const dashboardhelper = function () { ); } - teamMemberIds = teamMembers.map(member => member._id); + teamMemberIds = teamMembers.map((member) => member._id); const timeEntries = await timeentry.find({ dateOfWork: { diff --git a/src/helpers/helperModels/userProjects.js b/src/helpers/helperModels/userProjects.js index e325a0e39..a2f1f2b5e 100644 --- a/src/helpers/helperModels/userProjects.js +++ b/src/helpers/helperModels/userProjects.js @@ -8,7 +8,6 @@ const ProjectSchema = new Schema({ category: { type: String }, }); - const userProjectSchema = new Schema({ _id: { type: mongoose.SchemaTypes.ObjectId, ref: 'userProfile' }, diff --git a/src/helpers/notificationhelper.js b/src/helpers/notificationhelper.js index 19eea3ed6..8742bc7d1 100644 --- a/src/helpers/notificationhelper.js +++ b/src/helpers/notificationhelper.js @@ -41,7 +41,6 @@ const notificationhelper = function () { }); }; - return { notificationcreated, notificationedited, diff --git a/src/helpers/taskHelper.js b/src/helpers/taskHelper.js index 202208edb..e2f872523 100644 --- a/src/helpers/taskHelper.js +++ b/src/helpers/taskHelper.js @@ -1,10 +1,10 @@ -const moment = require("moment-timezone"); -const mongoose = require("mongoose"); -const userProfile = require("../models/userProfile"); -const timeentry = require("../models/timeentry"); -const team = require("../models/team"); -const Task = require("../models/task"); -const TaskNotification = require("../models/taskNotification"); +const moment = require('moment-timezone'); +const mongoose = require('mongoose'); +const userProfile = require('../models/userProfile'); +const timeentry = require('../models/timeentry'); +const team = require('../models/team'); +const Task = require('../models/task'); +const TaskNotification = require('../models/taskNotification'); const taskHelper = function () { const getTasksForTeams = async function (userId, requestor) { @@ -23,31 +23,31 @@ const taskHelper = function () { weeklySummaries: 1, timeOffFrom: 1, timeOffTill: 1, - } + }, ); if (userById === null) return null; const userRole = userById.role; const pdtstart = moment() - .tz("America/Los_Angeles") - .startOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .startOf('week') + .format('YYYY-MM-DD'); const pdtend = moment() - .tz("America/Los_Angeles") - .endOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .endOf('week') + .format('YYYY-MM-DD'); let teamMemberIds = [userid]; let teamMembers = []; const isRequestorOwnerLike = [ - "Administrator", - "Owner", - "Core Team", + 'Administrator', + 'Owner', + 'Core Team', ].includes(requestorRole); - const isUserOwnerLike = ["Administrator", "Owner", "Core Team"].includes( - userRole + const isUserOwnerLike = ['Administrator', 'Owner', 'Core Team'].includes( + userRole, ); switch (true) { @@ -61,20 +61,19 @@ const taskHelper = function () { weeklycommittedHours: 1, timeOffFrom: 1, timeOffTill: 1, - } + }, ); break; } case isRequestorOwnerLike && !isUserOwnerLike: { const teamsResult = await team.find( - { "members.userId": { $in: [userid] } }, - { members: 1 } + { 'members.userId': { $in: [userid] } }, + { members: 1 }, ); teamsResult.forEach((_myTeam) => { _myTeam.members.forEach((teamMember) => { - if (!teamMember.userId.equals(userid)) - teamMemberIds.push(teamMember.userId); + if (!teamMember.userId.equals(userid)) teamMemberIds.push(teamMember.userId); }); }); @@ -87,20 +86,19 @@ const taskHelper = function () { weeklycommittedHours: 1, timeOffFrom: 1, timeOffTill: 1, - } + }, ); break; } default: { const sharedTeamsResult = await team.find( - { "members.userId": { $all: [userid, requestorId] } }, - { members: 1 } + { 'members.userId': { $all: [userid, requestorId] } }, + { members: 1 }, ); sharedTeamsResult.forEach((_myTeam) => { _myTeam.members.forEach((teamMember) => { - if (!teamMember.userId.equals(userid)) - teamMemberIds.push(teamMember.userId); + if (!teamMember.userId.equals(userid)) teamMemberIds.push(teamMember.userId); }); }); @@ -113,7 +111,7 @@ const taskHelper = function () { weeklycommittedHours: 1, timeOffFrom: 1, timeOffTill: 1, - } + }, ); } } @@ -139,17 +137,17 @@ const taskHelper = function () { }; } if (timeEntry.isTangible) { - timeEntryByPerson[personIdStr].tangibleSeconds += - timeEntry.totalSeconds; + timeEntryByPerson[personIdStr].tangibleSeconds + += timeEntry.totalSeconds; } timeEntryByPerson[personIdStr].totalSeconds += timeEntry.totalSeconds; }); const teamMemberTasks = await Task.find( - { "resources.userID": { $in: teamMemberIds } }, - { "resources.profilePic": 0 } + { 'resources.userID': { $in: teamMemberIds } }, + { 'resources.profilePic': 0 }, ).populate({ - path: "wbsId", - select: "projectId", + path: 'wbsId', + select: 'projectId', }); const teamMemberTaskIds = teamMemberTasks.map((task) => task._id); const teamMemberTaskNotifications = await TaskNotification.find({ @@ -164,7 +162,7 @@ const taskHelper = function () { if (taskNotificationByTaskNdUser[taskNdUserID]) { taskNotificationByTaskNdUser[taskNdUserID].push( - teamMemberTaskNotification + teamMemberTaskNotification, ); } else { taskNotificationByTaskNdUser[taskNdUserID] = [ @@ -183,8 +181,7 @@ const taskHelper = function () { teamMemberTask.resources.forEach((resource) => { const resourceIdStr = resource.userID?.toString(); const taskNdUserID = `${taskIdStr},${resourceIdStr}`; - _teamMemberTask.taskNotifications = - taskNotificationByTaskNdUser[taskNdUserID] || []; + _teamMemberTask.taskNotifications = taskNotificationByTaskNdUser[taskNdUserID] || []; if (taskByPerson[resourceIdStr]) { taskByPerson[resourceIdStr].push(_teamMemberTask); } else { @@ -201,11 +198,11 @@ const taskHelper = function () { name: `${teamMember.firstName} ${teamMember.lastName}`, weeklycommittedHours: teamMember.weeklycommittedHours, totaltangibletime_hrs: - timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds / - 3600 || 0, + timeEntryByPerson[teamMember._id.toString()]?.tangibleSeconds + / 3600 || 0, totaltime_hrs: - timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600 || - 0, + timeEntryByPerson[teamMember._id.toString()]?.totalSeconds / 3600 + || 0, tasks: taskByPerson[teamMember._id.toString()] || [], timeOffFrom: teamMember.timeOffFrom || null, timeOffTill: teamMember.timeOffTill || null, @@ -504,13 +501,13 @@ const taskHelper = function () { }; const getTasksForSingleUser = function (userId) { const pdtstart = moment() - .tz("America/Los_Angeles") - .startOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .startOf('week') + .format('YYYY-MM-DD'); const pdtend = moment() - .tz("America/Los_Angeles") - .endOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .endOf('week') + .format('YYYY-MM-DD'); return userProfile.aggregate([ { $match: { @@ -519,33 +516,33 @@ const taskHelper = function () { }, { $project: { - personId: "$_id", - role: "$role", + personId: '$_id', + role: '$role', name: { - $concat: ["$firstName", " ", "$lastName"], + $concat: ['$firstName', ' ', '$lastName'], }, weeklycommittedHours: { $sum: [ - "$weeklycommittedHours", + '$weeklycommittedHours', { - $ifNull: ["$missedHours", 0], + $ifNull: ['$missedHours', 0], }, ], }, timeOffFrom: { - $ifNull: ["$timeOffFrom", null], + $ifNull: ['$timeOffFrom', null], }, timeOffTill: { - $ifNull: ["$timeOffTill", null], + $ifNull: ['$timeOffTill', null], }, }, }, { $lookup: { - from: "timeEntries", - localField: "personId", - foreignField: "personId", - as: "timeEntryData", + from: 'timeEntries', + localField: 'personId', + foreignField: 'personId', + as: 'timeEntryData', }, }, { @@ -558,18 +555,18 @@ const taskHelper = function () { role: 1, timeEntryData: { $filter: { - input: "$timeEntryData", - as: "timeentry", + input: '$timeEntryData', + as: 'timeentry', cond: { $and: [ { - $gte: ["$$timeentry.dateOfWork", pdtstart], + $gte: ['$$timeentry.dateOfWork', pdtstart], }, { - $lte: ["$$timeentry.dateOfWork", pdtend], + $lte: ['$$timeentry.dateOfWork', pdtend], }, { - $in: ["$$timeentry.entryType", ["default", null]], + $in: ['$$timeentry.entryType', ['default', null]], }, ], }, @@ -579,7 +576,7 @@ const taskHelper = function () { }, { $unwind: { - path: "$timeEntryData", + path: '$timeEntryData', preserveNullAndEmptyArrays: true, }, }, @@ -594,18 +591,18 @@ const taskHelper = function () { totalSeconds: { $cond: [ { - $gte: ["$timeEntryData.totalSeconds", 0], + $gte: ['$timeEntryData.totalSeconds', 0], }, - "$timeEntryData.totalSeconds", + '$timeEntryData.totalSeconds', 0, ], }, isTangible: { $cond: [ { - $gte: ["$timeEntryData.totalSeconds", 0], + $gte: ['$timeEntryData.totalSeconds', 0], }, - "$timeEntryData.isTangible", + '$timeEntryData.isTangible', false, ], }, @@ -616,9 +613,9 @@ const taskHelper = function () { tangibletime: { $cond: [ { - $eq: ["$isTangible", true], + $eq: ['$isTangible', true], }, - "$totalSeconds", + '$totalSeconds', 0, ], }, @@ -627,44 +624,44 @@ const taskHelper = function () { { $group: { _id: { - personId: "$personId", - weeklycommittedHours: "$weeklycommittedHours", - timeOffFrom: "$timeOffFrom", - timeOffTill: "$timeOffTill", - name: "$name", - role: "$role", + personId: '$personId', + weeklycommittedHours: '$weeklycommittedHours', + timeOffFrom: '$timeOffFrom', + timeOffTill: '$timeOffTill', + name: '$name', + role: '$role', }, totalSeconds: { - $sum: "$totalSeconds", + $sum: '$totalSeconds', }, tangibletime: { - $sum: "$tangibletime", + $sum: '$tangibletime', }, }, }, { $project: { _id: 0, - personId: "$_id.personId", - name: "$_id.name", - weeklycommittedHours: "$_id.weeklycommittedHours", - timeOffFrom: "$_id.timeOffFrom", - timeOffTill: "$_id.timeOffTill", - role: "$_id.role", + personId: '$_id.personId', + name: '$_id.name', + weeklycommittedHours: '$_id.weeklycommittedHours', + timeOffFrom: '$_id.timeOffFrom', + timeOffTill: '$_id.timeOffTill', + role: '$_id.role', totaltime_hrs: { - $divide: ["$totalSeconds", 3600], + $divide: ['$totalSeconds', 3600], }, totaltangibletime_hrs: { - $divide: ["$tangibletime", 3600], + $divide: ['$tangibletime', 3600], }, }, }, { $lookup: { - from: "tasks", - localField: "personId", - foreignField: "resources.userID", - as: "tasks", + from: 'tasks', + localField: 'personId', + foreignField: 'resources.userID', + as: 'tasks', }, }, { @@ -678,25 +675,25 @@ const taskHelper = function () { }, { $unwind: { - path: "$tasks", + path: '$tasks', preserveNullAndEmptyArrays: true, }, }, { $lookup: { - from: "wbs", - localField: "tasks.wbsId", - foreignField: "_id", - as: "projectId", + from: 'wbs', + localField: 'tasks.wbsId', + foreignField: '_id', + as: 'projectId', }, }, { $addFields: { - "tasks.projectId": { + 'tasks.projectId': { $cond: [ - { $ne: ["$projectId", []] }, - { $arrayElemAt: ["$projectId", 0] }, - "$tasks.projectId", + { $ne: ['$projectId', []] }, + { $arrayElemAt: ['$projectId', 0] }, + '$tasks.projectId', ], }, }, @@ -718,40 +715,40 @@ const taskHelper = function () { }, { $addFields: { - "tasks.projectId": "$tasks.projectId.projectId", + 'tasks.projectId': '$tasks.projectId.projectId', }, }, { $lookup: { - from: "taskNotifications", - localField: "tasks._id", - foreignField: "taskId", - as: "tasks.taskNotifications", + from: 'taskNotifications', + localField: 'tasks._id', + foreignField: 'taskId', + as: 'tasks.taskNotifications', }, }, { $group: { - _id: "$personId", - tasks: { $push: "$tasks" }, + _id: '$personId', + tasks: { $push: '$tasks' }, data: { - $first: "$$ROOT", + $first: '$$ROOT', }, }, }, { $addFields: { - "data.tasks": { + 'data.tasks': { $filter: { - input: "$tasks", - as: "task", - cond: { $ne: ["$$task", {}] }, + input: '$tasks', + as: 'task', + cond: { $ne: ['$$task', {}] }, }, }, }, }, { $replaceRoot: { - newRoot: "$data", + newRoot: '$data', }, }, ]); @@ -759,7 +756,7 @@ const taskHelper = function () { const getUserProfileFirstAndLastName = function (userId) { return userProfile.findById(userId).then((results) => { if (!results) { - return " "; + return ' '; } return `${results.firstName} ${results.lastName}`; }); diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index 3e02f1379..761ce178b 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -1,53 +1,53 @@ /* eslint-disable no-continue */ /* eslint-disable no-await-in-loop */ -const mongoose = require("mongoose"); -const moment = require("moment-timezone"); -const _ = require("lodash"); -const userProfile = require("../models/userProfile"); -const timeEntries = require("../models/timeentry"); -const badge = require("../models/badge"); -const myTeam = require("./helperModels/myTeam"); -const dashboardHelper = require("./dashboardhelper")(); -const reportHelper = require("./reporthelper")(); -const emailSender = require("../utilities/emailSender"); -const logger = require("../startup/logger"); -const Reason = require("../models/reason"); -const token = require("../models/profileInitialSetupToken"); -const cache = require("../utilities/nodeCache")(); -const timeOffRequest = require("../models/timeOffRequest"); +const mongoose = require('mongoose'); +const moment = require('moment-timezone'); +const _ = require('lodash'); +const userProfile = require('../models/userProfile'); +const timeEntries = require('../models/timeentry'); +const badge = require('../models/badge'); +const myTeam = require('./helperModels/myTeam'); +const dashboardHelper = require('./dashboardhelper')(); +const reportHelper = require('./reporthelper')(); +const emailSender = require('../utilities/emailSender'); +const logger = require('../startup/logger'); +const Reason = require('../models/reason'); +const token = require('../models/profileInitialSetupToken'); +const cache = require('../utilities/nodeCache')(); +const timeOffRequest = require('../models/timeOffRequest'); const userHelper = function () { // Update format to "MMM-DD-YY" from "YYYY-MMM-DD" (Confirmed with Jae) const earnedDateBadge = () => { const currentDate = new Date(Date.now()); - return moment(currentDate).tz("America/Los_Angeles").format("MMM-DD-YY"); + return moment(currentDate).tz('America/Los_Angeles').format('MMM-DD-YY'); }; const getTeamMembers = function (user) { const userId = mongoose.Types.ObjectId(user._id); // var teamid = userdetails.teamId; return myTeam.findById(userId).select({ - "myTeam._id": 0, - "myTeam.role": 0, - "myTeam.fullName": 0, + 'myTeam._id': 0, + 'myTeam.role': 0, + 'myTeam.fullName': 0, _id: 0, }); }; const getUserName = async function (userId) { const userid = mongoose.Types.ObjectId(userId); - return userProfile.findById(userid, "firstName lastName"); + return userProfile.findById(userid, 'firstName lastName'); }; const validateProfilePic = function (profilePic) { - const picParts = profilePic.split(","); + const picParts = profilePic.split(','); let result = true; const errors = []; if (picParts.length < 2) { return { result: false, - errors: "Invalid image", + errors: 'Invalid image', }; } @@ -55,13 +55,13 @@ const userHelper = function () { const imageSize = picParts[1].length; const sizeInBytes = (Math.ceil(imageSize / 4) * 3) / 1024; if (sizeInBytes > 50) { - errors.push("Image size should not exceed 50KB"); + errors.push('Image size should not exceed 50KB'); result = false; } - const imageType = picParts[0].split("/")[1].split(";")[0]; - if (imageType !== "jpeg" && imageType !== "png") { - errors.push("Image type shoud be either jpeg or png."); + const imageType = picParts[0].split('/')[1].split(';')[0]; + if (imageType !== 'jpeg' && imageType !== 'png') { + errors.push('Image type shoud be either jpeg or png.'); result = false; } @@ -72,12 +72,11 @@ const userHelper = function () { }; const formatTimeOffRequestsDescription = (inputString) => { - const searchTerm = "Notice:"; + const searchTerm = 'Notice:'; if (inputString.includes(searchTerm)) { const parts = inputString.split(searchTerm); - const formattedString = - `${parts[0]}
${searchTerm}` + - `${parts[1]}`; + const formattedString = `${parts[0]}
${searchTerm}` + + `${parts[1]}`; return formattedString; } return inputString; @@ -92,11 +91,10 @@ const userHelper = function () { coreTeamExtraHour, requestForTimeOffEmailBody, ) { - let finalParagraph = ""; + let finalParagraph = ''; if (timeRemaining === undefined) { - finalParagraph = - "

Life happens and we understand that. That’s why we allow 5 of them before taking action. This action usually includes removal from our team though, so please let your direct supervisor know what happened and do your best to avoid future blue squares if you are getting close to 5 and wish to avoid termination. Each blue square drops off after a year.

"; + finalParagraph = '

Life happens and we understand that. That’s why we allow 5 of them before taking action. This action usually includes removal from our team though, so please let your direct supervisor know what happened and do your best to avoid future blue squares if you are getting close to 5 and wish to avoid termination. Each blue square drops off after a year.

'; } else { finalParagraph = `Please complete ALL owed time this week (${timeRemaining + coreTeamExtraHour} hours) to avoid receiving another blue square. If you have any questions about any of this, please see the "One Community Core Team Policies and Procedures" page.`; } @@ -107,10 +105,10 @@ const userHelper = function () { ${ requestForTimeOffEmailBody ? `\n

Reason Time Requested Off: ${requestForTimeOffEmailBody}

` - : "" + : '' }

Description: ${formatTimeOffRequestsDescription( - infringement.description + infringement.description, )}

Total Infringements: This is your ${moment .localeData() @@ -132,10 +130,10 @@ const userHelper = function () { * @return {void} */ const emailWeeklySummariesForAllUsers = async (weekIndex = 1) => { - const currentFormattedDate = moment().tz("America/Los_Angeles").format(); + const currentFormattedDate = moment().tz('America/Los_Angeles').format(); logger.logInfo( - `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}` + `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}`, ); const emails = []; @@ -143,19 +141,15 @@ 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}` - ) - ); + results.sort((a, b) => `${a.firstName} ${a.lastName}`.localeCompare( + `${b.firstName} ${b.lastname}`, + )); for (let i = 0; i < results.length; i += 1) { const result = results[i]; @@ -181,19 +175,19 @@ const userHelper = function () { const mediaUrlLink = mediaUrl ? `${mediaUrl}` - : "Not provided!"; + : 'Not provided!'; 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. @@ -204,16 +198,16 @@ const userHelper = function () {
Weekly Summary (for the week ending on ${moment(dueDate) - .tz("America/Los_Angeles") - .format("YYYY-MMM-DD")}): + .tz('America/Los_Angeles') + .format('YYYY-MMM-DD')}):
${summary}
`; } else if ( - weeklySummaryOption === "Not Required" || - (!weeklySummaryOption && result.weeklySummaryNotReq) + weeklySummaryOption === 'Not Required' + || (!weeklySummaryOption && result.weeklySummaryNotReq) ) { weeklySummaryMessage = weeklySummaryNotRequiredMessage; } @@ -234,16 +228,16 @@ const userHelper = function () { weeklySummariesCount === 8 ? `

Total Valid Weekly Summaries: ${weeklySummariesCount}

` : `

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

` } ${ hoursLogged >= weeklycommittedHours ? `

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

` : `

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

` } ${weeklySummaryMessage} @@ -253,11 +247,11 @@ const userHelper = function () { // Necessary because our version of node is outdated // and doesn't have String.prototype.replaceAll let emailString = [...new Set(emails)].toString(); - while (emailString.includes(",")) { - emailString = emailString.replace(",", "\n"); + while (emailString.includes(',')) { + emailString = emailString.replace(',', '\n'); } - while (emailString.includes("\n")) { - emailString = emailString.replace("\n", ", "); + while (emailString.includes('\n')) { + emailString = emailString.replace('\n', ', '); } emailBody += `\n @@ -270,12 +264,12 @@ 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, - emailString + emailString, ); } catch (err) { logger.logException(err); @@ -296,8 +290,8 @@ const userHelper = function () { weeklySummaries: { $each: [ { - dueDate: moment().tz("America/Los_Angeles").endOf("week"), - summary: "", + dueDate: moment().tz('America/Los_Angeles').endOf('week'), + summary: '', }, ], $position: 0, @@ -316,29 +310,29 @@ const userHelper = function () { */ const assignBlueSquareForTimeNotMet = async () => { try { - const currentFormattedDate = moment().tz("America/Los_Angeles").format(); + const currentFormattedDate = moment().tz('America/Los_Angeles').format(); const currentUTCDate = moment - .tz("America/Los_Angeles") - .startOf("day") + .tz('America/Los_Angeles') + .startOf('day') .toISOString(); logger.logInfo( - `Job for assigning blue square for commitment not met starting at ${currentFormattedDate}` + `Job for assigning blue square for commitment not met starting at ${currentFormattedDate}`, ); const pdtStartOfLastWeek = moment() - .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 @@ -359,8 +353,8 @@ const userHelper = function () { let hasWeeklySummary = false; if ( - Array.isArray(user.weeklySummaries) && - user.weeklySummaries.length + Array.isArray(user.weeklySummaries) + && user.weeklySummaries.length ) { const { summary } = user.weeklySummaries[0]; if (summary) { @@ -374,13 +368,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; @@ -404,23 +397,23 @@ const userHelper = function () { lastWeekTangibleHrs: timeSpent || 0, }, }, - { new: true } + { new: true }, ); if ( - updateResult?.weeklySummaryOption === "Not Required" || - updateResult?.weeklySummaryNotReq + updateResult?.weeklySummaryOption === 'Not Required' + || updateResult?.weeklySummaryNotReq ) { hasWeeklySummary = true; } - const cutOffDate = moment().subtract(1, "year"); + const cutOffDate = moment().subtract(1, 'year'); const oldInfringements = []; for (let k = 0; k < updateResult?.infringements.length; k += 1) { if ( - updateResult?.infringements && - moment(updateResult?.infringements[k].date).diff(cutOffDate) >= 0 + updateResult?.infringements + && moment(updateResult?.infringements[k].date).diff(cutOffDate) >= 0 ) { oldInfringements.push(updateResult.infringements[k]); } else { @@ -436,15 +429,15 @@ const userHelper = function () { oldInfringements: { $each: oldInfringements, $slice: -10 }, }, }, - { new: true } + { new: true }, ); } // No extra hours is needed if blue squares isn't over 5. // length +1 is because new infringement hasn't been created at this stage. const coreTeamExtraHour = Math.max(0, oldInfringements.length + 1 - 5); - const utcStartMoment = moment(pdtStartOfLastWeek).add(1, "second"); - const utcEndMoment = moment(pdtEndOfLastWeek).subtract(1, "second"); + const utcStartMoment = moment(pdtStartOfLastWeek).add(1, 'second'); + const utcEndMoment = moment(pdtEndOfLastWeek).subtract(1, 'second'); const requestsForTimeOff = await timeOffRequest.find({ requestFor: personId, @@ -462,11 +455,11 @@ const userHelper = function () { if (hasTimeOffRequest) { [requestForTimeOff] = requestsForTimeOff; requestForTimeOffStartingDate = moment( - requestForTimeOff.startingDate - ).format("dddd YYYY-MM-DD"); + requestForTimeOff.startingDate, + ).format('dddd YYYY-MM-DD'); requestForTimeOffEndingDate = moment( - requestForTimeOff.endingDate - ).format("dddd YYYY-MM-DD"); + requestForTimeOff.endingDate, + ).format('dddd YYYY-MM-DD'); requestForTimeOffreason = requestForTimeOff.reason; requestForTimeOffEmailBody = `Unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}`; } @@ -545,12 +538,12 @@ const userHelper = function () { } } else { description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format( - "dddd YYYY-MM-DD" - )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`; + 'dddd YYYY-MM-DD', + )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`; } const infringement = { - date: moment().utc().format("YYYY-MM-DD"), + date: moment().utc().format('YYYY-MM-DD'), description, }; @@ -561,11 +554,11 @@ const userHelper = function () { infringements: infringement, }, }, - { new: true } + { new: true }, ); - let emailBody = ""; - if (person.role === "Core Team" && timeRemaining > 0) { + let emailBody = ''; + if (person.role === 'Core Team' && timeRemaining > 0) { emailBody = getInfringementEmailBody( status.firstName, status.lastName, @@ -583,30 +576,30 @@ const userHelper = function () { status.infringements.length, undefined, null, - requestForTimeOffEmailBody + requestForTimeOffEmailBody, ); } emailSender( status.email, - "New Infringement Assigned", + 'New Infringement Assigned', emailBody, null, - "onecommunityglobal@gmail.com", + 'onecommunityglobal@gmail.com', status.email, - null + null, ); 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; @@ -616,20 +609,20 @@ 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: { @@ -638,7 +631,7 @@ const userHelper = function () { hrs: elem.timeSpent_hrs, }, }, - } + }, ); } } @@ -651,13 +644,13 @@ 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 + false, ); } } catch (err) { @@ -667,50 +660,50 @@ const userHelper = function () { const applyMissedHourForCoreTeam = async () => { try { - const currentDate = moment().tz("America/Los_Angeles").format(); + const currentDate = moment().tz('America/Los_Angeles').format(); logger.logInfo( - `Job for applying missed hours for Core Team members starting at ${currentDate}` + `Job for applying missed hours for Core Team members starting at ${currentDate}`, ); const startOfLastWeek = moment() - .tz("America/Los_Angeles") - .startOf("week") - .subtract(1, "week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .startOf('week') + .subtract(1, 'week') + .format('YYYY-MM-DD'); const endOfLastWeek = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(1, "week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .endOf('week') + .subtract(1, 'week') + .format('YYYY-MM-DD'); const missedHours = await userProfile.aggregate([ { $match: { - role: "Core Team", + role: 'Core Team', isActive: true, }, }, { $lookup: { - from: "timeEntries", - localField: "_id", - foreignField: "personId", + from: 'timeEntries', + localField: '_id', + foreignField: 'personId', pipeline: [ { $match: { $expr: { $and: [ - { $eq: ["$isTangible", true] }, - { $gte: ["$dateOfWork", startOfLastWeek] }, - { $lte: ["$dateOfWork", endOfLastWeek] }, + { $eq: ['$isTangible', true] }, + { $gte: ['$dateOfWork', startOfLastWeek] }, + { $lte: ['$dateOfWork', endOfLastWeek] }, ], }, }, }, ], - as: "timeEntries", + as: 'timeEntries', }, }, { @@ -722,8 +715,8 @@ const userHelper = function () { $subtract: [ { $sum: [ - { $ifNull: ["$missedHours", 0] }, - "$weeklycommittedHours", + { $ifNull: ['$missedHours', 0] }, + '$weeklycommittedHours', ], }, { @@ -731,8 +724,8 @@ const userHelper = function () { { $sum: { $map: { - input: "$timeEntries", - in: "$$this.totalSeconds", + input: '$timeEntries', + in: '$$this.totalSeconds', }, }, }, @@ -766,13 +759,13 @@ const userHelper = function () { }; const deleteBlueSquareAfterYear = async () => { - const currentFormattedDate = moment().tz("America/Los_Angeles").format(); + const currentFormattedDate = moment().tz('America/Los_Angeles').format(); logger.logInfo( - `Job for deleting blue squares older than 1 year starting at ${currentFormattedDate}` + `Job for deleting blue squares older than 1 year starting at ${currentFormattedDate}`, ); - const cutOffDate = moment().subtract(1, "year").format("YYYY-MM-DD"); + const cutOffDate = moment().subtract(1, 'year').format('YYYY-MM-DD'); try { const results = await userProfile.updateMany( @@ -785,7 +778,7 @@ const userHelper = function () { }, }, }, - } + }, ); logger.logInfo(results); @@ -795,16 +788,16 @@ const userHelper = function () { }; const reActivateUser = async () => { - const currentFormattedDate = moment().tz("America/Los_Angeles").format(); + const currentFormattedDate = moment().tz('America/Los_Angeles').format(); logger.logInfo( - `Job for activating users based on scheduled re-activation date starting at ${currentFormattedDate}` + `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]; @@ -819,21 +812,21 @@ const userHelper = function () { endDate: user.endDate, }, }, - { new: true } + { new: true }, ); logger.logInfo( `User with id: ${user._id} was re-acticated at ${moment() - .tz("America/Los_Angeles") - .format()}.` + .tz('America/Los_Angeles') + .format()}.`, ); const id = user._id; const person = await userProfile.findById(id); - const endDate = moment(person.endDate).format("YYYY-MM-DD"); + const endDate = moment(person.endDate).format('YYYY-MM-DD'); logger.logInfo( `User with id: ${ user._id - } was re-acticated at ${moment().format()}.` + } was re-acticated at ${moment().format()}.`, ); const subject = `IMPORTANT:${person.firstName} ${person.lastName} has been RE-activated in the Highest Good Network`; @@ -849,12 +842,12 @@ const userHelper = function () {

The HGN A.I. (and One Community)

`; emailSender( - "onecommunityglobal@gmail.com", + 'onecommunityglobal@gmail.com', subject, emailBody, null, null, - person.email + person.email, ); } } @@ -868,7 +861,7 @@ const userHelper = function () { current, firstName, lastName, - emailAddress + emailAddress, ) { if (!current) return; const newOriginal = original.toObject(); @@ -879,58 +872,58 @@ const userHelper = function () { newInfringements = _.differenceWith( newCurrent, newOriginal, - (arrVal, othVal) => arrVal._id.equals(othVal._id) + (arrVal, othVal) => arrVal._id.equals(othVal._id), ); newInfringements.forEach((element) => { emailSender( emailAddress, - "New Infringement Assigned", + 'New Infringement Assigned', getInfringementEmailBody( firstName, lastName, element, - totalInfringements + totalInfringements, ), null, - "onecommunityglobal@gmail.com", - emailAddress + 'onecommunityglobal@gmail.com', + emailAddress, ); }); }; const replaceBadge = async function (personId, oldBadgeId, newBadgeId) { userProfile.updateOne( - { _id: personId, "badgeCollection.badge": oldBadgeId }, + { _id: personId, 'badgeCollection.badge': oldBadgeId }, { $set: { - "badgeCollection.$.badge": newBadgeId, - "badgeCollection.$.lastModified": Date.now().toString(), - "badgeCollection.$.count": 1, - "badgeCollection.$.earnedDate": [earnedDateBadge()], + 'badgeCollection.$.badge': newBadgeId, + 'badgeCollection.$.lastModified': Date.now().toString(), + 'badgeCollection.$.count': 1, + 'badgeCollection.$.earnedDate': [earnedDateBadge()], }, }, (err) => { if (err) { throw new Error(err); } - } + }, ); }; const increaseBadgeCount = async function (personId, badgeId) { userProfile.updateOne( - { _id: personId, "badgeCollection.badge": badgeId }, + { _id: personId, 'badgeCollection.badge': badgeId }, { - $inc: { "badgeCollection.$.count": 1 }, - $set: { "badgeCollection.$.lastModified": Date.now().toString() }, - $push: { "badgeCollection.$.earnedDate": earnedDateBadge() }, + $inc: { 'badgeCollection.$.count': 1 }, + $set: { 'badgeCollection.$.lastModified': Date.now().toString() }, + $push: { 'badgeCollection.$.earnedDate': earnedDateBadge() }, }, (err) => { if (err) { console.log(err); } - } + }, ); }; @@ -938,7 +931,7 @@ const userHelper = function () { personId, badgeId, count = 1, - featured = false + featured = false, ) { userProfile.findByIdAndUpdate( personId, @@ -957,7 +950,7 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); }; @@ -974,7 +967,7 @@ const userHelper = function () { if (err) { throw new Error(err); } - } + }, ); }; @@ -987,39 +980,43 @@ const userHelper = function () { const userInfo = await userProfile.findById(personId); let newEarnedDate = []; const recordToUpdate = userInfo.badgeCollection.find( - (item) => item.badge._id.toString() === badgeId.toString() + (item) => item.badge._id.toString() === badgeId.toString(), ); if (!recordToUpdate) { - throw new Error("Badge not found"); + throw new Error('Badge not found'); + } + // If the count is the same, do nothing + if (recordToUpdate.count === count) { + return; } const copyOfEarnedDate = recordToUpdate.earnedDate; - if (copyOfEarnedDate.length < count) { - // if the EarnedDate count is less than the new count, add a earned date to the end of the collection - while (copyOfEarnedDate.length < count) { + // Update: We refrain from automatically correcting the mismatch problem as we intend to preserve the original + // earned date even when a badge is deleted. This approach ensures that a record of badges earned is maintained, + // preventing oversight of any mismatches caused by bugs. + if (recordToUpdate.count < count) { + let dateToAdd = count - recordToUpdate.count; + // if the EarnedDate count is less than the new count, add a earned date to the end of the collection + while (dateToAdd > 0) { copyOfEarnedDate.push(earnedDateBadge()); + dateToAdd -= 1; } - } else { - // if the EarnedDate count is greater than the new count, remove the oldest earned date of the collection until it matches the new count - 1 - while (copyOfEarnedDate.length >= count) { - copyOfEarnedDate.shift(); - } - copyOfEarnedDate.push(earnedDateBadge()); } newEarnedDate = [...copyOfEarnedDate]; userProfile.updateOne( - { _id: personId, "badgeCollection.badge": badgeId }, + { _id: personId, 'badgeCollection.badge': badgeId }, { $set: { - "badgeCollection.$.count": count, - "badgeCollection.$.lastModified": Date.now().toString(), - "badgeCollection.$.earnedDate": newEarnedDate, + 'badgeCollection.$.count': count, + 'badgeCollection.$.lastModified': Date.now().toString(), + 'badgeCollection.$.earnedDate': newEarnedDate, + 'badgeCollection.$.hasBadgeDeletionImpact': recordToUpdate.count > count, // badge deletion impact set to true if the new count is less than the old count }, }, (err) => { if (err) { throw new Error(err); } - } + }, ); } catch (err) { logger.logException(err); @@ -1034,7 +1031,7 @@ const userHelper = function () { user, badgeCollection, hrs, - weeks + weeks, ) { // Check each Streak Greater than One to check if it works if (weeks < 3) { @@ -1045,7 +1042,7 @@ const userHelper = function () { .aggregate([ { $match: { - type: "X Hours for X Week Streak", + type: 'X Hours for X Week Streak', weeks: { $gt: 1, $lt: weeks }, totalHrs: hrs, }, @@ -1053,9 +1050,9 @@ const userHelper = function () { { $sort: { weeks: -1, totalHrs: -1 } }, { $group: { - _id: "$weeks", + _id: '$weeks', badges: { - $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" }, + $push: { _id: '$_id', hrs: '$totalHrs', weeks: '$weeks' }, }, }, }, @@ -1065,16 +1062,16 @@ const userHelper = function () { streak.badges.every((bdge) => { for (let i = 0; i < badgeCollection.length; i += 1) { if ( - badgeCollection[i].badge?.type === - "X Hours for X Week Streak" && - badgeCollection[i].badge?.weeks === bdge.weeks && - bdge.hrs === hrs && - !removed + badgeCollection[i].badge?.type + === 'X Hours for X Week Streak' + && badgeCollection[i].badge?.weeks === bdge.weeks + && bdge.hrs === hrs + && !removed ) { changeBadgeCount( personId, badgeCollection[i].badge._id, - badgeCollection[i].badge.count - 1 + badgeCollection[i].badge.count - 1, ); removed = true; return false; @@ -1090,20 +1087,20 @@ const userHelper = function () { const checkNoInfringementStreak = async function ( personId, user, - badgeCollection + badgeCollection, ) { let badgeOfType; for (let i = 0; i < badgeCollection.length; i += 1) { - if (badgeCollection[i].badge?.type === "No Infringement Streak") { + if (badgeCollection[i].badge?.type === 'No Infringement Streak') { if ( - badgeOfType && - badgeOfType.months <= badgeCollection[i].badge.months + badgeOfType + && badgeOfType.months <= badgeCollection[i].badge.months ) { removeDupBadge(personId, badgeOfType._id); badgeOfType = badgeCollection[i].badge; } else if ( - badgeOfType && - badgeOfType.months > badgeCollection[i].badge.months + badgeOfType + && badgeOfType.months > badgeCollection[i].badge.months ) { removeDupBadge(personId, badgeCollection[i].badge._id); } else if (!badgeOfType) { @@ -1112,7 +1109,7 @@ const userHelper = function () { } } await badge - .find({ type: "No Infringement Streak" }) + .find({ type: 'No Infringement Streak' }) .sort({ months: -1 }) .then((results) => { if (!Array.isArray(results) || !results.length) { @@ -1124,19 +1121,19 @@ const userHelper = function () { if (elem.months <= 12) { if ( - moment().diff(moment(user.createdDate), "months", true) >= - elem.months + 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 + user.infringements[user.infringements?.length - 1].date, ), - "months", - true - ) + 'months', + true, + ), ) >= elem.months ) { if (badgeOfType) { @@ -1144,7 +1141,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -1155,29 +1152,29 @@ const userHelper = function () { } } else if (user?.infringements?.length === 0) { if ( - moment().diff(moment(user.createdDate), "months", true) >= - elem.months + 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 + .date, ), - "months", - true - ) - ) >= - elem.months - 12 + 'months', + true, + ), + ) + >= elem.months - 12 ) { if (badgeOfType) { if (badgeOfType._id.toString() !== elem._id.toString()) { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(elem._id) + mongoose.Types.ObjectId(elem._id), ); } return false; @@ -1196,13 +1193,13 @@ const userHelper = function () { const checkMinHoursMultiple = async function ( personId, user, - badgeCollection + badgeCollection, ) { const badgesOfType = badgeCollection .map((obj) => obj.badge) - .filter((badgeItem) => badgeItem.type === "Minimum Hours Multiple"); + .filter((badgeItem) => badgeItem.type === 'Minimum Hours Multiple'); await badge - .find({ type: "Minimum Hours Multiple" }) + .find({ type: 'Minimum Hours Multiple' }) .sort({ multiple: -1 }) .then((results) => { if (!Array.isArray(results) || !results.length) { @@ -1213,16 +1210,16 @@ 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( - (badgeItem) => badgeItem._id.toString() === elem._id.toString() + (badgeItem) => badgeItem._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)); } @@ -1236,7 +1233,7 @@ const userHelper = function () { const duplicateBadges = []; for (let i = 0; i < badgeCollection.length; i += 1) { - if (badgeCollection[i].badge?.type === "Personal Max") { + if (badgeCollection[i].badge?.type === 'Personal Max') { if (!badgeOfType) { badgeOfType = badgeCollection[i]; } else { @@ -1247,23 +1244,23 @@ const userHelper = function () { await removeDupBadge(personId, b._id); } } - await badge.findOne({ type: "Personal Max" }).then((results) => { + await badge.findOne({ type: 'Personal Max' }).then((results) => { if ( - user.lastWeekTangibleHrs && - user.lastWeekTangibleHrs >= 1 && - user.lastWeekTangibleHrs === user.personalBestMaxHrs + user.lastWeekTangibleHrs + && user.lastWeekTangibleHrs >= 1 + && user.lastWeekTangibleHrs === user.personalBestMaxHrs ) { if (badgeOfType) { changeBadgeCount( personId, mongoose.Types.ObjectId(badgeOfType._id), - user.personalBestMaxHrs + user.personalBestMaxHrs, ); } else { addBadge( personId, mongoose.Types.ObjectId(results._id), - user.personalBestMaxHrs + user.personalBestMaxHrs, ); } } @@ -1274,17 +1271,17 @@ const userHelper = function () { const checkMostHrsWeek = async function (personId, user, badgeCollection) { if ( - user.weeklycommittedHours > 0 && - user.lastWeekTangibleHrs > user.weeklycommittedHours + user.weeklycommittedHours > 0 + && user.lastWeekTangibleHrs > user.weeklycommittedHours ) { const badgeOfType = badgeCollection - .filter((object) => object.badge.type === "Most Hrs in Week") + .filter((object) => object.badge.type === 'Most Hrs in Week') .map((object) => object.badge); - await badge.findOne({ type: "Most Hrs in Week" }).then((results) => { + await badge.findOne({ type: 'Most Hrs in Week' }).then((results) => { userProfile .aggregate([ { $match: { isActive: true } }, - { $group: { _id: 1, maxHours: { $max: "$lastWeekTangibleHrs" } } }, + { $group: { _id: 1, maxHours: { $max: '$lastWeekTangibleHrs' } } }, ]) .then((userResults) => { if (badgeOfType.length > 1) { @@ -1292,13 +1289,13 @@ const userHelper = function () { } if ( - user.lastWeekTangibleHrs && - user.lastWeekTangibleHrs >= userResults[0].maxHours + user.lastWeekTangibleHrs + && user.lastWeekTangibleHrs >= userResults[0].maxHours ) { if (badgeOfType.length) { increaseBadgeCount( personId, - mongoose.Types.ObjectId(badgeOfType[0]._id) + mongoose.Types.ObjectId(badgeOfType[0]._id), ); } else { addBadge(personId, mongoose.Types.ObjectId(results._id)); @@ -1314,12 +1311,12 @@ const userHelper = function () { // Handle Increasing the 1 week streak badges const badgesOfType = []; for (let i = 0; i < badgeCollection.length; i += 1) { - if (badgeCollection[i].badge?.type === "X Hours for X Week Streak") { + if (badgeCollection[i].badge?.type === 'X Hours for X Week Streak') { badgesOfType.push(badgeCollection[i].badge); } } await badge - .find({ type: "X Hours for X Week Streak", weeks: 1 }) + .find({ type: 'X Hours for X Week Streak', weeks: 1 }) .sort({ totalHrs: -1 }) .then((results) => { results.every((elem) => { @@ -1344,13 +1341,13 @@ const userHelper = function () { // Check each Streak Greater than One to check if it works await badge .aggregate([ - { $match: { type: "X Hours for X Week Streak", weeks: { $gt: 1 } } }, + { $match: { type: 'X Hours for X Week Streak', weeks: { $gt: 1 } } }, { $sort: { weeks: -1, totalHrs: -1 } }, { $group: { - _id: "$weeks", + _id: '$weeks', badges: { - $push: { _id: "$_id", hrs: "$totalHrs", weeks: "$weeks" }, + $push: { _id: '$_id', hrs: '$totalHrs', weeks: '$weeks' }, }, }, }, @@ -1362,19 +1359,19 @@ const userHelper = function () { let badgeOfType; for (let i = 0; i < badgeCollection.length; i += 1) { if ( - badgeCollection[i].badge?.type === - "X Hours for X Week Streak" && - badgeCollection[i].badge?.weeks === bdge.weeks + badgeCollection[i].badge?.type + === 'X Hours for X Week Streak' + && badgeCollection[i].badge?.weeks === bdge.weeks ) { if ( - badgeOfType && - badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs + 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) { @@ -1399,7 +1396,7 @@ const userHelper = function () { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(bdge._id) + mongoose.Types.ObjectId(bdge._id), ); removePrevHrBadge( @@ -1407,7 +1404,7 @@ const userHelper = function () { user, badgeCollection, bdge.hrs, - bdge.weeks + bdge.weeks, ); } else if (!badgeOfType) { addBadge(personId, mongoose.Types.ObjectId(bdge._id)); @@ -1416,19 +1413,19 @@ 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) + mongoose.Types.ObjectId(badgeOfType._id), ); removePrevHrBadge( personId, user, badgeCollection, bdge.hrs, - bdge.weeks + bdge.weeks, ); } return false; @@ -1445,16 +1442,16 @@ const userHelper = function () { const checkLeadTeamOfXplus = async function ( personId, user, - badgeCollection + badgeCollection, ) { const leaderRoles = [ - "Mentor", - "Manager", - "Administrator", - "Owner", - "Core Team", + 'Mentor', + 'Manager', + 'Administrator', + 'Owner', + 'Core Team', ]; - const approvedRoles = ["Mentor", "Manager"]; + const approvedRoles = ['Mentor', 'Manager']; if (!approvedRoles.includes(user.role)) return; let teamMembers; @@ -1479,16 +1476,16 @@ 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 (badgeCollection[i].badge?.type === 'Lead a team of X+') { if ( - badgeOfType && - badgeOfType.people <= badgeCollection[i].badge.people + badgeOfType + && badgeOfType.people <= badgeCollection[i].badge.people ) { removeDupBadge(personId, badgeOfType._id); badgeOfType = badgeCollection[i].badge; } else if ( - badgeOfType && - badgeOfType.people > badgeCollection[i].badge.people + badgeOfType + && badgeOfType.people > badgeCollection[i].badge.people ) { removeDupBadge(personId, badgeCollection[i].badge._id); } else if (!badgeOfType) { @@ -1497,7 +1494,7 @@ const userHelper = function () { } } await badge - .find({ type: "Lead a team of X+" }) + .find({ type: 'Lead a team of X+' }) .sort({ people: -1 }) .then((results) => { if (!Array.isArray(results) || !results.length) { @@ -1507,14 +1504,14 @@ const userHelper = function () { if (teamMembers && teamMembers.length >= bg.people) { if (badgeOfType) { if ( - badgeOfType._id.toString() !== bg._id.toString() && - badgeOfType.people < bg.people + badgeOfType._id.toString() !== bg._id.toString() + && badgeOfType.people < bg.people ) { replaceBadge( personId, mongoose.Types.ObjectId(badgeOfType._id), - mongoose.Types.ObjectId(bg._id) + mongoose.Types.ObjectId(bg._id), ); } return false; @@ -1531,39 +1528,39 @@ const userHelper = function () { const checkTotalHrsInCat = async function (personId, user, badgeCollection) { const hoursByCategory = user.hoursByCategory || {}; const categories = [ - "food", - "energy", - "housing", - "education", - "society", - "economics", - "stewardship", + 'food', + 'energy', + 'housing', + 'education', + 'society', + 'economics', + 'stewardship', ]; const badgesOfType = badgeCollection - .filter((object) => object.badge.type === "Total Hrs in Category") + .filter((object) => object.badge.type === 'Total Hrs in Category') .map((object) => object.badge); categories.forEach(async (category) => { const categoryHrs = Object.keys(hoursByCategory).find( - (elem) => elem === category + (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) { @@ -1575,7 +1572,7 @@ const userHelper = function () { const newCatg = category.charAt(0).toUpperCase() + category.slice(1); await badge - .find({ type: "Total Hrs in Category", category: newCatg }) + .find({ type: 'Total Hrs in Category', category: newCatg }) .sort({ totalHrs: -1 }) .then((results) => { @@ -1585,8 +1582,8 @@ const userHelper = function () { results.every((elem) => { if ( - hoursByCategory[categoryHrs] >= 100 && - hoursByCategory[categoryHrs] >= elem.totalHrs + hoursByCategory[categoryHrs] >= 100 + && hoursByCategory[categoryHrs] >= elem.totalHrs ) { let theBadge; for (let i = 0; i < badgesOfType.length; i += 1) { @@ -1601,13 +1598,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; @@ -1625,7 +1622,7 @@ const userHelper = function () { try { const users = await userProfile .find({ isActive: true }) - .populate("badgeCollection.badge"); + .populate('badgeCollection.badge'); for (let i = 0; i < users.length; i += 1) { const user = users[i]; const { _id, badgeCollection } = user; @@ -1652,13 +1649,13 @@ const userHelper = function () { const userId = mongoose.Types.ObjectId(personId); const pdtstart = moment() - .tz("America/Los_Angeles") - .startOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .startOf('week') + .format('YYYY-MM-DD'); const pdtend = moment() - .tz("America/Los_Angeles") - .endOf("week") - .format("YYYY-MM-DD"); + .tz('America/Los_Angeles') + .endOf('week') + .format('YYYY-MM-DD'); return timeEntries .find( @@ -1667,12 +1664,12 @@ const userHelper = function () { dateOfWork: { $gte: pdtstart, $lte: pdtend }, isTangible: true, }, - "totalSeconds" + 'totalSeconds', ) .then((results) => { const totalTangibleWeeklySeconds = results.reduce( (acc, { totalSeconds }) => acc + totalSeconds, - 0 + 0, ); return (totalTangibleWeeklySeconds / 3600).toFixed(2); }); @@ -1682,28 +1679,28 @@ const userHelper = function () { try { const users = await userProfile.find( { isActive: true, endDate: { $exists: true } }, - "_id isActive endDate" + '_id isActive endDate', ); for (let i = 0; i < users.length; i += 1) { const user = users[i]; const { endDate } = user; endDate.setHours(endDate.getHours() + 7); - if (moment().isAfter(moment(endDate).add(1, "days"))) { + if (moment().isAfter(moment(endDate).add(1, 'days'))) { await userProfile.findByIdAndUpdate( user._id, user.set({ isActive: false, }), - { new: true } + { new: true }, ); const id = user._id; const person = await userProfile.findById(id); - const lastDay = moment(person.endDate).format("YYYY-MM-DD"); + const lastDay = moment(person.endDate).format('YYYY-MM-DD'); logger.logInfo( `User with id: ${ user._id - } was de-acticated at ${moment().format()}.` + } was de-acticated at ${moment().format()}.`, ); const subject = `IMPORTANT:${person.firstName} ${person.lastName} has been deactivated in the Highest Good Network`; @@ -1719,12 +1716,12 @@ const userHelper = function () {

The HGN A.I. (and One Community)

`; emailSender( - "onecommunityglobal@gmail.com", + 'onecommunityglobal@gmail.com', subject, emailBody, null, null, - person.email + person.email, ); } } @@ -1745,16 +1742,16 @@ const userHelper = function () { const deleteOldTimeOffRequests = async () => { const endOfLastWeek = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(1, "week"); + .tz('America/Los_Angeles') + .endOf('week') + .subtract(1, 'week'); - const utcEndMoment = moment(endOfLastWeek).add(1, "second"); + const utcEndMoment = moment(endOfLastWeek).add(1, 'second'); try { await timeOffRequest.deleteMany({ endingDate: { $lte: utcEndMoment } }); - console.log("Deleted expired time off requests."); + console.log('Deleted expired time off requests.'); } catch (error) { - console.error("Error deleting expired time off requests:", error); + console.error('Error deleting expired time off requests:', error); } }; diff --git a/src/models/bmdashboard/buildingInventoryItem.js b/src/models/bmdashboard/buildingInventoryItem.js index 232c91010..ab8e904ed 100644 --- a/src/models/bmdashboard/buildingInventoryItem.js +++ b/src/models/bmdashboard/buildingInventoryItem.js @@ -128,7 +128,6 @@ const buildingTool = largeItemBase.discriminator('tool_item', new mongoose.Schem code: { type: String, default: '001' }, })); - //----------------- // EQUIPMENT SCHEMA //----------------- diff --git a/src/models/bmdashboard/buildingNewLesson.js b/src/models/bmdashboard/buildingNewLesson.js index 35fb0d562..f239135a7 100644 --- a/src/models/bmdashboard/buildingNewLesson.js +++ b/src/models/bmdashboard/buildingNewLesson.js @@ -16,9 +16,9 @@ const buildingNewLesson = new Schema({ { data: Buffer, contentType: String, - filename: String - } - ] + filename: String, + }, + ], }); module.exports = mongoose.model('buildingNewLesson', buildingNewLesson, 'buildingNewLessons'); diff --git a/src/models/bmdashboard/buildingTool.js b/src/models/bmdashboard/buildingTool.js index 2ed64f512..50441d22d 100644 --- a/src/models/bmdashboard/buildingTool.js +++ b/src/models/bmdashboard/buildingTool.js @@ -5,7 +5,7 @@ const { Schema } = mongoose; const buildingTool = new Schema({ itemType: { type: mongoose.SchemaTypes.ObjectId, ref: 'buildingInventoryType' }, project: { type: mongoose.SchemaTypes.ObjectId, ref: 'buildingProject' }, - code: { type: Number}, // add function to create code for on-site tool tracking.Not marked as 'required' as it breaks the tool purchase form functionality. + code: { type: Number }, // add function to create code for on-site tool tracking.Not marked as 'required' as it breaks the tool purchase form functionality. purchaseStatus: { type: String, enum: ['Rental', 'Purchase'] }, // add discriminator based on rental or purchase so these fields are required if tool is rented. Not marked as 'required' as it breaks the tool purchase form functionality. rentedOnDate: Date, diff --git a/src/models/bmdashboard/buldingLessonLike.js b/src/models/bmdashboard/buldingLessonLike.js index 5b16bc341..0ad2025d2 100644 --- a/src/models/bmdashboard/buldingLessonLike.js +++ b/src/models/bmdashboard/buldingLessonLike.js @@ -6,4 +6,4 @@ const LikeSchema = new Schema({ lesson: { type: mongoose.SchemaTypes.ObjectId, ref: 'buildingNewLesson', required: true }, }); - module.exports = mongoose.model('Like', LikeSchema); \ No newline at end of file + module.exports = mongoose.model('Like', LikeSchema); diff --git a/src/models/role.js b/src/models/role.js index 2ea52eec8..6cca0acdd 100644 --- a/src/models/role.js +++ b/src/models/role.js @@ -2,7 +2,6 @@ const mongoose = require('mongoose'); const { Schema } = mongoose; - const Role = new Schema({ roleName: { type: String, required: true, unique: true }, permissions: [String], diff --git a/src/models/rolePreset.js b/src/models/rolePreset.js index 1bf785e2d..34385485b 100644 --- a/src/models/rolePreset.js +++ b/src/models/rolePreset.js @@ -2,7 +2,6 @@ const mongoose = require('mongoose'); const { Schema } = mongoose; - const RolePermissionPresets = new Schema({ roleName: { type: String, required: true }, presetName: { type: String, required: true }, diff --git a/src/models/timeentry.js b/src/models/timeentry.js index 66d8d6575..4ae0b94fa 100644 --- a/src/models/timeentry.js +++ b/src/models/timeentry.js @@ -2,7 +2,6 @@ const mongoose = require('mongoose'); const { Schema } = mongoose; - const TimeEntry = new Schema({ entryType: { type: String, required: true, default: 'default' }, personId: { type: Schema.Types.ObjectId, ref: 'userProfile' }, diff --git a/src/models/userProfile.js b/src/models/userProfile.js index a922146f9..153028818 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,12 +15,11 @@ 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 }, @@ -39,8 +38,9 @@ const userProfileSchema = new Schema({ required: true, trim: true, minlength: 2, + index: true, }, - lastName: { type: String, required: true, minlength: 2 }, + lastName: { type: String, required: true, minlength: 2, index: true }, phoneNumber: [{ type: String, phoneNumber: String }], jobTitle: [{ type: String, jobTitle: String }], bio: { type: String }, @@ -49,7 +49,7 @@ const userProfileSchema = new Schema({ required: true, unique: true, validate: [ - validate({ validator: "isEmail", message: "Email address is invalid" }), + validate({ validator: 'isEmail', message: 'Email address is invalid' }), ], }, copiedAiPrompt: { type: Date, default: Date.now() }, @@ -68,14 +68,18 @@ const userProfileSchema = new Schema({ { _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: new Date()}, + lastModified: { type: Date, required: true, default: Date.now() }, + // This field is used to determine if the badge deletion will impact the user's badge collection. + // If the user has a badge with hasBadgeDeletionImpact set to true, then the a mismatch in badge + // count and earned date will be intentionally created. + hasBadgeDeletionImpact: { type: Boolean, default: false }, featured: { type: Boolean, required: true, @@ -114,13 +118,13 @@ const userProfileSchema = new Schema({ }, ], location: { - userProvided: { type: String, default: "" }, + userProvided: { type: String, default: '' }, coords: { - lat: { type: Number, default: "" }, - lng: { type: Number, default: "" }, + lat: { type: Number, default: '' }, + lng: { type: Number, default: '' }, }, - country: { type: String, default: "" }, - city: { type: String, default: "" }, + country: { type: String, default: '' }, + city: { type: String, default: '' }, }, oldInfringements: [ { @@ -142,7 +146,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 }, @@ -172,17 +176,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 }, }, @@ -193,27 +197,27 @@ const userProfileSchema = new Schema({ date: { type: Date, required: true, - default: moment().tz("America/Los_Angeles").toDate(), + 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 }, 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', }, }, infoCollections: [ @@ -228,22 +232,22 @@ const userProfileSchema = new Schema({ timeOffTill: { type: Date, default: undefined }, }); -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", + 'userProfile', userProfileSchema, - "userProfiles" + 'userProfiles', ); diff --git a/src/routes/actionItemRouter.js b/src/routes/actionItemRouter.js index 1ab20aea1..807dddeac 100644 --- a/src/routes/actionItemRouter.js +++ b/src/routes/actionItemRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (actionItem) { const controller = require('../controllers/actionItemController')(actionItem); const actionItemRouter = express.Router(); @@ -8,11 +7,9 @@ const routes = function (actionItem) { actionItemRouter.route('/actionItem') .post(controller.postactionItem); - actionItemRouter.route('/actionItem/user/:userId') .get(controller.getactionItem); - actionItemRouter.route('/actionItem/:actionItemId') .delete(controller.deleteactionItem) .put(controller.editactionItem); diff --git a/src/routes/badgeRouter.js b/src/routes/badgeRouter.js index 6326aa817..c9dc6ee7b 100644 --- a/src/routes/badgeRouter.js +++ b/src/routes/badgeRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (badge) { const controller = require('../controllers/badgeController')(badge); @@ -20,5 +19,4 @@ const routes = function (badge) { return badgeRouter; }; - module.exports = routes; diff --git a/src/routes/bmdashboard/bmMaterialsRouter.js b/src/routes/bmdashboard/bmMaterialsRouter.js index 733148d14..76200ff85 100644 --- a/src/routes/bmdashboard/bmMaterialsRouter.js +++ b/src/routes/bmdashboard/bmMaterialsRouter.js @@ -13,7 +13,6 @@ const routes = function (buildingMaterial) { materialsRouter.route('/updateMaterialRecordBulk') .post(controller.bmPostMaterialUpdateBulk); - return materialsRouter; }; diff --git a/src/routes/bmdashboard/bmToolRouter.js b/src/routes/bmdashboard/bmToolRouter.js index 4afb3b87b..e58895433 100644 --- a/src/routes/bmdashboard/bmToolRouter.js +++ b/src/routes/bmdashboard/bmToolRouter.js @@ -6,7 +6,7 @@ const routes = function (BuildingTool) { toolRouter.route('/tools/:toolId') .get(controller.fetchSingleTool); - + toolRouter.route('/tools/purchase') .post(controller.bmPurchaseTools); diff --git a/src/routes/dashboardRouter.js b/src/routes/dashboardRouter.js index 23ea5fc64..d623815c0 100644 --- a/src/routes/dashboardRouter.js +++ b/src/routes/dashboardRouter.js @@ -40,7 +40,6 @@ const route = function () { Dashboardrouter.route('/dashboard/makesuggestion/:userId') .post(controller.sendMakeSuggestion); - return Dashboardrouter; }; diff --git a/src/routes/forcePwdRouter.js b/src/routes/forcePwdRouter.js index 2156368a2..200aa9b7e 100644 --- a/src/routes/forcePwdRouter.js +++ b/src/routes/forcePwdRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (userProfile) { const forcePwdrouter = express.Router(); const controller = require('../controllers/forcePwdController')(userProfile); diff --git a/src/routes/informationRouter.js b/src/routes/informationRouter.js index 1627ed5b8..7a0c78e7b 100644 --- a/src/routes/informationRouter.js +++ b/src/routes/informationRouter.js @@ -1,11 +1,9 @@ const express = require('express'); - const routes = function (information) { const controller = require('../controllers/informationController')(information); const informationRouter = express.Router(); - informationRouter.route('/informations') .get(controller.getInformations) .post(controller.addInformation); diff --git a/src/routes/inventoryRouter.js b/src/routes/inventoryRouter.js index 5edc7f79d..b0bd3ac89 100644 --- a/src/routes/inventoryRouter.js +++ b/src/routes/inventoryRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (item, itemType) { const controller = require('../controllers/inventoryController')(item, itemType); @@ -36,5 +35,4 @@ const routes = function (item, itemType) { return inventoryRouter; }; - module.exports = routes; diff --git a/src/routes/isEmailExistsRouter.js b/src/routes/isEmailExistsRouter.js index d19b14fe2..4c21da9de 100644 --- a/src/routes/isEmailExistsRouter.js +++ b/src/routes/isEmailExistsRouter.js @@ -1,4 +1,3 @@ - const express = require('express'); const routes = function () { diff --git a/src/routes/loginRouter.js b/src/routes/loginRouter.js index f999cf122..1b52e2356 100644 --- a/src/routes/loginRouter.js +++ b/src/routes/loginRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function () { const loginrouter = express.Router(); const controller = require('../controllers/logincontroller')(); diff --git a/src/routes/notificationRouter.js b/src/routes/notificationRouter.js index 5614b91e4..d5883cb45 100644 --- a/src/routes/notificationRouter.js +++ b/src/routes/notificationRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (notification) { const controller = require('../controllers/notificationController')(notification); const notificationRouter = express.Router(); @@ -8,7 +7,6 @@ const routes = function (notification) { notificationRouter.route('/notification/user/:userId') .get(controller.getUserNotifications); - notificationRouter.route('/notification/:notificationId') .delete(controller.deleteUserNotification); diff --git a/src/routes/popupEditorBackupRouter.js b/src/routes/popupEditorBackupRouter.js index 48200f0aa..14257a3f2 100644 --- a/src/routes/popupEditorBackupRouter.js +++ b/src/routes/popupEditorBackupRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (popupEditorBackup) { const controller = require('../controllers/popupEditorBackupController')(popupEditorBackup); const popupEditorBackupRouter = express.Router(); diff --git a/src/routes/popupEditorRouter.js b/src/routes/popupEditorRouter.js index b21a5b285..dda2e94f3 100644 --- a/src/routes/popupEditorRouter.js +++ b/src/routes/popupEditorRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (popupEditor) { const controller = require('../controllers/popupEditorController')(popupEditor); const popupEditorRouter = express.Router(); diff --git a/src/routes/projectRouter.js b/src/routes/projectRouter.js index e400d3330..de55b2f55 100644 --- a/src/routes/projectRouter.js +++ b/src/routes/projectRouter.js @@ -1,16 +1,13 @@ const express = require('express'); - const routes = function (project) { const controller = require('../controllers/projectController')(project); const projectRouter = express.Router(); - projectRouter.route('/projects') .get(controller.getAllProjects) .post(controller.postProject); - projectRouter.route('/project/:projectId') .get(controller.getProjectById) .post(controller.putProject) @@ -20,12 +17,10 @@ const routes = function (project) { projectRouter.route('/projects/user/:userId') .get(controller.getUserProjects); - projectRouter.route('/project/:projectId/users/') .post(controller.assignProjectToUsers) .get(controller.getprojectMembership); - return projectRouter; }; diff --git a/src/routes/reasonRouter.js b/src/routes/reasonRouter.js index 765535ad1..1e38da5b6 100644 --- a/src/routes/reasonRouter.js +++ b/src/routes/reasonRouter.js @@ -19,7 +19,6 @@ const route = (ReasonModel, UserModel) => { reasonRouter.delete('/reason/:userId', reasonController.deleteReason); - return reasonRouter; }; diff --git a/src/routes/taskNotificationRouter.js b/src/routes/taskNotificationRouter.js index 2c90a405d..9f1120914 100644 --- a/src/routes/taskNotificationRouter.js +++ b/src/routes/taskNotificationRouter.js @@ -22,7 +22,6 @@ const routes = function (TaskNotification) { controller.markTaskNotificationAsRead, ); - // newly created endpoint TaskNotificationRouter.route( diff --git a/src/routes/taskRouter.js b/src/routes/taskRouter.js index e04b499eb..b404cea0a 100644 --- a/src/routes/taskRouter.js +++ b/src/routes/taskRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (task, userProfile) { const controller = require('../controllers/taskController')(task, userProfile); const wbsRouter = express.Router(); diff --git a/src/routes/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js index 1dd27f05b..ee7af1ca6 100644 --- a/src/routes/timeOffRequestRouter.js +++ b/src/routes/timeOffRequestRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (timeOffRequest) { const timeOffRequestRouter = express.Router(); const controller = require('../controllers/timeOffRequestController')(timeOffRequest); diff --git a/src/routes/timeZoneAPIRoutes.js b/src/routes/timeZoneAPIRoutes.js index c559d8e23..5682ed36f 100644 --- a/src/routes/timeZoneAPIRoutes.js +++ b/src/routes/timeZoneAPIRoutes.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function () { const controller = require('../controllers/timeZoneAPIController')(); const timeZoneAPIRouter = express.Router(); diff --git a/src/routes/userProfileRouter.js b/src/routes/userProfileRouter.js index ac567ebe8..74610ec50 100644 --- a/src/routes/userProfileRouter.js +++ b/src/routes/userProfileRouter.js @@ -2,7 +2,6 @@ import { body } from 'express-validator'; const express = require('express'); - const routes = function (userProfile) { const controller = require('../controllers/userProfileController')( userProfile, @@ -14,8 +13,8 @@ const routes = function (userProfile) { .route('/userProfile') .get(controller.getUserProfiles) .post( - body('firstName').customSanitizer(value => value.trim()), - body('lastName').customSanitizer(value => value.trim()), + body('firstName').customSanitizer((value) => value.trim()), + body('lastName').customSanitizer((value) => value.trim()), controller.postUserProfile, ); @@ -23,28 +22,28 @@ const routes = function (userProfile) { .route('/userProfile/:userId') .get(controller.getUserById) .put( - body('firstName').customSanitizer(value => value.trim()), - body('lastName').customSanitizer(value => value.trim()), - body('personalLinks').customSanitizer(value => value.map((link) => { - if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { - return { - ...link, - Name: link.Name.trim(), - Link: link.Link.replace(/\s/g, ''), - }; - } - throw new Error('Url not valid'); - })), - body('adminLinks').customSanitizer(value => value.map((link) => { - if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { - return { - ...link, - Name: link.Name.trim(), - Link: link.Link.replace(/\s/g, ''), - }; - } - throw new Error('Url not valid'); - })), + body('firstName').customSanitizer((value) => value.trim()), + body('lastName').customSanitizer((value) => value.trim()), + body('personalLinks').customSanitizer((value) => value.map((link) => { + if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { + return { + ...link, + Name: link.Name.trim(), + Link: link.Link.replace(/\s/g, ''), + }; + } + throw new Error('Url not valid'); + })), + body('adminLinks').customSanitizer((value) => value.map((link) => { + if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { + return { + ...link, + Name: link.Name.trim(), + Link: link.Link.replace(/\s/g, ''), + }; + } + throw new Error('Url not valid'); + })), controller.putUserProfile, ) .delete(controller.deleteUserProfile) @@ -54,6 +53,14 @@ const routes = function (userProfile) { .route('/userProfile/name/:name') .get(controller.getUserByName); + userProfileRouter + .route('/userProfile/singleName/:singleName') + .get(controller.getUserBySingleName); + + userProfileRouter + .route('/userProfile/fullName/:fullName') + .get(controller.getUserByFullName); + userProfileRouter.route('/refreshToken/:userId').get(controller.refreshToken); userProfileRouter diff --git a/src/routes/wbsRouter.js b/src/routes/wbsRouter.js index 08bfdc7b5..a5eb2d126 100644 --- a/src/routes/wbsRouter.js +++ b/src/routes/wbsRouter.js @@ -1,6 +1,5 @@ const express = require('express'); - const routes = function (wbs) { const controller = require('../controllers/wbsController')(wbs); const wbsRouter = express.Router(); diff --git a/src/startup/db.js b/src/startup/db.js index 02edb7c27..4308c5fd5 100644 --- a/src/startup/db.js +++ b/src/startup/db.js @@ -1,4 +1,3 @@ - const mongoose = require('mongoose'); const logger = require('./logger'); const userProfile = require('../models/userProfile'); @@ -24,8 +23,8 @@ const afterConnect = async () => { role: 'Volunteer', password: process.env.DEF_PWD, }) - .then(result => logger.logInfo(`TimeArchive account was created with id of ${result._id}`)) - .catch(error => logger.logException(error)); + .then((result) => logger.logInfo(`TimeArchive account was created with id of ${result._id}`)) + .catch((error) => logger.logException(error)); } } catch (error) { throw new Error(error); @@ -41,5 +40,5 @@ module.exports = function () { useFindAndModify: false, }) .then(afterConnect) - .catch(err => logger.logException(err)); + .catch((err) => logger.logException(err)); }; diff --git a/src/startup/logger.js b/src/startup/logger.js index d16f8ae3f..2417022a6 100644 --- a/src/startup/logger.js +++ b/src/startup/logger.js @@ -1,6 +1,5 @@ const Sentry = require('@sentry/node'); - exports.init = function () { Sentry.init({ dsn: process.env.SentryDSN_URL }); }; diff --git a/src/startup/middleware.js b/src/startup/middleware.js index 5f79f77b8..d75884b98 100644 --- a/src/startup/middleware.js +++ b/src/startup/middleware.js @@ -2,7 +2,6 @@ const jwt = require('jsonwebtoken'); const moment = require('moment'); const config = require('../config'); - module.exports = function (app) { app.all('*', (req, res, next) => { if (req.originalUrl === '/') { diff --git a/src/utilities/addMembersToTeams.js b/src/utilities/addMembersToTeams.js index b637fa2c1..62562a9cc 100644 --- a/src/utilities/addMembersToTeams.js +++ b/src/utilities/addMembersToTeams.js @@ -11,21 +11,21 @@ const UserProfile = require('../models/userProfile'); const Teams = require('../models/team'); const addMembersField = async () => { - await Teams.updateMany({}, { $set: { members: [] } }).catch(error => logger.logException('Error adding field:', error)); + await Teams.updateMany({}, { $set: { members: [] } }).catch((error) => logger.logException('Error adding field:', error)); const allUsers = await UserProfile.find({}); const updateOperations = allUsers .map((user) => { const { _id, teams, createdDate } = user; - return teams.map(team => Teams.updateOne({ _id: team }, { $addToSet: { members: { userId: _id, addDateTime: createdDate } } })); + return teams.map((team) => Teams.updateOne({ _id: team }, { $addToSet: { members: { userId: _id, addDateTime: createdDate } } })); }) .flat(); - await Promise.all(updateOperations).catch(error => logger.logException(error)); + await Promise.all(updateOperations).catch((error) => logger.logException(error)); }; const deleteMembersField = async () => { - await Teams.updateMany({}, { $unset: { members: '' } }).catch(err => console.error(err)); + await Teams.updateMany({}, { $unset: { members: '' } }).catch((err) => console.error(err)); }; const run = () => { @@ -42,7 +42,7 @@ const run = () => { }) // .then(deleteMembersField) .then(addMembersField) - .catch(err => logger.logException(err)) + .catch((err) => logger.logException(err)) .finally(() => { mongoose.connection.close(); console.log('Done! ✅'); diff --git a/src/utilities/addNewField.js b/src/utilities/addNewField.js index 947953683..c63085e94 100644 --- a/src/utilities/addNewField.js +++ b/src/utilities/addNewField.js @@ -94,7 +94,7 @@ const run = function () { // .then(deleteUserField) .then(addNewField) .then(checkNewField) - .catch(err => logger.logException(err)); // handles errors from the connect function + .catch((err) => logger.logException(err)); // handles errors from the connect function }; run(); diff --git a/src/utilities/createInitialPermissions.js b/src/utilities/createInitialPermissions.js index 86a79b94c..0d290fc5c 100644 --- a/src/utilities/createInitialPermissions.js +++ b/src/utilities/createInitialPermissions.js @@ -221,7 +221,6 @@ const permissionsRoles = [ }, ]; - const createInitialPermissions = async () => { // Create Initial Owner const userEmail = { email: 'jae@onecommunityglobal.org' }; @@ -239,7 +238,7 @@ const createInitialPermissions = async () => { const { roleName, permissions } = permissionsRoles[i]; if (!onlyUpdateOwner || roleName === 'Owner') { - const roleDataBase = allRoles.find(role => role.roleName === roleName); + const roleDataBase = allRoles.find((role) => role.roleName === roleName); // If role does not exist in db, create it if (!roleDataBase) { @@ -249,7 +248,7 @@ const createInitialPermissions = async () => { role.save(); // If role exists in db and does not have every permission, add the missing permissions - } else if (!permissions.every(perm => roleDataBase.permissions.includes(perm))) { + } else if (!permissions.every((perm) => roleDataBase.permissions.includes(perm))) { const roleId = roleDataBase._id; promises.push(Role.findById(roleId, (_, record) => { @@ -264,7 +263,7 @@ const createInitialPermissions = async () => { } // Update Default presets - const presetDataBase = allPresets.find(preset => preset.roleName === roleName && preset.presetName === 'default'); + const presetDataBase = allPresets.find((preset) => preset.roleName === roleName && preset.presetName === 'default'); // If role does not exist in db, create it if (!presetDataBase) { @@ -275,7 +274,7 @@ const createInitialPermissions = async () => { defaultPreset.save(); // If role exists in db and is not updated, update default - } else if (!presetDataBase.permissions.every(perm => permissions.includes(perm)) || !permissions.every(perm => presetDataBase.permissions.includes(perm))) { + } else if (!presetDataBase.permissions.every((perm) => permissions.includes(perm)) || !permissions.every((perm) => presetDataBase.permissions.includes(perm))) { const presetId = presetDataBase._id; promises.push(RolePreset.findById(presetId, (_, record) => { diff --git a/src/utilities/escapeRegex.js b/src/utilities/escapeRegex.js index cf7563e26..985904878 100644 --- a/src/utilities/escapeRegex.js +++ b/src/utilities/escapeRegex.js @@ -1,4 +1,3 @@ - const escapeRegex = function (text) { return `^${text.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&')}$`; }; diff --git a/src/utilities/escapeRegexUnitTest.js b/src/utilities/escapeRegexUnitTest.js index c42fb5bf7..ec72375a0 100644 --- a/src/utilities/escapeRegexUnitTest.js +++ b/src/utilities/escapeRegexUnitTest.js @@ -1,7 +1,6 @@ const assert = require('assert'); const escapeRegex = require('./escapeRegex'); - let str = '.'; let regex = new RegExp(escapeRegex(str)); assert(regex.test(str) && !regex.test('a'), "'.' not escaped"); diff --git a/src/utilities/logPermissionChangeByAccount.js b/src/utilities/logPermissionChangeByAccount.js index 0d3f72f76..3c2198933 100644 --- a/src/utilities/logPermissionChangeByAccount.js +++ b/src/utilities/logPermissionChangeByAccount.js @@ -8,7 +8,7 @@ const changedPermissionsLogger = async (req, res, next) => { }; // Helper function finds the latest log related to the permission -const findLatestRelatedLog = roleId => new Promise((resolve, reject) => { +const findLatestRelatedLog = (roleId) => new Promise((resolve, reject) => { PermissionChangeLog.findOne({ roleId }) .sort({ logDateTime: -1 }) .exec((err, document) => { @@ -36,14 +36,13 @@ const logPermissionChangeByAccount = async (requestBody) => { const document = await findLatestRelatedLog(roleId); if (document) { - permissionsRemoved = document.permissions.filter(item => !(permissions.includes(item))); - permissionsAdded = permissions.filter(item => !(document.permissions.includes(item))); + permissionsRemoved = document.permissions.filter((item) => !(permissions.includes(item))); + permissionsAdded = permissions.filter((item) => !(document.permissions.includes(item))); } else { // else this is the first permissions change log for this particular role permissionsAdded = permissions; } - const logEntry = new PermissionChangeLog({ logDateTime: dateTime, roleId, diff --git a/src/utilities/nodeCache.js b/src/utilities/nodeCache.js index 50f8fef63..7856a4c55 100644 --- a/src/utilities/nodeCache.js +++ b/src/utilities/nodeCache.js @@ -1,4 +1,3 @@ - const NodeCache = require('node-cache'); const logger = require('../startup/logger'); diff --git a/src/utilities/permissions.js b/src/utilities/permissions.js index ebf35b2a1..ff522900e 100644 --- a/src/utilities/permissions.js +++ b/src/utilities/permissions.js @@ -1,7 +1,6 @@ const Role = require('../models/role'); const UserProfile = require('../models/userProfile'); - const hasRolePermission = async (role, action) => Role.findOne({ roleName: role }) .exec() .then(({ permissions }) => permissions.includes(action)) diff --git a/src/utilities/yearMonthDayDateValidator.js b/src/utilities/yearMonthDayDateValidator.js index 0568329a9..82a32a263 100644 --- a/src/utilities/yearMonthDayDateValidator.js +++ b/src/utilities/yearMonthDayDateValidator.js @@ -1,5 +1,5 @@ const moment = require('moment-timezone'); -const yearMonthDayDateValidator = inputDate => (moment(inputDate, 'YYYY-MM-DD', true).format() !== 'Invalid date'); +const yearMonthDayDateValidator = (inputDate) => (moment(inputDate, 'YYYY-MM-DD', true).format() !== 'Invalid date'); module.exports = yearMonthDayDateValidator; diff --git a/src/websockets/TimerService/connectionsHandler.js b/src/websockets/TimerService/connectionsHandler.js index 6658321bf..46f136b3d 100644 --- a/src/websockets/TimerService/connectionsHandler.js +++ b/src/websockets/TimerService/connectionsHandler.js @@ -21,7 +21,7 @@ export function removeConnection(connections, userId, connToRemove) { const userConnetions = connections.get(userId); if (!userConnetions) return; - const newConns = userConnetions.filter(conn => conn !== connToRemove); + const newConns = userConnetions.filter((conn) => conn !== connToRemove); if (newConns.length === 0) connections.delete(userId); else connections.set(userId, newConns); } @@ -46,5 +46,5 @@ export function broadcastToSameUser(connections, userId, data) { export function hasOtherConn(connections, userId, anotherConn) { if (!connections.has(userId)) return false; const userConnections = connections.get(userId); - return userConnections.some(con => con !== anotherConn && con.readyState === WebSocket.OPEN); + return userConnections.some((con) => con !== anotherConn && con.readyState === WebSocket.OPEN); }