Skip to content

Commit

Permalink
Merge pull request #1142 from OneCommunityGlobal/jatin_toggle_invisib…
Browse files Browse the repository at this point in the history
…ility_permission_self_and_others

Jatin toggle invisibility permission self and others
  • Loading branch information
one-community authored Dec 31, 2024
2 parents 28dd3f4 + 0829701 commit 9fbb125
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 69 deletions.
10 changes: 4 additions & 6 deletions src/controllers/badgeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const badgeController = function (Badge) {
// };

const getAllBadges = async function (req, res) {
console.log(req.body.requestor); // Retain logging from development branch for debugging
// console.log(req.body.requestor); // Retain logging from development branch for debugging

// Check if the user has any of the following permissions
if (
Expand All @@ -29,7 +29,7 @@ const badgeController = function (Badge) {
!(await helper.hasPermission(req.body.requestor, 'updateBadges')) &&
!(await helper.hasPermission(req.body.requestor, 'deleteBadges'))
) {
console.log('in if statement'); // Retain logging from development branch for debugging
// console.log('in if statement'); // Retain logging from development branch for debugging
res.status(403).send('You are not authorized to view all badge data.');
return;
}
Expand Down Expand Up @@ -129,12 +129,10 @@ const badgeController = function (Badge) {
const combinedEarnedDate = [...grouped[badge].earnedDate, ...item.earnedDate];
const timestampArray = combinedEarnedDate.map((date) => new Date(date).getTime());
timestampArray.sort((a, b) => a - b);
grouped[badge].earnedDate = timestampArray.map((timestamp) =>
new Date(timestamp)
grouped[badge].earnedDate = timestampArray.map((timestamp) => new Date(timestamp)
.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' })
.replace(/ /g, '-')
.replace(',', ''),
);
.replace(',', ''));
}
}
if (existingBadges[badge]) {
Expand Down
75 changes: 46 additions & 29 deletions src/controllers/bmdashboard/bmConsumableController.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ const bmConsumableController = function (BuildingConsumable) {

const bmPostConsumableUpdateRecord = function (req, res) {
const {
quantityUsed, quantityWasted, qtyUsedLogUnit, qtyWastedLogUnit, stockAvailable, consumable,
quantityUsed,
quantityWasted,
qtyUsedLogUnit,
qtyWastedLogUnit,
stockAvailable,
consumable,
} = req.body;
let unitsUsed = quantityUsed;
let unitsWasted = quantityWasted;
Expand All @@ -91,50 +96,62 @@ const bmConsumableController = function (BuildingConsumable) {
if (quantityWasted >= 0 && qtyWastedLogUnit === 'percent') {
unitsWasted = (stockAvailable / 100) * quantityWasted;
}
if (unitsUsed > stockAvailable || unitsWasted > stockAvailable || (unitsUsed + unitsWasted) > stockAvailable) {
return res.status(500).send({ message: 'Please check the used and wasted stock values. Either individual values or their sum exceeds the total stock available.' });
} if (unitsUsed < 0 || unitsWasted < 0) {
return res.status(500).send({ message: 'Please check the used and wasted stock values. Negative numbers are invalid.' });
if (
unitsUsed > stockAvailable ||
unitsWasted > stockAvailable ||
unitsUsed + unitsWasted > stockAvailable
) {
return res
.status(500)
.send({
message:
'Please check the used and wasted stock values. Either individual values or their sum exceeds the total stock available.',
});
}
if (unitsUsed < 0 || unitsWasted < 0) {
return res
.status(500)
.send({
message: 'Please check the used and wasted stock values. Negative numbers are invalid.',
});
}

const newStockUsed = parseFloat((consumable.stockUsed + unitsUsed).toFixed(4));
const newStockWasted = parseFloat((consumable.stockWasted + unitsWasted).toFixed(4));
const newAvailable = parseFloat((stockAvailable - (unitsUsed + unitsWasted)).toFixed(4));

const newStockUsed = parseFloat((consumable.stockUsed + unitsUsed).toFixed(4));
const newStockWasted = parseFloat((consumable.stockWasted + unitsWasted).toFixed(4));
const newAvailable = parseFloat((stockAvailable - (unitsUsed + unitsWasted)).toFixed(4));

BuildingConsumable.updateOne(
{ _id: consumable._id },
{
$set: {
stockUsed: newStockUsed,
stockWasted: newStockWasted,
stockAvailable: newAvailable,
},
$push: {
updateRecord: {
date: req.body.date,
createdBy: req.body.requestor.requestorId,
quantityUsed: unitsUsed,
quantityWasted: unitsWasted,
},
BuildingConsumable.updateOne(
{ _id: consumable._id },
{
$set: {
stockUsed: newStockUsed,
stockWasted: newStockWasted,
stockAvailable: newAvailable,
},
$push: {
updateRecord: {
date: req.body.date,
createdBy: req.body.requestor.requestorId,
quantityUsed: unitsUsed,
quantityWasted: unitsWasted,
},

},
)
},
)
.then((results) => {
res.status(200).send(results);
})
.catch((error) => {
console.log('error: ', error);
res.status(500).send({ message: error });
});
};
};

return {
fetchBMConsumables,
bmPurchaseConsumables,
bmPostConsumableUpdateRecord
bmPostConsumableUpdateRecord,
};
};

module.exports = bmConsumableController;
module.exports = bmConsumableController;
48 changes: 22 additions & 26 deletions src/controllers/bmdashboard/bmInventoryTypeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,39 +32,36 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
}

const fetchToolTypes = async (req, res) => {

try {
ToolType
.find()
ToolType.find()
.populate([
{
path: 'available',
select: '_id code project',
populate: {
path: 'project',
select: '_id name'
}
},
{
path: 'using',
select: '_id code project',
populate: {
path: 'project',
select: '_id name'
}
}
{
path: 'available',
select: '_id code project',
populate: {
path: 'project',
select: '_id name',
},
},
{
path: 'using',
select: '_id code project',
populate: {
path: 'project',
select: '_id name',
},
},
])
.exec()
.then(result => {
.then((result) => {
res.status(200).send(result);
})
.catch(error => {
console.error("fetchToolTypes error: ", error);
.catch((error) => {
console.error('fetchToolTypes error: ', error);
res.status(500).send(error);
});

} catch (err) {
console.log("error: ", err)
console.log('error: ', err);
res.json(err);
}
};
Expand Down Expand Up @@ -269,7 +266,6 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
}
}


async function fetchInventoryByType(req, res) {
const { type } = req.params;
let SelectedType = InvType;
Expand Down Expand Up @@ -409,4 +405,4 @@ function bmInventoryTypeController(InvType, MatType, ConsType, ReusType, ToolTyp
};
}

module.exports = bmInventoryTypeController;
module.exports = bmInventoryTypeController;
2 changes: 1 addition & 1 deletion src/controllers/reasonSchedulingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,4 @@ module.exports = {
getSingleReason,
patchReason,
deleteReason,
};
};
2 changes: 0 additions & 2 deletions src/controllers/teamController.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,6 @@ const teamcontroller = function (Team) {
});
};
const updateTeamVisibility = async (req, res) => {
console.log('==============> 9 ');

const { visibility, teamId, userId } = req.body;

try {
Expand Down
42 changes: 39 additions & 3 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,6 @@ const userProfileController = function (UserProfile, Project) {
let originalRecord = {};
if (PROTECTED_EMAIL_ACCOUNT.includes(record.email)) {
originalRecord = objectUtils.deepCopyMongooseObjectWithLodash(record);
// console.log('originalRecord', originalRecord);
}
// validate userprofile pic

Expand Down Expand Up @@ -1577,6 +1576,43 @@ const userProfileController = function (UserProfile, Project) {
}
};

const toggleInvisibility = async function (req, res) {
const { userId } = req.params;
const { isVisible } = req.body;

if (!mongoose.Types.ObjectId.isValid(userId)) {
res.status(400).send({
error: 'Bad Request',
});
return;
}
if (!(await hasPermission(req.body.requestor, 'toggleInvisibility'))) {
res.status(403).send('You are not authorized to change user visibility');
return;
}

cache.removeCache(`user-${userId}`);
UserProfile.findByIdAndUpdate(userId, { $set: { isVisible } }, (err, _) => {
if (err) {
return res.status(500).send(`Could not Find user with id ${userId}`);
}
// Check if there's a cache for all users and update it accordingly
const isUserInCache = cache.hasCache('allusers');
if (isUserInCache) {
const allUserData = JSON.parse(cache.getCache('allusers'));
const userIdx = allUserData.findIndex((users) => users._id === userId);
const userData = allUserData[userIdx];
userData.isVisible = isVisible;
allUserData.splice(userIdx, 1, userData);
cache.setCache('allusers', JSON.stringify(allUserData));
}

return res.status(200).send({
message: 'User visibility updated successfully',
isVisible,
});
})}

const addInfringements = async function (req, res) {
if (!(await hasPermission(req.body.requestor, 'addInfringements'))) {
res.status(403).send('You are not authorized to add blue square');
Expand Down Expand Up @@ -1690,7 +1726,6 @@ const userProfileController = function (UserProfile, Project) {
return;
}
const { userId, blueSquareId } = req.params;
// console.log(userId, blueSquareId);

UserProfile.findById(userId, async (err, record) => {
if (err || !record) {
Expand Down Expand Up @@ -1853,7 +1888,7 @@ const userProfileController = function (UserProfile, Project) {
console.log(error)
return res.status(500)
}
}
};

return {
postUserProfile,
Expand All @@ -1877,6 +1912,7 @@ const userProfileController = function (UserProfile, Project) {
getUserByFullName,
changeUserRehireableStatus,
authorizeUser,
toggleInvisibility,
addInfringements,
editInfringements,
deleteInfringements,
Expand Down
4 changes: 4 additions & 0 deletions src/routes/userProfileRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ const routes = function (userProfile, project) {
.route('/userProfile/:userId/rehireable')
.patch(controller.changeUserRehireableStatus);

userProfileRouter
.route('/userProfile/:userId/toggleInvisibility')
.patch(controller.toggleInvisibility);

userProfileRouter
.route('/userProfile/singleName/:singleName')
.get(controller.getUserBySingleName);
Expand Down
5 changes: 3 additions & 2 deletions src/utilities/createInitialPermissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const permissionsRoles = [
'changeUserRehireableStatus',
'updatePassword',
'deleteUserProfile',
'toggleInvisibility',
'addInfringements',
'editInfringements',
'deleteInfringements',
Expand Down Expand Up @@ -256,9 +257,9 @@ const permissionsRoles = [
'seeUsersInDashboard',

'changeUserRehireableStatus',

'toggleInvisibility',
'manageAdminLinks',
'removeUserFromTask',

'editHeaderMessage',
],
},
Expand Down

0 comments on commit 9fbb125

Please sign in to comment.