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

Nikita fix badge categories count and assignment issues - backend #1153

Open
wants to merge 3 commits 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
1 change: 1 addition & 0 deletions src/cronjobs/userProfileJobs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const moment = require('moment-timezone');
const userhelper = require('../helpers/userHelper')();

const userProfileJobs = () => {
console.log('User Profile Jobs Started');
const allUserProfileJobs = new CronJob(
// '* * * * *', // Comment out for testing. Run Every minute.
'1 0 * * 0', // Every Sunday, 1 minute past midnight.
Expand Down
163 changes: 83 additions & 80 deletions src/helpers/userHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -1919,95 +1919,98 @@ const userHelper = function () {
});
};

// 'Total Hrs in Category'
const removeBadge = async function (personId, badgeId) {
userProfile.updateOne(
{ _id: personId },
{
$pull: {
badgeCollection: { badge: badgeId },
},
},
(err) => {
if (err) {
throw new Error(err);
}
},
);
};

const addBadgeCategory = async function (personId, newBadge, badgeCollection) {
// console.log('adding new badge category --- ', newBadge.category);
// remove all badges of Type 'Total Hrs in Category' and category from the user
for (let i = 0; i < badgeCollection.length; i += 1) {
if (
badgeCollection[i].type === 'Total Hrs in Category' &&
badgeCollection[i].category === newBadge.category
) {
removeBadge(personId, badgeCollection[i]._id);
// console.log(
// `Badge removed category ${badgeCollection[i].category} and totalHrs ${badgeCollection[i].totalHrs}`,
// );
}
}

// add the new badge
addBadge(personId, newBadge._id);
};

