Skip to content

Commit

Permalink
Merge pull request #607 from OneCommunityGlobal/development
Browse files Browse the repository at this point in the history
Backend Release to Main [1.17]
  • Loading branch information
one-community authored Nov 11, 2023
2 parents d45e601 + e9f78f3 commit faf0cce
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 26 deletions.
3 changes: 3 additions & 0 deletions src/controllers/badgeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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 badgeController = function (Badge) {
const getAllBadges = async function (req, res) {
Expand Down Expand Up @@ -47,6 +48,8 @@ const badgeController = function (Badge) {
if (result) {
record.badgeCollection = req.body.badgeCollection;

if (cache.hasCache(`user-${userToBeAssigned}`)) cache.removeCache(`user-${userToBeAssigned}`);

record.save()
.then(results => res.status(201).send(results._id))
.catch(errors => res.status(500).send(errors));
Expand Down
24 changes: 12 additions & 12 deletions src/controllers/bmdashboard/bmMaterialsController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const mongoose = require('mongoose')
const mongoose = require('mongoose');

const bmMaterialsController = function (ItemMaterial) {
const bmMaterialsList = async function _matsList(req, res) {
Expand All @@ -7,42 +7,42 @@ const bmMaterialsController = function (ItemMaterial) {
.populate([
{
path: 'project',
select: '_id projectName'
select: '_id projectName',
},
{
path: 'inventoryItemType',
select: '_id name uom totalStock totalAvailable'
select: '_id name uom totalStock totalAvailable',
},
{
path: 'usageRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName'
}
select: '_id firstName lastName',
},
},
{
path: 'updateRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName'
}
select: '_id firstName lastName',
},
},
{
path: 'purchaseRecord',
populate: {
path: 'createdBy',
select: '_id firstName lastName'
}
}
select: '_id firstName lastName',
},
},
])
.exec()
.then(results => res.status(200).send(results))
.catch(error => res.status(500).send(error))
.catch(error => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};
return { bmMaterialsList };
};

module.exports = bmMaterialsController;
module.exports = bmMaterialsController;
79 changes: 79 additions & 0 deletions src/controllers/bmdashboard/bmProjectController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// TODO: uncomment when executing auth checks
// const jwt = require('jsonwebtoken');
// const config = require('../../config');

