From 10ac728173fc99dba01b0835eb239464e9f58b7a Mon Sep 17 00:00:00 2001
From: abdel
Date: Fri, 11 Aug 2023 20:10:37 -0500
Subject: [PATCH 1/9] add timeOffRequest model,set timeOffRequestRouter, set
timeOffRequestController
---
src/controllers/timeOffRequestController.js | 11 +++++++++++
src/models/timeOffRequest.js | 14 ++++++++++++++
src/routes/timeOffRequestRouter.js | 14 ++++++++++++++
src/startup/routes.js | 3 +++
4 files changed, 42 insertions(+)
create mode 100644 src/controllers/timeOffRequestController.js
create mode 100644 src/models/timeOffRequest.js
create mode 100644 src/routes/timeOffRequestRouter.js
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
new file mode 100644
index 000000000..97162c8fe
--- /dev/null
+++ b/src/controllers/timeOffRequestController.js
@@ -0,0 +1,11 @@
+const timeOffRequestController = function (timeOffRequest) {
+ const getTimeOffRequests = (req, res) => {
+ res.status(200).send("test")
+ };
+
+ return {
+ getTimeOffRequests,
+ };
+};
+
+module.exports = timeOffRequestController;
\ No newline at end of file
diff --git a/src/models/timeOffRequest.js b/src/models/timeOffRequest.js
new file mode 100644
index 000000000..dd025f7b3
--- /dev/null
+++ b/src/models/timeOffRequest.js
@@ -0,0 +1,14 @@
+const mongoose = require('mongoose');
+
+const { Schema } = mongoose;
+
+const timeOffRequest = new Schema({
+ requestFor: { type: mongoose.SchemaTypes.ObjectId, ref: 'userProfile' },
+ reason: { type: 'String', required: true },
+ startingDate: { type: Date, required: true },
+ endingDate: { type: Date },
+ duration: { type: Number, required: true } // in weeks
+
+});
+
+module.exports = mongoose.model('timeOffRequest', timeOffRequest, 'timeOffRequests');
\ No newline at end of file
diff --git a/src/routes/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js
new file mode 100644
index 000000000..b6a7be8cd
--- /dev/null
+++ b/src/routes/timeOffRequestRouter.js
@@ -0,0 +1,14 @@
+const express = require('express');
+
+
+const routes = function (timeOffRequest) {
+ const timeOffRequestRouter = express.Router();
+ const controller = require('../controllers/timeOffRequestController')(timeOffRequest);
+
+ timeOffRequestRouter.route('/getTimeOffRequests')
+ .get(controller.getTimeOffRequests);
+
+ return timeOffRequestRouter;
+};
+
+module.exports = routes;
diff --git a/src/startup/routes.js b/src/startup/routes.js
index 1efc52937..b5410c6d6 100644
--- a/src/startup/routes.js
+++ b/src/startup/routes.js
@@ -17,6 +17,7 @@ const role = require('../models/role');
const ownerMessage = require('../models/ownerMessage');
const ownerStandardMessage = require('../models/ownerStandardMessage');
const mouseoverText = require('../models/mouseoverText');
+const timeOffRequest = require('../models/timeOffRequest');
const userProfileRouter = require('../routes/userProfileRouter')(userProfile);
const badgeRouter = require('../routes/badgeRouter')(badge);
@@ -45,6 +46,7 @@ const roleRouter = require('../routes/roleRouter')(role);
const ownerMessageRouter = require('../routes/ownerMessageRouter')(ownerMessage);
const ownerStandardMessageRouter = require('../routes/ownerStandardMessageRouter')(ownerStandardMessage);
const mouseoverTextRouter = require('../routes/mouseoverTextRouter')(mouseoverText);
+const timeOffRequestRouter = require('../routes/timeOffRequestRouter')(timeOffRequest);
module.exports = function (app) {
app.use('/api', forgotPwdRouter);
@@ -72,4 +74,5 @@ module.exports = function (app) {
app.use('/api', ownerMessageRouter);
app.use('/api', ownerStandardMessageRouter);
app.use('/api', mouseoverTextRouter);
+ app.use('/api', timeOffRequestRouter);
};
From ca8cf16e348425724f96fff32b6e39c593693aa9 Mon Sep 17 00:00:00 2001
From: abdel
Date: Sat, 12 Aug 2023 15:05:41 -0500
Subject: [PATCH 2/9] add setTimeOffRequest,add getTimeOffRequests,add
getTimeOffRequestbyId
---
src/controllers/timeOffRequestController.js | 66 ++++++++++++++++++++-
src/routes/timeOffRequestRouter.js | 9 +++
2 files changed, 73 insertions(+), 2 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index 97162c8fe..9d479fc0e 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -1,10 +1,72 @@
-const timeOffRequestController = function (timeOffRequest) {
- const getTimeOffRequests = (req, res) => {
+const mongoose = require('mongoose');
+const moment = require('moment');
+
+const timeOffRequestController = function (TimeOffRequest) {
+ const setTimeOffRequest = async (req, res) => {
+
+ const { duration, startingDate, reason, requestFor } = req.body
+ if (!duration || !startingDate || !reason || !requestFor) {
+ res.status(400).send("bad request")
+ return;
+ }
+ try {
+ const startDate = moment(startingDate, 'MM/DD/YY');
+
+ const endDate = startDate.clone().add(Number(duration), 'weeks');
+
+ const endingDate = endDate.format('MM/DD/YY');
+
+ const newTimeOffRequest = new TimeOffRequest();
+
+ newTimeOffRequest.requestFor = mongoose.Types.ObjectId(requestFor)
+ newTimeOffRequest.reason = reason
+ newTimeOffRequest.startingDate = new Date(startingDate)
+ newTimeOffRequest.endingDate = new Date(endingDate)
+ newTimeOffRequest.duration = Number(duration)
+
+ const savedRequest = await newTimeOffRequest.save();
+ res.status(201).send(savedRequest)
+ } catch (error) {
+ res.status(500).send(error)
+ }
+
+ };
+
+ const getTimeOffRequests = async (req, res) => {
+ try {
+ const allRequests = await TimeOffRequest.find();
+ res.status(200).json(allRequests);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const getTimeOffRequestbyId = async (req, res) => {
+ const requestId = req.params.id;
+
+ try {
+ const request = await TimeOffRequest.findById(requestId);
+
+ if (!request) {
+ res.status(404).json({ error: 'Time off request not found' });
+ return;
+ }
+
+ res.status(200).json(request);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const updateTimeOffRequest = async (req, res) => {
res.status(200).send("test")
};
return {
+ setTimeOffRequest,
getTimeOffRequests,
+ getTimeOffRequestbyId,
+ updateTimeOffRequest
};
};
diff --git a/src/routes/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js
index b6a7be8cd..42b3d6ec8 100644
--- a/src/routes/timeOffRequestRouter.js
+++ b/src/routes/timeOffRequestRouter.js
@@ -5,9 +5,18 @@ const routes = function (timeOffRequest) {
const timeOffRequestRouter = express.Router();
const controller = require('../controllers/timeOffRequestController')(timeOffRequest);
+ timeOffRequestRouter.route('/setTimeOffRequest')
+ .post(controller.setTimeOffRequest);
+
timeOffRequestRouter.route('/getTimeOffRequests')
.get(controller.getTimeOffRequests);
+ timeOffRequestRouter.route('/getTimeOffRequest/:id')
+ .get(controller.getTimeOffRequestbyId);
+
+ timeOffRequestRouter.route('/updateTimeOffRequest')
+ .post(controller.updateTimeOffRequest);
+
return timeOffRequestRouter;
};
From f330ff75443402610f4223fc5be1b3437524c6ce Mon Sep 17 00:00:00 2001
From: abdel
Date: Sat, 12 Aug 2023 19:45:21 -0500
Subject: [PATCH 3/9] add deleteTimeOffRequestById, add
updateTimeOffRequestById
---
src/controllers/timeOffRequestController.js | 63 +++++++++++++++++++--
src/routes/timeOffRequestRouter.js | 7 ++-
2 files changed, 62 insertions(+), 8 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index 9d479fc0e..caa719bde 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -35,7 +35,7 @@ const timeOffRequestController = function (TimeOffRequest) {
const getTimeOffRequests = async (req, res) => {
try {
const allRequests = await TimeOffRequest.find();
- res.status(200).json(allRequests);
+ res.status(200).send(allRequests);
} catch (error) {
res.status(500).send(error);
}
@@ -48,25 +48,76 @@ const timeOffRequestController = function (TimeOffRequest) {
const request = await TimeOffRequest.findById(requestId);
if (!request) {
- res.status(404).json({ error: 'Time off request not found' });
+ res.status(404).send('Time off request not found');
return;
}
- res.status(200).json(request);
+ res.status(200).send(request);
} catch (error) {
res.status(500).send(error);
}
};
- const updateTimeOffRequest = async (req, res) => {
- res.status(200).send("test")
+ const updateTimeOffRequestById = async (req, res) => {
+ const requestId = req.params.id;
+ const { duration, startingDate, reason, requestFor } = req.body
+ if (!duration || !startingDate || !reason || !requestFor) {
+ res.status(400).send("bad request")
+ return;
+ }
+ const startDate = moment(startingDate, 'MM/DD/YY');
+
+ const endDate = startDate.clone().add(Number(duration), 'weeks');
+
+ const endingDate = endDate.format('MM/DD/YY');
+
+ const updateData = {
+ requestFor: mongoose.Types.ObjectId(requestFor),
+ reason: reason,
+ startingDate: new Date(startingDate),
+ endingDate: new Date(endingDate),
+ duration: duration,
+ };
+
+ try {
+ const updatedRequest = await TimeOffRequest.findByIdAndUpdate(requestId, updateData, {
+ new: true,
+ });
+
+ if (!updatedRequest) {
+ res.status(404).send('Time off request not found');
+ return;
+ }
+
+ res.status(200).send(updatedRequest);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const deleteTimeOffRequestById = async (req, res) => {
+ const requestId = req.params.id;
+
+ try {
+ const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId);
+
+ if (!deletedRequest) {
+ res.status(404).send('Time off request not found');
+ return;
+ }
+
+ res.status(200).send('Time off request deleted successfully');
+ } catch (error) {
+ res.status(500).send(error);
+ }
};
return {
setTimeOffRequest,
getTimeOffRequests,
getTimeOffRequestbyId,
- updateTimeOffRequest
+ updateTimeOffRequestById,
+ deleteTimeOffRequestById
};
};
diff --git a/src/routes/timeOffRequestRouter.js b/src/routes/timeOffRequestRouter.js
index 42b3d6ec8..1dd27f05b 100644
--- a/src/routes/timeOffRequestRouter.js
+++ b/src/routes/timeOffRequestRouter.js
@@ -14,8 +14,11 @@ const routes = function (timeOffRequest) {
timeOffRequestRouter.route('/getTimeOffRequest/:id')
.get(controller.getTimeOffRequestbyId);
- timeOffRequestRouter.route('/updateTimeOffRequest')
- .post(controller.updateTimeOffRequest);
+ timeOffRequestRouter.route('/updateTimeOffRequest/:id')
+ .post(controller.updateTimeOffRequestById);
+
+ timeOffRequestRouter.route('/deleteTimeOffRequest/:id')
+ .delete(controller.deleteTimeOffRequestById);
return timeOffRequestRouter;
};
From 17f81294182385009d802d832c2bae5849a4edea Mon Sep 17 00:00:00 2001
From: abdel
Date: Sat, 19 Aug 2023 18:14:09 -0500
Subject: [PATCH 4/9] update getTimeOffRequests in the timeOffRequestController
with aggregate function
---
src/controllers/timeOffRequestController.js | 27 +++++++++++++++++++--
1 file changed, 25 insertions(+), 2 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index caa719bde..9e89cda3b 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -34,8 +34,31 @@ const timeOffRequestController = function (TimeOffRequest) {
const getTimeOffRequests = async (req, res) => {
try {
- const allRequests = await TimeOffRequest.find();
- res.status(200).send(allRequests);
+ const allRequests = await TimeOffRequest.aggregate([
+ {
+ $sort: { requestFor: 1 } // Sort by requestFor in ascending order
+ },
+ {
+ $group: {
+ _id: "$requestFor",
+ requests: { $push: "$$ROOT" } // Group requests by requestFor
+ }
+ },
+ {
+ $project: {
+ _id: 0,
+ requestFor: "$_id",
+ requests: 1
+ }
+ }
+ ]);
+
+ const formattedRequests = {};
+ allRequests.forEach(request => {
+ formattedRequests[request.requestFor] = request.requests;
+ });
+
+ res.status(200).send(formattedRequests);
} catch (error) {
res.status(500).send(error);
}
From e707e88ea41c9349c40c19ad2fc13b2e6ba8cf3c Mon Sep 17 00:00:00 2001
From: abdel
Date: Sat, 2 Sep 2023 20:38:14 -0500
Subject: [PATCH 5/9] update assignBlueSquareForTimeNotMet
---
src/controllers/timeOffRequestController.js | 9 +-
src/controllers/userProfileController.js | 12 +-
src/helpers/userHelper.js | 121 ++++++++++++--------
3 files changed, 84 insertions(+), 58 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index 9e89cda3b..c11534418 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -3,7 +3,6 @@ const moment = require('moment');
const timeOffRequestController = function (TimeOffRequest) {
const setTimeOffRequest = async (req, res) => {
-
const { duration, startingDate, reason, requestFor } = req.body
if (!duration || !startingDate || !reason || !requestFor) {
res.status(400).send("bad request")
@@ -27,6 +26,7 @@ const timeOffRequestController = function (TimeOffRequest) {
const savedRequest = await newTimeOffRequest.save();
res.status(201).send(savedRequest)
} catch (error) {
+ console.log(error)
res.status(500).send(error)
}
@@ -83,8 +83,8 @@ const timeOffRequestController = function (TimeOffRequest) {
const updateTimeOffRequestById = async (req, res) => {
const requestId = req.params.id;
- const { duration, startingDate, reason, requestFor } = req.body
- if (!duration || !startingDate || !reason || !requestFor) {
+ const { duration, startingDate, reason } = req.body
+ if (!duration || !startingDate || !reason || !requestId) {
res.status(400).send("bad request")
return;
}
@@ -95,7 +95,6 @@ const timeOffRequestController = function (TimeOffRequest) {
const endingDate = endDate.format('MM/DD/YY');
const updateData = {
- requestFor: mongoose.Types.ObjectId(requestFor),
reason: reason,
startingDate: new Date(startingDate),
endingDate: new Date(endingDate),
@@ -129,7 +128,7 @@ const timeOffRequestController = function (TimeOffRequest) {
return;
}
- res.status(200).send('Time off request deleted successfully');
+ res.status(200).send(deletedRequest);
} catch (error) {
res.status(500).send(error);
}
diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js
index 5b88454ea..d2b23ca63 100644
--- a/src/controllers/userProfileController.js
+++ b/src/controllers/userProfileController.js
@@ -38,7 +38,7 @@ function ValidatePassword(req, res) {
!userId === requestor.requestorId
&& !hasPermission(requestor.role, 'updatePassword')
) {
- res.status(403).send({
+ res.status(403).send({
error: "You are unauthorized to update this user's password",
});
return;
@@ -505,11 +505,11 @@ const userProfileController = function (UserProfile) {
});
return user
- .save()
- .then(() => {
- res.status(200).send({ message: 'updated property' });
- })
- .catch(error => res.status(500).send(error));
+ .save()
+ .then(() => {
+ res.status(200).send({ message: 'updated property' });
+ })
+ .catch(error => res.status(500).send(error));
})
.catch(error => res.status(500).send(error));
};
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 75288f916..ee2d023fd 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -9,6 +9,7 @@ const badge = require('../models/badge');
const myTeam = require('./helperModels/myTeam');
const dashboardHelper = require('./dashboardhelper')();
const reportHelper = require('./reporthelper')();
+const timeOffRequest = require("../models/timeOffRequest")
const emailSender = require('../utilities/emailSender');
@@ -35,10 +36,10 @@ const userHelper = function () {
let dd = today.getDate();
- mm = mm < 10 ? `0${ mm}` : mm;
- dd = dd < 10 ? `0${ dd}` : dd;
+ mm = mm < 10 ? `0${mm}` : mm;
+ dd = dd < 10 ? `0${dd}` : dd;
- const formatedDate = `${yyyy }-${ mm }-${ dd}`;
+ const formatedDate = `${yyyy}-${mm}-${dd}`;
return formatedDate;
};
@@ -92,8 +93,8 @@ const userHelper = function () {
Date Assigned: ${infringement.date}
Description: ${infringement.description}
Total Infringements: This is your ${moment
- .localeData()
- .ordinal(totalInfringements)} blue square of 5.
+ .localeData()
+ .ordinal(totalInfringements)} blue square of 5.
Life happens and we understand that. That’s why we allow 5 of them before taking action. This action usually includes removal from our team though, so please let your direct supervisor know what happened and do your best to avoid future blue squares if you are getting close to 5 and wish to avoid termination. Each blue square drops off after a year.
Thank you,
One Community
`;
@@ -176,8 +177,8 @@ const userHelper = function () {
Weekly Summary
(for the week ending on ${moment(dueDate)
- .tz('America/Los_Angeles')
- .format('YYYY-MMM-DD')}):
+ .tz('America/Los_Angeles')
+ .format('YYYY-MMM-DD')}):
${summary}
@@ -198,19 +199,16 @@ const userHelper = function () {
Media URL: ${mediaUrlLink || 'Not provided!'}
- ${
- weeklySummariesCount === 8
- ? `
Total Valid Weekly Summaries: ${weeklySummariesCount}
`
- : `
Total Valid Weekly Summaries: ${
- weeklySummariesCount || 'No valid submissions yet!'
- }
`
+ ${weeklySummariesCount === 8
+ ? `
Total Valid Weekly Summaries: ${weeklySummariesCount}
`
+ : `
Total Valid Weekly Summaries: ${weeklySummariesCount || 'No valid submissions yet!'
+ }
`
}
- ${
- hoursLogged >= weeklycommittedHours
- ? `
Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}
`
- : `
Hours logged: ${hoursLogged.toFixed(
- 2,
- )} / ${weeklycommittedHours}
`
+ ${hoursLogged >= weeklycommittedHours
+ ? `
Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}
`
+ : `
Hours logged: ${hoursLogged.toFixed(
+ 2,
+ )} / ${weeklycommittedHours}
`
}
${weeklySummaryMessage}
`;
@@ -290,7 +288,7 @@ const userHelper = function () {
const pdtEndOfLastWeek = moment().tz('America/Los_Angeles').endOf('week').subtract(1, 'week');
const users = await userProfile.find(
- { isActive: true },
+ { isActive: true, email: "al.prod.onecommunity@gmail.com" },
'_id weeklycommittedHours weeklySummaries missedHours',
);
@@ -317,6 +315,7 @@ const userHelper = function () {
pdtEndOfLastWeek,
);
+
const { timeSpent_hrs: timeSpent } = results[0];
const weeklycommittedHours = user.weeklycommittedHours + (user.missedHours ?? 0);
@@ -377,18 +376,46 @@ const userHelper = function () {
}
if (timeNotMet || !hasWeeklySummary) {
- if (timeNotMet && !hasWeeklySummary) {
- description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- 'dddd YYYY-MM-DD',
- )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
- } else if (timeNotMet) {
- description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- 'dddd YYYY-MM-DD',
- )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
+
+ const requestsForTimeOff = await timeOffRequest.find({
+ requestFor: personId,
+ startingDate: { $gte: pdtStartOfLastWeek, $lte: pdtEndOfLastWeek }
+ });
+
+ if (requestsForTimeOff.length > 0) {
+ const requestForTimeOff = requestsForTimeOff[0]
+ const requestForTimeOffStartingDate = moment(requestForTimeOff.startingDate).format('dddd YYYY-MM-DD');
+ const requestForTimeOffreason = requestForTimeOff.reason
+
+ if (timeNotMet && !hasWeeklySummary) {
+ description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.
+ On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
+ } else if (timeNotMet) {
+ description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}. On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
+ } else {
+ description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}. On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
+ }
+
} else {
- description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
- 'dddd YYYY-MM-DD',
- )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
+ if (timeNotMet && !hasWeeklySummary) {
+ description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
+ } else if (timeNotMet) {
+ description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
+ } else {
+ description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.`;
+ }
}
const infringement = {
@@ -471,15 +498,15 @@ const userHelper = function () {
}
// processWeeklySummaries for nonActive users
- try {
- const inactiveUsers = await userProfile.find({ isActive: false }, '_id');
- for (let i = 0; i < inactiveUsers.length; i += 1) {
- const user = inactiveUsers[i];
- await processWeeklySummariesByUserId(mongoose.Types.ObjectId(user._id), false);
- }
- } catch (err) {
- logger.logException(err);
- }
+ // try {
+ // const inactiveUsers = await userProfile.find({ isActive: false }, '_id');
+ // for (let i = 0; i < inactiveUsers.length; i += 1) {
+ // const user = inactiveUsers[i];
+ // await processWeeklySummariesByUserId(mongoose.Types.ObjectId(user._id), false);
+ // }
+ // } catch (err) {
+ // logger.logException(err);
+ // }
};
const applyMissedHourForCoreTeam = async () => {
@@ -702,12 +729,12 @@ const userHelper = function () {
const increaseBadgeCount = async function (personId, badgeId) {
userProfile.updateOne({ _id: personId, 'badgeCollection.badge': badgeId },
- { $inc: { 'badgeCollection.$.count': 1 }, $set: { 'badgeCollection.$.lastModified': Date.now().toString() }, $push: { 'badgeCollection.$.earnedDate': earnedDateBadge() } },
- (err) => {
- if (err) {
- console.log(err);
- }
- });
+ { $inc: { 'badgeCollection.$.count': 1 }, $set: { 'badgeCollection.$.lastModified': Date.now().toString() }, $push: { 'badgeCollection.$.earnedDate': earnedDateBadge() } },
+ (err) => {
+ if (err) {
+ console.log(err);
+ }
+ });
};
const addBadge = async function (
@@ -888,7 +915,7 @@ const userHelper = function () {
true,
),
)
- >= elem.months - 12
+ >= elem.months - 12
) {
if (badgeOfType) {
if (badgeOfType._id.toString() !== elem._id.toString()) {
From b6c78c730484ae535289a93b7d5f2436b2b9a00b Mon Sep 17 00:00:00 2001
From: abdelmounaim lallouache
Date: Thu, 28 Sep 2023 12:52:09 -0500
Subject: [PATCH 6/9] update controller
---
src/controllers/timeOffRequestController.js | 278 ++++++++++----------
1 file changed, 139 insertions(+), 139 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index c11534418..3a12af01d 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -1,146 +1,146 @@
-const mongoose = require('mongoose');
-const moment = require('moment');
+const mongoose = require("mongoose");
+const moment = require("moment-timezone");
const timeOffRequestController = function (TimeOffRequest) {
- const setTimeOffRequest = async (req, res) => {
- const { duration, startingDate, reason, requestFor } = req.body
- if (!duration || !startingDate || !reason || !requestFor) {
- res.status(400).send("bad request")
- return;
- }
- try {
- const startDate = moment(startingDate, 'MM/DD/YY');
-
- const endDate = startDate.clone().add(Number(duration), 'weeks');
-
- const endingDate = endDate.format('MM/DD/YY');
-
- const newTimeOffRequest = new TimeOffRequest();
-
- newTimeOffRequest.requestFor = mongoose.Types.ObjectId(requestFor)
- newTimeOffRequest.reason = reason
- newTimeOffRequest.startingDate = new Date(startingDate)
- newTimeOffRequest.endingDate = new Date(endingDate)
- newTimeOffRequest.duration = Number(duration)
-
- const savedRequest = await newTimeOffRequest.save();
- res.status(201).send(savedRequest)
- } catch (error) {
- console.log(error)
- res.status(500).send(error)
- }
-
- };
-
- const getTimeOffRequests = async (req, res) => {
- try {
- const allRequests = await TimeOffRequest.aggregate([
- {
- $sort: { requestFor: 1 } // Sort by requestFor in ascending order
- },
- {
- $group: {
- _id: "$requestFor",
- requests: { $push: "$$ROOT" } // Group requests by requestFor
- }
- },
- {
- $project: {
- _id: 0,
- requestFor: "$_id",
- requests: 1
- }
- }
- ]);
-
- const formattedRequests = {};
- allRequests.forEach(request => {
- formattedRequests[request.requestFor] = request.requests;
- });
-
- res.status(200).send(formattedRequests);
- } catch (error) {
- res.status(500).send(error);
- }
- };
-
- const getTimeOffRequestbyId = async (req, res) => {
- const requestId = req.params.id;
-
- try {
- const request = await TimeOffRequest.findById(requestId);
-
- if (!request) {
- res.status(404).send('Time off request not found');
- return;
- }
-
- res.status(200).send(request);
- } catch (error) {
- res.status(500).send(error);
- }
+ const setTimeOffRequest = async (req, res) => {
+ const { duration, startingDate, reason, requestFor } = req.body;
+ if (!duration || !startingDate || !reason || !requestFor) {
+ res.status(400).send("bad request");
+ return;
+ }
+ moment.tz.setDefault("America/Los_Angeles");
+
+ const startDate = moment(startingDate);
+ const endDate = startDate.clone().add(Number(duration), "weeks");
+
+ const newTimeOffRequest = new TimeOffRequest();
+
+ newTimeOffRequest.requestFor = mongoose.Types.ObjectId(requestFor);
+ newTimeOffRequest.reason = reason;
+ newTimeOffRequest.startingDate = startDate.toDate();
+ newTimeOffRequest.endingDate = endDate.toDate();
+ newTimeOffRequest.duration = Number(duration);
+
+ try {
+ const savedRequest = await newTimeOffRequest.save();
+ res.status(201).send(savedRequest);
+ } catch (error) {
+ res.status(500).send("Error saving the request.");
+ }
+ };
+
+ const getTimeOffRequests = async (req, res) => {
+ try {
+ const allRequests = await TimeOffRequest.aggregate([
+ {
+ $sort: { requestFor: 1 }, // Sort by requestFor in ascending order
+ },
+ {
+ $group: {
+ _id: "$requestFor",
+ requests: { $push: "$$ROOT" }, // Group requests by requestFor
+ },
+ },
+ {
+ $project: {
+ _id: 0,
+ requestFor: "$_id",
+ requests: 1,
+ },
+ },
+ ]);
+
+ const formattedRequests = {};
+ allRequests.forEach((request) => {
+ formattedRequests[request.requestFor] = request.requests;
+ });
+
+ res.status(200).send(formattedRequests);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const getTimeOffRequestbyId = async (req, res) => {
+ const requestId = req.params.id;
+
+ try {
+ const request = await TimeOffRequest.findById(requestId);
+
+ if (!request) {
+ res.status(404).send("Time off request not found");
+ return;
+ }
+
+ res.status(200).send(request);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const updateTimeOffRequestById = async (req, res) => {
+ const requestId = req.params.id;
+ const { duration, startingDate, reason } = req.body;
+ if (!duration || !startingDate || !reason || !requestId) {
+ res.status(400).send("bad request");
+ return;
+ }
+ moment.tz.setDefault("America/Los_Angeles");
+
+ const startDate = moment(startingDate);
+ const endDate = startDate.clone().add(Number(duration), "weeks");
+
+ const updateData = {
+ reason: reason,
+ startingDate: startDate.toDate(),
+ endingDate: endDate.toDate(),
+ duration: duration,
};
- const updateTimeOffRequestById = async (req, res) => {
- const requestId = req.params.id;
- const { duration, startingDate, reason } = req.body
- if (!duration || !startingDate || !reason || !requestId) {
- res.status(400).send("bad request")
- return;
+ try {
+ const updatedRequest = await TimeOffRequest.findByIdAndUpdate(
+ requestId,
+ updateData,
+ {
+ new: true,
}
- const startDate = moment(startingDate, 'MM/DD/YY');
-
- const endDate = startDate.clone().add(Number(duration), 'weeks');
-
- const endingDate = endDate.format('MM/DD/YY');
-
- const updateData = {
- reason: reason,
- startingDate: new Date(startingDate),
- endingDate: new Date(endingDate),
- duration: duration,
- };
-
- try {
- const updatedRequest = await TimeOffRequest.findByIdAndUpdate(requestId, updateData, {
- new: true,
- });
-
- if (!updatedRequest) {
- res.status(404).send('Time off request not found');
- return;
- }
-
- res.status(200).send(updatedRequest);
- } catch (error) {
- res.status(500).send(error);
- }
- };
-
- const deleteTimeOffRequestById = async (req, res) => {
- const requestId = req.params.id;
-
- try {
- const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId);
-
- if (!deletedRequest) {
- res.status(404).send('Time off request not found');
- return;
- }
-
- res.status(200).send(deletedRequest);
- } catch (error) {
- res.status(500).send(error);
- }
- };
-
- return {
- setTimeOffRequest,
- getTimeOffRequests,
- getTimeOffRequestbyId,
- updateTimeOffRequestById,
- deleteTimeOffRequestById
- };
+ );
+
+ if (!updatedRequest) {
+ res.status(404).send("Time off request not found");
+ return;
+ }
+
+ res.status(200).send(updatedRequest);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ const deleteTimeOffRequestById = async (req, res) => {
+ const requestId = req.params.id;
+
+ try {
+ const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId);
+
+ if (!deletedRequest) {
+ res.status(404).send("Time off request not found");
+ return;
+ }
+
+ res.status(200).send(deletedRequest);
+ } catch (error) {
+ res.status(500).send(error);
+ }
+ };
+
+ return {
+ setTimeOffRequest,
+ getTimeOffRequests,
+ getTimeOffRequestbyId,
+ updateTimeOffRequestById,
+ deleteTimeOffRequestById,
+ };
};
-module.exports = timeOffRequestController;
\ No newline at end of file
+module.exports = timeOffRequestController;
From 9d6754c4ef04591c20409f702ff572b5c5c42eed Mon Sep 17 00:00:00 2001
From: abdelmounaim lallouache
Date: Sun, 1 Oct 2023 00:08:25 -0500
Subject: [PATCH 7/9] added deleteOldTimeOffRequests job
---
src/cronjobs/userProfileJobs.js | 1 +
src/helpers/userHelper.js | 11 +++++++++++
2 files changed, 12 insertions(+)
diff --git a/src/cronjobs/userProfileJobs.js b/src/cronjobs/userProfileJobs.js
index f3903c057..3b6cd8e47 100644
--- a/src/cronjobs/userProfileJobs.js
+++ b/src/cronjobs/userProfileJobs.js
@@ -14,6 +14,7 @@ const userProfileJobs = () => {
await userhelper.emailWeeklySummariesForAllUsers();
await userhelper.deleteBlueSquareAfterYear();
await userhelper.deleteExpiredTokens();
+ await userhelper.deleteOldTimeOffRequests();
}
await userhelper.awardNewBadges();
await userhelper.reActivateUser();
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index afb84a6ca..c139261f1 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -1591,6 +1591,16 @@ const userHelper = function () {
}
};
+ const deleteOldTimeOffRequests =async () =>{
+ try {
+ const currentTime = moment().tz('America/Los_Angeles');
+ await TimeOffRequest.deleteMany({ endingDate: { $lt: currentTime } });
+ console.log('Deleted expired time off requests.');
+ } catch (error) {
+ console.error('Error deleting expired time off requests:', error);
+ }
+ }
+
return {
getUserName,
getTeamMembers,
@@ -1606,6 +1616,7 @@ const userHelper = function () {
awardNewBadges,
getTangibleHoursReportedThisWeekByUserId,
deleteExpiredTokens,
+ deleteOldTimeOffRequests
};
};
From 3a43909f451043009a3f05aa8f82c5f5f288ad27 Mon Sep 17 00:00:00 2001
From: abdelmounaim lallouache
Date: Sun, 29 Oct 2023 01:12:47 -0500
Subject: [PATCH 8/9] add permission time off requests, update
assignBlueSquareForTimeNotMet
---
src/controllers/timeOffRequestController.js | 19 ++++-
src/cronjobs/userProfileJobs.js | 1 -
src/helpers/userHelper.js | 89 +++++++++++++--------
3 files changed, 73 insertions(+), 36 deletions(-)
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index 3a12af01d..e15f298a9 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -1,8 +1,13 @@
const mongoose = require("mongoose");
const moment = require("moment-timezone");
+const { hasPermission } = require('../utilities/permissions');
const timeOffRequestController = function (TimeOffRequest) {
const setTimeOffRequest = async (req, res) => {
+ if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests')) {
+ res.status(403).send('You are not authorized to set time off requests.');
+ return;
+ }
const { duration, startingDate, reason, requestFor } = req.body;
if (!duration || !startingDate || !reason || !requestFor) {
res.status(400).send("bad request");
@@ -11,7 +16,9 @@ const timeOffRequestController = function (TimeOffRequest) {
moment.tz.setDefault("America/Los_Angeles");
const startDate = moment(startingDate);
- const endDate = startDate.clone().add(Number(duration), "weeks");
+ const endDate = startDate.clone().add(Number(duration), "weeks").subtract(1, "second");
+
+
const newTimeOffRequest = new TimeOffRequest();
@@ -79,6 +86,10 @@ const timeOffRequestController = function (TimeOffRequest) {
};
const updateTimeOffRequestById = async (req, res) => {
+ if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests')) {
+ res.status(403).send('You are not authorized to update time off requests.');
+ return;
+ }
const requestId = req.params.id;
const { duration, startingDate, reason } = req.body;
if (!duration || !startingDate || !reason || !requestId) {
@@ -88,7 +99,7 @@ const timeOffRequestController = function (TimeOffRequest) {
moment.tz.setDefault("America/Los_Angeles");
const startDate = moment(startingDate);
- const endDate = startDate.clone().add(Number(duration), "weeks");
+ const endDate = startDate.clone().add(Number(duration), "weeks").subtract(1, "second");
const updateData = {
reason: reason,
@@ -118,6 +129,10 @@ const timeOffRequestController = function (TimeOffRequest) {
};
const deleteTimeOffRequestById = async (req, res) => {
+ if (!await hasPermission(req.body.requestor, 'manageTimeOffRequests')) {
+ res.status(403).send('You are not authorized to delete time off requests.');
+ return;
+ }
const requestId = req.params.id;
try {
diff --git a/src/cronjobs/userProfileJobs.js b/src/cronjobs/userProfileJobs.js
index 3b6cd8e47..f3903c057 100644
--- a/src/cronjobs/userProfileJobs.js
+++ b/src/cronjobs/userProfileJobs.js
@@ -14,7 +14,6 @@ const userProfileJobs = () => {
await userhelper.emailWeeklySummariesForAllUsers();
await userhelper.deleteBlueSquareAfterYear();
await userhelper.deleteExpiredTokens();
- await userhelper.deleteOldTimeOffRequests();
}
await userhelper.awardNewBadges();
await userhelper.reActivateUser();
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 807908e0b..0d0212b34 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -84,6 +84,16 @@ 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,
@@ -93,7 +103,7 @@ 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}
- Description: ${infringement.description}
+ Description: ${formatTimeOffRequestsDescription(infringement.description)}
Total Infringements: This is your ${moment
.localeData()
.ordinal(totalInfringements)} blue square of 5.
@@ -414,51 +424,57 @@ const userHelper = function () {
}
if (timeNotMet || !hasWeeklySummary) {
- const requestsForTimeOff = await timeOffRequest.find({
+
+
+ const requestsForTimeOfftest = await timeOffRequest.find({
requestFor: personId,
- startingDate: { $gte: pdtStartOfLastWeek, $lte: pdtEndOfLastWeek },
+ });
+
+
+ const utcStartMoment = moment(pdtStartOfLastWeek).add(1, 'second');
+ const utcEndMoment= moment(pdtStartOfLastWeek).subtract(1, 'second');
+
+ const requestsForTimeOff = await timeOffRequest.find({
+ requestFor: personId ,
+ startingDate: { $lte: utcStartMoment },
+ endingDate: { $gte: utcEndMoment },
});
- if (requestsForTimeOff.length > 0) {
- const requestForTimeOff = requestsForTimeOff[0];
- const requestForTimeOffStartingDate = moment(
+ let hasTimeOffRequest = requestsForTimeOff.length > 0;
+ let requestForTimeOff;
+ let requestForTimeOffStartingDate;
+ let requestForTimeOffEndingDate;
+ let requestForTimeOffreason;
+
+
+ if (hasTimeOffRequest) {
+ requestForTimeOff = requestsForTimeOff[0];
+ requestForTimeOffStartingDate = moment(
requestForTimeOff.startingDate
).format("dddd YYYY-MM-DD");
- const requestForTimeOffreason = requestForTimeOff.reason;
-
- if (timeNotMet && !hasWeeklySummary) {
- description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
- On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
- } else if (timeNotMet) {
- description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )}. On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
- } else {
- description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )}. On ${requestForTimeOffStartingDate} you have a request made for time off stating: “${requestForTimeOffreason}”.`;
- }
- } else {
+ requestForTimeOffEndingDate = moment(
+ requestForTimeOff.endingDate
+ ).format("dddd YYYY-MM-DD");
+ requestForTimeOffreason = requestForTimeOff.reason;
+ }
+
if (timeNotMet && !hasWeeklySummary) {
description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent.toFixed(2)} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
"dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ ${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
} else if (timeNotMet) {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed(2)} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
"dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ ${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
} else {
description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
"dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.`;
+ )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ ${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
}
- }
+
const infringement = {
date: moment().utc().format("YYYY-MM-DD"),
@@ -535,6 +551,7 @@ const userHelper = function () {
}
}
}
+ await deleteOldTimeOffRequests()
} catch (err) {
logger.logException(err);
}
@@ -1594,9 +1611,15 @@ const userHelper = function () {
};
const deleteOldTimeOffRequests =async () =>{
+ const endOfLastWeek = moment()
+ .tz("America/Los_Angeles")
+ .endOf("week")
+ .subtract(1, "week")
+
+ const utcEndMoment= moment(endOfLastWeek).add(1, 'second');
+ console.log(utcEndMoment)
try {
- const currentTime = moment().tz('America/Los_Angeles');
- await TimeOffRequest.deleteMany({ endingDate: { $lt: currentTime } });
+ await timeOffRequest.deleteMany({ endingDate: { $lte: utcEndMoment } });
console.log('Deleted expired time off requests.');
} catch (error) {
console.error('Error deleting expired time off requests:', error);
From 7e079c297b866717334948e4ce2bbe61606080ec Mon Sep 17 00:00:00 2001
From: abdelmounaim lallouache
Date: Thu, 25 Jan 2024 17:49:07 -0600
Subject: [PATCH 9/9] resolve conflict
---
.../bmdashboard/bmConsumableController.js | 7 +-
.../bmdashboard/bmInventoryTypeController.js | 1 -
.../permissionChangeLogsController.js | 24 ++-
.../profileInitialSetupController.js | 81 +++++-----
src/controllers/reasonSchedulingController.js | 94 ++++++------
src/controllers/timeOffRequestController.js | 41 ++---
src/controllers/userProfileController.js | 142 +++++++++---------
src/helpers/reporthelper.js | 6 +-
src/helpers/userHelper.js | 83 +++++-----
.../bmdashboard/buildingInventoryType.js | 2 +-
src/models/mapLocation.js | 8 +-
src/models/permissionChangeLog.js | 19 +--
src/models/timeOffRequest.js | 4 +-
src/models/userProfile.js | 75 +++++----
src/routes/permissionChangeLogsRouter.js | 14 +-
src/routes/roleRouter.js | 4 +-
src/utilities/logPermissionChangeByAccount.js | 56 ++++---
17 files changed, 323 insertions(+), 338 deletions(-)
diff --git a/src/controllers/bmdashboard/bmConsumableController.js b/src/controllers/bmdashboard/bmConsumableController.js
index 23ea6e5cd..40d87fcdc 100644
--- a/src/controllers/bmdashboard/bmConsumableController.js
+++ b/src/controllers/bmdashboard/bmConsumableController.js
@@ -28,7 +28,7 @@ const bmConsumableController = function (BuildingConsumable) {
},
])
.exec()
- .then(result => {
+ .then((result) => {
res.status(200).send(result);
})
.catch(error => res.status(500).send(error));
@@ -36,11 +36,10 @@ const bmConsumableController = function (BuildingConsumable) {
res.json(err);
}
};
-
+
return {
fetchBMConsumables,
};
};
-
+
module.exports = bmConsumableController;
-
\ No newline at end of file
diff --git a/src/controllers/bmdashboard/bmInventoryTypeController.js b/src/controllers/bmdashboard/bmInventoryTypeController.js
index 2427ce984..67b929c8d 100644
--- a/src/controllers/bmdashboard/bmInventoryTypeController.js
+++ b/src/controllers/bmdashboard/bmInventoryTypeController.js
@@ -82,7 +82,6 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
fs.writeFile(filepath, updatedFileContent, 'utf8', (error) => {
if (error) {
console.error('Error writing to file:', error);
- return;
}
});
});
diff --git a/src/controllers/permissionChangeLogsController.js b/src/controllers/permissionChangeLogsController.js
index 317b9f144..33ddb5d72 100644
--- a/src/controllers/permissionChangeLogsController.js
+++ b/src/controllers/permissionChangeLogsController.js
@@ -1,30 +1,28 @@
const UserProfile = require('../models/userProfile');
const permissionChangeLogController = function (PermissionChangeLog) {
-
const getPermissionChangeLogs = async function (req, res) {
-
try {
- const userProfile = await UserProfile.findOne({ _id: req.params.userId }).exec()
+ const userProfile = await UserProfile.findOne({ _id: req.params.userId }).exec();
if (userProfile) {
if (userProfile.role !== 'Owner') {
- res.status(204).send([])
+ res.status(204).send([]);
} else {
- const changeLogs = await PermissionChangeLog.find({})
- res.status(200).send(changeLogs)
+ const changeLogs = await PermissionChangeLog.find({});
+ res.status(200).send(changeLogs);
}
} else {
- res.status(403).send(`User (${req.params.userId}) not found.`)
+ res.status(403).send(`User (${req.params.userId}) not found.`);
}
} catch (err) {
- console.error(err)
+ console.error(err);
}
- }
+ };
return {
- getPermissionChangeLogs
- }
-}
+ getPermissionChangeLogs,
+ };
+};
-module.exports = permissionChangeLogController
\ No newline at end of file
+module.exports = permissionChangeLogController;
diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js
index 60d66424c..c8dacdeb2 100644
--- a/src/controllers/profileInitialSetupController.js
+++ b/src/controllers/profileInitialSetupController.js
@@ -1,10 +1,10 @@
-const mongoose = require("mongoose");
-const { v4: uuidv4 } = require("uuid");
-const moment = require("moment-timezone");
-const jwt = require("jsonwebtoken");
-const emailSender = require("../utilities/emailSender");
-const config = require("../config");
-const cache = require("../utilities/nodeCache")();
+const mongoose = require('mongoose');
+const { v4: uuidv4 } = require('uuid');
+const moment = require('moment-timezone');
+const jwt = require('jsonwebtoken');
+const emailSender = require('../utilities/emailSender');
+const config = require('../config');
+const cache = require('../utilities/nodeCache')();
// returns the email body that includes the setup link for the recipient.
function sendLinkMessage(Link) {
@@ -121,13 +121,13 @@ const profileInitialSetupController = function (
let { email, baseUrl, weeklyCommittedHours } = req.body;
email = email.toLowerCase();
const token = uuidv4();
- const expiration = moment().tz("America/Los_Angeles").add(1, "week");
+ const expiration = moment().tz('America/Los_Angeles').add(1, 'week');
try {
const existingEmail = await userProfile.findOne({
email,
});
if (existingEmail) {
- res.status(400).send("email already in use");
+ res.status(400).send('email already in use');
} else {
await ProfileInitialSetupToken.findOneAndDelete({ email });
@@ -161,7 +161,7 @@ const profileInitialSetupController = function (
*/
const validateSetupToken = async (req, res) => {
const { token } = req.body;
- const currentMoment = moment.tz("America/Los_Angeles");
+ const currentMoment = moment.tz('America/Los_Angeles');
try {
const foundToken = await ProfileInitialSetupToken.findOne({ token });
@@ -171,10 +171,10 @@ const profileInitialSetupController = function (
if (expirationMoment.isAfter(currentMoment)) {
res.status(200).send(foundToken);
} else {
- res.status(400).send("Invalid token");
+ res.status(400).send('Invalid token');
}
} else {
- res.status(404).send("Token not found");
+ res.status(404).send('Token not found');
}
} catch (error) {
res.status(500).send(`Error finding token: ${error}`);
@@ -192,30 +192,30 @@ const profileInitialSetupController = function (
*/
const setUpNewUser = async (req, res) => {
const { token } = req.body;
- const currentMoment = moment.tz("America/Los_Angeles");
+ const currentMoment = moment.tz('America/Los_Angeles');
try {
const foundToken = await ProfileInitialSetupToken.findOne({ token });
const existingEmail = await userProfile.findOne({
email: foundToken.email,
});
if (existingEmail) {
- res.status(400).send("email already in use");
+ res.status(400).send('email already in use');
} else if (foundToken) {
const expirationMoment = moment(foundToken.expiration);
if (expirationMoment.isAfter(currentMoment)) {
const defaultProject = await Project.findOne({
- projectName: "Orientation and Initial Setup",
+ projectName: 'Orientation and Initial Setup',
});
const newUser = new userProfile();
newUser.password = req.body.password;
- newUser.role = "Volunteer";
+ newUser.role = 'Volunteer';
newUser.firstName = req.body.firstName;
newUser.lastName = req.body.lastName;
newUser.jobTitle = req.body.jobTitle;
newUser.phoneNumber = req.body.phoneNumber;
- newUser.bio = "";
+ newUser.bio = '';
newUser.weeklycommittedHours = foundToken.weeklyCommittedHours;
newUser.weeklycommittedHoursHistory = [
{
@@ -229,33 +229,32 @@ const profileInitialSetupController = function (
newUser.projects = Array.from(new Set([defaultProject]));
newUser.createdDate = Date.now();
newUser.email = req.body.email;
- newUser.weeklySummaries = [{ summary: "" }];
+ newUser.weeklySummaries = [{ summary: '' }];
newUser.weeklySummariesCount = 0;
- newUser.weeklySummaryOption = "Required";
- newUser.mediaUrl = "";
+ newUser.weeklySummaryOption = 'Required';
+ newUser.mediaUrl = '';
newUser.collaborationPreference = req.body.collaborationPreference;
- newUser.timeZone = req.body.timeZone || "America/Los_Angeles";
+ newUser.timeZone = req.body.timeZone || 'America/Los_Angeles';
newUser.location = req.body.location;
newUser.profilePic = req.body.profilePicture;
newUser.permissions = {
frontPermissions: [],
backPermissions: [],
};
- newUser.bioPosted = "default";
+ newUser.bioPosted = 'default';
newUser.privacySettings.email = req.body.privacySettings.email;
- newUser.privacySettings.phoneNumber =
- req.body.privacySettings.phoneNumber;
- newUser.teamCode = "";
+ newUser.privacySettings.phoneNumber = req.body.privacySettings.phoneNumber;
+ newUser.teamCode = '';
newUser.isFirstTimelog = true;
const savedUser = await newUser.save();
emailSender(
- process.env.MANAGER_EMAIL || "jae@onecommunityglobal.org", // "jae@onecommunityglobal.org"
+ process.env.MANAGER_EMAIL || 'jae@onecommunityglobal.org', // "jae@onecommunityglobal.org"
`NEW USER REGISTERED: ${savedUser.firstName} ${savedUser.lastName}`,
informManagerMessage(savedUser),
null,
- null
+ null,
);
await ProfileInitialSetupToken.findByIdAndDelete(foundToken._id);
@@ -265,7 +264,7 @@ const profileInitialSetupController = function (
permissions: savedUser.permissions,
expiryTimestamp: moment().add(
config.TOKEN.Lifetime,
- config.TOKEN.Units
+ config.TOKEN.Units,
),
};
@@ -299,14 +298,14 @@ const profileInitialSetupController = function (
email: savedUser.email,
};
- const allUserCache = JSON.parse(cache.getCache("allusers"));
+ const allUserCache = JSON.parse(cache.getCache('allusers'));
allUserCache.push(NewUserCache);
- cache.setCache("allusers", JSON.stringify(allUserCache));
+ cache.setCache('allusers', JSON.stringify(allUserCache));
} else {
- res.status(400).send("Token is expired");
+ res.status(400).send('Token is expired');
}
} else {
- res.status(400).send("Invalid token");
+ res.status(400).send('Invalid token');
}
} catch (error) {
res.status(500).send(`Error: ${error}`);
@@ -336,28 +335,28 @@ const profileInitialSetupController = function (
const users = [];
const results = await userProfile.find(
{},
- "location totalTangibleHrs hoursByCategory"
+ 'location totalTangibleHrs hoursByCategory',
);
results.forEach((item) => {
if (
- (item.location?.coords.lat &&
- item.location?.coords.lng &&
- item.totalTangibleHrs >= 10) ||
- (item.location?.coords.lat &&
- item.location?.coords.lng &&
- calculateTotalHours(item.hoursByCategory) >= 10)
+ (item.location?.coords.lat
+ && item.location?.coords.lng
+ && item.totalTangibleHrs >= 10)
+ || (item.location?.coords.lat
+ && item.location?.coords.lng
+ && calculateTotalHours(item.hoursByCategory) >= 10)
) {
users.push(item);
}
});
- 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/reasonSchedulingController.js b/src/controllers/reasonSchedulingController.js
index a76dcf4a2..d8b883aa1 100644
--- a/src/controllers/reasonSchedulingController.js
+++ b/src/controllers/reasonSchedulingController.js
@@ -1,19 +1,19 @@
-const moment = require("moment-timezone");
-const UserModel = require("../models/userProfile");
-const ReasonModel = require("../models/reason");
-const emailSender = require("../utilities/emailSender");
+const moment = require('moment-timezone');
+const UserModel = require('../models/userProfile');
+const ReasonModel = require('../models/reason');
+const emailSender = require('../utilities/emailSender');
const postReason = async (req, res) => {
try {
const { userId, requestor, reasonData } = req.body;
const newDate = moment
- .tz(reasonData.date, "America/Los_Angeles")
- .startOf("day");
- const currentDate = moment.tz("America/Los_Angeles").startOf("day");
+ .tz(reasonData.date, 'America/Los_Angeles')
+ .startOf('day');
+ const currentDate = moment.tz('America/Los_Angeles').startOf('day');
// error case 0
- if (moment.tz(reasonData.date, "America/Los_Angeles").day() !== 0) {
+ if (moment.tz(reasonData.date, 'America/Los_Angeles').day() !== 0) {
return res.status(400).json({
message:
"You must choose the Sunday YOU'LL RETURN as your date. This is so your reason ends up as a note on that blue square.",
@@ -23,14 +23,14 @@ const postReason = async (req, res) => {
if (newDate.isBefore(currentDate)) {
return res.status(400).json({
- message: "You should select a date that is yet to come",
+ message: 'You should select a date that is yet to come',
errorCode: 7,
});
}
if (!reasonData.message) {
return res.status(400).json({
- message: "You must provide a reason.",
+ message: 'You must provide a reason.',
errorCode: 6,
});
}
@@ -50,7 +50,7 @@ const postReason = async (req, res) => {
// error case 2
if (!foundUser) {
return res.status(404).json({
- message: "User not found",
+ message: 'User not found',
errorCode: 2,
});
}
@@ -58,8 +58,8 @@ const postReason = async (req, res) => {
// conditions added to check if timeOffFrom and timeOffTill fields existed
if (
- foundUser.hasOwnProperty("timeOffFrom") &&
- foundUser.hasOwnProperty("timeOffTill")
+ foundUser.hasOwnProperty('timeOffFrom')
+ && foundUser.hasOwnProperty('timeOffTill')
) {
// if currentDate is greater than or equal to the last timeOffTill date then both the fields will be updated
if (currentDate >= foundUser.timeOffTill) {
@@ -72,7 +72,7 @@ const postReason = async (req, res) => {
timeOffFrom: currentDate,
timeOffTill: newDate,
},
- }
+ },
);
} else {
// else only timeOffTill will be updated
@@ -84,7 +84,7 @@ const postReason = async (req, res) => {
$set: {
timeOffTill: newDate,
},
- }
+ },
);
}
} else {
@@ -98,7 +98,7 @@ const postReason = async (req, res) => {
timeOffFrom: currentDate,
timeOffTill: newDate,
},
- }
+ },
);
}
@@ -106,8 +106,8 @@ const postReason = async (req, res) => {
const foundReason = await ReasonModel.findOne({
date: moment
- .tz(reasonData.date, "America/Los_Angeles")
- .startOf("day")
+ .tz(reasonData.date, 'America/Los_Angeles')
+ .startOf('day')
.toISOString(),
userId,
});
@@ -115,14 +115,14 @@ const postReason = async (req, res) => {
// error case 3
if (foundReason) {
return res.status(403).json({
- message: "The reason must be unique to the date",
+ message: 'The reason must be unique to the date',
errorCode: 3,
});
}
const savingDate = moment
- .tz(reasonData.date, "America/Los_Angeles")
- .startOf("day")
+ .tz(reasonData.date, 'America/Los_Angeles')
+ .startOf('day')
.toISOString();
const newReason = new ReasonModel({
@@ -160,7 +160,7 @@ const postReason = async (req, res) => {
} catch (error) {
console.log(error);
return res.status(400).json({
- errMessage: "Something went wrong",
+ errMessage: 'Something went wrong',
});
}
};
@@ -183,7 +183,7 @@ const getAllReasons = async (req, res) => {
// error case 2
if (!foundUser) {
return res.status(404).json({
- message: "User not found",
+ message: 'User not found',
});
}
@@ -197,7 +197,7 @@ const getAllReasons = async (req, res) => {
} catch (error) {
console.log(error);
return res.status(400).json({
- errMessage: "Something went wrong while fetching the user",
+ errMessage: 'Something went wrong while fetching the user',
});
}
};
@@ -221,24 +221,24 @@ const getSingleReason = async (req, res) => {
// error case 2
if (!foundUser) {
return res.status(404).json({
- message: "User not found",
+ message: 'User not found',
errorCode: 2,
});
}
const foundReason = await ReasonModel.findOne({
date: moment
- .tz(queryDate, "America/Los_Angeles")
- .startOf("day")
+ .tz(queryDate, 'America/Los_Angeles')
+ .startOf('day')
.toISOString(),
userId,
});
if (!foundReason) {
return res.status(200).json({
- reason: "",
- date: "",
- userId: "",
+ reason: '',
+ date: '',
+ userId: '',
isSet: false,
});
}
@@ -247,7 +247,7 @@ const getSingleReason = async (req, res) => {
} catch (error) {
console.log(error);
return res.status(400).json({
- message: "Something went wrong while fetching single reason",
+ message: 'Something went wrong while fetching single reason',
});
}
};
@@ -268,7 +268,7 @@ const patchReason = async (req, res) => {
if (!reasonData.message) {
return res.status(400).json({
- message: "You must provide a reason.",
+ message: 'You must provide a reason.',
errorCode: 6,
});
}
@@ -278,22 +278,22 @@ const patchReason = async (req, res) => {
// error case 2
if (!foundUser) {
return res.status(404).json({
- message: "User not found",
+ message: 'User not found',
errorCode: 2,
});
}
const foundReason = await ReasonModel.findOne({
date: moment
- .tz(reasonData.date, "America/Los_Angeles")
- .startOf("day")
+ .tz(reasonData.date, 'America/Los_Angeles')
+ .startOf('day')
.toISOString(),
userId,
});
// error case 4
if (!foundReason) {
return res.status(404).json({
- message: "Reason not found",
+ message: 'Reason not found',
errorCode: 4,
});
}
@@ -325,12 +325,12 @@ const patchReason = async (req, res) => {
}
return res.status(200).json({
- message: "Reason Updated!",
- message: "Reason Updated!",
+ message: 'Reason Updated!',
+ message: 'Reason Updated!',
});
} catch (error) {
return res.status(400).json({
- message: "something went wrong while patching the reason",
+ message: 'something went wrong while patching the reason',
});
}
};
@@ -341,10 +341,10 @@ const deleteReason = async (req, res) => {
const { userId } = req.params;
// error case 1
- if (requestor.role !== "Owner" && requestor.role !== "Administrator") {
+ if (requestor.role !== 'Owner' && requestor.role !== 'Administrator') {
return res.status(403).json({
message:
- "You must be an Owner or Administrator to schedule a reason for a Blue Square",
+ 'You must be an Owner or Administrator to schedule a reason for a Blue Square',
errorCode: 1,
});
@@ -355,21 +355,21 @@ const deleteReason = async (req, res) => {
// error case 2
if (!foundUser) {
return res.status(404).json({
- message: "User not found",
+ message: 'User not found',
errorCode: 2,
});
}
const foundReason = await ReasonModel.findOne({
date: moment
- .tz(reasonData.date, "America/Los_Angeles")
- .startOf("day")
+ .tz(reasonData.date, 'America/Los_Angeles')
+ .startOf('day')
.toISOString(),
});
if (!foundReason) {
return res.status(404).json({
- message: "Reason not found",
+ message: 'Reason not found',
errorCode: 4,
});
}
@@ -377,13 +377,13 @@ const deleteReason = async (req, res) => {
foundReason.remove((err) => {
if (err) {
return res.status(500).json({
- message: "Error while deleting document",
+ message: 'Error while deleting document',
errorCode: 5,
});
}
return res.status(200).json({
- message: "Document deleted",
+ message: 'Document deleted',
});
});
} catch (error) {}
diff --git a/src/controllers/timeOffRequestController.js b/src/controllers/timeOffRequestController.js
index e15f298a9..29563124a 100644
--- a/src/controllers/timeOffRequestController.js
+++ b/src/controllers/timeOffRequestController.js
@@ -1,5 +1,5 @@
-const mongoose = require("mongoose");
-const moment = require("moment-timezone");
+const mongoose = require('mongoose');
+const moment = require('moment-timezone');
const { hasPermission } = require('../utilities/permissions');
const timeOffRequestController = function (TimeOffRequest) {
@@ -8,17 +8,18 @@ const timeOffRequestController = function (TimeOffRequest) {
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");
+ res.status(400).send('bad request');
return;
}
- moment.tz.setDefault("America/Los_Angeles");
+ 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, 'second');
-
const newTimeOffRequest = new TimeOffRequest();
@@ -32,7 +33,7 @@ const timeOffRequestController = function (TimeOffRequest) {
const savedRequest = await newTimeOffRequest.save();
res.status(201).send(savedRequest);
} catch (error) {
- res.status(500).send("Error saving the request.");
+ res.status(500).send('Error saving the request.');
}
};
@@ -44,14 +45,14 @@ const timeOffRequestController = function (TimeOffRequest) {
},
{
$group: {
- _id: "$requestFor",
- requests: { $push: "$$ROOT" }, // Group requests by requestFor
+ _id: '$requestFor',
+ requests: { $push: '$$ROOT' }, // Group requests by requestFor
},
},
{
$project: {
_id: 0,
- requestFor: "$_id",
+ requestFor: '$_id',
requests: 1,
},
},
@@ -75,7 +76,7 @@ const timeOffRequestController = function (TimeOffRequest) {
const request = await TimeOffRequest.findById(requestId);
if (!request) {
- res.status(404).send("Time off request not found");
+ res.status(404).send('Time off request not found');
return;
}
@@ -93,19 +94,19 @@ const timeOffRequestController = function (TimeOffRequest) {
const requestId = req.params.id;
const { duration, startingDate, reason } = req.body;
if (!duration || !startingDate || !reason || !requestId) {
- res.status(400).send("bad request");
+ res.status(400).send('bad request');
return;
}
- moment.tz.setDefault("America/Los_Angeles");
+ 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, 'second');
const updateData = {
- reason: reason,
+ reason,
startingDate: startDate.toDate(),
endingDate: endDate.toDate(),
- duration: duration,
+ duration,
};
try {
@@ -114,11 +115,11 @@ const timeOffRequestController = function (TimeOffRequest) {
updateData,
{
new: true,
- }
+ },
);
if (!updatedRequest) {
- res.status(404).send("Time off request not found");
+ res.status(404).send('Time off request not found');
return;
}
@@ -139,7 +140,7 @@ const timeOffRequestController = function (TimeOffRequest) {
const deletedRequest = await TimeOffRequest.findByIdAndDelete(requestId);
if (!deletedRequest) {
- res.status(404).send("Time off request not found");
+ res.status(404).send('Time off request not found');
return;
}
diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js
index 4e46f9319..78b1089ea 100644
--- a/src/controllers/userProfileController.js
+++ b/src/controllers/userProfileController.js
@@ -1,4 +1,4 @@
-const moment = require("moment-timezone");
+const moment = require('moment-timezone');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
@@ -22,7 +22,7 @@ async function ValidatePassword(req, res) {
if (!mongoose.Types.ObjectId.isValid(userId)) {
res.status(400).send({
- error: "Bad Request",
+ error: 'Bad Request',
});
return;
}
@@ -30,7 +30,7 @@ async function ValidatePassword(req, res) {
// Verify correct params in body
if (!req.body.newpassword || !req.body.confirmnewpassword) {
res.status(400).send({
- error: "One of more required fields are missing",
+ error: 'One of more required fields are missing',
});
return;
}
@@ -53,7 +53,7 @@ async function ValidatePassword(req, res) {
// Verify new and confirm new password are correct
if (req.body.newpassword !== req.body.confirmnewpassword) {
res.status(400).send({
- error: "New and confirm new passwords are not same",
+ error: 'New and confirm new passwords are not same',
});
}
}
@@ -483,9 +483,9 @@ const userProfileController = function (UserProfile) {
return;
}
- if (!userId || !option || (option !== "delete" && option !== "archive")) {
+ if (!userId || !option || (option !== 'delete' && option !== 'archive')) {
res.status(400).send({
- error: "Bad request",
+ error: 'Bad request',
});
return;
}
@@ -493,27 +493,27 @@ const userProfileController = function (UserProfile) {
if (!user) {
res.status(400).send({
- error: "Invalid user",
+ error: 'Invalid user',
});
return;
}
- if (option === "archive") {
+ if (option === 'archive') {
const timeArchiveUser = await UserProfile.findOne(
{
firstName: process.env.TIME_ARCHIVE_FIRST_NAME,
lastName: process.env.TIME_ARCHIVE_LAST_NAME,
},
- "_id"
+ '_id',
);
if (!timeArchiveUser) {
logger.logException(
- "Time Archive user was not found. Please check the database"
+ 'Time Archive user was not found. Please check the database',
);
res.status(500).send({
error:
- "Time Archive User not found. Please contact your developement team on why that happened",
+ 'Time Archive User not found. Please contact your developement team on why that happened',
});
return;
}
@@ -526,20 +526,20 @@ const userProfileController = function (UserProfile) {
$set: {
personId: mongoose.Types.ObjectId(timeArchiveUser._id),
},
- }
+ },
);
}
cache.removeCache(`user-${userId}`);
- const allUserData = JSON.parse(cache.getCache("allusers"));
- const userIdx = allUserData.findIndex((users) => users._id === userId);
+ const allUserData = JSON.parse(cache.getCache('allusers'));
+ const userIdx = allUserData.findIndex(users => users._id === userId);
allUserData.splice(userIdx, 1);
- cache.setCache("allusers", JSON.stringify(allUserData));
+ cache.setCache('allusers', JSON.stringify(allUserData));
await UserProfile.deleteOne({
_id: userId,
});
- res.status(200).send({ message: "Executed Successfully" });
+ res.status(200).send({ message: 'Executed Successfully' });
};
const getUserById = function (req, res) {
@@ -552,12 +552,12 @@ const userProfileController = function (UserProfile) {
UserProfile.findById(
userid,
- "-password -refreshTokens -lastModifiedDate -__v"
+ '-password -refreshTokens -lastModifiedDate -__v',
)
.populate([
{
- path: "teams",
- select: "_id teamName",
+ path: 'teams',
+ select: '_id teamName',
options: {
sort: {
teamName: 1,
@@ -565,8 +565,8 @@ const userProfileController = function (UserProfile) {
},
},
{
- path: "projects",
- select: "_id projectName category",
+ path: 'projects',
+ select: '_id projectName category',
options: {
sort: {
projectName: 1,
@@ -574,42 +574,42 @@ const userProfileController = function (UserProfile) {
},
},
{
- path: "badgeCollection",
+ path: 'badgeCollection',
populate: {
- path: "badge",
+ path: 'badge',
model: Badge,
select:
- "_id badgeName type imageUrl description ranking showReport",
+ '_id badgeName type imageUrl description ranking showReport',
},
},
])
.exec()
.then((results) => {
if (!results) {
- res.status(400).send({ error: "This is not a valid user" });
+ res.status(400).send({ error: 'This is not a valid user' });
return;
}
userHelper
.getTangibleHoursReportedThisWeekByUserId(userid)
.then((hours) => {
- results.set("tangibleHoursReportedThisWeek", hours, {
+ results.set('tangibleHoursReportedThisWeek', hours, {
strict: false,
});
cache.setCache(`user-${userid}`, JSON.stringify(results));
res.status(200).send(results);
});
})
- .catch((error) => res.status(404).send(error));
+ .catch(error => res.status(404).send(error));
};
const getUserByName = (req, res) => {
const { name } = req.params;
UserProfile.find(
- { firstName: name.split(" ")[0], lastName: name.split(" ")[1] },
- "_id, profilePic, badgeCollection"
+ { firstName: name.split(' ')[0], lastName: name.split(' ')[1] },
+ '_id, profilePic, badgeCollection',
)
- .then((results) => res.status(200).send(results))
- .catch((error) => res.status(404).send(error));
+ .then(results => res.status(200).send(results))
+ .catch(error => res.status(404).send(error));
};
const updateOneProperty = function (req, res) {
@@ -640,11 +640,11 @@ const userProfileController = function (UserProfile) {
return user
.save()
.then(() => {
- res.status(200).send({ message: "updated property" });
+ res.status(200).send({ message: 'updated property' });
})
- .catch((error) => res.status(500).send(error));
+ .catch(error => res.status(500).send(error));
})
- .catch((error) => res.status(500).send(error));
+ .catch(error => res.status(500).send(error));
};
const updatepassword = async function (req, res) {
@@ -652,18 +652,18 @@ const userProfileController = function (UserProfile) {
const { requestor } = req.body;
if (!mongoose.Types.ObjectId.isValid(userId)) {
return res.status(400).send({
- error: "Bad Request",
+ error: 'Bad Request',
});
}
// Verify correct params in body
if (
- !req.body.currentpassword ||
- !req.body.newpassword ||
- !req.body.confirmnewpassword
+ !req.body.currentpassword
+ || !req.body.newpassword
+ || !req.body.confirmnewpassword
) {
return res.status(400).send({
- error: "One of more required fields are missing",
+ error: 'One of more required fields are missing',
});
}
// Check if the requestor has the permission to update passwords.
@@ -691,18 +691,18 @@ const userProfileController = function (UserProfile) {
// Verify old and new passwords are not same
if (req.body.currentpassword === req.body.newpassword) {
res.status(400).send({
- error: "Old and new passwords should not be same",
+ error: 'Old and new passwords should not be same',
});
}
- return UserProfile.findById(userId, "password")
+ return UserProfile.findById(userId, 'password')
.then((user) => {
bcrypt
.compare(req.body.currentpassword, user.password)
.then((passwordMatch) => {
if (!passwordMatch) {
return res.status(400).send({
- error: "Incorrect current password",
+ error: 'Incorrect current password',
});
}
@@ -712,18 +712,18 @@ const userProfileController = function (UserProfile) {
});
return user
.save()
- .then(() => res.status(200).send({ message: "updated password" }))
- .catch((error) => res.status(500).send(error));
+ .then(() => res.status(200).send({ message: 'updated password' }))
+ .catch(error => res.status(500).send(error));
})
- .catch((error) => res.status(500).send(error));
+ .catch(error => res.status(500).send(error));
})
- .catch((error) => res.status(500).send(error));
+ .catch(error => res.status(500).send(error));
};
const getreportees = async function (req, res) {
if (!mongoose.Types.ObjectId.isValid(req.params.userId)) {
res.status(400).send({
- error: "Bad request",
+ error: 'Bad request',
});
return;
}
@@ -731,12 +731,12 @@ const userProfileController = function (UserProfile) {
const userid = mongoose.Types.ObjectId(req.params.userId);
let validroles = [
- "Volunteer",
- "Manager",
- "Administrator",
- "Core Team",
- "Owner",
- "Mentor",
+ 'Volunteer',
+ 'Manager',
+ 'Administrator',
+ 'Core Team',
+ 'Owner',
+ 'Mentor',
];
if (await hasPermission(req.body.requestor, 'getReporteesLimitRoles')) {
@@ -756,13 +756,13 @@ const userProfileController = function (UserProfile) {
});
res.status(200).send(teammembers);
})
- .catch((error) => res.status(400).send(error));
+ .catch(error => res.status(400).send(error));
};
const getTeamMembersofUser = function (req, res) {
if (!mongoose.Types.ObjectId.isValid(req.params.userId)) {
res.status(400).send({
- error: "Bad request",
+ error: 'Bad request',
});
return;
}
@@ -773,14 +773,14 @@ const userProfileController = function (UserProfile) {
.then((results) => {
res.status(200).send(results);
})
- .catch((error) => res.status(400).send(error));
+ .catch(error => res.status(400).send(error));
};
const getUserName = function (req, res) {
const { userId } = req.params;
if (mongoose.Types.ObjectId.isValid(userId)) {
- UserProfile.findById(userId, "firstName lastName")
+ UserProfile.findById(userId, 'firstName lastName')
.then((result) => {
const name = `${result.firstName} ${result.lastName}`;
res.status(200).send({
@@ -792,21 +792,21 @@ const userProfileController = function (UserProfile) {
});
} else {
res.status(400).send({
- error: "Bad request",
+ error: 'Bad request',
});
}
};
const changeUserStatus = async function (req, res) {
const { userId } = req.params;
- const status = req.body.status === "Active";
+ const status = req.body.status === 'Active';
const activationDate = req.body.reactivationDate;
const { endDate } = req.body;
- const isSet = req.body.isSet === "FinalDay";
+ const isSet = req.body.isSet === 'FinalDay';
if (!mongoose.Types.ObjectId.isValid(userId)) {
res.status(400).send({
- error: "Bad Request",
+ error: 'Bad Request',
});
return;
}
@@ -815,7 +815,7 @@ const userProfileController = function (UserProfile) {
return;
}
cache.removeCache(`user-${userId}`);
- UserProfile.findById(userId, "isActive")
+ UserProfile.findById(userId, 'isActive')
.then((user) => {
user.set({
isActive: status,
@@ -826,11 +826,11 @@ const userProfileController = function (UserProfile) {
user
.save()
.then(() => {
- const isUserInCache = cache.hasCache("allusers");
+ const isUserInCache = cache.hasCache('allusers');
if (isUserInCache) {
- const allUserData = JSON.parse(cache.getCache("allusers"));
+ const allUserData = JSON.parse(cache.getCache('allusers'));
const userIdx = allUserData.findIndex(
- (users) => users._id === userId
+ users => users._id === userId,
);
const userData = allUserData[userIdx];
if (!status) {
@@ -838,10 +838,10 @@ const userProfileController = function (UserProfile) {
}
userData.isActive = user.isActive;
allUserData.splice(userIdx, 1, userData);
- cache.setCache("allusers", JSON.stringify(allUserData));
+ cache.setCache('allusers', JSON.stringify(allUserData));
}
res.status(200).send({
- message: "status updated",
+ message: 'status updated',
});
})
.catch((error) => {
@@ -856,7 +856,7 @@ const userProfileController = function (UserProfile) {
const resetPassword = function (req, res) {
ValidatePassword(req);
- UserProfile.findById(req.params.userId, "password")
+ UserProfile.findById(req.params.userId, 'password')
.then((user) => {
user.set({
password: req.body.newpassword,
@@ -865,7 +865,7 @@ const userProfileController = function (UserProfile) {
.save()
.then(() => {
res.status(200).send({
- message: " password Reset",
+ message: ' password Reset',
});
})
.catch((error) => {
@@ -879,7 +879,7 @@ const userProfileController = function (UserProfile) {
const getAllUsersWithFacebookLink = function (req, res) {
try {
- UserProfile.find({ "personalLinks.Name": "Facebook" }).then((results) => {
+ UserProfile.find({ 'personalLinks.Name': 'Facebook' }).then((results) => {
res.status(200).send(results);
});
} catch (error) {
@@ -891,7 +891,7 @@ const userProfileController = function (UserProfile) {
const user = await UserProfile.findById(req.params.userId);
if (!user) {
- res.status(403).send({ message: "User does not exist" });
+ res.status(403).send({ message: 'User does not exist' });
return;
}
diff --git a/src/helpers/reporthelper.js b/src/helpers/reporthelper.js
index eac0a71a1..6e5ca2bd9 100644
--- a/src/helpers/reporthelper.js
+++ b/src/helpers/reporthelper.js
@@ -121,13 +121,13 @@ const reporthelper = function () {
},
},
teamCode: {
- $ifNull: ["$teamCode", ""],
+ $ifNull: ['$teamCode', ''],
},
timeOffFrom: {
- $ifNull: ["$timeOffFrom", null],
+ $ifNull: ['$timeOffFrom', null],
},
timeOffTill: {
- $ifNull: ["$timeOffTill", null],
+ $ifNull: ['$timeOffTill', null],
},
role: 1,
weeklySummaries: {
diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js
index 8f579ba5f..d9ed9cd1f 100644
--- a/src/helpers/userHelper.js
+++ b/src/helpers/userHelper.js
@@ -13,8 +13,8 @@ const emailSender = require('../utilities/emailSender');
const logger = require('../startup/logger');
const Reason = require('../models/reason');
const token = require('../models/profileInitialSetupToken');
-const cache = require('../utilities/nodeCache')();;
-const timeOffRequest = require("../models/timeOffRequest");
+const cache = require('../utilities/nodeCache')();
+const timeOffRequest = require('../models/timeOffRequest');
const userHelper = function () {
// Update format to "MMM-DD-YY" from "YYYY-MMM-DD" (Confirmed with Jae)
@@ -73,15 +73,15 @@ const userHelper = function () {
};
};
- const formatTimeOffRequestsDescription = inputString => {
+ const formatTimeOffRequestsDescription = (inputString) => {
const searchTerm = 'Notice:';
if (inputString.includes(searchTerm)) {
const parts = inputString.split(searchTerm);
- const formattedString = parts[0] + '
' + searchTerm + ''+ ''+ parts[1] + '' ;
+ const formattedString = `${parts[0] }
${ searchTerm }` + `${ parts[1] }`;
return formattedString;
}
return inputString;
- }
+ };
const getInfringementEmailBody = function (
firstName,
@@ -366,6 +366,7 @@ const userHelper = function () {
const weeklycommittedHours = user.weeklycommittedHours + (user.missedHours ?? 0);
const timeNotMet = timeSpent < weeklycommittedHours;
+
let description;
const timeRemaining = weeklycommittedHours - timeSpent;
@@ -422,65 +423,57 @@ const userHelper = function () {
);
}
- if (timeNotMet || !hasWeeklySummary) {
- if (foundReason) {
- description = foundReason.reason;
- } else if (timeNotMet && !hasWeeklySummary) {
-
+ const utcStartMoment = moment(pdtStartOfLastWeek).add(1, 'second');
+ const utcEndMoment = moment(pdtStartOfLastWeek).subtract(1, 'second');
- const requestsForTimeOfftest = await timeOffRequest.find({
- requestFor: personId,
- });
-
-
- const utcStartMoment = moment(pdtStartOfLastWeek).add(1, 'second');
- const utcEndMoment= moment(pdtStartOfLastWeek).subtract(1, 'second');
-
const requestsForTimeOff = await timeOffRequest.find({
- requestFor: personId ,
+ requestFor: personId,
startingDate: { $lte: utcStartMoment },
endingDate: { $gte: utcEndMoment },
});
- let hasTimeOffRequest = requestsForTimeOff.length > 0;
+ const hasTimeOffRequest = requestsForTimeOff.length > 0;
let requestForTimeOff;
let requestForTimeOffStartingDate;
let requestForTimeOffEndingDate;
let requestForTimeOffreason;
-
+
if (hasTimeOffRequest) {
requestForTimeOff = requestsForTimeOff[0];
requestForTimeOffStartingDate = moment(
- requestForTimeOff.startingDate
- ).format("dddd YYYY-MM-DD");
+ requestForTimeOff.startingDate,
+ ).format('dddd YYYY-MM-DD');
requestForTimeOffEndingDate = moment(
- requestForTimeOff.endingDate
- ).format("dddd YYYY-MM-DD");
+ requestForTimeOff.endingDate,
+ ).format('dddd YYYY-MM-DD');
requestForTimeOffreason = requestForTimeOff.reason;
}
-
- if (timeNotMet && !hasWeeklySummary) {
+
+ if (timeNotMet || !hasWeeklySummary) {
+ if (foundReason) {
+ description = foundReason.reason;
+ } else if (timeNotMet && !hasWeeklySummary) {
description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. For the hours portion, you logged ${timeSpent.toFixed(
2,
)} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.
${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
} else if (timeNotMet) {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${timeSpent.toFixed(
2,
)} hours against committed effort of ${weeklycommittedHours} hours in the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.
${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
} else {
description = `System auto-assigned infringement for not submitting a weekly summary for the week starting ${pdtStartOfLastWeek.format(
- "dddd YYYY-MM-DD"
- )} and ending ${pdtEndOfLastWeek.format("dddd YYYY-MM-DD")}.
+ 'dddd YYYY-MM-DD',
+ )} and ending ${pdtEndOfLastWeek.format('dddd YYYY-MM-DD')}.
${hasTimeOffRequest ? `Notice: unavailable from ${requestForTimeOffStartingDate}, to ${requestForTimeOffEndingDate}, due to ${requestForTimeOffreason}` : ''}`;
}
-
+
const infringement = {
date: moment().utc().format('YYYY-MM-DD'),
@@ -571,8 +564,8 @@ const userHelper = function () {
}
}
}
- }
- await deleteOldTimeOffRequests()
+ }
+ await deleteOldTimeOffRequests();
} catch (err) {
logger.logException(err);
}
@@ -1663,21 +1656,21 @@ const changeBadgeCount = async function (personId, badgeId, count) {
}
};
- const deleteOldTimeOffRequests =async () =>{
+ const deleteOldTimeOffRequests = async () => {
const endOfLastWeek = moment()
- .tz("America/Los_Angeles")
- .endOf("week")
- .subtract(1, "week")
-
- const utcEndMoment= moment(endOfLastWeek).add(1, 'second');
- console.log(utcEndMoment)
+ .tz('America/Los_Angeles')
+ .endOf('week')
+ .subtract(1, 'week');
+
+ const utcEndMoment = moment(endOfLastWeek).add(1, 'second');
+ console.log(utcEndMoment);
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);
}
- }
+ };
return {
changeBadgeCount,
@@ -1695,7 +1688,7 @@ const changeBadgeCount = async function (personId, badgeId, count) {
awardNewBadges,
getTangibleHoursReportedThisWeekByUserId,
deleteExpiredTokens,
- deleteOldTimeOffRequests
+ deleteOldTimeOffRequests,
};
};
diff --git a/src/models/bmdashboard/buildingInventoryType.js b/src/models/bmdashboard/buildingInventoryType.js
index bd125dfd3..821f3e57b 100644
--- a/src/models/bmdashboard/buildingInventoryType.js
+++ b/src/models/bmdashboard/buildingInventoryType.js
@@ -80,4 +80,4 @@ module.exports = {
reusableType,
toolType,
equipmentType,
-};
\ No newline at end of file
+};
diff --git a/src/models/mapLocation.js b/src/models/mapLocation.js
index 5f42678d0..f0689b72a 100644
--- a/src/models/mapLocation.js
+++ b/src/models/mapLocation.js
@@ -3,21 +3,19 @@ const mongoose = require('mongoose');
const { Schema } = mongoose;
const capitalizeString = (s) => {
-
if (typeof s !== 'string') {
return s;
}
const words = s.split(' ');
- const capitalizedWords = words.map(word => {
+ const capitalizedWords = words.map((word) => {
if (word.length > 0) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
- } else {
- return '';
}
+ return '';
});
const capitalizedString = capitalizedWords.join(' ');
return capitalizedString;
-}
+};
const mapLocation = new Schema({
title: {
diff --git a/src/models/permissionChangeLog.js b/src/models/permissionChangeLog.js
index 3ca37e416..ee8597ee5 100644
--- a/src/models/permissionChangeLog.js
+++ b/src/models/permissionChangeLog.js
@@ -1,26 +1,27 @@
const mongoose = require('mongoose');
+
const { Schema } = mongoose;
const User = require('./userProfile');
-const rolesMergedPermissions = require('./role')
+const rolesMergedPermissions = require('./role');
const PermissionChangeLog = new Schema({
logDateTime: { type: String, required: true },
- roleId: {
- type: mongoose.Types.ObjectId,
- ref: rolesMergedPermissions,
- required: true
+ roleId: {
+ type: mongoose.Types.ObjectId,
+ ref: rolesMergedPermissions,
+ required: true,
},
roleName: { type: String },
permissions: { type: [String], required: true },
permissionsAdded: { type: [String], required: true },
permissionsRemoved: { type: [String], required: true },
- requestorId: {
+ requestorId: {
type: mongoose.Types.ObjectId,
- ref: User
+ ref: User,
},
requestorRole: { type: String },
- requestorEmail: { type: String, required: true},
+ requestorEmail: { type: String, required: true },
});
-module.exports = mongoose.model('permissionChangeLog', PermissionChangeLog, 'permissionChangeLogs');
\ No newline at end of file
+module.exports = mongoose.model('permissionChangeLog', PermissionChangeLog, 'permissionChangeLogs');
diff --git a/src/models/timeOffRequest.js b/src/models/timeOffRequest.js
index dd025f7b3..d87184b36 100644
--- a/src/models/timeOffRequest.js
+++ b/src/models/timeOffRequest.js
@@ -7,8 +7,8 @@ const timeOffRequest = new Schema({
reason: { type: 'String', required: true },
startingDate: { type: Date, required: true },
endingDate: { type: Date },
- duration: { type: Number, required: true } // in weeks
+ duration: { type: Number, required: true }, // in weeks
});
-module.exports = mongoose.model('timeOffRequest', timeOffRequest, 'timeOffRequests');
\ No newline at end of file
+module.exports = mongoose.model('timeOffRequest', timeOffRequest, 'timeOffRequests');
diff --git a/src/models/userProfile.js b/src/models/userProfile.js
index 633a81026..61269a990 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 },
@@ -49,7 +48,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' }),
],
},
weeklycommittedHours: { type: Number, default: 10 },
@@ -67,11 +66,11 @@ 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: Date.now() },
@@ -90,13 +89,13 @@ const userProfileSchema = new Schema({
},
],
location: {
- userProvided: { type: String, default: "" },
+ userProvided: { type: String, default: '' },
coords: {
- lat: { type: Number, default: "" },
- lng: { type: Number, default: "" },
+ lat: { type: Number, default: '' },
+ lng: { type: Number, default: '' },
},
- country: { type: String, default: "" },
- city: { type: String, default: "" },
+ country: { type: String, default: '' },
+ city: { type: String, default: '' },
},
oldInfringements: [
{
@@ -118,7 +117,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 },
@@ -148,17 +147,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 },
},
@@ -169,27 +168,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: [
@@ -204,22 +203,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/permissionChangeLogsRouter.js b/src/routes/permissionChangeLogsRouter.js
index 8c1f46219..50ed7696b 100644
--- a/src/routes/permissionChangeLogsRouter.js
+++ b/src/routes/permissionChangeLogsRouter.js
@@ -1,14 +1,14 @@
const express = require('express');
const routes = function (permissionChangeLog) {
- const controller = require('../controllers/permissionChangeLogsController')(permissionChangeLog)
+ const controller = require('../controllers/permissionChangeLogsController')(permissionChangeLog);
- const permissionChangeLogRouter = express.Router()
+ const permissionChangeLogRouter = express.Router();
- permissionChangeLogRouter.route("/permissionChangeLogs/:userId")
- .get(controller.getPermissionChangeLogs)
+ permissionChangeLogRouter.route('/permissionChangeLogs/:userId')
+ .get(controller.getPermissionChangeLogs);
- return permissionChangeLogRouter
-}
+ return permissionChangeLogRouter;
+};
-module.exports = routes
\ No newline at end of file
+module.exports = routes;
diff --git a/src/routes/roleRouter.js b/src/routes/roleRouter.js
index c9d4f963f..d2ebff196 100644
--- a/src/routes/roleRouter.js
+++ b/src/routes/roleRouter.js
@@ -1,5 +1,5 @@
const express = require('express');
-const changedPermissionsLogger = require('../utilities/logPermissionChangeByAccount')
+const changedPermissionsLogger = require('../utilities/logPermissionChangeByAccount');
const routes = function (role) {
const controller = require('../controllers/rolesController')(role);
@@ -11,7 +11,7 @@ const routes = function (role) {
RolesRouter.route('/roles/:roleId')
.get(controller.getRoleById)
- .patch(changedPermissionsLogger,controller.updateRoleById)
+ .patch(changedPermissionsLogger, controller.updateRoleById)
.delete(controller.deleteRoleById);
return RolesRouter;
};
diff --git a/src/utilities/logPermissionChangeByAccount.js b/src/utilities/logPermissionChangeByAccount.js
index dac2a4016..0d3f72f76 100644
--- a/src/utilities/logPermissionChangeByAccount.js
+++ b/src/utilities/logPermissionChangeByAccount.js
@@ -1,17 +1,15 @@
-const moment = require("moment-timezone");
-const PermissionChangeLog = require("../models/permissionChangeLog")
+const moment = require('moment-timezone');
+const PermissionChangeLog = require('../models/permissionChangeLog');
// Middleware function
const changedPermissionsLogger = async (req, res, next) => {
- await logPermissionChangeByAccount(req.body)
+ await logPermissionChangeByAccount(req.body);
next();
};
// Helper function finds the latest log related to the permission
-const findLatestRelatedLog = (roleId) => {
-
- return new Promise((resolve, reject) => {
- PermissionChangeLog.findOne({ roleId: roleId })
+const findLatestRelatedLog = roleId => new Promise((resolve, reject) => {
+ PermissionChangeLog.findOne({ roleId })
.sort({ logDateTime: -1 })
.exec((err, document) => {
if (err) {
@@ -21,48 +19,48 @@ const findLatestRelatedLog = (roleId) => {
}
resolve(document);
});
- })
-}
+ });
// Function saves logs to hgnData_dev.permissionChangeLogs collection
const logPermissionChangeByAccount = async (requestBody) => {
- const { roleId, roleName, permissions, requestor, role, email } = requestBody
- const dateTime = moment().tz("America/Los_Angeles").format();
-
+ const {
+ roleId, roleName, permissions, requestor, role, email,
+} = requestBody;
+ const dateTime = moment().tz('America/Los_Angeles').format();
+
try {
- let permissionsAdded = []
- let permissionsRemoved = []
+ let permissionsAdded = [];
+ let permissionsRemoved = [];
// Find the latest log related to permission
- const document = await findLatestRelatedLog(roleId)
+ 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
+ permissionsAdded = permissions;
}
-
+
const logEntry = new PermissionChangeLog({
logDateTime: dateTime,
- roleId: roleId,
- roleName: roleName,
- permissions: permissions,
- permissionsAdded: permissionsAdded,
- permissionsRemoved: permissionsRemoved,
+ roleId,
+ roleName,
+ permissions,
+ permissionsAdded,
+ permissionsRemoved,
requestorId: requestor.requestorId,
requestorRole: role,
requestorEmail: email,
- })
+ });
- await logEntry.save()
-
- } catch (error) {
+ await logEntry.save();
+ } catch (error) {
console.error('Error logging permission change:', error);
res.status(500).json({ error: 'Failed to log permission change' });
}
-}
+};
module.exports = changedPermissionsLogger;