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

Roberto fix assigning duplicate badges #666

Merged
merged 4 commits into from
Mar 16, 2024
Merged
Changes from 2 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
129 changes: 82 additions & 47 deletions src/controllers/badgeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,28 @@ const badgeController = function (Badge) {
};

/**
* Updated Date: 12/06/2023
* Updated By: Shengwei
* Updated Date: 12/17/2023
* Updated By: Roberto
* Function added:
* - Added data validation for earned date and badge count mismatch.
* - Added fillEarnedDateToMatchCount function to resolve earned date and badge count mismatch.
* - Refactored data validation for duplicate badge id.
* - Added data validation for badge count should greater than 0.
* - Added formatDate function to format date to MMM-DD-YY.
* - Added logic to combine duplicate badges into one with updated properties.
*/

const formatDate = () => {
const currentDate = new Date(Date.now());
return moment(currentDate).tz('America/Los_Angeles').format('MMM-DD-YY');
};

const fillEarnedDateToMatchCount = (earnedDate, count) => {
const result = [...earnedDate];
while (result.length < count) {
result.push(formatDate());
const currentDate = moment(new Date(Date.now())).tz('America/Los_Angeles').format('MMM-DD-YY');

if (earnedDate.length > count) {
const elementsToRemove = earnedDate.length - count;
earnedDate.splice(-elementsToRemove);
}

const additionalDates = new Array(count - earnedDate.length).fill(currentDate);
const result = [...earnedDate, ...additionalDates];

return result;
};

Expand All @@ -66,51 +68,84 @@ const badgeController = function (Badge) {
res.status(400).send('Can not find the user to be assigned.');
return;
}
const badgeCounts = {};
// This line is using the forEach function to group badges in the badgeCollection
// array in the request body.
// Validation: No duplicate badge id;
try {
req.body.badgeCollection.forEach((element) => {
if (badgeCounts[element.badge]) {
throw new Error('Duplicate badges sent in.');
// res.status(500).send('Duplicate badges sent in.');
// return;

const badgeGroups = req.body.badgeCollection.reduce((grouped, item) => {
const { badge } = item;

if (typeof item.count !== 'number') {
item.count = Number(item.count);
if (Number.isNaN(item.count)) {
return grouped;
}
badgeCounts[element.badge] = element.count;
// Validation: count should be greater than 0
if (element.count < 1) {
throw new Error('Badge count should be greater than 0.');
}
// if count is 0, skip
if (item.count === 0) {
return grouped;
}

if (!grouped[badge]) {
// If the badge is not in the grouped object, add a new entry
grouped[badge] = {
count: item.count,
lastModified: item.lastModified ? item.lastModified : Date.now(),
featured: item.featured || false,
earnedDate: item.earnedDate,
};
} else {
// If the badge is already in the grouped object, update properties
grouped[badge].count += item.count;
grouped[badge].lastModified = Date.now();
grouped[badge].featured = grouped[badge].featured || item.featured || false;

// Combine and sort earnedDate arrays
if (Array.isArray(item.earnedDate)) {
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).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' })
.replace(/ /g, '-')
.replace(',', ''));
}
if (element.count !== element.earnedDate.length) {
element.earnedDate = fillEarnedDateToMatchCount(
element.earnedDate,
element.count,
);
element.lastModified = Date.now();
logger.logInfo(
`Badge count and earned dates mismatched found. ${Date.now()} was generated for user ${userToBeAssigned}. Badge record ID ${
element._id
}; Badge Type ID ${element.badge}`,
}

// if count doesn't match earnedDate length, fill earnedDate with current date
if (grouped[badge].earnedDate.length !== grouped[badge].count) {
grouped[badge].earnedDate = fillEarnedDateToMatchCount(
grouped[badge].earnedDate,
grouped[badge].count,
);
}
});
} catch (err) {
res.status(500).send(`Internal Error: Badge Collection. ${ err.message}`);
return;
}
record.badgeCollection = req.body.badgeCollection;
grouped[badge].lastModified = Date.now();
logger.logInfo(
`Badge count and earned dates mismatched found. ${Date.now()} was generated for user ${userToBeAssigned}. Badge record ID ${
item._id
}; Badge Type ID ${badge}`,
);
}

return grouped;
}, {});

// Convert badgeGroups object to array
const badgeGroupsArray = Object.entries(badgeGroups).map(([badge, data]) => ({
badge,
count: data.count,
lastModified: data.lastModified,
featured: data.featured,
earnedDate: data.earnedDate,
}));

record.badgeCollection = badgeGroupsArray;

if (cache.hasCache(`user-${userToBeAssigned}`)) {
cache.removeCache(`user-${userToBeAssigned}`);
}
// Save Updated User Profile

record
.save()
.then(results => res.status(201).send(results._id))
.catch((err) => {
logger.logException(err);
res.status(500).send('Internal Error: Unable to save the record.');
.save()
.then(results => res.status(201).send(results._id))
.catch((err) => {
logger.logException(err);
res.status(500).send('Internal Error: Unable to save the record.');
});
});
};
Expand Down
Loading