Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 82 additions & 4 deletions src/controllers/currentWarningsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,52 @@
const mongoose = require('mongoose');
const userProfile = require('../models/userProfile');
const helper = require('../utilities/permissions');
const { setOutdatedWarningsFlag } = require('../utilities/warningsCache');
const currentWarningsController = function (currentWarnings) {
const normalizeWarningTitle = (warningTitle /*: string */) => warningTitle.toLowerCase().trim();

const checkIfSpecialCharacter = (warning) => {
return !/^[a-zA-Z][a-zA-Z0-9,+-]*(?: [a-zA-Z0-9,+-]+)*$/.test(warning);
};

const addMissingOrderValues = async (warnings) => {
const updates = [];
warnings.forEach((warning, index) => {
if (warning.order === null || warning.order === undefined || warning.order === -1) {
updates.push({
updateOne: {
filter: { _id: warning._id },
update: { $set: { order: index } },
},
});
}
});

if (updates.length > 0) {
await currentWarnings.bulkWrite(updates);
}
// only updates warnings missing an order value
return warnings.map((warning, index) => ({
...warning,
order: warning.order ?? index,
}));
};

const getCurrentWarnings = async (req, res) => {
try {
const response = await currentWarnings.find({});
const response = await currentWarnings.find({}).sort({ order: 1 });

const missingOrder = response.some(
(warning) => warning.order === null || warning.order === undefined || warning.order === -1,
);

const updatedWarnings = missingOrder ? await addMissingOrderValues(response) : response;
if (response.length === 0) {
return res.status(400).send({ message: 'No records', response: response });
}
return res.status(200).send({ currentWarningDescriptions: response });
return res.status(200).send({ currentWarningDescriptions: updatedWarnings });
} catch (error) {
console.log('Entered error of fetch warnings');
res.status(401).send({ message: error.message || error });
}
};
Expand Down Expand Up @@ -55,6 +85,7 @@ const currentWarningsController = function (currentWarnings) {
isPermanent,
}).save();

