From 5765f8a02846b5f35a6072d4c6cc610a7b3034f0 Mon Sep 17 00:00:00 2001 From: abdelmounaim lallouache Date: Sat, 9 Mar 2024 15:09:58 -0600 Subject: [PATCH 1/2] rebuilt blue square scheduler --- src/controllers/reasonSchedulingController.js | 2 +- src/controllers/timeOffRequestController.js | 169 ++++++++++++++++-- src/helpers/userHelper.js | 41 ++--- src/models/timeOffRequest.js | 2 +- src/routes/timeOffRequestRouter.js | 4 +- src/startup/routes.js | 2 +- 6 files changed, 170 insertions(+), 50 deletions(-) diff --git a/src/controllers/reasonSchedulingController.js b/src/controllers/reasonSchedulingController.js index d8b883aa1..a227e7f3e 100644 --- a/src/controllers/reasonSchedulingController.js +++ b/src/controllers/reasonSchedulingController.js @@ -2,7 +2,7 @@ const moment = require('moment-timezone'); const UserModel = require('../models/userProfile'); const ReasonModel = require('../models/reason'); const emailSender = require('../utilities/emailSender'); - +// no longer in use replaced with timeoff requests const postReason = async (req, res) => { try { const { userId, requestor, reasonData } = req.body; diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js index 3144a4f52..2d41b4406 100644 --- a/src/controllers/timeOffRequestController.js +++ b/src/controllers/timeOffRequestController.js @@ -1,17 +1,142 @@ const mongoose = require('mongoose'); const moment = require('moment-timezone'); const { hasPermission } = require('../utilities/permissions'); +const emailSender = require("../utilities/emailSender"); -const timeOffRequestController = function (TimeOffRequest) { +const userNotificationEmail = (name, action = '') => { + const message = + action === 'delete' + ? `

Hello,

+

We wanted to inform you that your scheduled time-off request has been deleted.

+

No further action is needed on your part regarding this request.

+

Thank you,

+

One Community

` + : `

Hello,

+

Thank you ${name} for scheduling your time off.

+

The Admin and your Managers have been notified of this request and no further action is needed on your part.

+

Thank you,

+

One Community

`; + return message; +} + +const adminsNotificationEmail = ( + firstName, + lastName, + startDate, + endDate, + action = '' +) => { + const message = + action === 'delete' + ? `

Hello,

+

${firstName} ${lastName} had initially requested time off from ${moment( + startDate + ).format("YYYY-MM-DD")} to ${moment(endDate).format("YYYY-MM-DD")}.

+

We wanted to update you that this time-off request has been canceled.

+

If any schedule adjustments or plans were made, please take note to revert them accordingly.

+

Thank you for your understanding,

+

One Community

` + : `

Hello,

+

${firstName} ${lastName} has requested the following week off: ${moment( + startDate + ).format('YYYY-MM-DD')} to ${moment(endDate).format('YYYY-MM-DD')}

+

If you need to, please make a note of this in your schedule and make any necessary plans for their action item(s).
+ As an additional reminder, their name in the Leaderboard and Tasks list will also reflect their absence for the time they are off.

+

Thank you,

+

One Community

`; + return message; +} + + + +const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { + const notifyUser = async (userId, action = '') => { + try { + const user = await UserProfile.findById( + userId, + 'firstName lastName email' + ); + const { firstName, email } = user; + + emailSender( + email, + 'Your requested time off has been scheduled!', + userNotificationEmail(firstName, action), + null, + null, + null + ); + } catch (err) { + console.log(err); + } + }; + + const notifyAdmins = async (startDate, endDate, userId, action = '') => { + try { + const user = await UserProfile.findById( + userId, + 'firstName lastName' + ); + const { firstName, lastName } = user; + const userTeams = await Team.find({ 'members.userId': userId }); + + const uniqueUserIds = {}; + + userTeams.forEach((element) => { + element.members.forEach((member) => { + if (!uniqueUserIds[member.userId] && !member.userId.equals(userId)) { + uniqueUserIds[member.userId] = true; + } + }); + }); + + const uniqueUserIdsArray = Object.keys(uniqueUserIds); + + const userProfiles = await UserProfile.find({ + _id: { $in: uniqueUserIdsArray }, + }); + + const rolesToInclude = ['Manager', 'Mentor', 'Administrator', 'Owner']; + const userEmails = userProfiles.map((userProfile) => { + if (rolesToInclude.includes(userProfile.role)) { + return userProfile.email; + } else { + return null; + } + }); + + if (Array.isArray(userEmails) && userEmails.length > 0) { + userEmails.forEach((email) => { + emailSender( + email, + `Blue Square Reason for ${firstName} ${lastName} has been set`, + adminsNotificationEmail( + firstName, + lastName, + startDate, + endDate, + action + ), + null, + null, + null + ); + }); + } + } catch (err) { + console.log(err); + } + }; const setTimeOffRequest = async (req, res) => { + try { const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); - if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission) { + const setOwnRequested = req.body.requestor.requestorId === req.body.requestFor; + + if (!(await hasPermission(req.body.requestor, "manageTimeOffRequests")) && !hasRolePermission && !setOwnRequested) { res.status(403).send('You are not authorized to set time off requests.'); return; } - const { - duration, startingDate, reason, requestFor, -} = req.body; + const { duration, startingDate, reason, requestFor} = req.body; if (!duration || !startingDate || !reason || !requestFor) { res.status(400).send('bad request'); return; @@ -19,7 +144,7 @@ const timeOffRequestController = function (TimeOffRequest) { moment.tz.setDefault('America/Los_Angeles'); const startDate = moment(startingDate); - const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, 'second'); + const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, "day");; const newTimeOffRequest = new TimeOffRequest(); @@ -29,9 +154,12 @@ const timeOffRequestController = function (TimeOffRequest) { newTimeOffRequest.endingDate = endDate.toDate(); newTimeOffRequest.duration = Number(duration); - try { - const savedRequest = await newTimeOffRequest.save(); + const savedRequest = await newTimeOffRequest.save(); res.status(201).send(savedRequest); + if (savedRequest && setOwnRequested) { + await notifyUser(requestFor); + await notifyAdmins(startingDate, endDate, requestFor); + } } catch (error) { res.status(500).send('Error saving the request.'); } @@ -87,6 +215,7 @@ const timeOffRequestController = function (TimeOffRequest) { }; const updateTimeOffRequestById = async (req, res) => { + try { 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.'); @@ -101,7 +230,7 @@ const timeOffRequestController = function (TimeOffRequest) { moment.tz.setDefault('America/Los_Angeles'); const startDate = moment(startingDate); - const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, 'second'); + const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, 'day'); const updateData = { reason, @@ -110,7 +239,7 @@ const timeOffRequestController = function (TimeOffRequest) { duration, }; - try { + const updatedRequest = await TimeOffRequest.findByIdAndUpdate( requestId, updateData, @@ -131,14 +260,17 @@ const timeOffRequestController = function (TimeOffRequest) { }; const deleteTimeOffRequestById = async (req, res) => { + try { const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); - if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission) { + const requestId = req.params.id; + const document = await TimeOffRequest.findById(requestId); + const deleteOwnRequest = document?.requestFor.toString() === req.body.requestor.requestorId; + + if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests') && !hasRolePermission && !deleteOwnRequest) { res.status(403).send('You are not authorized to set time off requests.'); return; } - const requestId = req.params.id; - - try { + const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId); if (!deletedRequest) { @@ -147,6 +279,15 @@ const timeOffRequestController = function (TimeOffRequest) { } res.status(200).send(deletedRequest); + if (deleteOwnRequest) { + await notifyUser(deletedRequest.requestFor, "delete"); + await notifyAdmins( + deletedRequest.startingDate, + deletedRequest.endingDate, + deletedRequest.requestFor, + "delete" + ); + } } catch (error) { res.status(500).send(error); } diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index 761ce178b..eb5d08c3a 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -71,17 +71,6 @@ const userHelper = function () { }; }; - const formatTimeOffRequestsDescription = (inputString) => { - const searchTerm = 'Notice:'; - if (inputString.includes(searchTerm)) { - const parts = inputString.split(searchTerm); - const formattedString = `${parts[0]}
${searchTerm}` - + `${parts[1]}`; - return formattedString; - } - return inputString; - }; - const getInfringementEmailBody = function ( firstName, lastName, @@ -102,14 +91,9 @@ const userHelper = function () { const text = `Dear ${firstName} ${lastName},

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

