diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index cb11d50a1c..a6f7240c0f 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -9,6 +9,7 @@ const TrainingContract = require('../models/TrainingContract'); const CourseBill = require('../models/CourseBill'); const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); +const DatesUtilsHelper = require('./dates/utils'); const { MM_YYYY, MONTH, DD_MM_YYYY, SHORT_DURATION_H_MM, OFFICIAL } = require('./constants'); const UtilsHelper = require('./utils'); const NumbersHelper = require('./numbers'); @@ -246,10 +247,30 @@ exports.generate = async (completionCertificateId) => { for (const [planId, bills] of Object.entries(billsGroupedByPlan)) { const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, planId)); - const priceDetails = HourlyPaymentPlansHelper - .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps); + let previousELearningDuration; + if (hourlyPaymentPlan.elearningLimit) { + const firstCertificateMonthStart = [month, ...certificates.map(c => c.month)] + .map(m => CompaniDate(m, MM_YYYY).startOf(MONTH).toISO()) + .sort(DatesUtilsHelper.ascendingSort)[0]; + + if (CompaniDate(firstCertificateMonthStart).isBefore(startOfMonth)) { + const dates = { startDate: firstCertificateMonthStart, endDate: CompaniDate(startOfMonth).toISO() }; + previousELearningDuration = await CoursesHelper.getTraineeELearningDuration(course, trainee._id, dates); + } + } + + const priceDetails = HourlyPaymentPlansHelper.getPricesFromDurations( + hourlyPaymentPlan, + durationPerStep, + eLearningDuration, + course.subProgram.steps, + previousELearningDuration + ); const hasPricedStep = Object.values(priceDetails).some(line => line.stepId); - if (!hasPricedStep && CompaniDuration(eLearningDuration).isShorterThan('PT900S')) continue; + const eLearningPrice = get(priceDetails, 'elearning.price', 0); + const isELearningNotBillable = CompaniDuration(eLearningDuration).isShorterThan('PT900S') || + NumbersHelper.isEqualTo(eLearningPrice, 0); + if (!hasPricedStep && isELearningNotBillable) continue; const descriptionDetails = HourlyPaymentPlansHelper.getPriceDetails(priceDetails); const price = NumbersHelper diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index dc15c71b53..9d2d9148b4 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -152,11 +152,22 @@ const formatCourse = (course, traineesCompanyAtCourseRegistrationByCourse) => { return { ...course, trainees: courseTrainees, prices: coursePrices }; }; -const getBillRanks = async (courseIds, isVendorUser) => { - if (!courseIds.length) return {}; +const getBillInfos = async (courseIds, isVendorUser, shouldComputePreviousBillsSum) => { + if (!courseIds.length) return { billRanks: {}, validatedHourlyBillsAmount: {} }; const bills = await CourseBill - .find({ course: { $in: courseIds } }, { course: 1, companies: 1, billedAt: 1, maturityDate: 1 }) + .find( + { course: { $in: courseIds } }, + { + course: 1, + companies: 1, + billedAt: 1, + maturityDate: 1, + hourlyPaymentPlan: 1, + mainFee: 1, + billingPurchaseList: 1, + } + ) .populate({ path: 'courseCreditNote', select: 'courseBill', options: { isVendorUser } }) .setOptions({ isVendorUser }) .lean(); @@ -171,17 +182,27 @@ const getBillRanks = async (courseIds, isVendorUser) => { const billsGroupedByCourse = groupBy(sortedBills, bill => `${bill.course}-${[...bill.companies].sort().join(',')}`); - const ranks = {}; + const billRanks = {}; for (const billsGroupedByCompanies of Object.values(billsGroupedByCourse)) { for (let i = 0; i < billsGroupedByCompanies.length; i++) { - ranks[billsGroupedByCompanies[i]._id] = { index: i + 1, billsCount: billsGroupedByCompanies.length }; + billRanks[billsGroupedByCompanies[i]._id] = { index: i + 1, billsCount: billsGroupedByCompanies.length }; } } - return ranks; + if (!shouldComputePreviousBillsSum) return { billRanks, validatedHourlyBillsAmount: {} }; + + const validatedHourlyBills = sortedBills.filter(bill => bill.billedAt && bill.hourlyPaymentPlan); + const validatedHourlyBillsAmount = mapValues( + groupBy(validatedHourlyBills, 'course'), + billsOfCourse => NumbersHelper.toNumber(billsOfCourse + .reduce((acc, bill) => NumbersHelper.add(acc, exports.getDetailWithTaxes(bill).netExclTaxes), 0)) + ); + + return { billRanks, validatedHourlyBillsAmount }; }; exports.list = async (query, credentials) => { + const isVendorUser = !!get(credentials, 'role.vendor'); if (query.action === LIST) { const courseBills = await CourseBill .find({ course: query.course }) @@ -189,8 +210,8 @@ exports.list = async (query, credentials) => { .populate({ path: 'companies', select: 'name' }) .populate({ path: 'payer.fundingOrganisation', select: 'name' }) .populate({ path: 'payer.company', select: 'name' }) - .populate({ path: 'courseCreditNote', options: { isVendorUser: !!get(credentials, 'role.vendor') } }) - .setOptions({ isVendorUser: !!get(credentials, 'role.vendor') }) + .populate({ path: 'courseCreditNote', options: { isVendorUser } }) + .setOptions({ isVendorUser }) .lean(); return courseBills @@ -250,9 +271,9 @@ exports.list = async (query, credentials) => { ), { path: 'payer.fundingOrganisation', select: 'name' }, { path: 'payer.company', select: 'name' }, - { path: 'courseCreditNote', options: { isVendorUser: !!get(credentials, 'role.vendor') } }, + { path: 'courseCreditNote', options: { isVendorUser } }, ]) - .setOptions({ isVendorUser: !!get(credentials, 'role.vendor') }) + .setOptions({ isVendorUser }) .lean(); let traineesWithLongEnoughActivityHistory = {}; @@ -306,7 +327,7 @@ exports.list = async (query, credentials) => { } const courseIds = filteredCourseBills.map(bill => bill.course._id); - const billRanks = await getBillRanks(courseIds, !!get(credentials, 'role.vendor')); + const { billRanks, validatedHourlyBillsAmount } = await getBillInfos(courseIds, isVendorUser, !query.isValidated); return filteredCourseBills.map((bill) => { const { netExclTaxes, netInclTaxes } = exports.getDetailWithTaxes(bill); @@ -314,6 +335,9 @@ exports.list = async (query, credentials) => { return { ...bill, rank: billRanks[bill._id], + ...validatedHourlyBillsAmount[bill.course._id] && { + validatedHourlyBillsAmount: validatedHourlyBillsAmount[bill.course._id], + }, ...(query.startDate && query.endDate ? { course: formatCourse(bill.course, traineesCompanyAtCourseRegistrationByCourse), @@ -333,6 +357,7 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => { .populate({ path: 'slots', select: 'startDate endDate trainers step', + options: { sort: { startDate: 1 } }, populate: { path: 'step', select: 'durationCountedPerTrainer' }, }) .populate({ @@ -342,8 +367,9 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => { }) .lean(); + const dates = { startDate: course.slots[0].startDate, endDate: CompaniDate().toISO() }; const { slotsWithAttendance, eLearningDuration } = await CoursesHelper - .getTraineeDurations(course, course.trainees[0]); + .getTraineeDurations(course, course.trainees[0], dates); const durationPerStep = CourseSlotsHelper.getDurationPerStep(slotsWithAttendance); const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 6d428c5496..d4a03efa65 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -1420,11 +1420,34 @@ exports.getRealELearningDuration = (activityHistories) => { return eLearningDuration; }; -exports.getTraineeDurations = async (course, traineeId, dates) => { +exports.getTraineeELearningDuration = async (course, traineeId, dates) => { const REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS .split(',') .map(id => new ObjectId(id)); + const eLearningSteps = course.subProgram.steps.filter(step => step.type === E_LEARNING); + const activityHistories = await ActivityHistory + .find({ activity: { $in: eLearningSteps.flatMap(s => s.activities) }, user: traineeId }) + .lean(); + + if (UtilsHelper.doesArrayIncludeId(REAL_ELEARNING_DURATION_SUBPROGRAM_IDS, course.subProgram._id)) { + const filteredActivityHistories = dates + ? activityHistories.filter(aH => CompaniDate(aH.date).isSameOrBetween(dates.startDate, dates.endDate)) + : activityHistories; + + return exports.getRealELearningDuration(filteredActivityHistories); + } + + const activityHistoriesGroupedByActivity = groupBy(activityHistories, 'activity'); + const eLearningStepsWithAH = eLearningSteps.map(s => ({ + ...s, + activities: s.activities.map(a => ({ _id: a, activityHistories: activityHistoriesGroupedByActivity[a] || [] })), + })); + + return exports.getELearningDuration(eLearningStepsWithAH, traineeId, dates); +}; + +exports.getTraineeDurations = async (course, traineeId, dates) => { const slots = dates ? course.slots.filter(slot => CompaniDate(slot.startDate).isSameOrBetween(dates.startDate, dates.endDate)) : course.slots; @@ -1436,25 +1459,7 @@ exports.getTraineeDurations = async (course, traineeId, dates) => { const slotsWithAttendance = slots .filter(slot => UtilsHelper.doesArrayIncludeId(attendances.map(a => a.courseSlot), slot._id)); - const eLearningSteps = course.subProgram.steps.filter(step => step.type === E_LEARNING); - const activityHistories = await ActivityHistory - .find({ activity: { $in: eLearningSteps.flatMap(s => s.activities) }, user: traineeId }) - .lean(); - - let eLearningDuration; - if (UtilsHelper.doesArrayIncludeId(REAL_ELEARNING_DURATION_SUBPROGRAM_IDS, course.subProgram._id)) { - const filteredActivityHistories = dates - ? activityHistories.filter(aH => CompaniDate(aH.date).isSameOrBetween(dates.startDate, dates.endDate)) - : activityHistories; - eLearningDuration = exports.getRealELearningDuration(filteredActivityHistories); - } else { - const activityHistoriesGroupedByActivity = groupBy(activityHistories, 'activity'); - const eLearningStepsWithAH = eLearningSteps.map(s => ({ - ...s, - activities: s.activities.map(a => ({ _id: a, activityHistories: activityHistoriesGroupedByActivity[a] || [] })), - })); - eLearningDuration = exports.getELearningDuration(eLearningStepsWithAH, traineeId, dates); - } + const eLearningDuration = await exports.getTraineeELearningDuration(course, traineeId, dates); return { slotsWithAttendance, eLearningDuration }; }; diff --git a/src/helpers/hourlyPaymentPlans.js b/src/helpers/hourlyPaymentPlans.js index e17432947e..af1551021b 100644 --- a/src/helpers/hourlyPaymentPlans.js +++ b/src/helpers/hourlyPaymentPlans.js @@ -1,9 +1,15 @@ const NumbersHelper = require('./numbers'); const UtilsHelper = require('./utils'); const { CompaniDuration } = require('./dates/companiDurations'); -const { SHORT_DURATION_H_MM } = require('./constants'); +const { SHORT_DURATION_H_MM, PT0S } = require('./constants'); -exports.getPricesFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration, steps) => { +exports.getPricesFromDurations = ( + hourlyPaymentPlan, + durationPerStep, + eLearningDuration, + steps, + previousELearningDuration = CompaniDuration() +) => { const stepsPrices = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => { const stepPrice = hourlyPaymentPlan.prices.find(p => UtilsHelper.areObjectIdsEquals(p.step, stepId)); if (!stepPrice) return acc; @@ -15,9 +21,17 @@ exports.getPricesFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningD return { ...acc, [stepId]: { stepId, stepName, duration, price } }; }, {}); + const eLearningMonthDuration = CompaniDuration(eLearningDuration); + let billableELearningDuration = eLearningMonthDuration; + if (hourlyPaymentPlan.elearningLimit) { + const remainingDuration = CompaniDuration(hourlyPaymentPlan.elearningLimit).subtract(previousELearningDuration); + if (remainingDuration.isShorterThan(eLearningMonthDuration)) { + billableELearningDuration = remainingDuration.isShorterThan(PT0S) ? CompaniDuration(PT0S) : remainingDuration; + } + } const eLearning = hourlyPaymentPlan.elearningPrice && { - duration: CompaniDuration(eLearningDuration), - price: NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice), + duration: eLearningMonthDuration, + price: NumbersHelper.multiply(billableELearningDuration.asHours(), hourlyPaymentPlan.elearningPrice), }; return { ...stepsPrices, ...eLearning && { elearning: eLearning } }; diff --git a/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 394ee4e411..79409fe5e0 100644 --- a/src/helpers/subPrograms.js +++ b/src/helpers/subPrograms.js @@ -9,6 +9,7 @@ const Course = require('../models/Course'); const UserCompany = require('../models/UserCompany'); const { INTER_B2C, STRICTLY_E_LEARNING, DRAFT, PUBLISHED } = require('./constants'); const { CompaniDate } = require('./dates/companiDates'); +const { CompaniDuration } = require('./dates/companiDurations'); const NotificationHelper = require('./notifications'); const UtilsHelper = require('./utils'); @@ -127,11 +128,18 @@ exports.updateSubProgram = async (subProgramId, payload) => { if (payload.hourlyPaymentPlan) { const { hourlyPaymentPlanId, prices, elearningPrice } = payload.hourlyPaymentPlan; + const elearningLimit = payload.hourlyPaymentPlan.elearningLimit && + CompaniDuration(payload.hourlyPaymentPlan.elearningLimit).asSeconds(); if (hourlyPaymentPlanId && prices.length) { - const updateQuery = elearningPrice - ? { $set: { 'hourlyPaymentPlans.$.prices': prices, 'hourlyPaymentPlans.$.elearningPrice': elearningPrice } } - : { $set: { 'hourlyPaymentPlans.$.prices': prices }, $unset: { 'hourlyPaymentPlans.$.elearningPrice': '' } }; + const updateQuery = { + $set: { + 'hourlyPaymentPlans.$.prices': prices, + ...elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': elearningPrice }, + ...elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': elearningLimit }, + }, + ...!elearningLimit && { $unset: { 'hourlyPaymentPlans.$.elearningLimit': '' } }, + }; return SubProgram.updateOne({ _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, updateQuery); } @@ -145,7 +153,15 @@ exports.updateSubProgram = async (subProgramId, payload) => { return SubProgram.updateOne( { _id: subProgramId }, - { $push: { hourlyPaymentPlans: { prices, ...elearningPrice && { elearningPrice } } } } + { + $push: { + hourlyPaymentPlans: { + prices, + ...elearningPrice && { elearningPrice }, + ...elearningLimit && { elearningLimit }, + }, + }, + } ); } diff --git a/src/helpers/translate.js b/src/helpers/translate.js index 37a4ed9b9f..489b7f3215 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -109,6 +109,7 @@ module.exports = { subProgramHourlyPaymentPlanUsed: 'Forbidden: this hourly payment plan is used by a course.', subProgramHourlyPaymentPlanAlreadyExists: 'Forbidden: an identical hourly payment plan already exists.', subProgramHourlyPaymentPlanNoELearningStep: 'Forbidden: this sub-program has no e-learning step.', + subProgramHourlyPaymentPlanNoELearningPrice: 'Forbidden: the e-learning price is required.', subProgramHasPaymentPlan: 'Forbidden: this sub-program already has payment plans.', subProgramHasHourlyPaymentPlan: 'Forbidden: this sub-program already has hourly payment plans.', subProgramPaymentPlanAlreadyExists: 'Forbidden: a payment plan with the same prices already exists.', @@ -495,6 +496,7 @@ module.exports = { subProgramHourlyPaymentPlanUsed: 'Impossible : cette tarification est utilisée par des factures.', subProgramHourlyPaymentPlanAlreadyExists: 'Impossible : une tarification identique existe déjà.', subProgramHourlyPaymentPlanNoELearningStep: 'Impossible : ce sous-programme n\'a pas d\'étape e-learning.', + subProgramHourlyPaymentPlanNoELearningPrice: 'Impossible : le prix e-learning est requis.', subProgramHasPaymentPlan: 'Impossible : ce sous-programme a déjà des échéanciers.', subProgramHasHourlyPaymentPlan: 'Impossible : ce sous-programme a déjà des tarifications au réel.', subProgramPaymentPlanAlreadyExists: 'Impossible : un échéancier avec les mêmes montants existe déjà.', diff --git a/src/models/SubProgram.js b/src/models/SubProgram.js index e37cf8cba1..652fdd8843 100644 --- a/src/models/SubProgram.js +++ b/src/models/SubProgram.js @@ -2,7 +2,13 @@ const mongoose = require('mongoose'); const has = require('lodash/has'); const mongooseLeanVirtuals = require('mongoose-lean-virtuals'); const { DRAFT, PUBLISHED, E_LEARNING, TRAINER_ROLES } = require('../helpers/constants'); -const { formatQuery, queryMiddlewareList } = require('./preHooks/validate'); +const { + formatQuery, + queryMiddlewareList, + getDocMiddlewareList, + getDocListMiddlewareList, +} = require('./preHooks/validate'); +const { formatSecondsToISODuration } = require('../helpers/dates/utils'); const STATUS_TYPES = [DRAFT, PUBLISHED]; @@ -31,6 +37,7 @@ const SubProgramSchema = mongoose.Schema({ hourlyAmount: { type: Number, required: true }, }], elearningPrice: { type: Number }, + elearningLimit: { type: Number }, }], default: undefined, }, @@ -77,7 +84,23 @@ SubProgramSchema.virtual('areStepsValid').get(setAreStepsValid); SubProgramSchema.virtual('isStrictlyELearning').get(setIsStrictlyELearning); +function formatELearningLimit(doc) { + if (!doc || !doc.hourlyPaymentPlans) return; + + for (const plan of doc.hourlyPaymentPlans) { + if (plan.elearningLimit) plan.elearningLimit = formatSecondsToISODuration(plan.elearningLimit); + } +} + +function formatELearningLimitList(docs) { + for (const doc of docs) { + formatELearningLimit(doc); + } +} + queryMiddlewareList.map(middleware => SubProgramSchema.pre(middleware, formatQuery)); +getDocMiddlewareList.map(middleware => SubProgramSchema.post(middleware, formatELearningLimit)); +getDocListMiddlewareList.map(middleware => SubProgramSchema.post(middleware, formatELearningLimitList)); SubProgramSchema.plugin(mongooseLeanVirtuals); diff --git a/src/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 958895db0b..449a122fe4 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -19,6 +19,7 @@ const { } = require('../../helpers/constants'); const translate = require('../../helpers/translate'); const UtilsHelper = require('../../helpers/utils'); +const { CompaniDuration } = require('../../helpers/dates/companiDurations'); const { CompaniDate } = require('../../helpers/dates/companiDates'); const { language } = translate; @@ -181,7 +182,7 @@ exports.authorizeSubProgramUpdate = async (req) => { if (subProgram.status !== PUBLISHED) throw Boom.forbidden(); if ((subProgram.paymentPlans || []).length) throw Boom.forbidden(translate[language].subProgramHasPaymentPlan); - const { hourlyPaymentPlanId, prices, elearningPrice } = req.payload.hourlyPaymentPlan; + const { hourlyPaymentPlanId, prices, elearningPrice, elearningLimit } = req.payload.hourlyPaymentPlan; if (hourlyPaymentPlanId) { const subProgramHppIds = (subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id); const hourlyPaymentPlanExists = UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId); @@ -203,15 +204,22 @@ exports.authorizeSubProgramUpdate = async (req) => { const isDuplicate = (subProgram.hourlyPaymentPlans || []) .some(hpp => !UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId) && hpp.elearningPrice === elearningPrice && + (hpp.elearningLimit + ? !!elearningLimit && CompaniDuration(hpp.elearningLimit).isEquivalentTo(elearningLimit) + : !elearningLimit) && hpp.prices.length === prices.length && hpp.prices.every(hp => prices .some(p => UtilsHelper.areObjectIdsEquals(p.step, hp.step) && p.hourlyAmount === hp.hourlyAmount))); if (isDuplicate) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanAlreadyExists); } - if (elearningPrice && !subProgram.steps.some(s => s.type === E_LEARNING)) { + const hasELearningStep = subProgram.steps.some(s => s.type === E_LEARNING); + if (elearningPrice && !hasELearningStep) { throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanNoELearningStep); } + if (prices.length && !elearningPrice && hasELearningStep) { + throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanNoELearningPrice); + } } return null; diff --git a/src/routes/subPrograms.js b/src/routes/subPrograms.js index f0705d5f3e..50f21e8984 100644 --- a/src/routes/subPrograms.js +++ b/src/routes/subPrograms.js @@ -12,6 +12,7 @@ const { authorizeStepReuse, getSubProgram, } = require('./preHandlers/subPrograms'); +const { durationStrictlyPositive } = require('./validations/utils'); const { update, remove, @@ -83,6 +84,8 @@ exports.plugin = { .required(), }), elearningPrice: Joi.number().positive(), + elearningLimit: durationStrictlyPositive + .when('elearningPrice', { is: Joi.exist(), otherwise: Joi.forbidden() }), }).required(), }), Joi.object({ archivedAt: Joi.date().allow('') }) diff --git a/tests/integration/seed/subProgramsSeed.js b/tests/integration/seed/subProgramsSeed.js index 58c3734c8f..d041f7d958 100644 --- a/tests/integration/seed/subProgramsSeed.js +++ b/tests/integration/seed/subProgramsSeed.js @@ -191,6 +191,12 @@ const subProgramsList = [ status: PUBLISHED, steps: [stepsList[2]._id], }, + { // 17 published, on site step and e-learning step + _id: new ObjectId(), + name: 'subProgram 17', + status: PUBLISHED, + steps: [stepsList[0]._id, stepsList[2]._id], + }, ]; const programsList = [ diff --git a/tests/integration/subPrograms.test.js b/tests/integration/subPrograms.test.js index bef63abb11..10cfe0aa7b 100644 --- a/tests/integration/subPrograms.test.js +++ b/tests/integration/subPrograms.test.js @@ -535,6 +535,34 @@ describe('SUBPROGRAMS ROUTES - PUT /subprograms/{_id}', () => { expect(response.statusCode).toBe(403); }); + it('should return 400 if the e-learning limit is sent without e-learning price', async () => { + const payload = { + hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }], elearningLimit: 'PT36000S' }, + }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 403 if the e-learning price is missing on a subProgram with an e-learning step', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[17]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 403 if an identical hourly payment plan already exists', async () => { const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 40 }] } }; diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index cbe7a43941..028e1a10a5 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -804,7 +804,8 @@ describe('generate', () => { hourlyPaymentPlan, durationPerStep, 'PT3H30M', - completionCertificate.course.subProgram.steps + completionCertificate.course.subProgram.steps, + undefined ); sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); sinon.assert.calledOnceWithExactly( @@ -825,7 +826,8 @@ describe('generate', () => { const companyId = new ObjectId(); const courseId = new ObjectId(); const month = '03-2025'; - const hourlyPaymentPlan = { _id: new ObjectId(), prices: [], elearningPrice: 20 }; + const hourlyPaymentPlan = { _id: new ObjectId(), prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const previousELearningDuration = CompaniDuration({ hours: 8 }); const billId = new ObjectId(); const durationPerStep = { [stepId]: CompaniDuration({ minutes: 390 }) }; const slotList = [ @@ -921,13 +923,15 @@ describe('generate', () => { findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); getDurationPerStep.returns(durationPerStep); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); - findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findActivityHistories.onCall(0).returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findActivityHistories.onCall(1).returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); findBills.returns(SinonMongoose.stubChainedQueries( [{ _id: billId, hourlyPaymentPlan: hourlyPaymentPlan._id }], ['setOptions', 'lean'] )); getPricesFromDurations.returns({ elearning: { duration: CompaniDuration({ seconds: 200 }), price: '1.11' } }); - getRealELearningDuration.returns('PT200S'); + getRealELearningDuration.onCall(0).returns('PT200S'); + getRealELearningDuration.onCall(1).returns(previousELearningDuration); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); uploadCourseFile.returns({ publicId: '1234', link: 'tests/1234' }); @@ -980,12 +984,21 @@ describe('generate', () => { { query: 'lean' }, ] ); - SinonMongoose.calledOnceWithExactly( + SinonMongoose.calledWithExactly( findActivityHistories, [ { query: 'find', args: [{ activity: { $in: activitiesIds }, user: traineeId }] }, { query: 'lean' }, - ] + ], + 0 + ); + SinonMongoose.calledWithExactly( + findActivityHistories, + [ + { query: 'find', args: [{ activity: { $in: activitiesIds }, user: traineeId }] }, + { query: 'lean' }, + ], + 1 ); sinon.assert.calledOnceWithExactly( getDurationPerStep, @@ -1021,7 +1034,8 @@ describe('generate', () => { { query: 'lean' }, ] ); - sinon.assert.calledOnceWithExactly(getRealELearningDuration, [activityHistories[0]]); + sinon.assert.calledWithExactly(getRealELearningDuration.getCall(0), [activityHistories[0]]); + sinon.assert.calledWithExactly(getRealELearningDuration.getCall(1), [activityHistories[1]]); sinon.assert.calledOnceWithExactly(formatIdentity, { firstname: 'Jean', lastname: 'Saitrien' }, 'FL'); sinon.assert.calledOnceWithExactly( getPdf, @@ -1091,7 +1105,8 @@ describe('generate', () => { hourlyPaymentPlan, durationPerStep, 'PT200S', - completionCertificate.course.subProgram.steps + completionCertificate.course.subProgram.steps, + previousELearningDuration ); sinon.assert.notCalled(getPriceDetails); sinon.assert.notCalled(updateOneBill); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index 29b602c9ca..36f373f0a0 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -470,6 +470,7 @@ describe('list', () => { const singleSubProgramId = new ObjectId(); const interSubProgramId = new ObjectId(); const activitiesIds = [new ObjectId(), new ObjectId()]; + const hourlyPaymentPlan = new ObjectId(); const periodBills = [ { _id: billIds[0], @@ -524,6 +525,7 @@ describe('list', () => { companies: [companies[1]], mainFee: { price: 320, count: 1 }, payer: { name: 'Funder' }, + hourlyPaymentPlan, maturityDate: '2025-06-13T14:00:00.000Z', }, { @@ -626,6 +628,32 @@ describe('list', () => { companies: [companies[1]._id], maturityDate: '2025-06-13T14:00:00.000Z', }, + { + _id: new ObjectId(), + course: courseIds[2], + companies: [companies[0]._id], + billedAt: '2025-05-10T14:00:00.000Z', + hourlyPaymentPlan, + mainFee: { price: 100, count: 1 }, + billingPurchaseList: [{ price: 10, count: 2 }], + }, + { + _id: new ObjectId(), + course: courseIds[2], + companies: [companies[0]._id], + billedAt: '2025-05-20T14:00:00.000Z', + hourlyPaymentPlan, + mainFee: { price: 50, count: 1 }, + }, + { + _id: new ObjectId(), + course: courseIds[2], + companies: [companies[0]._id], + billedAt: '2025-05-25T14:00:00.000Z', + hourlyPaymentPlan, + mainFee: { price: 900, count: 1 }, + courseCreditNote: { _id: new ObjectId() }, + }, { _id: billIds[3], course: courseIds[3], @@ -713,6 +741,8 @@ describe('list', () => { companies: [companies[1]], mainFee: { price: 320, count: 1 }, payer: { name: 'Funder' }, + hourlyPaymentPlan, + validatedHourlyBillsAmount: 170, maturityDate: '2025-06-13T14:00:00.000Z', course: { _id: courseIds[2], @@ -860,7 +890,15 @@ describe('list', () => { query: 'find', args: [ { course: { $in: [courseIds[0], courseIds[2], courseIds[3], courseIds[5]] } }, - { course: 1, companies: 1, billedAt: 1, maturityDate: 1 }, + { + course: 1, + companies: 1, + billedAt: 1, + maturityDate: 1, + hourlyPaymentPlan: 1, + mainFee: 1, + billingPurchaseList: 1, + }, ], }, { @@ -1027,7 +1065,18 @@ describe('list', () => { [ { query: 'find', - args: [{ course: { $in: [courseId] } }, { course: 1, companies: 1, billedAt: 1, maturityDate: 1 }], + args: [ + { course: { $in: [courseId] } }, + { + course: 1, + companies: 1, + billedAt: 1, + maturityDate: 1, + hourlyPaymentPlan: 1, + mainFee: 1, + billingPurchaseList: 1, + }, + ], }, { query: 'populate', @@ -1133,7 +1182,18 @@ describe('list', () => { [ { query: 'find', - args: [{ course: { $in: [courseId] } }, { course: 1, companies: 1, billedAt: 1, maturityDate: 1 }], + args: [ + { course: { $in: [courseId] } }, + { + course: 1, + companies: 1, + billedAt: 1, + maturityDate: 1, + hourlyPaymentPlan: 1, + mainFee: 1, + billingPurchaseList: 1, + }, + ], }, { query: 'populate', @@ -1183,7 +1243,11 @@ describe('computePriceFromDurations', () => { const priceDetails = { stepId: { stepName: 'étape', duration: CompaniDuration({ minutes: 120 }), price: '300' } }; const steps = [{ _id: new ObjectId(), name: 'étape' }]; - const course = { subProgram: { hourlyPaymentPlans, steps }, slots: [], trainees: [traineeId] }; + const course = { + subProgram: { hourlyPaymentPlans, steps }, + slots: [{ startDate: '2025-01-10T09:00:00.000Z' }], + trainees: [traineeId], + }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); getTraineeDurations.returns({ slotsWithAttendance, eLearningDuration }); @@ -1203,6 +1267,7 @@ describe('computePriceFromDurations', () => { args: [{ path: 'slots', select: 'startDate endDate trainers step', + options: { sort: { startDate: 1 } }, populate: { path: 'step', select: 'durationCountedPerTrainer' }, }], }, @@ -1217,7 +1282,12 @@ describe('computePriceFromDurations', () => { { query: 'lean' }, ] ); - sinon.assert.calledOnceWithExactly(getTraineeDurations, course, traineeId); + sinon.assert.calledOnceWithExactly( + getTraineeDurations, + course, + traineeId, + { startDate: '2025-01-10T09:00:00.000Z', endDate: sinon.match.string } + ); sinon.assert.calledOnceWithExactly(getDurationPerStep, slotsWithAttendance); sinon.assert.calledOnceWithExactly( getPricesFromDurations, diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js index 8a9c05cd14..4886a22480 100644 --- a/tests/unit/helpers/hourlyPaymentPlans.test.js +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -36,6 +36,46 @@ describe('getPricesFromDurations', () => { expect(result.elearning.duration.asMinutes()).toBe(90); }); + it('should not cap the billed e-learning if no previous duration and duration is lower than limit', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const noPreviousDuration = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, []); + + expect(noPreviousDuration.elearning.price).toBe('60'); + }); + + it('should not cap the billed e-learning if previous and current duration sum is lower than limit ', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const limitNotReached = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 6 })); + + expect(limitNotReached.elearning.price).toBe('60'); + }); + + it('should cap the billed e-learning with the remaining allowed duration', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const limitReachedThisMonth = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 8 })); + + expect(limitReachedThisMonth.elearning.price).toBe('40'); + expect(limitReachedThisMonth.elearning.duration.asHours()).toBe(3); + }); + it('should not bill e-learning if limit already reached', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const limitAlreadyReached = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 12 })); + + expect(limitAlreadyReached.elearning.price).toBe('0'); + }); + it('should not return e-learning line if there is no e-learning price', () => { const steps = [{ _id: new ObjectId(), name: 'étape A' }]; const hourlyPaymentPlan = { prices: [{ step: steps[0]._id, hourlyAmount: 40 }] }; diff --git a/tests/unit/helpers/subPrograms.test.js b/tests/unit/helpers/subPrograms.test.js index aa82ae32dc..358990600e 100644 --- a/tests/unit/helpers/subPrograms.test.js +++ b/tests/unit/helpers/subPrograms.test.js @@ -824,14 +824,28 @@ describe('updateSubProgram', () => { it('should add a new plan if payload.hourlyPaymentPlan has no id', async () => { const subProgramId = new ObjectId(); const stepId = new ObjectId(); - const payload = { hourlyPaymentPlan: { prices: [{ step: stepId, hourlyAmount: 50 }], elearningPrice: 30 } }; + const payload = { + hourlyPaymentPlan: { + prices: [{ step: stepId, hourlyAmount: 50 }], + elearningPrice: 30, + elearningLimit: 'PT72000S', + }, + }; await SubProgramHelper.updateSubProgram(subProgramId, payload); sinon.assert.calledOnceWithExactly( updateOne, { _id: subProgramId }, - { $push: { hourlyPaymentPlans: { prices: [{ step: stepId, hourlyAmount: 50 }], elearningPrice: 30 } } } + { + $push: { + hourlyPaymentPlans: { + prices: [{ step: stepId, hourlyAmount: 50 }], + elearningPrice: 30, + elearningLimit: 72000, + }, + }, + } ); sinon.assert.notCalled(findOne); sinon.assert.notCalled(findOneAndUpdate); @@ -841,7 +855,7 @@ describe('updateSubProgram', () => { const subProgramId = new ObjectId(); const hourlyPaymentPlanId = new ObjectId(); const prices = [{ step: new ObjectId(), hourlyAmount: 60 }]; - const payload = { hourlyPaymentPlan: { hourlyPaymentPlanId, prices } }; + const payload = { hourlyPaymentPlan: { hourlyPaymentPlanId, prices, elearningPrice: 30 } }; await SubProgramHelper.updateSubProgram(subProgramId, payload); @@ -849,8 +863,8 @@ describe('updateSubProgram', () => { updateOne, { _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, { - $set: { 'hourlyPaymentPlans.$.prices': prices }, - $unset: { 'hourlyPaymentPlans.$.elearningPrice': '' }, + $set: { 'hourlyPaymentPlans.$.prices': prices, 'hourlyPaymentPlans.$.elearningPrice': 30 }, + $unset: { 'hourlyPaymentPlans.$.elearningLimit': '' }, } ); sinon.assert.notCalled(findOne);