Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Muhideen_UpdatingBadgesSchema #1220

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
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
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

166 changes: 145 additions & 21 deletions src/controllers/badgeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const UserProfile = require('../models/userProfile');
const helper = require('../utilities/permissions');
const escapeRegex = require('../utilities/escapeRegex');
const cacheClosure = require('../utilities/nodeCache');
// const userHelper = require('../helpers/userHelper')();
const userHelper = require('../helpers/userHelper')();

const badgeController = function (Badge) {
/**
Expand All @@ -13,23 +13,137 @@ const badgeController = function (Badge) {
*/
const cache = cacheClosure();

// const awardBadgesTest = async function (req, res) {
// await userHelper.awardNewBadges();
// res.status(200).send('Badges awarded');
const awardBadgesTest = async function (req, res) {
await userHelper.awardNewBadges();
res.status(200).send('Badges awarded');
};

const updateBadgeUsers = async function (req, res) {
console.log('Assigning Users to Badges');

try {
// First make sure all badges have users array
await Badge.updateMany({ users: { $exists: false } }, { $set: { users: [] } });

// Get all user profiles with badges
const userProfiles = await UserProfile.find({
'badgeCollection.0': { $exists: true },
}).select('_id badgeCollection');

// Filter out any null badge items and validate badge IDs
const updatePromises = userProfiles.map((profile) =>
Promise.all(
profile.badgeCollection
.filter((badgeItem) => badgeItem && badgeItem.badge) // Filter out null items
.map((badgeItem) =>
Badge.findByIdAndUpdate(badgeItem.badge, {
$addToSet: {
users: {
userId: profile._id,
},
},
}).catch((err) =>
console.error(`Error updating badge ${badgeItem.badge}: ${err.message}`),
),
),
),
);

await Promise.all(updatePromises);

// Clear cache
if (cache.hasCache('allBadges')) {
cache.removeCache('allBadges');
}

const totalUpdates = userProfiles.reduce(
(sum, profile) =>
sum + (profile.badgeCollection?.filter((item) => item && item.badge)?.length || 0),
0,
);

res.status(200).send({
message: `Successfully processed ${totalUpdates} badge-user associations`,
processedUsers: userProfiles.length,
});
} catch (error) {
console.error('Full error:', error);
res.status(500).send({
error: 'Error updating badge users',
details: error.message,
});
}
};

const updateBadgesWithUsers = async function (req, res) {
console.log('Updating Badges');

try {
// Find badges that don't have users field
const badgesToUpdate = await Badge.find({
users: { $exists: false },
});

if (badgesToUpdate.length === 0) {
return res.status(200).send({ message: 'No badges need updating' });
}

// Update all matching badges with empty users array
await Badge.updateMany({ users: { $exists: false } }, { $set: { users: [] } });

// Clear cache since badges were updated
if (cache.hasCache('allBadges')) {
cache.removeCache('allBadges');
}

res.status(200).send({
message: `Successfully updated ${badgesToUpdate.length} badges with users array`,
updatedBadges: badgesToUpdate,
});
} catch (error) {
res.status(500).send({
error: 'Error updating badges',
details: error.message,
});
}
};

// const getBadge = async function (req, res) {
// const { badgeId } = req.params;

// try {
// const badge = await Badge.findById(badgeId)
// .populate({
// path: 'project',
// select: '_id projectName',
// })
// .populate({
// path: 'users.userId',
// select: '_id',
// });

// if (!badge) {
// return res.status(404).send({ error: 'Badge not found' });
// }

// res.status(200).send(badge);
// } catch (error) {
// res.status(500).send({ error: error.message });
// }
// };

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

// Check if the user has any of the following permissions
// Check permissions
if (
!(await helper.hasPermission(req.body.requestor, 'seeBadges')) &&
!(await helper.hasPermission(req.body.requestor, 'assignBadges')) &&
!(await helper.hasPermission(req.body.requestor, 'createBadges')) &&
!(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('User not authorized');
res.status(403).send('You are not authorized to view all badge data.');
return;
}
Expand All @@ -42,12 +156,16 @@ const badgeController = function (Badge) {

Badge.find(
{},
'badgeName type multiple weeks months totalHrs people imageUrl category project ranking description showReport',
'badgeName type multiple weeks months totalHrs people imageUrl category project ranking description showReport users',
)
.populate({
path: 'project',
select: '_id projectName',
})
.populate({
path: 'users.userId',
select: '_id username firstName lastName', // Populate firstName and profileName
})
.sort({
ranking: 1,
badgeName: 1,
Expand Down Expand Up @@ -90,7 +208,7 @@ const badgeController = function (Badge) {
let totalNewBadges = 0;
const existingBadges = {};
if (record.badgeCollection && Array.isArray(record.badgeCollection)) {
record.badgeCollection.forEach(badgeItem => {
record.badgeCollection.forEach((badgeItem) => {
existingBadges[badgeItem.badge] = badgeItem.count;
});
}
Expand All @@ -109,7 +227,6 @@ const badgeController = function (Badge) {
return grouped;
}


if (!grouped[badge]) {
// If the badge is not in the grouped object, add a new entry
grouped[badge] = {
Expand Down Expand Up @@ -182,7 +299,7 @@ const badgeController = function (Badge) {

if (result.length > 0) {
res.status(400).send({
error: `Another badge with name ${result[0].badgeName} already exists. Sorry, but badge names should be like snowflakes, no two should be the same. Please choose a different name for this badge so it can be proudly unique.`,
error: `Another badge with name ${result[0].badgeName} already exists...`,
});
return;
}
Expand All @@ -202,9 +319,10 @@ const badgeController = function (Badge) {
badge.ranking = req.body.ranking;
badge.description = req.body.description;
badge.showReport = req.body.showReport;
badge.users = []; // Initialize empty users array

const newBadge = await badge.save();
// remove cache after new badge is saved

if (cache.getCache('allBadges')) {
cache.removeCache('allBadges');
}
Expand Down Expand Up @@ -258,6 +376,11 @@ const badgeController = function (Badge) {
const { badgeId } = req.params;
const imageUrl = null;

if (!req.body || Object.keys(req.body).length <= 1) {
// Call updateBadgesWithUsers if no update data provided
return updateBadgesWithUsers(req, res);
}

// If has req.body.file than upload image and insert that url
// into imageUrl
if (req.body.file) {
Expand Down Expand Up @@ -293,6 +416,7 @@ const badgeController = function (Badge) {
res.status(200).send({ message: 'Badge successfully updated' });
});
};

const getBadgeCount = async function (req, res) {
const userId = mongoose.Types.ObjectId(req.params.userId);

Expand All @@ -305,8 +429,7 @@ const badgeController = function (Badge) {
// Return badge count from user profile
res.status(200).send({ count: record.badgeCount });
});
}

};

const putBadgecount = async function (req, res) {
const userId = mongoose.Types.ObjectId(req.params.userId);
Expand All @@ -320,7 +443,7 @@ const badgeController = function (Badge) {

record
.save()
.then(results => res.status(201).send(results._id))
.then((results) => res.status(201).send(results._id))
.catch((err) => {
res.status(500).send(err);
});
Expand All @@ -339,22 +462,23 @@ const badgeController = function (Badge) {

record.save();
res.status(201).send({ count: record.badgeCount });

});
}

};

return {
// awardBadgesTest,
awardBadgesTest,
// getBadge,
getAllBadges,
assignBadges,
postBadge,
deleteBadge,
putBadge,
getBadgeCount,
putBadgecount,
resetBadgecount
resetBadgecount,
updateBadgesWithUsers,
updateBadgeUsers,
};
};

module.exports = badgeController;
module.exports = badgeController;
22 changes: 11 additions & 11 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -1827,20 +1827,20 @@ const userProfileController = function (UserProfile, Project) {
}
};

const updateUserInformation = async function (req,res){
const updateUserInformation = async function (req, res) {
try {
const data=req.body;
data.map(async (e)=> {
const data = req.body;
data.map(async (e) => {
let result = await UserProfile.findById(e.user_id);
result[e.item]=e.value
let newdata=await result.save()
})
res.status(200).send({ message: 'Update successful'});
result[e.item] = e.value;
let newdata = await result.save();
});
res.status(200).send({ message: 'Update successful' });
} catch (error) {
console.log(error)
return res.status(500)
console.log(error);
return res.status(500);
}
}
};

return {
postUserProfile,
Expand Down Expand Up @@ -1871,7 +1871,7 @@ const userProfileController = function (UserProfile, Project) {
getAllTeamCode,
getAllTeamCodeHelper,
updateUserInformation,
getUserProfileBasicInfo
getUserProfileBasicInfo,
};
};

Expand Down
5 changes: 5 additions & 0 deletions src/cronjobs/userProfileJobs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { CronJob } = require('cron');
const moment = require('moment-timezone');

const userhelper = require('../helpers/userHelper')();
const badgeController = require('../controllers/badgeController');

const userProfileJobs = () => {
const allUserProfileJobs = new CronJob(
Expand All @@ -16,6 +17,10 @@ const userProfileJobs = () => {
await userhelper.emailWeeklySummariesForAllUsers();
await userhelper.deleteBlueSquareAfterYear();
await userhelper.deleteExpiredTokens();

// New badge-related jobs
await badgeController.updateBadgesWithUsers();
await badgeController.updateBadgeUsers();
}
await userhelper.awardNewBadges();
await userhelper.reActivateUser();
Expand Down
Loading