Date Assigned: ${infringement.date}

\ - ${ - requestForTimeOffEmailBody - ? `\n

Reason Time Requested Off: ${requestForTimeOffEmailBody}

` - : '' - } -

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

+

Description: ${ + requestForTimeOffEmailBody ? requestForTimeOffEmailBody : + infringement.description }

Total Infringements: This is your ${moment .localeData() .ordinal(totalInfringements)} blue square of 5.

@@ -343,11 +327,6 @@ const userHelper = function () { const person = await userProfile.findById(user._id); - const foundReason = await Reason.findOne({ - date: currentUTCDate, - userId: user._id, - }); - const personId = mongoose.Types.ObjectId(user._id); let hasWeeklySummary = false; @@ -437,7 +416,7 @@ const userHelper = function () { const coreTeamExtraHour = Math.max(0, oldInfringements.length + 1 - 5); const utcStartMoment = moment(pdtStartOfLastWeek).add(1, 'second'); - const utcEndMoment = moment(pdtEndOfLastWeek).subtract(1, 'second'); + const utcEndMoment = moment(pdtEndOfLastWeek).subtract(1, 'day').subtract(1, 'second'); const requestsForTimeOff = await timeOffRequest.find({ requestFor: personId, @@ -453,7 +432,7 @@ const userHelper = function () { let requestForTimeOffEmailBody; if (hasTimeOffRequest) { - [requestForTimeOff] = requestsForTimeOff; + requestForTimeOff = requestsForTimeOff[0]; requestForTimeOffStartingDate = moment( requestForTimeOff.startingDate, ).format('dddd YYYY-MM-DD'); @@ -461,12 +440,12 @@ const userHelper = function () { requestForTimeOff.endingDate, ).format('dddd YYYY-MM-DD'); requestForTimeOffreason = requestForTimeOff.reason; - requestForTimeOffEmailBody = `Unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}`; + requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, Due to ${requestForTimeOffreason}` } if (timeNotMet || !hasWeeklySummary) { - if (foundReason) { - description = foundReason.reason; + if (hasTimeOffRequest) { + description = requestForTimeOffreason; } else if (timeNotMet && !hasWeeklySummary) { if (person.role === 'Core Team') { description = ( @@ -545,6 +524,7 @@ const userHelper = function () { const infringement = { date: moment().utc().format('YYYY-MM-DD'), description, + createdDate : hasTimeOffRequest ? moment(requestForTimeOff.createdAt).format("YYYY-MM-DD") : null }; const status = await userProfile.findByIdAndUpdate( @@ -1746,10 +1726,9 @@ const userHelper = function () { .endOf('week') .subtract(1, 'week'); - const utcEndMoment = moment(endOfLastWeek).add(1, 'second'); + const utcEndMoment = moment(endOfLastWeek).subtract(1, 'day').add(1, 'second'); try { await timeOffRequest.deleteMany({ endingDate: { $lte: utcEndMoment } }); - console.log('Deleted expired time off requests.'); } catch (error) { console.error('Error deleting expired time off requests:', error); } diff --git a/src/models/timeOffRequest.js b/src/models/timeOffRequest.js index d87184b36..b4e21a071 100644 --- a/src/models/timeOffRequest.js +++ b/src/models/timeOffRequest.js @@ -9,6 +9,6 @@ const timeOffRequest = new Schema({ endingDate: { type: Date }, duration: { type: Number, required: true }, // in weeks -}); +}, { timestamps: true }); module.exports = mongoose.model('timeOffRequest', timeOffRequest, 'timeOffRequests'); diff --git a/src/routes/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js index ee7af1ca6..c14dca60e 100644 --- a/src/routes/timeOffRequestRouter.js +++ b/src/routes/timeOffRequestRouter.js @@ -1,8 +1,8 @@ const express = require('express'); -const routes = function (timeOffRequest) { +const routes = function (timeOffRequest , Team, UserProfile) { const timeOffRequestRouter = express.Router(); - const controller = require('../controllers/timeOffRequestController')(timeOffRequest); + const controller = require('../controllers/timeOffRequestController')(timeOffRequest, Team, UserProfile); timeOffRequestRouter.route('/setTimeOffRequest') .post(controller.setTimeOffRequest); diff --git a/src/startup/routes.js b/src/startup/routes.js index b650ef824..1b1f90b89 100644 --- a/src/startup/routes.js +++ b/src/startup/routes.js @@ -99,7 +99,7 @@ const mouseoverTextRouter = require('../routes/mouseoverTextRouter')( ); const mapLocationRouter = require('../routes/mapLocationsRouter')(mapLocations); -const timeOffRequestRouter = require('../routes/timeOffRequestRouter')(timeOffRequest); +const timeOffRequestRouter = require('../routes/timeOffRequestRouter')(timeOffRequest,team,userProfile); // bm dashboard const bmLoginRouter = require('../routes/bmdashboard/bmLoginRouter')(); From 170486c4f3466134f05c5985119bd22939b9a5dd Mon Sep 17 00:00:00 2001 From: abdelmounaim lallouache Date: Sat, 9 Mar 2024 15:13:18 -0600 Subject: [PATCH 2/2] rebuilt blue square scheduler --- src/controllers/actionItemController.js | 2 +- src/controllers/badgeController.js | 4 +- .../bmdashboard/bmConsumableController.js | 2 +- .../bmdashboard/bmInventoryTypeController.js | 16 +- .../bmdashboard/bmMaterialsController.js | 14 +- .../bmdashboard/bmNewLessonController.js | 10 +- .../bmdashboard/bmProjectController.js | 6 +- .../bmdashboard/bmToolController.js | 8 +- src/controllers/dashBoardController.js | 12 +- src/controllers/informationController.js | 10 +- src/controllers/inventoryController.js | 80 ++-- src/controllers/mapLocationsController.js | 4 +- src/controllers/mouseoverTextController.js | 10 +- .../popupEditorBackupController.js | 14 +- src/controllers/popupEditorController.js | 16 +- .../profileInitialSetupController.js | 4 +- src/controllers/reportsController.js | 2 +- src/controllers/rolePresetsController.js | 14 +- src/controllers/rolesController.js | 22 +- src/controllers/taskController.js | 84 ++-- src/controllers/taskNotificationController.js | 8 +- src/controllers/teamController.js | 22 +- src/controllers/timeEntryController.js | 4 +- src/controllers/timeOffRequestController.js | 68 ++- src/controllers/userProfileController.js | 36 +- src/controllers/wbsController.js | 14 +- src/helpers/dashboardhelper.js | 2 +- src/helpers/taskHelper.js | 4 +- src/helpers/userHelper.js | 27 +- src/models/bmdashboard/buildingIssue.js | 2 +- src/models/userProfile.js | 95 ++--- src/routes/timeOffRequestRouter.js | 2 +- src/routes/userProfileRouter.js | 12 +- src/startup/db.js | 6 +- src/startup/routes.js | 2 +- src/utilities/addMembersToTeams.js | 10 +- src/utilities/addNewField.js | 2 +- src/utilities/createInitialPermissions.js | 387 +++++++++--------- src/utilities/logPermissionChangeByAccount.js | 6 +- src/utilities/yearMonthDayDateValidator.js | 2 +- .../TimerService/connectionsHandler.js | 4 +- 41 files changed, 522 insertions(+), 527 deletions(-) diff --git a/src/controllers/actionItemController.js b/src/controllers/actionItemController.js index f694013d4..c7fadd6d6 100644 --- a/src/controllers/actionItemController.js +++ b/src/controllers/actionItemController.js @@ -107,7 +107,7 @@ 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 { diff --git a/src/controllers/badgeController.js b/src/controllers/badgeController.js index 0df008386..4531c8e32 100644 --- a/src/controllers/badgeController.js +++ b/src/controllers/badgeController.js @@ -39,7 +39,7 @@ const badgeController = function (Badge) { cache.setCache('allBadges', results); res.status(200).send(results); }) - .catch((error) => res.status(500).send(error)); + .catch(error => res.status(500).send(error)); }; /** @@ -166,7 +166,7 @@ const badgeController = function (Badge) { } res.status(201).send(results); }) - .catch((errors) => res.status(500).send(errors)); + .catch(errors => res.status(500).send(errors)); }); }; diff --git a/src/controllers/bmdashboard/bmConsumableController.js b/src/controllers/bmdashboard/bmConsumableController.js index 4125cfb2d..40d87fcdc 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 81ac38146..f01a019c1 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); } @@ -117,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); } @@ -141,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); } @@ -181,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 1757ab8dd..207e2428a 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 c2e24f286..e0ffc0863 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; diff --git a/src/controllers/bmdashboard/bmProjectController.js b/src/controllers/bmdashboard/bmProjectController.js index 1b9237c44..a4f6712e0 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 e62153875..c620255b7 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 660922e07..c99be696c 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -56,7 +56,7 @@ const dashboardcontroller = function () { .then(() => { res.status(200).send("Successfully saved AI prompt."); }) - .catch((error) => res.status(500).send(error)); + .catch(error => res.status(500).send(error)); } }; @@ -82,7 +82,7 @@ const dashboardcontroller = function () { }); } }) - .catch((error) => res.status(500).send(error)); + .catch(error => res.status(500).send(error)); }; const monthlydata = function (req, res) { @@ -133,7 +133,7 @@ const dashboardcontroller = function () { }); } }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const orgData = function (req, res) { @@ -143,7 +143,7 @@ const dashboardcontroller = function () { .then((results) => { res.status(200).send(results[0]); }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const getBugReportEmailBody = function ( @@ -234,7 +234,7 @@ const dashboardcontroller = function () { let fieldaaray = []; if (suggestionData.field.length) { fieldaaray = suggestionData.field.map( - (item) => `

${item}

+ item => `

${item}

${args[3][item]}

`, ); } @@ -319,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/informationController.js b/src/controllers/informationController.js index 92c0a7855..792620995 100644 --- a/src/controllers/informationController.js +++ b/src/controllers/informationController.js @@ -18,7 +18,7 @@ const informationController = function (Information) { cache.setCache('informations', results); res.status(200).send(results); }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const addInformation = function (req, res) { @@ -41,9 +41,9 @@ const informationController = function (Information) { } res.status(201).send(newInformation); }) - .catch((error) => res.status(400).send(error)); + .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) { @@ -56,7 +56,7 @@ const informationController = function (Information) { } res.status(200).send(deletedInformation); }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; // Update existing information by id @@ -70,7 +70,7 @@ const informationController = function (Information) { } res.status(200).send(updatedInformation); }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; return { diff --git a/src/controllers/inventoryController.js b/src/controllers/inventoryController.js index 02aedf578..125c594cc 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,8 +80,8 @@ 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( { @@ -103,7 +103,7 @@ const inventoryController = function (Item, ItemType) { ) .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'); @@ -137,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) { @@ -171,8 +171,8 @@ 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( @@ -191,8 +191,8 @@ const inventoryController = function (Item, ItemType) { .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'); @@ -256,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, @@ -276,12 +276,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'); }; @@ -345,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, @@ -365,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'); }; @@ -426,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, @@ -446,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'); }; @@ -464,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) { @@ -503,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) { @@ -536,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) { @@ -563,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/mapLocationsController.js b/src/controllers/mapLocationsController.js index dee7f2684..c7a359718 100644 --- a/src/controllers/mapLocationsController.js +++ b/src/controllers/mapLocationsController.js @@ -18,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], @@ -42,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 bb96aa3ca..74fae9847 100644 --- a/src/controllers/mouseoverTextController.js +++ b/src/controllers/mouseoverTextController.js @@ -5,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) { @@ -28,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/popupEditorBackupController.js b/src/controllers/popupEditorBackupController.js index 9e12545cc..8c4a7349c 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) { @@ -39,8 +39,8 @@ const popupEditorBackupController = function (PopupEditorBackups) { 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) { @@ -64,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) { diff --git a/src/controllers/popupEditorController.js b/src/controllers/popupEditorController.js index 1c62dd6b1..33afbb9c8 100644 --- a/src/controllers/popupEditorController.js +++ b/src/controllers/popupEditorController.js @@ -3,14 +3,14 @@ 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) { @@ -32,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) { @@ -55,8 +55,8 @@ 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 })); }); }; diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js index cd40e356c..fa4613063 100644 --- a/src/controllers/profileInitialSetupController.js +++ b/src/controllers/profileInitialSetupController.js @@ -345,13 +345,13 @@ const profileInitialSetupController = function ( users.push(item); } }); - const modifiedUsers = users.map((item) => ({ + const modifiedUsers = users.map(item => ({ location: item.location, })); const mapUsers = await MapLocation.find({}); const combined = [...modifiedUsers, ...mapUsers]; - const countries = combined.map((user) => user.location.country); + const countries = combined.map(user => user.location.country); const totalUniqueCountries = [...new Set(countries)].length; res.status(200).send({ CountryCount: totalUniqueCountries }); } catch (error) { diff --git a/src/controllers/reportsController.js b/src/controllers/reportsController.js index c5f678586..8f4aba87b 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 454275126..3a7dc18c8 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 a69343520..3966d8ba7 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,8 +33,8 @@ 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) { @@ -60,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)); }); }; @@ -73,7 +73,7 @@ const rolesController = function (Role) { const { roleId } = req.params; Role.findById(roleId) - .then((result) => ( + .then(result => ( result .remove() .then(UserProfile @@ -92,10 +92,10 @@ 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 { diff --git a/src/controllers/taskController.js b/src/controllers/taskController.js index ac6053269..47aff4d02 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 5d999b800..256c5249e 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 4a90aea99..6bb12012a 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)); }); }; @@ -178,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 b99fe3bd4..597a9f3eb 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 2d41b4406..d21249b23 100644 --- a/src/controllers/timeOffRequestController.js +++ b/src/controllers/timeOffRequestController.js @@ -1,11 +1,10 @@ const mongoose = require('mongoose'); const moment = require('moment-timezone'); const { hasPermission } = require('../utilities/permissions'); -const emailSender = require("../utilities/emailSender"); +const emailSender = require('../utilities/emailSender'); const userNotificationEmail = (name, action = '') => { - const message = - action === 'delete' + const message = action === 'delete' ? `

Hello,

We wanted to inform you that your scheduled time-off request has been deleted.

No further action is needed on your part regarding this request.

@@ -17,71 +16,69 @@ const userNotificationEmail = (name, action = '') => {

Thank you,

One Community

`; return message; -} +}; const adminsNotificationEmail = ( firstName, lastName, startDate, endDate, - action = '' + action = '', ) => { - const message = - action === 'delete' + const message = action === 'delete' ? `

Hello,

${firstName} ${lastName} had initially requested time off from ${moment( - startDate - ).format("YYYY-MM-DD")} to ${moment(endDate).format("YYYY-MM-DD")}.

+ startDate, + ).format('YYYY-MM-DD')} to ${moment(endDate).format('YYYY-MM-DD')}.

We wanted to update you that this time-off request has been canceled.

If any schedule adjustments or plans were made, please take note to revert them accordingly.

Thank you for your understanding,

One Community

` : `

Hello,

${firstName} ${lastName} has requested the following week off: ${moment( - startDate + startDate, ).format('YYYY-MM-DD')} to ${moment(endDate).format('YYYY-MM-DD')}

If you need to, please make a note of this in your schedule and make any necessary plans for their action item(s).
As an additional reminder, their name in the Leaderboard and Tasks list will also reflect their absence for the time they are off.

Thank you,

One Community

`; return message; -} - +}; -const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { +const timeOffRequestController = function (TimeOffRequest, Team, UserProfile) { const notifyUser = async (userId, action = '') => { try { const user = await UserProfile.findById( userId, - 'firstName lastName email' + 'firstName lastName email', ); const { firstName, email } = user; - + emailSender( email, 'Your requested time off has been scheduled!', userNotificationEmail(firstName, action), null, null, - null + null, ); } catch (err) { console.log(err); } }; - + const notifyAdmins = async (startDate, endDate, userId, action = '') => { try { const user = await UserProfile.findById( userId, - 'firstName lastName' + 'firstName lastName', ); const { firstName, lastName } = user; const userTeams = await Team.find({ 'members.userId': userId }); - + const uniqueUserIds = {}; - + userTeams.forEach((element) => { element.members.forEach((member) => { if (!uniqueUserIds[member.userId] && !member.userId.equals(userId)) { @@ -89,22 +86,21 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { } }); }); - + const uniqueUserIdsArray = Object.keys(uniqueUserIds); - + const userProfiles = await UserProfile.find({ _id: { $in: uniqueUserIdsArray }, }); - + const rolesToInclude = ['Manager', 'Mentor', 'Administrator', 'Owner']; const userEmails = userProfiles.map((userProfile) => { if (rolesToInclude.includes(userProfile.role)) { return userProfile.email; - } else { - return null; } + return null; }); - + if (Array.isArray(userEmails) && userEmails.length > 0) { userEmails.forEach((email) => { emailSender( @@ -115,11 +111,11 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { lastName, startDate, endDate, - action + action, ), null, null, - null + null, ); }); } @@ -132,11 +128,13 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { const hasRolePermission = ['Owner', 'Administrator'].includes(req.body.requestor.role); const setOwnRequested = req.body.requestor.requestorId === req.body.requestFor; - if (!(await hasPermission(req.body.requestor, "manageTimeOffRequests")) && !hasRolePermission && !setOwnRequested) { + if (!(await hasPermission(req.body.requestor, 'manageTimeOffRequests')) && !hasRolePermission && !setOwnRequested) { res.status(403).send('You are not authorized to set time off requests.'); return; } - const { duration, startingDate, reason, requestFor} = req.body; + const { + duration, startingDate, reason, requestFor, +} = req.body; if (!duration || !startingDate || !reason || !requestFor) { res.status(400).send('bad request'); return; @@ -144,7 +142,7 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { moment.tz.setDefault('America/Los_Angeles'); const startDate = moment(startingDate); - const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, "day");; + const endDate = startDate.clone().add(Number(duration), 'weeks').subtract(1, 'day'); const newTimeOffRequest = new TimeOffRequest(); @@ -239,7 +237,7 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { duration, }; - + const updatedRequest = await TimeOffRequest.findByIdAndUpdate( requestId, updateData, @@ -270,7 +268,7 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { res.status(403).send('You are not authorized to set time off requests.'); return; } - + const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId); if (!deletedRequest) { @@ -280,12 +278,12 @@ const timeOffRequestController = function (TimeOffRequest , Team, UserProfile) { res.status(200).send(deletedRequest); if (deleteOwnRequest) { - await notifyUser(deletedRequest.requestFor, "delete"); + await notifyUser(deletedRequest.requestFor, 'delete'); await notifyAdmins( deletedRequest.startingDate, deletedRequest.endingDate, deletedRequest.requestFor, - "delete" + 'delete', ); } } catch (error) { diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index 7fabddb70..bf09a1e3b 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) { @@ -271,7 +271,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) { @@ -368,7 +368,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 ( @@ -497,7 +497,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)); }); }; @@ -565,7 +565,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)); @@ -632,7 +632,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) => { @@ -644,7 +644,7 @@ const userProfileController = function (UserProfile) { .then((results) => { res.status(200).send(results); }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const updateOneProperty = function (req, res) { @@ -681,9 +681,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) { @@ -757,11 +757,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) { @@ -800,7 +800,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) { @@ -817,7 +817,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) { @@ -874,7 +874,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) { @@ -970,7 +970,7 @@ const userProfileController = function (UserProfile) { } res.status(200).send(users); }) - .catch((error) => res.status(500).send(error)); + .catch(error => res.status(500).send(error)); }; function escapeRegExp(string) { @@ -982,7 +982,7 @@ const userProfileController = function (UserProfile) { // Creates an array containing the first and last name and filters out whitespace const fullName = req.params.fullName .split(' ') - .filter((name) => name !== ''); + .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'); @@ -1007,7 +1007,7 @@ const userProfileController = function (UserProfile) { } res.status(200).send(users); }) - .catch((error) => res.status(500).send(error)); + .catch(error => res.status(500).send(error)); }; return { diff --git a/src/controllers/wbsController.js b/src/controllers/wbsController.js index 3fdb1392c..b4231a59d 100644 --- a/src/controllers/wbsController.js +++ b/src/controllers/wbsController.js @@ -12,8 +12,8 @@ const wbsController = function (WBS) { "wbsName isActive modifiedDatetime", ) .sort({ modifiedDatetime: -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 postWBS = async function (req, res) { @@ -49,8 +49,8 @@ const wbsController = function (WBS) { _wbs .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 deleteWBS = async function (req, res) { @@ -81,8 +81,8 @@ const wbsController = function (WBS) { const getWBS = function (req, res) { WBS.find() - .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 })); }; const getWBSById = function (req, res) { @@ -91,7 +91,7 @@ const wbsController = function (WBS) { .then((results) => { res.status(200).send(results); }) - .catch((error) => res.status(404).send(error)); + .catch(error => res.status(404).send(error)); }; const getWBSByUserId = async function (req, res) { diff --git a/src/helpers/dashboardhelper.js b/src/helpers/dashboardhelper.js index 2652c8587..bd78fb559 100644 --- a/src/helpers/dashboardhelper.js +++ b/src/helpers/dashboardhelper.js @@ -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/taskHelper.js b/src/helpers/taskHelper.js index e892a562a..68be0e1f0 100644 --- a/src/helpers/taskHelper.js +++ b/src/helpers/taskHelper.js @@ -120,7 +120,7 @@ const taskHelper = function () { } } - teamMemberIds = teamMembers.map((member) => member._id); + teamMemberIds = teamMembers.map(member => member._id); const timeEntries = await timeentry.find({ dateOfWork: { @@ -153,7 +153,7 @@ const taskHelper = function () { path: 'wbsId', select: 'projectId', }); - const teamMemberTaskIds = teamMemberTasks.map((task) => task._id); + const teamMemberTaskIds = teamMemberTasks.map(task => task._id); const teamMemberTaskNotifications = await TaskNotification.find({ taskId: { $in: teamMemberTaskIds }, }); diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index eb5d08c3a..3e9dc8593 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -92,8 +92,7 @@ const userHelper = function () {

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

Date Assigned: ${infringement.date}

\

Description: ${ - requestForTimeOffEmailBody ? requestForTimeOffEmailBody : - infringement.description }

+ requestForTimeOffEmailBody || infringement.description }

Total Infringements: This is your ${moment .localeData() .ordinal(totalInfringements)} blue square of 5.

@@ -283,7 +282,7 @@ const userHelper = function () { }, }, }) - .catch((error) => logger.logException(error)); + .catch(error => logger.logException(error)); }; /** @@ -440,7 +439,7 @@ const userHelper = function () { requestForTimeOff.endingDate, ).format('dddd YYYY-MM-DD'); requestForTimeOffreason = requestForTimeOff.reason; - requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, Due to ${requestForTimeOffreason}` + requestForTimeOffEmailBody = `You had scheduled time off From ${requestForTimeOffStartingDate}, To ${requestForTimeOffEndingDate}, Due to ${requestForTimeOffreason}`; } if (timeNotMet || !hasWeeklySummary) { @@ -524,7 +523,7 @@ const userHelper = function () { const infringement = { date: moment().utc().format('YYYY-MM-DD'), description, - createdDate : hasTimeOffRequest ? moment(requestForTimeOff.createdAt).format("YYYY-MM-DD") : null + createdDate: hasTimeOffRequest ? moment(requestForTimeOff.createdAt).format('YYYY-MM-DD') : null, }; const status = await userProfile.findByIdAndUpdate( @@ -960,7 +959,7 @@ const userHelper = function () { const userInfo = await userProfile.findById(personId); let newEarnedDate = []; const recordToUpdate = userInfo.badgeCollection.find( - (item) => item.badge._id.toString() === badgeId.toString(), + item => item.badge._id.toString() === badgeId.toString(), ); if (!recordToUpdate) { throw new Error('Badge not found'); @@ -1176,8 +1175,8 @@ const userHelper = function () { badgeCollection, ) { const badgesOfType = badgeCollection - .map((obj) => obj.badge) - .filter((badgeItem) => badgeItem.type === 'Minimum Hours Multiple'); + .map(obj => obj.badge) + .filter(badgeItem => badgeItem.type === 'Minimum Hours Multiple'); await badge .find({ type: 'Minimum Hours Multiple' }) .sort({ multiple: -1 }) @@ -1194,7 +1193,7 @@ const userHelper = function () { >= elem.multiple ) { const theBadge = badgesOfType.find( - (badgeItem) => badgeItem._id.toString() === elem._id.toString(), + badgeItem => badgeItem._id.toString() === elem._id.toString(), ); return theBadge ? increaseBadgeCount( @@ -1255,8 +1254,8 @@ const userHelper = function () { && user.lastWeekTangibleHrs > user.weeklycommittedHours ) { const badgeOfType = badgeCollection - .filter((object) => object.badge.type === 'Most Hrs in Week') - .map((object) => object.badge); + .filter(object => object.badge.type === 'Most Hrs in Week') + .map(object => object.badge); await badge.findOne({ type: 'Most Hrs in Week' }).then((results) => { userProfile .aggregate([ @@ -1518,12 +1517,12 @@ const userHelper = function () { ]; const badgesOfType = badgeCollection - .filter((object) => object.badge.type === 'Total Hrs in Category') - .map((object) => object.badge); + .filter(object => object.badge.type === 'Total Hrs in Category') + .map(object => object.badge); categories.forEach(async (category) => { const categoryHrs = Object.keys(hoursByCategory).find( - (elem) => elem === category, + elem => elem === category, ); let badgeOfType; diff --git a/src/models/bmdashboard/buildingIssue.js b/src/models/bmdashboard/buildingIssue.js index 089117ce1..976f3fb33 100644 --- a/src/models/bmdashboard/buildingIssue.js +++ b/src/models/bmdashboard/buildingIssue.js @@ -14,4 +14,4 @@ const buildingIssue = new Schema({ // relatedLesson: { type: mongoose.SchemaTypes.ObjectId, ref: 'buildingNewLesson', required: true }, }); -module.exports = mongoose.model('buildingIssue', buildingIssue, 'buildingIssues'); \ No newline at end of file +module.exports = mongoose.model('buildingIssue', buildingIssue, 'buildingIssues'); diff --git a/src/models/userProfile.js b/src/models/userProfile.js index 68a9d127a..0aaba5dfc 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 }, @@ -41,7 +40,9 @@ const userProfileSchema = new Schema({ minlength: 2, index: true, }, - lastName: { type: String, required: true, minlength: 2, index: true }, + lastName: { + type: String, required: true, minlength: 2, index: true, +}, phoneNumber: [{ type: String, phoneNumber: String }], jobTitle: [{ type: String, jobTitle: String }], bio: { type: String }, @@ -50,7 +51,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() }, @@ -69,14 +70,14 @@ 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: new Date() }, hasBadgeDeletionImpact: { type: Boolean, default: false }, featured: { type: Boolean, @@ -100,29 +101,29 @@ const userProfileSchema = new Schema({ type: String, required: true, enum: [ - "Better Descriptions", - "Log Time to Tasks", - "Log Time as You Go", - "Log Time to Action Items", - "Intangible Time Log w/o Reason", + 'Better Descriptions', + 'Log Time to Tasks', + 'Log Time as You Go', + 'Log Time to Action Items', + 'Intangible Time Log w/o Reason', ], }, color: { type: String, - enum: ["red", "blue", "white", "yellow"], + enum: ['red', 'blue', 'white', 'yellow'], required: true, - default: "white", + default: 'white', }, }, ], 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: [ { @@ -144,7 +145,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 }, @@ -174,17 +175,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 }, }, @@ -195,27 +196,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: [ @@ -230,22 +231,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/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js index c14dca60e..4083652f6 100644 --- a/src/routes/timeOffRequestRouter.js +++ b/src/routes/timeOffRequestRouter.js @@ -1,6 +1,6 @@ const express = require('express'); -const routes = function (timeOffRequest , Team, UserProfile) { +const routes = function (timeOffRequest, Team, UserProfile) { const timeOffRequestRouter = express.Router(); const controller = require('../controllers/timeOffRequestController')(timeOffRequest, Team, UserProfile); diff --git a/src/routes/userProfileRouter.js b/src/routes/userProfileRouter.js index 74610ec50..51c9089e5 100644 --- a/src/routes/userProfileRouter.js +++ b/src/routes/userProfileRouter.js @@ -13,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, ); @@ -22,9 +22,9 @@ 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) => { + 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, @@ -34,7 +34,7 @@ const routes = function (userProfile) { } throw new Error('Url not valid'); })), - body('adminLinks').customSanitizer((value) => value.map((link) => { + body('adminLinks').customSanitizer(value => value.map((link) => { if (link.Name.replace(/\s/g, '') || link.Link.replace(/\s/g, '')) { return { ...link, diff --git a/src/startup/db.js b/src/startup/db.js index 4308c5fd5..c3c61807c 100644 --- a/src/startup/db.js +++ b/src/startup/db.js @@ -23,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); @@ -40,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/routes.js b/src/startup/routes.js index 1b1f90b89..30faaf0f7 100644 --- a/src/startup/routes.js +++ b/src/startup/routes.js @@ -99,7 +99,7 @@ const mouseoverTextRouter = require('../routes/mouseoverTextRouter')( ); const mapLocationRouter = require('../routes/mapLocationsRouter')(mapLocations); -const timeOffRequestRouter = require('../routes/timeOffRequestRouter')(timeOffRequest,team,userProfile); +const timeOffRequestRouter = require('../routes/timeOffRequestRouter')(timeOffRequest, team, userProfile); // bm dashboard const bmLoginRouter = require('../routes/bmdashboard/bmLoginRouter')(); diff --git a/src/utilities/addMembersToTeams.js b/src/utilities/addMembersToTeams.js index 62562a9cc..b637fa2c1 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 c63085e94..947953683 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 7cf4be76b..2f794af02 100644 --- a/src/utilities/createInitialPermissions.js +++ b/src/utilities/createInitialPermissions.js @@ -1,229 +1,229 @@ -const Role = require("../models/role"); -const RolePreset = require("../models/rolePreset"); -const User = require("../models/userProfile"); +const Role = require('../models/role'); +const RolePreset = require('../models/rolePreset'); +const User = require('../models/userProfile'); const permissionsRoles = [ { - roleName: "Administrator", + roleName: 'Administrator', permissions: [ // Reports - "getWeeklySummaries", - "getReports", // Doesn't do anything on back-end. - "totalValidWeeklySummaries", + 'getWeeklySummaries', + 'getReports', // Doesn't do anything on back-end. + 'totalValidWeeklySummaries', // Badges - "seeBadges", - "assignBadges", - "createBadges", - "deleteBadges", - "updateBadges", + 'seeBadges', + 'assignBadges', + 'createBadges', + 'deleteBadges', + 'updateBadges', // Popups - "createPopup", - "updatePopup", + 'createPopup', + 'updatePopup', // Projects - "deleteProject", - "postProject", - "putProject", - "assignProjectToUsers", + 'deleteProject', + 'postProject', + 'putProject', + 'assignProjectToUsers', // Tasks - "importTask", - "postTask", - "updateTask", - "swapTask", - "deleteTask", - "updateNum", + 'importTask', + 'postTask', + 'updateTask', + 'swapTask', + 'deleteTask', + 'updateNum', // Teams - "postTeam", - "deleteTeam", - "putTeam", - "assignTeamToUsers", + 'postTeam', + 'deleteTeam', + 'putTeam', + 'assignTeamToUsers', // Time Entries - "editTimeEntry", - "deleteTimeEntry", + 'editTimeEntry', + 'deleteTimeEntry', // 'postTimeEntry',? // User Profile - "putRole", - "postUserProfile", - "putUserProfile", - "putUserProfileImportantInfo", - "changeUserStatus", - "updatePassword", - "deleteUserProfile", - "infringementAuthorizer", + 'putRole', + 'postUserProfile', + 'putUserProfile', + 'putUserProfileImportantInfo', + 'changeUserStatus', + 'updatePassword', + 'deleteUserProfile', + 'infringementAuthorizer', // WBS - "postWbs", - "deleteWbs", + 'postWbs', + 'deleteWbs', // Inv - "getAllInvInProjectWBS", - "postInvInProjectWBS", - "getAllInvInProject", - "postInvInProject", - "transferInvById", - "delInvById", - "unWasteInvById", - "getInvIdInfo", - "putInvById", - "getInvTypeById", - "putInvType", - "getAllInvType", - "postInvType", + 'getAllInvInProjectWBS', + 'postInvInProjectWBS', + 'getAllInvInProject', + 'postInvInProject', + 'transferInvById', + 'delInvById', + 'unWasteInvById', + 'getInvIdInfo', + 'putInvById', + 'getInvTypeById', + 'putInvType', + 'getAllInvType', + 'postInvType', // General - "getUserProfiles", - "getProjectMembers", + 'getUserProfiles', + 'getProjectMembers', - "getTimeZoneAPIKey", - "checkLeadTeamOfXplus", + 'getTimeZoneAPIKey', + 'checkLeadTeamOfXplus', ], }, { - roleName: "Volunteer", - permissions: ["getReporteesLimitRoles", "suggestTask"], + roleName: 'Volunteer', + permissions: ['getReporteesLimitRoles', 'suggestTask'], }, { - roleName: "Core Team", + roleName: 'Core Team', permissions: [ - "getUserProfiles", - "getProjectMembers", - "getAllInvInProjectWBS", - "postInvInProjectWBS", - "getAllInvInProject", - "postInvInProject", - "transferInvById", - "delInvById", - "unWasteInvById", - "getInvIdInfo", - "putInvById", - "getInvTypeById", - "putInvType", - "getAllInvType", - "postInvType", - "getWeeklySummaries", - "getReports", - "getTimeZoneAPIKey", - "checkLeadTeamOfXplus", + 'getUserProfiles', + 'getProjectMembers', + 'getAllInvInProjectWBS', + 'postInvInProjectWBS', + 'getAllInvInProject', + 'postInvInProject', + 'transferInvById', + 'delInvById', + 'unWasteInvById', + 'getInvIdInfo', + 'putInvById', + 'getInvTypeById', + 'putInvType', + 'getAllInvType', + 'postInvType', + 'getWeeklySummaries', + 'getReports', + 'getTimeZoneAPIKey', + 'checkLeadTeamOfXplus', ], }, { - roleName: "Manager", + roleName: 'Manager', permissions: [ - "getUserProfiles", - "getProjectMembers", - "putUserProfile", - "infringementAuthorizer", - "getReporteesLimitRoles", - "updateTask", - "putTeam", - "getAllInvInProjectWBS", - "postInvInProjectWBS", - "getAllInvInProject", - "postInvInProject", - "transferInvById", - "delInvById", - "unWasteInvById", - "getInvIdInfo", - "putInvById", - "getInvTypeById", - "putInvType", - "getAllInvType", - "postInvType", - "getTimeZoneAPIKey", - "checkLeadTeamOfXplus", + 'getUserProfiles', + 'getProjectMembers', + 'putUserProfile', + 'infringementAuthorizer', + 'getReporteesLimitRoles', + 'updateTask', + 'putTeam', + 'getAllInvInProjectWBS', + 'postInvInProjectWBS', + 'getAllInvInProject', + 'postInvInProject', + 'transferInvById', + 'delInvById', + 'unWasteInvById', + 'getInvIdInfo', + 'putInvById', + 'getInvTypeById', + 'putInvType', + 'getAllInvType', + 'postInvType', + 'getTimeZoneAPIKey', + 'checkLeadTeamOfXplus', ], }, { - roleName: "Mentor", + roleName: 'Mentor', permissions: [ - "suggestTask", - "getUserProfiles", - "getProjectMembers", - "putUserProfile", - "infringementAuthorizer", - "getReporteesLimitRoles", - "getAllInvInProjectWBS", - "postInvInProjectWBS", - "getAllInvInProject", - "postInvInProject", - "transferInvById", - "delInvById", - "unWasteInvById", - "getInvIdInfo", - "putInvById", - "getInvTypeById", - "putInvType", - "getAllInvType", - "postInvType", - "getTimeZoneAPIKey", - "checkLeadTeamOfXplus", + 'suggestTask', + 'getUserProfiles', + 'getProjectMembers', + 'putUserProfile', + 'infringementAuthorizer', + 'getReporteesLimitRoles', + 'getAllInvInProjectWBS', + 'postInvInProjectWBS', + 'getAllInvInProject', + 'postInvInProject', + 'transferInvById', + 'delInvById', + 'unWasteInvById', + 'getInvIdInfo', + 'putInvById', + 'getInvTypeById', + 'putInvType', + 'getAllInvType', + 'postInvType', + 'getTimeZoneAPIKey', + 'checkLeadTeamOfXplus', ], }, { - roleName: "Owner", + roleName: 'Owner', permissions: [ - "postRole", - "deleteRole", - "putRole", - "addDeleteEditOwners", - "putUserProfilePermissions", - "changeUserStatus", - "seeBadges", - "assignBadges", - "createBadges", - "deleteBadges", - "updateBadges", - "createPopup", - "updatePopup", - "deleteProject", - "postProject", - "putProject", - "assignProjectToUsers", - "importTask", - "postTask", - "updateNum", - "updateTask", - "swapTask", - "deleteTask", - "postTeam", - "deleteTeam", - "putTeam", - "assignTeamToUsers", - "editTimeEntry", - "deleteTimeEntry", - "updatePassword", - "getUserProfiles", - "getProjectMembers", - "postUserProfile", - "putUserProfile", - "putUserProfileImportantInfo", - "deleteUserProfile", - "infringementAuthorizer", - "postWbs", - "deleteWbs", - "getAllInvInProjectWBS", - "postInvInProjectWBS", - "getAllInvInProject", - "postInvInProject", - "transferInvById", - "delInvById", - "unWasteInvById", - "getInvIdInfo", - "putInvById", - "getInvTypeById", - "putInvType", - "getAllInvType", - "postInvType", - "getWeeklySummaries", - "getReports", - "getTimeZoneAPIKey", - "checkLeadTeamOfXplus", - "editTeamCode", - "totalValidWeeklySummaries", + 'postRole', + 'deleteRole', + 'putRole', + 'addDeleteEditOwners', + 'putUserProfilePermissions', + 'changeUserStatus', + 'seeBadges', + 'assignBadges', + 'createBadges', + 'deleteBadges', + 'updateBadges', + 'createPopup', + 'updatePopup', + 'deleteProject', + 'postProject', + 'putProject', + 'assignProjectToUsers', + 'importTask', + 'postTask', + 'updateNum', + 'updateTask', + 'swapTask', + 'deleteTask', + 'postTeam', + 'deleteTeam', + 'putTeam', + 'assignTeamToUsers', + 'editTimeEntry', + 'deleteTimeEntry', + 'updatePassword', + 'getUserProfiles', + 'getProjectMembers', + 'postUserProfile', + 'putUserProfile', + 'putUserProfileImportantInfo', + 'deleteUserProfile', + 'infringementAuthorizer', + 'postWbs', + 'deleteWbs', + 'getAllInvInProjectWBS', + 'postInvInProjectWBS', + 'getAllInvInProject', + 'postInvInProject', + 'transferInvById', + 'delInvById', + 'unWasteInvById', + 'getInvIdInfo', + 'putInvById', + 'getInvTypeById', + 'putInvType', + 'getAllInvType', + 'postInvType', + 'getWeeklySummaries', + 'getReports', + 'getTimeZoneAPIKey', + 'checkLeadTeamOfXplus', + 'editTeamCode', + 'totalValidWeeklySummaries', ], }, ]; const createInitialPermissions = async () => { // Create Initial Owner - const userEmail = { email: "jae@onecommunityglobal.org" }; - const update = { role: "Owner" }; + const userEmail = { email: 'jae@onecommunityglobal.org' }; + const update = { role: 'Owner' }; await User.findOneAndUpdate(userEmail, update); // Get Roles From DB @@ -238,8 +238,7 @@ const createInitialPermissions = async () => { 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) { @@ -250,8 +249,7 @@ const createInitialPermissions = async () => { // 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( @@ -262,35 +260,34 @@ const createInitialPermissions = async () => { } }); record.save(); - }) + }), ); } } // 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) { const defaultPreset = new RolePreset(); defaultPreset.roleName = roleName; - defaultPreset.presetName = "default"; + defaultPreset.presetName = 'default'; defaultPreset.permissions = permissions; 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) => { record.permissions = permissions; record.save(); - }) + }), ); } } diff --git a/src/utilities/logPermissionChangeByAccount.js b/src/utilities/logPermissionChangeByAccount.js index 3c2198933..2e2b66772 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,8 +36,8 @@ 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; diff --git a/src/utilities/yearMonthDayDateValidator.js b/src/utilities/yearMonthDayDateValidator.js index 82a32a263..0568329a9 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 46f136b3d..6658321bf 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); }