setOutdatedWarningsFlag();
const updatedWarnings = await currentWarnings.find({});
return res.status(201).send({ newWarnings: updatedWarnings });
} catch (error) {
Expand All @@ -63,6 +94,14 @@ const currentWarningsController = function (currentWarnings) {
};

const editWarningDescription = async (req, res) => {
if (
!(await helper.hasPermission(req.body.requestor, 'addWarningTracker')) &&
!(await helper.hasPermission(req.body.requestor, 'deleteWarningTracker'))
) {
res.status(403).send('You are not authorized to edit a WarningTracker.');
return;
}

try {
const { editedWarning } = req.body;
const normalizedWarningTitle = normalizeWarningTitle(editedWarning.warningTitle);
Expand Down Expand Up @@ -91,11 +130,49 @@ const currentWarningsController = function (currentWarnings) {
warning.warningTitle = trimmedWarning;

await warning.save();
setOutdatedWarningsFlag();
res.status(201).send({ message: 'warning description was updated' });
} catch (error) {
res.status(401).send({ message: error.message || error });
}
};

const reorderWarningDescriptions = async (req, res) => {
if (
!(await helper.hasPermission(req.body.requestor, 'addWarningTracker')) &&
!(await helper.hasPermission(req.body.requestor, 'deleteWarningTracker'))
) {
res.status(403).send('You are not authorized to edit the order of the WarningTrackers.');
return;
}
try {
const reorderedWarningDescriptions = req.body.warningDescriptions;
const response = await currentWarnings.find({}).sort({ order: 1 });

reorderedWarningDescriptions.map((warning, index) => (warning.order = index));
await currentWarnings.bulkWrite(
response.map((warning, index) => ({
updateOne: {
filter: { _id: warning._id },
update: {
$set: {
order: reorderedWarningDescriptions.findIndex(
(warn) => warn.warningTitle === warning.warningTitle,
),
},
},
},
})),
);

setOutdatedWarningsFlag();
res.status(201).send({
reorderedWarningDescriptions: reorderedWarningDescriptions,
});
} catch (error) {
res.status(401).send({ message: error.message || error });
}
};
const updateWarningDescription = async (req, res) => {
if (
!(await helper.hasPermission(req.body.requestor, 'reactivateWarningTracker')) &&
Expand All @@ -116,7 +193,7 @@ const currentWarningsController = function (currentWarnings) {
[{ $set: { activeWarning: { $not: '$activeWarning' } } }],
{ new: true },
);

setOutdatedWarningsFlag();
res.status(201).send({ message: 'warning description was updated' });
} catch (error) {
res.status(401).send({ message: error.message || error });
Expand Down Expand Up @@ -148,7 +225,7 @@ const currentWarningsController = function (currentWarnings) {
},
},
);

setOutdatedWarningsFlag();
return res.status(200);
} catch (error) {
res.status(401).send({ message: error.message || error });
Expand All @@ -161,6 +238,7 @@ const currentWarningsController = function (currentWarnings) {
updateWarningDescription,
deleteWarningDescription,
editWarningDescription,
reorderWarningDescriptions,
};
};
module.exports = currentWarningsController;
105 changes: 92 additions & 13 deletions src/controllers/warningsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,27 @@ const currentWarnings = require('../models/currentWarnings');
const emailSender = require('../utilities/emailSender');
const userHelper = require('../helpers/userHelper')();
const BlueSquareEmailAssignment = require('../models/BlueSquareEmailAssignment');
const {
clearOutdatedWarningsFlag,
areWarningsInfoOutdated,
} = require('../utilities/warningsCache');

let currentWarningDescriptions = null;
async function getWarningDescriptions() {
currentWarningDescriptions = await currentWarnings.find(
{ activeWarning: true },
{ warningTitle: 1, _id: 0, abbreviation: 1 },
);
currentWarningDescriptions = await currentWarnings
.find({ activeWarning: true }, { warningTitle: 1, _id: 1, abbreviation: 1, order: 1 })
.sort({ order: 1 });
clearOutdatedWarningsFlag();
}

const checkWarningDescriptions = async () => {
const warningsOutdated = areWarningsInfoOutdated();
if (!currentWarningDescriptions || warningsOutdated) {
await getWarningDescriptions();
}
return warningsOutdated;
};

const convertObjectToArray = (obj) => {
const arr = [];
for (const key of obj) {
Expand Down Expand Up @@ -173,6 +185,31 @@ const sortByColorAndDate = (a, b) => {
return colorComparison;
};

const checkIfWarningDescriptionMatchesWarningTrackerTitle = (warnings) => {
for (const { warningTitle, _id } of currentWarningDescriptions) {
warnings = warnings.map((warning) => {
// If warning has a warningId but description of warning does not match tracker's title, then the warning description is updated
if (_id.toString() === warning?.warningId && warningTitle !== warning?.description) {
return { ...warning, description: warningTitle };
}
return warning;
});
}
return warnings;
};

const updateWarningsMissingTrackerId = (warnings) => {
for (const { warningTitle, _id } of currentWarningDescriptions) {
warnings = warnings.map((warning) => {
if (!warning?.warningId && warningTitle === warning?.description) {
return { ...warning, warningId: _id };
}
return warning;
});
}
return warnings;
};

const filterWarnings = (
warningDescriptions,
warnings,
Expand Down Expand Up @@ -238,34 +275,71 @@ const filterWarnings = (
});

const completedData = [];

for (const { warningTitle, abbreviation } of warningDescriptions) {
for (const { warningTitle, abbreviation, order } of warningDescriptions) {
completedData.push({
title: warningTitle,
warnings: warns[warningTitle] ? warns[warningTitle] : [],
abbreviation: abbreviation || null,
order,
});
}

return { completedData, sendEmail, size };
};

const updateAllWarnings = async (userId) => {
await checkWarningDescriptions();
try {
let userWarningList = [];
const users = await userProfile
.find({ isActive: true, firstName: 'Anthony' }, '_id warnings firstName lastName')
.lean();

if (!users) {
return { msg: 'No user records retrieved from database' };
}

await Promise.all(
users.map(async (user) => {
const updatedUserWarnings = await checkIfWarningDescriptionMatchesWarningTrackerTitle(
user.warnings,
);
const userWarnings = await updateWarningsMissingTrackerId(updatedUserWarnings);
await userProfile.findByIdAndUpdate(
user._id,
{ $set: { warnings: userWarnings } },
{ new: true },
);
if (userId === user._id.toString()) {
userWarningList = userWarnings;
}
}),
);
return userWarningList;
} catch (error) {
return { error };
}
};

const warningsController = function (UserProfile) {
const getWarningsByUserId = async function (req, res) {
if (!currentWarningDescriptions) {
await getWarningDescriptions();
}
const warningsOutdated = await checkWarningDescriptions();

const { userId } = req.params;

try {
const record = await UserProfile.findById(userId);
const record = await UserProfile.findById(userId).lean();

if (!record || !record.warnings) {
return res.status(400).send({ message: 'no valiud records' });
}

const { completedData } = filterWarnings(currentWarningDescriptions, record.warnings);
let warningsList = record.warnings;
if (warningsOutdated) {
warningsList = await updateAllWarnings(userId);
}

const { completedData } = filterWarnings(currentWarningDescriptions, warningsList);
return res.status(201).send({ warnings: completedData });
} catch (error) {
return res.status(401).send({ message: error.message || error });
Expand Down Expand Up @@ -314,7 +388,12 @@ const warningsController = function (UserProfile) {
const { userId } = req.params;
const { warningsArray, issueBlueSquare, monitorData, iconId, color, date, description } =
req.body;

let warningId = '';
for (const { warningTitle, _id } of currentWarningDescriptions) {
if (warningTitle === description) {
warningId = _id;
}
}
const record = await UserProfile.findById(userId);

if (!record || !record.warnings) {
Expand All @@ -338,7 +417,7 @@ const warningsController = function (UserProfile) {

const updateData = warningsArray
? { $push: { warnings: { $each: warningsArray } } }
: { $push: { warnings: { userId, iconId, color, date, description } } };
: { $push: { warnings: { userId, iconId, color, date, description, warningId } } };

const updatedWarnings = await UserProfile.findByIdAndUpdate({ _id: userId }, updateData, {
new: true,
Expand Down
1 change: 1 addition & 0 deletions src/models/currentWarnings.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const currentWarnings = new Schema({
isPermanent: { type: Boolean, required: true },
isSpecial: { type: Boolean },
abbreviation: { type: String },
order: { type: Number },
});

module.exports = mongoose.model('currentWarning', currentWarnings, 'currentWarnings');
1 change: 1 addition & 0 deletions src/models/userProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ const userProfileSchema = new Schema({
default: 'white',
},
iconId: { type: String, required: false },
warningId: { type: String, default: null },
},
],
location: {
Expand Down
3 changes: 2 additions & 1 deletion src/routes/curentWarningsRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const route = function (currentWarnings) {
currentWarningsRouter
.route('/currentWarnings')
.get(controller.getCurrentWarnings)
.post(controller.postNewWarningDescription);
.post(controller.postNewWarningDescription)
.put(controller.reorderWarningDescriptions);

currentWarningsRouter.route('/currentWarnings/edit').put(controller.editWarningDescription);

Expand Down
17 changes: 17 additions & 0 deletions src/utilities/warningsCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
let outdated = false;

const setOutdatedWarningsFlag = () => {
outdated = true;
};

const clearOutdatedWarningsFlag = () => {
outdated = false;
};

const areWarningsInfoOutdated = () => outdated;

module.exports = {
setOutdatedWarningsFlag,
clearOutdatedWarningsFlag,
areWarningsInfoOutdated,
};
Loading