|
| 1 | +const LEVELS = ['year6', 'year7', 'year8', 'year9', 'year10', 'year11']; |
| 2 | + |
| 3 | +const getCleanAnswers = answers => Object.keys(answers).reduce((acc, key) => { |
| 4 | + const { submitted, score, time, sameWeek } = answers[key]; |
| 5 | + const year = 'year' + key.split('-')[0]; |
| 6 | + const afterMigration = time && time > 1661382000000 ? true : false; |
| 7 | + |
| 8 | + if (!submitted) return acc; |
| 9 | + if (!LEVELS.includes(year)) return acc; |
| 10 | + |
| 11 | + acc[year] = acc[year] || {}; |
| 12 | + acc[year][key] = { |
| 13 | + score, time, sameWeek, afterMigration |
| 14 | + } |
| 15 | + |
| 16 | + return acc; |
| 17 | +}, {}); |
| 18 | + |
| 19 | +const getBonus = (numberCompleted) => { |
| 20 | + let count = 0; |
| 21 | + for (let x = 0; x < numberCompleted; x++) { |
| 22 | + count += x + 1; |
| 23 | + } |
| 24 | + return count; |
| 25 | +}; |
| 26 | + |
| 27 | +const isValidScore = (score) => { |
| 28 | + if (typeof score !== 'number') return false; |
| 29 | + if (score > 0 && score <= 100) return true; |
| 30 | + return false; |
| 31 | +}; |
| 32 | + |
| 33 | +const getNumberAfterMigration = (answerGroup) => |
| 34 | + Object.entries(answerGroup).reduce((acc, [, value]) => { |
| 35 | + if (value.afterMigration) return acc + 1; |
| 36 | + |
| 37 | + return acc; |
| 38 | + }, 0); |
| 39 | + |
| 40 | +const getPoints = (answerGroup) => |
| 41 | + Object.entries(answerGroup).reduce((acc, [, value]) => { |
| 42 | + if (value.score && isValidScore(value.score)) { |
| 43 | + if (!value.afterMigration) return acc; |
| 44 | + |
| 45 | + acc += value.score; |
| 46 | + |
| 47 | + if (value.sameWeek) { |
| 48 | + acc += 20 * (value.score / 100); |
| 49 | + } |
| 50 | + } |
| 51 | + return acc; |
| 52 | + }, 0); |
| 53 | + |
| 54 | +const calculatePgYearPoints = (answerGroup, adjustment) => { |
| 55 | + const bonus = getBonus(Object.keys(answerGroup).length); |
| 56 | + |
| 57 | + // Remove bonus of PGs done premigration |
| 58 | + const negativeBonus = getBonus( |
| 59 | + Object.keys(answerGroup).length - getNumberAfterMigration(answerGroup) |
| 60 | + ); |
| 61 | + |
| 62 | + const points = getPoints(answerGroup); |
| 63 | + |
| 64 | + return Math.ceil(bonus + points - negativeBonus) + (adjustment || 0); |
| 65 | +}; |
| 66 | + |
| 67 | +const getPgPoints = (user) => { |
| 68 | + const awardAdjustments = user?.awardAdjustments || {}; |
| 69 | + const cleanAnswers = getCleanAnswers(user?.answers || {}) |
| 70 | + |
| 71 | + return LEVELS.reduce((acc, level) => { |
| 72 | + acc[level] = calculatePgYearPoints(cleanAnswers[level] || {}, awardAdjustments[level]) |
| 73 | + return acc; |
| 74 | + }, {}) |
| 75 | +} |
| 76 | + |
| 77 | +module.exports = { |
| 78 | + LEVELS, |
| 79 | + getPgPoints, |
| 80 | + getCleanAnswers |
| 81 | +} |
0 commit comments