const checkTotalHrsInCat = async function (personId, user, badgeCollection) {
console.log('Category Badge');
const hoursByCategory = user.hoursByCategory || {};
// categories in badges are capitalized
// categories in user.hoursByCategory are not capitalized
const categories = [
'food',
'energy',
'housing',
'education',
'society',
'economics',
'stewardship',
'Food',
'Energy',
'Housing',
'Education',
'Society',
'Economics',
'Stewardship',
];

const badgesOfType = badgeCollection
.filter((object) => object.badge.type === 'Total Hrs in Category')
.map((object) => object.badge);

categories.forEach(async (category) => {
const categoryHrs = Object.keys(hoursByCategory).find((elem) => elem === category);

let badgeOfType;
for (let i = 0; i < badgeCollection.length; i += 1) {
if (
badgeCollection[i].badge?.type === 'Total Hrs in Category' &&
badgeCollection[i].badge?.category === category
) {
if (badgeOfType && badgeOfType.totalHrs <= badgeCollection[i].badge.totalHrs) {
removeDupBadge(personId, badgeOfType._id);
badgeOfType = badgeCollection[i].badge;
} else if (badgeOfType && badgeOfType.totalHrs > badgeCollection[i].badge.totalHrs) {
removeDupBadge(personId, badgeCollection[i].badge._id);
} else if (!badgeOfType) {
badgeOfType = badgeCollection[i].badge;
}
}
}

const newCatg = category.charAt(0).toUpperCase() + category.slice(1);
const categoryHrsKey = Object.keys(hoursByCategory).find(
(elem) => elem === category.toLowerCase(),
);

// all badges of type 'Total Hrs in Category' in descending order of totalHrs
await badge
.find({ type: 'Total Hrs in Category', category: newCatg })

.find({ type: 'Total Hrs in Category', category })
.sort({ totalHrs: -1 })
.then((results) => {
if (!Array.isArray(results) || !results.length || !categoryHrs) {
return;
}
// loop results to check if user has earned the badge

results.every((elem) => {
if (
hoursByCategory[categoryHrs] >= 100 &&
hoursByCategory[categoryHrs] >= elem.totalHrs
) {
let theBadge;
for (let i = 0; i < badgesOfType.length; i += 1) {
if (badgesOfType[i]._id.toString() === elem._id.toString()) {
theBadge = badgesOfType[i]._id;
break;
}
}
if (theBadge) {
increaseBadgeCount(personId, mongoose.Types.ObjectId(theBadge));
return false;
}
if (badgeOfType) {
if (
badgeOfType._id.toString() !== elem._id.toString() &&
badgeOfType.totalHrs < elem.totalHrs
) {
replaceBadge(
personId,
mongoose.Types.ObjectId(badgeOfType._id),
mongoose.Types.ObjectId(elem._id),
);
}
return false;
for (let i = 0; i < results.length; i += 1) {
const badge = results[i];

if (hoursByCategory[categoryHrsKey] >= badge.totalHrs) {
// if condition -- criteria met
const badgeIndex = badgesOfType.findIndex(
(badgeItem) => badgeItem._id.toString() === badge._id.toString(),
);
// user has not earned this badge
if (badgeIndex === -1) {
addBadgeCategory(personId, badge, badgesOfType);
}
addBadge(personId, mongoose.Types.ObjectId(elem._id));
return false;
break;
}
return true;
});
}
});
});
};

const awardNewBadges = async () => {
try {
const users = await userProfile.find({ isActive: true }).populate('badgeCollection.badge');
// for testing do 1 user with id = x
// const users = await userProfile
// .find({ _id: 'x' })
// .populate('badgeCollection.badge');
for (let i = 0; i < users.length; i += 1) {
const user = users[i];
const { _id, badgeCollection } = user;
Expand Down Expand Up @@ -2066,10 +2069,10 @@ const userHelper = function () {
sendThreeWeeks,
followup,
) {
let subject;
let emailBody;
recipients.push('[email protected]');
recipients = recipients.toString();
let subject;
let emailBody;
recipients.push('[email protected]');
recipients = recipients.toString();
if (reactivationDate) {
subject = `IMPORTANT: ${firstName} ${lastName} has been PAUSED in the Highest Good Network`;
emailBody = `<p>Management, </p>
Expand All @@ -2094,7 +2097,6 @@ const userHelper = function () {

<p>One Community</p>`;
emailSender(email, subject, emailBody, null, recipients, email);

} else if (endDate && isSet && followup) {
subject = `IMPORTANT: The last day for ${firstName} ${lastName} has been set in the Highest Good Network`;
emailBody = `<p>Management, </p>
Expand All @@ -2106,8 +2108,7 @@ const userHelper = function () {

<p>One Community</p>`;
emailSender(email, subject, emailBody, null, recipients, email);

} else if (endDate && isSet ) {
} else if (endDate && isSet) {
subject = `IMPORTANT: The last day for ${firstName} ${lastName} has been set in the Highest Good Network`;
emailBody = `<p>Management, </p>

Expand All @@ -2118,8 +2119,7 @@ const userHelper = function () {

<p>One Community</p>`;
emailSender(email, subject, emailBody, null, recipients, email);

} else if(endDate){
} else if (endDate) {
subject = `IMPORTANT: ${firstName} ${lastName} has been deactivated in the Highest Good Network`;
emailBody = `<p>Management, </p>

Expand All @@ -2130,10 +2130,9 @@ const userHelper = function () {

<p>One Community</p>`;
emailSender(email, subject, emailBody, null, recipients, email);
};

}

};

const deActivateUser = async () => {
try {
const emailReceivers = await userProfile.find(
Expand All @@ -2149,14 +2148,18 @@ const userHelper = function () {
const user = users[i];
const { endDate, finalEmailThreeWeeksSent } = user;
endDate.setHours(endDate.getHours() + 7);
// notify reminder set final day before 2 weeks
if(finalEmailThreeWeeksSent && moment().isBefore(moment(endDate).subtract(2, 'weeks')) && moment().isAfter(moment(endDate).subtract(3, 'weeks'))){
// notify reminder set final day before 2 weeks
if (
finalEmailThreeWeeksSent &&
moment().isBefore(moment(endDate).subtract(2, 'weeks')) &&
moment().isAfter(moment(endDate).subtract(3, 'weeks'))
) {
const id = user._id;
const person = await userProfile.findById(id);
const lastDay = moment(person.endDate).format('YYYY-MM-DD');
logger.logInfo(`User with id: ${user._id}'s final Day is set at ${moment().format()}.`);
person.teams.map(async (teamId) => {
const managementEmails = await userHelper.getTeamManagementEmail(teamId);
const managementEmails = await userHelper.getTeamManagementEmail(teamId);
if (Array.isArray(managementEmails) && managementEmails.length > 0) {
managementEmails.forEach((management) => {
recipients.push(management.email);
Expand Down
Loading