const bmMProjectController = function (BuildingProject) {
// TODO: uncomment when executing auth checks
// const { JWT_SECRET } = config;

const fetchAllProjects = async (req, res) => {
//! Note: for easier testing this route currently returns all projects from the db
// TODO: uncomment the lines below to return only projects where field buildingManager === userid
// const token = req.headers.authorization;
// const { userid } = jwt.verify(token, JWT_SECRET);
try {
const projectData = await BuildingProject
// TODO: uncomment this line to filter by buildingManager field
// .find({ buildingManager: userid })
.find()
.populate([
{
path: 'buildingManager',
select: '_id firstName lastName email',
},
{
path: 'team',
select: '_id firstName lastName email',
},
])
.exec()
.then(result => result)
.catch(error => res.status(500).send(error));
res.status(200).send(projectData);
} catch (err) {
res.json(err);
}
};

// fetches single project by project id
const fetchSingleProject = async (req, res) => {
//! Note: for easier testing this route currently returns the project without an auth check
// TODO: uncomment the lines below to check the user's ability to view the current project
// const token = req.headers.authorization;
// const { userid } = jwt.verify(token, JWT_SECRET);
const { projectId } = req.params;
try {
BuildingProject
.findById(projectId)
.populate([
{
path: 'buildingManager',
select: '_id firstName lastName email',
},
{
path: 'team',
select: '_id firstName lastName email',
},
])
.exec()
.then(project => res.status(200).send(project))
// TODO: uncomment this block to execute the auth check
// authenticate request by comparing userId param with buildingManager id field
// Note: _id has type object and must be converted to string
// .then((project) => {
// if (userid !== project.buildingManager._id.toString()) {
// return res.status(403).send({
// message: 'You are not authorized to view this record.',
// });
// }
// return res.status(200).send(project);
// })
.catch(error => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};
return { fetchAllProjects, fetchSingleProject };
};

module.exports = bmMProjectController;
45 changes: 37 additions & 8 deletions src/helpers/userHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,29 @@ const userHelper = function () {
firstName,
lastName,
infringement,
totalInfringements
totalInfringements,
timeRemaining
) {
let final_paragraph = '';

if (timeRemaining == undefined) {
final_paragraph = '<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 {
final_paragraph = `<p>Life happens and we understand that. Please make up the missed hours this following week though to avoid getting another blue square. So you know what’s needed, the missing/incomplete hours (${timeRemaining} hours) have been added to your current week and this new weekly total can be seen at the top of your dashboard.</p>
<p>Reminder also that each blue square is removed from your profile 1 year after it was issued.</p>`;
}

const text = `Dear <b>${firstName} ${lastName}</b>,
<p>Oops, it looks like something happened and you’ve managed to get a blue square.</p>
<p><b>Date Assigned:</b> ${infringement.date}</p>
<p><b>Description:</b> ${infringement.description}</p>
<p><b>Total Infringements:</b> This is your <b>${moment
.localeData()
.ordinal(totalInfringements)}</b> blue square of 5.</p>
<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>
${final_paragraph}
<p>Thank you,<br />
One Community</p>`;

return text;
};

Expand Down Expand Up @@ -322,6 +333,8 @@ const userHelper = function () {
for (let i = 0; i < users.length; i += 1) {
const user = users[i];

const person = await userProfile.findById(user._id);

const foundReason = await Reason.findOne({
date: currentUTCDate,
userId: user._id,
Expand Down Expand Up @@ -356,6 +369,9 @@ const userHelper = function () {
const timeNotMet = timeSpent < weeklycommittedHours;
let description;

const timeRemaining = weeklycommittedHours - timeSpent;


const updateResult = await userProfile.findByIdAndUpdate(
personId,
{
Expand Down Expand Up @@ -446,15 +462,28 @@ const userHelper = function () {
{ new: true }
);

emailSender(
status.email,
"New Infringement Assigned",
getInfringementEmailBody(
let emailBody = '';
if (person.role == 'Core Team' && timeRemaining > 0) {
emailBody = getInfringementEmailBody(
status.firstName,
status.lastName,
infringement,
status.infringements.length
),
status.infringements.length,
timeRemaining,
);
} else {
emailBody = getInfringementEmailBody(
status.firstName,
status.lastName,
infringement,
status.infringements.length,
);
}

emailSender(
status.email,
'New Infringement Assigned',
emailBody,
null,
"[email protected]"
);
Expand Down
15 changes: 15 additions & 0 deletions src/models/bmdashboard/buildingProject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose = require('mongoose');

const { Schema } = mongoose;

const buildingProject = new Schema({
isActive: Boolean,
name: String,
template: String, // construction template (ie Earthbag Village)
location: String, // use lat/lng instead?
dateCreated: { type: Date, default: Date.now },
buildingManager: { type: mongoose.SchemaTypes.ObjectId, ref: 'userProfile' }, // BM's id
team: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'userProfile' }],
});

module.exports = mongoose.model('buildingProject', buildingProject, 'buildingProjects');
6 changes: 3 additions & 3 deletions src/models/inventoryItemMaterial.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ const InventoryItemMaterial = new Schema({
poId: { type: String, required: true },
sellerId: { type: String, required: true },
quantity: { type: Number, required: true }, // adds to stockBought
unitPrice: {type: Number, required: true},
unitPrice: { type: Number, required: true },
currency: { type: String, required: true },
subtotal: { type: Number, required: true },
tax: { type: Number, required: true },
shipping: { type: Number, required: true },
}]
})
}],
});

module.exports = mongoose.model('inventoryItemMaterial', InventoryItemMaterial, 'inventoryMaterial');
4 changes: 2 additions & 2 deletions src/routes/bmdashboard/bmMaterialsRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ materialsRouter.route('/materials')
.get(controller.bmMaterialsList);

return materialsRouter;
}
};

module.exports = routes;
module.exports = routes;
16 changes: 16 additions & 0 deletions src/routes/bmdashboard/bmProjectRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const express = require('express');

const routes = function (buildingProject) {
const projectRouter = express.Router();
const controller = require('../../controllers/bmdashboard/bmProjectController')(buildingProject);

projectRouter.route('/projects')
.get(controller.fetchAllProjects);

projectRouter.route('/project/:projectId')
.get(controller.fetchSingleProject);

return projectRouter;
};

module.exports = routes;
4 changes: 4 additions & 0 deletions src/startup/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const profileInitialSetuptoken = require('../models/profileInitialSetupToken');
const reason = require('../models/reason');
const mouseoverText = require('../models/mouseoverText');
const inventoryItemMaterial = require('../models/inventoryItemMaterial');
const buildingProject = require('../models/bmdashboard/buildingProject');


const userProfileRouter = require('../routes/userProfileRouter')(userProfile);
const badgeRouter = require('../routes/badgeRouter')(badge);
Expand Down Expand Up @@ -59,6 +61,7 @@ const mouseoverTextRouter = require('../routes/mouseoverTextRouter')(mouseoverTe
// bm dashboard
const bmLoginRouter = require('../routes/bmdashboard/bmLoginRouter')();
const bmMaterialsRouter = require('../routes/bmdashboard/bmMaterialsRouter')(inventoryItemMaterial);
const bmProjectRouter = require('../routes/bmdashboard/bmProjectRouter')(buildingProject);

module.exports = function (app) {
app.use('/api', forgotPwdRouter);
Expand Down Expand Up @@ -93,4 +96,5 @@ module.exports = function (app) {
// bm dashboard
app.use('/api/bm', bmLoginRouter);
app.use('/api/bm', bmMaterialsRouter);
app.use('/api/bm', bmProjectRouter);
};
2 changes: 1 addition & 1 deletion src/utilities/escapeRegex.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

const escapeRegex = function (text) {
return text.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
return `^${text.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&')}&`;
};

module.exports = escapeRegex;

0 comments on commit faf0cce

Please sign in to comment.