Skip to content

Commit

Permalink
Merge pull request #592 from OneCommunityGlobal/Abdel_log_requested_t…
Browse files Browse the repository at this point in the history
…ime_off_for_blue_squares

Abdel log requested time off for blue squares
  • Loading branch information
one-community authored Jan 29, 2024
2 parents 560c57a + 9db11df commit 6ab1216
Show file tree
Hide file tree
Showing 19 changed files with 496 additions and 222 deletions.
7 changes: 3 additions & 4 deletions src/controllers/bmdashboard/bmConsumableController.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,18 @@ const bmConsumableController = function (BuildingConsumable) {
},
])
.exec()
.then(result => {
.then((result) => {
res.status(200).send(result);
})
.catch(error => res.status(500).send(error));
} catch (err) {
res.json(err);
}
};

return {
fetchBMConsumables,
};
};

module.exports = bmConsumableController;

1 change: 0 additions & 1 deletion src/controllers/bmdashboard/bmInventoryTypeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
writeFile(filepath, updatedFileContent, 'utf8', (error) => {
if (error) {
console.error('Error writing to file:', error);
return;
}
});
});
Expand Down
24 changes: 11 additions & 13 deletions src/controllers/permissionChangeLogsController.js
Original file line number Diff line number Diff line change
@@ -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
module.exports = permissionChangeLogController;
81 changes: 40 additions & 41 deletions src/controllers/profileInitialSetupController.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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 });

Expand Down Expand Up @@ -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 });

Expand All @@ -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}`);
Expand All @@ -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 = [
{
Expand All @@ -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 || "[email protected]", // "[email protected]"
process.env.MANAGER_EMAIL || '[email protected]', // "[email protected]"
`NEW USER REGISTERED: ${savedUser.firstName} ${savedUser.lastName}`,
informManagerMessage(savedUser),
null,
null
null,
);
await ProfileInitialSetupToken.findByIdAndDelete(foundToken._id);

Expand All @@ -265,7 +264,7 @@ const profileInitialSetupController = function (
permissions: savedUser.permissions,
expiryTimestamp: moment().add(
config.TOKEN.Lifetime,
config.TOKEN.Units
config.TOKEN.Units,
),
};

Expand Down Expand Up @@ -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}`);
Expand Down Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit 6ab1216

Please sign in to comment.