Skip to content

Commit

Permalink
Resolve conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
ptrpengdev committed Feb 17, 2024
2 parents a335b47 + 0e6a1b4 commit f0eb025
Show file tree
Hide file tree
Showing 4 changed files with 167 additions and 66 deletions.
51 changes: 42 additions & 9 deletions src/controllers/badgeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,23 @@ const escapeRegex = require('../utilities/escapeRegex');
const cache = require('../utilities/nodeCache')();
const logger = require('../startup/logger');


const badgeController = function (Badge) {
/**
* getAllBadges handles badges retrieval.
* @param {Object} req - Request object.
* @returns {Array<Object>} List containing badge records.
*/
const getAllBadges = async function (req, res) {
if (!(await hasPermission(req.body.requestor, 'seeBadges'))) {
res.status(403).send('You are not authorized to view all badge data.');
return;
}
// Add cache to reduce database query and optimize performance
if (cache.hasCache('allBadges')) {
res.status(200).send(cache.getCache('allBadges'));
return;
}

Badge.find(
{},
Expand All @@ -25,8 +36,11 @@ const badgeController = function (Badge) {
ranking: 1,
badgeName: 1,
})
.then(results => res.status(200).send(results))
.catch(error => res.status(404).send(error));
.then((results) => {
cache.setCache('allBadges', results);
res.status(200).send(results);
})
.catch(error => res.status(500).send(error));
};

/**
Expand Down Expand Up @@ -59,11 +73,12 @@ const badgeController = function (Badge) {
return;
}
const badgeCounts = {};
let newBadgeCollection = [];
// This line is using the forEach function to group badges in the badgeCollection
// array in the request body.
// Validation: No duplicate badge id;
try {
req.body.badgeCollection.forEach((element) => {
newBadgeCollection = req.body.badgeCollection.map((element) => {
if (badgeCounts[element.badge]) {
throw new Error('Duplicate badges sent in.');
}
Expand All @@ -78,15 +93,19 @@ const badgeController = function (Badge) {
res.status(500).send(`Internal Error: Badge Collection. ${ err.message}`);
return;
}
record.badgeCollection = req.body.badgeCollection;
record.badgeCollection = newBadgeCollection;

if (cache.hasCache(`user-${userToBeAssigned}`)) {
cache.removeCache(`user-${userToBeAssigned}`);
}
// Save Updated User Profile
record
.save()
.then(results => res.status(201).send(results._id))
.then((result) => {
// TO-DO - add user back to cache. For some reason, the saved records lead to badge img loading failure in frontend.
// cache.setCache(`user-${userToBeAssigned}`, JSON.stringify(result));
res.status(201).send(result._id);
})
.catch((err) => {
logger.logException(err);
res.status(500).send('Internal Error: Unable to save the record.');
Expand Down Expand Up @@ -129,7 +148,13 @@ const badgeController = function (Badge) {

badge
.save()
.then(results => res.status(201).send(results))
.then((results) => {
// remove cache after new badge is saved
if (cache.getCache('allBadges')) {
cache.removeCache('allBadges');
}
res.status(201).send(results);
})
.catch(errors => res.status(500).send(errors));
});
};
Expand All @@ -154,11 +179,15 @@ const badgeController = function (Badge) {
const deleteRecord = record.remove();

Promise.all([removeBadgeFromProfile, deleteRecord])
.then(
.then(() => {
// remove cache after new badge is deleted
if (cache.getCache('allBadges')) {
cache.removeCache('allBadges');
}
res.status(200).send({
message: 'Badge successfully deleted and user profiles updated',
}),
)
});
})
.catch((errors) => {
res.status(500).send(errors);
});
Expand Down Expand Up @@ -205,6 +234,10 @@ const badgeController = function (Badge) {
res.status(400).send({ error: 'No valid records found' });
return;
}
// remove cache after new badge is updated
if (cache.getCache('allBadges')) {
cache.removeCache('allBadges');
}
res.status(200).send({ message: 'Badge successfully updated' });
});
};
Expand Down
42 changes: 37 additions & 5 deletions src/controllers/informationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,22 @@ const mongoose = require('mongoose');
// const userProfile = require('../models/userProfile');
// const hasPermission = require('../utilities/permissions');
const escapeRegex = require('../utilities/escapeRegex');

const cache = require('../utilities/nodeCache')();

const informationController = function (Information) {
const getInformations = function (req, res) {
// return all informations if cache is available
if (cache.hasCache('informations')) {
res.status(200).send(cache.getCache('informations'));
return;
}

Information.find({}, 'infoName infoContent visibility')
.then(results => res.status(200).send(results))
.then((results) => {
// cache results
cache.setCache('informations', results);
res.status(200).send(results);
})
.catch(error => res.status(404).send(error));
};

Expand All @@ -24,21 +34,43 @@ const informationController = function (Information) {
_info.infoContent = req.body.infoContent || 'Unspecified';
_info.visibility = req.body.visibility || '0';
_info.save()
.then(newInformation => res.status(201).send(newInformation))
.then((newInformation) => {
// remove cache if cache is available
if (cache.hasCache('informations')) {
cache.removeCache('informations');
return;
}
res.status(201).send(newInformation);
})
.catch(error => res.status(400).send(error));
})
.catch(error => res.status(500).send({ error }));
};

const deleteInformation = function (req, res) {
Information.findOneAndDelete({ _id: req.params.id })
.then(deletedInformation => res.status(200).send(deletedInformation))
.then((deletedInformation) =>{
// remove cache if cache is available
if (cache.hasCache('informations')) {
cache.removeCache('informations');
return;
}
res.status(200).send(deletedInformation);
})
.catch(error => res.status(400).send(error));
};

// Update existing information by id
const updateInformation = function (req, res) {
Information.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true })
.then(updatedInformation => res.status(200).send(updatedInformation))
.then((updatedInformation) => {
// remove cache if cache is available
if (cache.hasCache('informations')) {
cache.removeCache('informations');
return;
}
res.status(200).send(updatedInformation);
})
.catch(error => res.status(400).send(error));
};

Expand Down
123 changes: 71 additions & 52 deletions src/helpers/userHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,16 @@ const userHelper = function () {
infringement,
totalInfringements,
timeRemaining,
requestForTimeOffEmailBody
coreTeamExtraHour,
requestForTimeOffEmailBody,
) {
let finalParagraph = "";

if (timeRemaining === undefined) {
finalParagraph =
"<p>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.</p>";
} else {
finalParagraph =
'Please complete ALL owened time this week to avoid receiving another blue square. If you have any questions about any of this, please see the <a href="https://www.onecommunityglobal.org/policies-and-procedures/">One Community Core Team Policies and Procedures page </a>" ';
finalParagraph = `Please complete ALL owed time this week (${timeRemaining + coreTeamExtraHour} hours) to avoid receiving another blue square. If you have any questions about any of this, please see the <a href="https://www.onecommunityglobal.org/policies-and-procedures/">"One Community Core Team Policies and Procedures"</a> page.`;
}

const text = `Dear <b>${firstName} ${lastName}</b>,
Expand All @@ -116,8 +116,7 @@ const userHelper = function () {
.localeData()
.ordinal(totalInfringements)}</b> blue square of 5.</p>
${finalParagraph}
<p>Thank you,<br />
One Community</p>`;
<p>Thank you, One Community</p>`;

return text;
};
Expand Down Expand Up @@ -476,56 +475,73 @@ const userHelper = function () {
if (foundReason) {
description = foundReason.reason;
} else if (timeNotMet && !hasWeeklySummary) {
if (person.role === "Core Team") {
description = `System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. In the week starting ${pdtStartOfLastWeek.format(
"dddd YYYY-MM-DD"
)} and ending ${pdtEndOfLastWeek.format(
"dddd YYYY-MM-DD"
)}. You logged ${timeSpent.toFixed(
2
)} hours against committed effort of ${
person.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
} hours owend for last week + ${coreTeamExtraHour} hours owend for this being your ${moment
.localeData()
.ordinal(
oldInfringements.length + 1
)} blue square. So you should have completed ${weeklycommittedHours} hours and you only completed ${timeSpent.toFixed(
2
)} hours.`;
if (person.role === 'Core Team') {
description = (
`System auto-assigned infringement for two reasons: not meeting weekly volunteer time commitment as well as not submitting a weekly summary. In the week starting ${
pdtStartOfLastWeek.format('dddd YYYY-MM-DD')
} and ending ${
pdtEndOfLastWeek.format('dddd YYYY-MM-DD')
}, you logged ${
timeSpent.toFixed(2)
} hours against a committed effort of ${
person.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
} hours owed for last week + ${
coreTeamExtraHour
} hours owed for this being your ${
moment.localeData().ordinal(oldInfringements.length + 1)
} blue square. So you should have completed ${
weeklycommittedHours
} hours and you completed ${
timeSpent.toFixed(2)
} hours.`
);
} else {
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")}.`;
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 a 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) {
if (person.role === "Core Team") {
description = `System auto-assigned infringement for not meeting weekly volunteer time commitment. In the week starting ${pdtStartOfLastWeek.format(
"dddd YYYY-MM-DD"
)} and ending ${pdtEndOfLastWeek.format(
"dddd YYYY-MM-DD"
)}. You logged ${timeSpent.toFixed(
2
)} hours against committed effort of ${
user.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
} hours owend for last week + ${coreTeamExtraHour} hours owend for this being your ${moment
.localeData()
.ordinal(
oldInfringements.length + 1
)} blue square. So you should have completed ${weeklycommittedHours} hours and you only completed ${timeSpent.toFixed(
2
)} hours.`;
if (person.role === 'Core Team') {
description = (
`System auto-assigned infringement for not meeting weekly volunteer time commitment. In the week starting ${
pdtStartOfLastWeek.format('dddd YYYY-MM-DD')
} and ending ${
pdtEndOfLastWeek.format('dddd YYYY-MM-DD')
}, you logged ${
timeSpent.toFixed(2)
} hours against a committed effort of ${
user.weeklycommittedHours
} hours + ${
person.missedHours ?? 0
} hours owed for last week + ${
coreTeamExtraHour
} hours owed for this being your ${
moment.localeData().ordinal(oldInfringements.length + 1)
} blue square. So you should have completed ${
weeklycommittedHours
} hours and you completed ${
timeSpent.toFixed(2)
} hours.`);
} else {
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")}.`;
description = (
`System auto-assigned infringement for not meeting weekly volunteer time commitment. You logged ${
timeSpent.toFixed(2)
} hours against a 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(
Expand Down Expand Up @@ -556,14 +572,17 @@ const userHelper = function () {
infringement,
status.infringements.length,
timeRemaining,
requestForTimeOffEmailBody
coreTeamExtraHour,
requestForTimeOffEmailBody,
);
} else {
emailBody = getInfringementEmailBody(
status.firstName,
status.lastName,
infringement,
status.infringements.length,
undefined,
null,
requestForTimeOffEmailBody
);
}
Expand Down
17 changes: 17 additions & 0 deletions src/utilities/exceptionHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const logger = require('../startup/logger');

const exceptionHandler = (err, req, res, next) => {
logger.logException(err);

const errStatus = err.statusCode || 500;
const errMsg = err.message || 'Internal Server Error. Please try again later. If the problem persists, please contact support ID.';
res.status(errStatus).json({
success: false,
status: errStatus,
message: errMsg,
stack: !process.env.NODE_ENV || process.env.NODE_ENV === 'local' ? err.stack : {},
});
next();
};

export default exceptionHandler;

0 comments on commit f0eb025

Please sign in to comment.