From ca51fc3af866d4b8058b9181e1e53c47dce20637 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 27 Oct 2026 15:19:53 +0100 Subject: [PATCH 01/53] COM-4313 - create GET /trainerBills --- src/controllers/trainerBillController.js | 16 ++++- src/helpers/trainerBills.js | 6 ++ src/helpers/translate.js | 4 ++ src/routes/preHandlers/trainerBills.js | 13 ++++ src/routes/trainerBills.js | 17 ++++- tests/integration/seed/trainerBillsSeed.js | 9 ++- tests/integration/trainerBills.test.js | 74 +++++++++++++++++++++- tests/unit/helpers/trainerBills.test.js | 31 +++++++++ 8 files changed, 164 insertions(+), 6 deletions(-) diff --git a/src/controllers/trainerBillController.js b/src/controllers/trainerBillController.js index e17f574070..dcead18522 100644 --- a/src/controllers/trainerBillController.js +++ b/src/controllers/trainerBillController.js @@ -23,4 +23,18 @@ const create = async (req) => { } }; -module.exports = { create }; +const list = async (req) => { + try { + const trainerBills = await TrainerBillsHelper.list(req.query); + + return { + message: trainerBills.length ? translate[language].trainerBillsFound : translate[language].trainerBillsNotFound, + data: { trainerBills }, + }; + } catch (e) { + req.log('error', e); + return Boom.isBoom(e) ? e : Boom.badImplementation(e); + } +}; + +module.exports = { create, list }; diff --git a/src/helpers/trainerBills.js b/src/helpers/trainerBills.js index 71a790a7f0..427681898e 100644 --- a/src/helpers/trainerBills.js +++ b/src/helpers/trainerBills.js @@ -94,3 +94,9 @@ exports.createBill = async (payload, credentials) => { return trainerBill; }; + +exports.list = async query => TrainerBill + .find({ trainer: query.trainer }, { number: 1, amount: 1, submittedAt: 1, file: 1 }) + .populate({ path: 'payment', select: 'status' }) + .sort({ submittedAt: -1 }) + .lean(); diff --git a/src/helpers/translate.js b/src/helpers/translate.js index 9a706ccf0f..1de6db4f02 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -226,6 +226,8 @@ module.exports = { trainerBillNumberAlreadyUsed: 'This bill number is already used.', trainerBillUpdated: 'Trainer bill updated.', trainerBillRemoved: 'Trainer bill removed.', + trainerBillsFound: 'Trainer bills found.', + trainerBillsNotFound: 'Trainer bills not found.', trainerPaymentUpdated: 'Trainer payment updated.', trainerPaymentRemoved: 'Trainer payment removed.', trainerPaymentWrongStatus: 'Impossible : trainer payment is not pending.', @@ -607,6 +609,8 @@ module.exports = { trainerBillNumberAlreadyUsed: 'Ce numéro de facture est déjà utilisé.', trainerBillUpdated: 'Facture de l\'intervenant·e modifiée.', trainerBillRemoved: 'Facture de l\'intervenant·e annulée.', + trainerBillsFound: 'Factures de l\'intervenant·e trouvées.', + trainerBillsNotFound: 'Factures de l\'intervenant·e non trouvées.', trainerPaymentUpdated: 'Paiement de l\'intervenant·e modifié.', trainerPaymentRemoved: 'Paiement de l\'intervenant·e supprimé.', trainerPaymentWrongStatus: 'Suppression impossible : le paiement n\'est pas en attente.', diff --git a/src/routes/preHandlers/trainerBills.js b/src/routes/preHandlers/trainerBills.js index d9f25de8d2..3ef6f294dc 100644 --- a/src/routes/preHandlers/trainerBills.js +++ b/src/routes/preHandlers/trainerBills.js @@ -1,6 +1,7 @@ const Boom = require('@hapi/boom'); const CourseSlot = require('../../models/CourseSlot'); const TrainerBill = require('../../models/TrainerBill'); +const User = require('../../models/User'); const UtilsHelper = require('../../helpers/utils'); const translate = require('../../helpers/translate'); @@ -36,3 +37,15 @@ exports.authorizeTrainerBillCreation = async (req) => { return Boom.isBoom(e) ? e : Boom.badImplementation(e); } }; + +exports.authorizeTrainerBillsGet = async (req) => { + try { + const trainer = await User.countDocuments({ _id: req.query.trainer, 'role.vendor': { $exists: true } }); + if (!trainer) throw Boom.notFound(); + + return null; + } catch (e) { + req.log('error', e); + return Boom.isBoom(e) ? e : Boom.badImplementation(e); + } +}; diff --git a/src/routes/trainerBills.js b/src/routes/trainerBills.js index 1128f65e25..7b29897f1b 100644 --- a/src/routes/trainerBills.js +++ b/src/routes/trainerBills.js @@ -1,7 +1,7 @@ const Joi = require('joi'); Joi.objectId = require('joi-objectid')(Joi); -const { create } = require('../controllers/trainerBillController'); -const { authorizeTrainerBillCreation } = require('./preHandlers/trainerBills'); +const { create, list } = require('../controllers/trainerBillController'); +const { authorizeTrainerBillCreation, authorizeTrainerBillsGet } = require('./preHandlers/trainerBills'); const { formDataPayload, objectIdOrArray } = require('./validations/utils'); exports.plugin = { @@ -25,5 +25,18 @@ exports.plugin = { }, handler: create, }); + + server.route({ + method: 'GET', + path: '/', + options: { + auth: { scope: ['user:read-{query.trainer}'] }, + validate: { + query: Joi.object({ trainer: Joi.objectId().required() }), + }, + pre: [{ method: authorizeTrainerBillsGet }], + }, + handler: list, + }); }, }; diff --git a/tests/integration/seed/trainerBillsSeed.js b/tests/integration/seed/trainerBillsSeed.js index edbf5c8ca0..ee2ec5ba69 100644 --- a/tests/integration/seed/trainerBillsSeed.js +++ b/tests/integration/seed/trainerBillsSeed.js @@ -2,13 +2,14 @@ const { ObjectId } = require('mongodb'); const Course = require('../../../src/models/Course'); const CourseSlot = require('../../../src/models/CourseSlot'); const TrainerBill = require('../../../src/models/TrainerBill'); +const TrainerPayment = require('../../../src/models/TrainerPayment'); const Program = require('../../../src/models/Program'); const Step = require('../../../src/models/Step'); const SubProgram = require('../../../src/models/SubProgram'); const { authCompany } = require('../../seed/authCompaniesSeed'); const { deleteNonAuthenticationSeeds } = require('../helpers/db'); const { vendorAdmin, trainer, trainerAndCoach } = require('../../seed/authUsersSeed'); -const { INTRA, PUBLISHED, GLOBAL } = require('../../../src/helpers/constants'); +const { INTRA, PUBLISHED, GLOBAL, PENDING, PAID } = require('../../../src/helpers/constants'); const step = { _id: new ObjectId(), type: 'on_site', name: 'étape', status: PUBLISHED, theoreticalDuration: 60 }; @@ -105,6 +106,11 @@ const trainerBillList = [ }, ]; +const trainerPaymentList = [ + { _id: new ObjectId(), number: 'REG-00098', trainerBill: trainerBillId, amount: 100, status: PENDING }, + { _id: new ObjectId(), number: 'REG-00099', trainerBill: paidTrainerBillId, amount: 100, status: PAID }, +]; + const populateDB = async () => { await deleteNonAuthenticationSeeds(); @@ -115,6 +121,7 @@ const populateDB = async () => { Step.create(step), CourseSlot.create(courseSlotsList), TrainerBill.create(trainerBillList), + TrainerPayment.create(trainerPaymentList), ]); }; diff --git a/tests/integration/trainerBills.test.js b/tests/integration/trainerBills.test.js index 7f9bc54639..24fc70a45b 100644 --- a/tests/integration/trainerBills.test.js +++ b/tests/integration/trainerBills.test.js @@ -6,8 +6,8 @@ const TrainerBill = require('../../src/models/TrainerBill'); const TrainerPayment = require('../../src/models/TrainerPayment'); const CourseSlot = require('../../src/models/CourseSlot'); const GCloudStorageHelper = require('../../src/helpers/gCloudStorage'); -const { trainer, trainerAndCoach } = require('../seed/authUsersSeed'); -const { populateDB, courseSlotsList } = require('./seed/trainerBillsSeed'); +const { trainer, trainerAndCoach, coach } = require('../seed/authUsersSeed'); +const { populateDB, courseSlotsList, paidTrainerBillId } = require('./seed/trainerBillsSeed'); const { PENDING } = require('../../src/helpers/constants'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); const { generateFormData, getStream } = require('./utils'); @@ -265,3 +265,73 @@ describe('TRAINER BILLS ROUTES - POST /trainerbills', () => { }); }); }); + +describe('TRAINER BILLS ROUTES - GET /trainerbills', () => { + let authToken; + + beforeEach(async () => { + await populateDB(); + }); + + describe('TRAINER', () => { + beforeEach(async () => { + authToken = await getToken('trainer'); + }); + + it('should get own trainer bills, sorted by submission date', async () => { + const response = await app.inject({ + method: 'GET', + url: `/trainerbills?trainer=${trainer._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + expect(response.result.data.trainerBills.length).toBe(2); + expect(response.result.data.trainerBills[0]._id).toEqual(paidTrainerBillId); + }); + + it('should return 403 if trying to get other trainer\'s bills', async () => { + const response = await app.inject({ + method: 'GET', + url: `/trainerbills?trainer=${trainerAndCoach._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(403); + }); + }); + + describe('Other roles', () => { + it('should return 404 if user in query has no vendor role', async () => { + authToken = await getToken('coach'); + + const response = await app.inject({ + method: 'GET', + url: `/trainerbills?trainer=${coach._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(404); + }); + + const roles = [ + { name: 'helper', expectedCode: 403 }, + { name: 'planning_referent', expectedCode: 403 }, + { name: 'client_admin', expectedCode: 403 }, + { name: 'training_organisation_manager', expectedCode: 403 }, + ]; + roles.forEach((role) => { + it(`should return ${role.expectedCode} as user is ${role.name}`, async () => { + authToken = await getToken(role.name); + + const response = await app.inject({ + method: 'GET', + url: `/trainerbills?trainer=${trainer._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(role.expectedCode); + }); + }); + }); +}); diff --git a/tests/unit/helpers/trainerBills.test.js b/tests/unit/helpers/trainerBills.test.js index 327ba49c6d..4048fd68fe 100644 --- a/tests/unit/helpers/trainerBills.test.js +++ b/tests/unit/helpers/trainerBills.test.js @@ -296,3 +296,34 @@ describe('createBill', () => { ); }); }); + +describe('list', () => { + let trainerBillFind; + + beforeEach(() => { + trainerBillFind = sinon.stub(TrainerBill, 'find'); + }); + + afterEach(() => { + trainerBillFind.restore(); + }); + + it('should return the trainer bills', async () => { + const trainerId = new ObjectId(); + const trainerBills = [{ _id: new ObjectId(), number: 'FACT_0001', payment: { status: PENDING } }]; + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'sort', 'lean'])); + + const result = await TrainerBillsHelper.list({ trainer: trainerId }); + + expect(result).toEqual(trainerBills); + SinonMongoose.calledOnceWithExactly( + trainerBillFind, + [ + { query: 'find', args: [{ trainer: trainerId }, { number: 1, amount: 1, submittedAt: 1, file: 1 }] }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'sort', args: [{ submittedAt: -1 }] }, + { query: 'lean' }, + ] + ); + }); +}); From cbe851338419df108203519f7b190a3088b232ea Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 27 Oct 2026 17:39:51 +0100 Subject: [PATCH 02/53] COM-4314: can add hourly payment plan --- src/helpers/courseBills.js | 7 +- src/helpers/courses.js | 2 +- src/helpers/subPrograms.js | 24 +++++++ src/helpers/translate.js | 10 +++ src/models/Course.js | 1 + src/models/SubProgram.js | 11 +++ src/routes/courseBills.js | 1 + src/routes/preHandlers/courseBills.js | 20 +++++- src/routes/preHandlers/subPrograms.js | 39 ++++++++++- src/routes/subPrograms.js | 20 ++++++ tests/integration/courseBills.test.js | 38 +++++++++++ tests/integration/seed/courseBillsSeed.js | 13 +++- tests/integration/seed/subProgramsSeed.js | 3 + tests/integration/subPrograms.test.js | 81 ++++++++++++++++++++++- tests/unit/helpers/courseBills.test.js | 10 +++ tests/unit/helpers/courses.test.js | 8 +-- tests/unit/helpers/subPrograms.test.js | 54 +++++++++++++++ 17 files changed, 332 insertions(+), 10 deletions(-) diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 08826c5f70..005b328362 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -337,8 +337,13 @@ exports.createBillList = async (payload) => { vat = vendorCompany.vat; } + if (payload.hourlyPaymentPlanId) { + await Course.updateOne({ _id: payload.course }, { $set: { hourlyPaymentPlan: payload.hourlyPaymentPlanId } }); + } + if (payload.quantity === 1) { - const billCreated = await CourseBill.create({ ...omit(payload, 'quantity'), ...vat && { vat } }); + const billCreated = await CourseBill + .create({ ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), ...vat && { vat } }); if (payload.mainFee.percentage) { const trainerFees = (course.prices || []).reduce((acc, price) => { diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 19844f26a5..7e9c7f7afe 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -580,7 +580,7 @@ const getCourseForOperations = async (courseId, credentials, origin) => { }, { path: 'subProgram', - select: origin === WEBAPP ? 'program steps paymentPlans' : 'program steps', + select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans' : 'program steps', populate: [ { path: 'program', select: 'learningGoals' }, ...(origin === WEBAPP diff --git a/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 644b9d545e..394ee4e411 100644 --- a/src/helpers/subPrograms.js +++ b/src/helpers/subPrograms.js @@ -125,6 +125,30 @@ exports.updateSubProgram = async (subProgramId, payload) => { return SubProgram.updateOne({ _id: subProgramId }, { $push: { paymentPlans: { prices } } }); } + if (payload.hourlyPaymentPlan) { + const { hourlyPaymentPlanId, prices, elearningPrice } = payload.hourlyPaymentPlan; + + if (hourlyPaymentPlanId && prices.length) { + const updateQuery = elearningPrice + ? { $set: { 'hourlyPaymentPlans.$.prices': prices, 'hourlyPaymentPlans.$.elearningPrice': elearningPrice } } + : { $set: { 'hourlyPaymentPlans.$.prices': prices }, $unset: { 'hourlyPaymentPlans.$.elearningPrice': '' } }; + + return SubProgram.updateOne({ _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, updateQuery); + } + + if (hourlyPaymentPlanId && !prices.length) { + return SubProgram.updateOne( + { _id: subProgramId }, + { $pull: { hourlyPaymentPlans: { _id: hourlyPaymentPlanId } } } + ); + } + + return SubProgram.updateOne( + { _id: subProgramId }, + { $push: { hourlyPaymentPlans: { prices, ...elearningPrice && { elearningPrice } } } } + ); + } + const subProgram = await SubProgram .findOneAndUpdate({ _id: subProgramId }, { $set: { status: payload.status } }) .populate({ path: 'steps', select: 'activities type' }) diff --git a/src/helpers/translate.js b/src/helpers/translate.js index 9a706ccf0f..f719bb1413 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -105,6 +105,11 @@ module.exports = { trainerBillHourlyAmountNotFound: 'Unprocessable: trainer\'s role does not match any price for this step.', paidSlotsBeforeSubProgramEffectiveDate: 'Forbidden: a slot is paid after effectiveDate.', subProgramPaymentPlanNotFound: 'This payment plan does not exist.', + subProgramHourlyPaymentPlanNotFound: 'This hourly payment plan does not exist.', + subProgramHourlyPaymentPlanAlreadyExists: 'Forbidden: an identical hourly payment plan already exists.', + subProgramHourlyPaymentPlanNoELearningStep: 'Forbidden: this sub-program has no e-learning step.', + 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.', /* Steps */ stepUpdated: 'Step updated.', @@ -482,6 +487,11 @@ module.exports = { + 'cette étape.', paidSlotsBeforeSubProgramEffectiveDate: 'Impossible: un créneau est noté réglé après la date d\'effet renseignée.', subProgramPaymentPlanNotFound: 'Cet échéancier n\'existe pas.', + subProgramHourlyPaymentPlanNotFound: 'Cette tarification n\'existe pas.', + subProgramHourlyPaymentPlanAlreadyExists: 'Impossible : une tarification identique existe déjà.', + subProgramHourlyPaymentPlanNoELearningStep: 'Impossible : ce sous-programme n\'a pas d\'étape e-learning.', + 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à.', /* Steps */ stepsFound: 'Liste des étapes trouvée.', diff --git a/src/models/Course.js b/src/models/Course.js index fb8bc587b2..e5ff9198c4 100644 --- a/src/models/Course.js +++ b/src/models/Course.js @@ -129,6 +129,7 @@ const CourseSchema = mongoose.Schema({ })], default: undefined, }, + hourlyPaymentPlan: { type: mongoose.Schema.Types.ObjectId }, }, { timestamps: true }); CourseSchema.virtual('slots', { diff --git a/src/models/SubProgram.js b/src/models/SubProgram.js index 180428a686..e37cf8cba1 100644 --- a/src/models/SubProgram.js +++ b/src/models/SubProgram.js @@ -23,6 +23,17 @@ const SubProgramSchema = mongoose.Schema({ }], default: undefined, }, + hourlyPaymentPlans: { + type: [{ + prices: [{ + _id: false, + step: { type: mongoose.Schema.Types.ObjectId, ref: 'Step', required: true }, + hourlyAmount: { type: Number, required: true }, + }], + elearningPrice: { type: Number }, + }], + default: undefined, + }, paymentPlans: { type: [{ prices: { type: [Number], required: true } }], default: undefined }, subjectToVat: { type: Boolean }, sheetTemplateId: { type: String }, diff --git a/src/routes/courseBills.js b/src/routes/courseBills.js index 0b2ac1f245..46d3ec223c 100644 --- a/src/routes/courseBills.js +++ b/src/routes/courseBills.js @@ -92,6 +92,7 @@ exports.plugin = { }).xor('company', 'fundingOrganisation') .required(), maturityDate: Joi.when('quantity', { is: 1, then: requiredDateToISOString, otherwise: dateToISOString }), + hourlyPaymentPlanId: Joi.objectId(), }), }, pre: [{ method: authorizeCourseBillListCreation }], diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 8504c7facd..6014b269f4 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -20,14 +20,32 @@ const { const { language } = translate; exports.authorizeCourseBillListCreation = async (req) => { - const { course: courseId, companies: companiesIds, payer, mainFee, quantity, maturityDate } = req.payload; + const { + course: courseId, + companies: companiesIds, + payer, + mainFee, + quantity, + maturityDate, + hourlyPaymentPlanId, + } = req.payload; const course = await Course .findOne({ _id: courseId }, { type: 1, expectedBillsCount: 1, companies: 1, prices: 1, interruptionDates: 1 }) + .populate({ path: 'subProgram', select: 'hourlyPaymentPlans' }) .lean(); if (!course) throw Boom.notFound(); + if (hourlyPaymentPlanId) { + if (course.type !== SINGLE) throw Boom.forbidden(); + + const hourlyPaymentPlans = get(course, 'subProgram.hourlyPaymentPlans') || []; + if (!UtilsHelper.doesArrayIncludeId(hourlyPaymentPlans.map(hpp => hpp._id), hourlyPaymentPlanId)) { + throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); + } + } + const isCourseInterrupted = UtilsHelper.isCourseInterrupted(course.interruptionDates); if (isCourseInterrupted) throw Boom.forbidden(); diff --git a/src/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 4a966263d4..80a27ccbb4 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -73,7 +73,8 @@ exports.authorizeSubProgramUpdate = async (req) => { const isArchiving = has(req.payload, 'archivedAt') && !unarchiveSubProgram; if (isArchiving && subProgram.status !== PUBLISHED) throw Boom.forbidden(); - const allowedFieldsForPublishedSubProgram = req.payload.prices || req.payload.paymentPlan || req.payload.name || + const allowedFieldsForPublishedSubProgram = req.payload.prices || req.payload.paymentPlan || + req.payload.hourlyPaymentPlan || req.payload.name || has(req.payload, 'subjectToVat') || has(req.payload, 'archivedAt'); if (subProgram.status !== DRAFT && !allowedFieldsForPublishedSubProgram) throw Boom.forbidden(); @@ -159,6 +160,10 @@ exports.authorizeSubProgramUpdate = async (req) => { if (req.payload.paymentPlan) { if (subProgram.status !== PUBLISHED) throw Boom.forbidden(); + if ((subProgram.hourlyPaymentPlans || []).length) { + throw Boom.forbidden(translate[language].subProgramHasHourlyPaymentPlan); + } + const { paymentPlanId, prices } = req.payload.paymentPlan; if (paymentPlanId) { const paymentPlanExists = UtilsHelper @@ -171,6 +176,38 @@ exports.authorizeSubProgramUpdate = async (req) => { if (isDuplicate) throw Boom.forbidden(translate[language].subProgramPaymentPlanAlreadyExists); } + if (req.payload.hourlyPaymentPlan) { + if (subProgram.status !== PUBLISHED) throw Boom.forbidden(); + if ((subProgram.paymentPlans || []).length) throw Boom.forbidden(translate[language].subProgramHasPaymentPlan); + + const { hourlyPaymentPlanId, prices, elearningPrice } = req.payload.hourlyPaymentPlan; + if (hourlyPaymentPlanId) { + const hourlyPaymentPlanExists = UtilsHelper + .doesArrayIncludeId((subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id), hourlyPaymentPlanId); + if (!hourlyPaymentPlanExists) throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); + } + + if (prices.length) { + const nonELearningStepIds = subProgram.steps.filter(s => s.type !== E_LEARNING).map(s => s._id); + const pricedStepIds = prices.map(p => p.step); + const areStepsInvalid = pricedStepIds.length !== nonELearningStepIds.length || + nonELearningStepIds.some(stepId => !UtilsHelper.doesArrayIncludeId(pricedStepIds, stepId)); + if (areStepsInvalid) throw Boom.forbidden(translate[language].subProgramMissingStepPrice); + + const isDuplicate = (subProgram.hourlyPaymentPlans || []) + .some(hpp => !UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId) && + hpp.elearningPrice === elearningPrice && + 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)) { + throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanNoELearningStep); + } + } + return null; }; diff --git a/src/routes/subPrograms.js b/src/routes/subPrograms.js index b33b77871e..f0705d5f3e 100644 --- a/src/routes/subPrograms.js +++ b/src/routes/subPrograms.js @@ -65,6 +65,26 @@ exports.plugin = { }), }).required(), }), + Joi.object({ + hourlyPaymentPlan: Joi.object({ + hourlyPaymentPlanId: Joi.objectId(), + prices: Joi.when('hourlyPaymentPlanId', { + is: Joi.exist(), + then: Joi.array().items({ + step: Joi.objectId().required(), + hourlyAmount: Joi.number().positive().required(), + }), + otherwise: Joi.array() + .items({ + step: Joi.objectId().required(), + hourlyAmount: Joi.number().positive().required(), + }) + .min(1) + .required(), + }), + elearningPrice: Joi.number().positive(), + }).required(), + }), Joi.object({ archivedAt: Joi.date().allow('') }) ), }, diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index ae8abd1c39..099ce16d3d 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -3,6 +3,7 @@ const { expect } = require('expect'); const { ObjectId } = require('mongodb'); const set = require('lodash/set'); const omit = require('lodash/omit'); +const Course = require('../../src/models/Course'); const CourseBill = require('../../src/models/CourseBill'); const app = require('../../server'); const { @@ -11,6 +12,7 @@ const { coursesList, courseFundingOrganisationList, billingItemList, + hourlyPaymentPlanId, } = require('./seed/courseBillsSeed'); const { authCompany, otherCompany, companyWithoutSubscription } = require('../seed/authCompaniesSeed'); @@ -884,6 +886,42 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(billsCountAfter).toBe(billsCountBefore + 2); }); + it('should create a bill and link the hourly payment plan to a SINGLE course', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(200); + + const course = await Course.findOne({ _id: coursesList[12]._id }, { hourlyPaymentPlan: 1 }).lean(); + expect(course.hourlyPaymentPlan).toEqual(hourlyPaymentPlanId); + }); + + it('should return 404 if hourly payment plan does not exist on the subProgram', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, hourlyPaymentPlanId: new ObjectId() }, + }); + + expect(response.statusCode).toBe(404); + }); + + it('should return 403 if hourly payment plan is sent for a non SINGLE course', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...intraCoursePayload, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should create several bills for SINGLE course with prices array', async () => { const billsCountBefore = await CourseBill.countDocuments({ course: coursesList[12]._id }); diff --git a/tests/integration/seed/courseBillsSeed.js b/tests/integration/seed/courseBillsSeed.js index db48837ae5..ed9cb860ba 100644 --- a/tests/integration/seed/courseBillsSeed.js +++ b/tests/integration/seed/courseBillsSeed.js @@ -32,7 +32,17 @@ const { trainer, vendorAdmin, auxiliary } = require('../../seed/authUsersSeed'); const steps = [{ _id: new ObjectId(), type: 'on_site', name: 'étape', status: PUBLISHED, theoreticalDuration: 60 }]; -const subProgramList = [{ _id: new ObjectId(), name: 'subProgram 1', steps: [steps[0]._id], status: PUBLISHED }]; +const hourlyPaymentPlanId = new ObjectId(); + +const subProgramList = [ + { + _id: new ObjectId(), + name: 'subProgram 1', + steps: [steps[0]._id], + status: PUBLISHED, + hourlyPaymentPlans: [{ _id: hourlyPaymentPlanId, prices: [{ step: steps[0]._id, hourlyAmount: 50 }] }], + }, +]; const programList = [{ _id: new ObjectId(), name: 'Program 1', subPrograms: [subProgramList[0]._id] }]; @@ -628,4 +638,5 @@ module.exports = { courseFundingOrganisationList, coursesList, billingItemList, + hourlyPaymentPlanId, }; diff --git a/tests/integration/seed/subProgramsSeed.js b/tests/integration/seed/subProgramsSeed.js index 4cfc1fbdd8..3eaa3c8c3f 100644 --- a/tests/integration/seed/subProgramsSeed.js +++ b/tests/integration/seed/subProgramsSeed.js @@ -102,6 +102,7 @@ const stepsList = [ ]; const paymentPlanId = new ObjectId(); +const hourlyPaymentPlanId = new ObjectId(); const subProgramsList = [ { _id: new ObjectId(), name: 'subProgram 0', status: DRAFT, steps: [stepsList[0]._id, stepsList[1]._id] }, @@ -159,6 +160,7 @@ const subProgramsList = [ name: 'subProgram 13', status: PUBLISHED, steps: [stepsList[0]._id], + hourlyPaymentPlans: [{ _id: hourlyPaymentPlanId, prices: [{ step: stepsList[0]._id, hourlyAmount: 40 }] }], }, { // 14 draft, e-learning - to be published on program 3, where subProgram 11 is already archived+published _id: new ObjectId(), @@ -301,4 +303,5 @@ module.exports = { cardsList, tester, paymentPlanId, + hourlyPaymentPlanId, }; diff --git a/tests/integration/subPrograms.test.js b/tests/integration/subPrograms.test.js index cce94ff6fc..17e6ba18be 100644 --- a/tests/integration/subPrograms.test.js +++ b/tests/integration/subPrograms.test.js @@ -10,7 +10,14 @@ const Step = require('../../src/models/Step'); const NotificationHelper = require('../../src/helpers/notifications'); const UtilsHelper = require('../../src/helpers/utils'); const { VAEI_COACH, ARCHITECT } = require('../../src/helpers/constants'); -const { populateDB, subProgramsList, stepsList, tester, paymentPlanId } = require('./seed/subProgramsSeed'); +const { + populateDB, + subProgramsList, + stepsList, + tester, + paymentPlanId, + hourlyPaymentPlanId, +} = require('./seed/subProgramsSeed'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); const { authCompany, otherCompany } = require('../seed/authCompaniesSeed'); @@ -482,6 +489,78 @@ describe('SUBPROGRAMS ROUTES - PUT /subprograms/{_id}', () => { expect(updatedSubProgram.paymentPlans.length).toBe(2); }); + it('should add a new hourly payment plan', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(200); + const updatedSubProgram = await SubProgram.findById(subProgramsList[13]._id).lean(); + expect(updatedSubProgram.hourlyPaymentPlans.length).toBe(2); + }); + + it('should update an existing hourly payment plan', async () => { + const payload = { + hourlyPaymentPlan: { hourlyPaymentPlanId, prices: [{ step: stepsList[0]._id, hourlyAmount: 70 }] }, + }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(200); + const updatedSubProgram = await SubProgram.findById(subProgramsList[13]._id).lean(); + expect(updatedSubProgram.hourlyPaymentPlans.length).toBe(1); + expect(updatedSubProgram.hourlyPaymentPlans[0].prices[0].hourlyAmount).toBe(70); + }); + + it('should return 403 if an identical hourly payment plan already exists', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 40 }] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(403); + }); + + it('should return 403 if adding payment plan on a subProgram with hourly payment plans', async () => { + const payload = { paymentPlan: { prices: [100, 200] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(403); + }); + + it('should return 403 if adding hourly payment plan on a subProgram with payment plans', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[2]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 404 if payment plan _id does not exist', async () => { const payload = { paymentPlan: { paymentPlanId: new ObjectId(), prices: [100] } }; diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index c3b7b0aa08..70204dbb13 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -1147,6 +1147,7 @@ describe('list', () => { describe('createBillList', () => { let findOneCourse; + let updateOneCourse; let createCourseBill; let insertManyCourseBills; let addBillingPurchase; @@ -1155,6 +1156,7 @@ describe('createBillList', () => { beforeEach(() => { findOneCourse = sinon.stub(Course, 'findOne'); + updateOneCourse = sinon.stub(Course, 'updateOne'); createCourseBill = sinon.stub(CourseBill, 'create'); insertManyCourseBills = sinon.stub(CourseBill, 'insertMany'); addBillingPurchase = sinon.stub(CourseBillHelper, 'addBillingPurchase'); @@ -1164,6 +1166,7 @@ describe('createBillList', () => { afterEach(() => { findOneCourse.restore(); + updateOneCourse.restore(); createCourseBill.restore(); insertManyCourseBills.restore(); addBillingPurchase.restore(); @@ -1180,12 +1183,19 @@ describe('createBillList', () => { companies: [new ObjectId()], payer: { fundingOrganisation: new ObjectId() }, maturityDate: '2025-04-29T22:00:00.000Z', + hourlyPaymentPlanId: new ObjectId(), }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); await CourseBillHelper.createBillList(payload); + sinon.assert.calledOnceWithExactly( + updateOneCourse, + { _id: payload.course }, + { $set: { hourlyPaymentPlan: payload.hourlyPaymentPlanId } } + ); + sinon.assert.calledOnceWithExactly( createCourseBill, { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index e75585aed0..935d9b41c5 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -2886,7 +2886,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3001,7 +3001,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3109,7 +3109,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3291,7 +3291,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans', populate: [ { path: 'program', select: 'learningGoals' }, { diff --git a/tests/unit/helpers/subPrograms.test.js b/tests/unit/helpers/subPrograms.test.js index 52628bee2a..aa82ae32dc 100644 --- a/tests/unit/helpers/subPrograms.test.js +++ b/tests/unit/helpers/subPrograms.test.js @@ -820,6 +820,60 @@ describe('updateSubProgram', () => { }); }); + describe('update hourly payment plan', () => { + 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 } }; + + await SubProgramHelper.updateSubProgram(subProgramId, payload); + + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: subProgramId }, + { $push: { hourlyPaymentPlans: { prices: [{ step: stepId, hourlyAmount: 50 }], elearningPrice: 30 } } } + ); + sinon.assert.notCalled(findOne); + sinon.assert.notCalled(findOneAndUpdate); + }); + + it('should update an existing plan if payload.hourlyPaymentPlan has an id and prices', async () => { + const subProgramId = new ObjectId(); + const hourlyPaymentPlanId = new ObjectId(); + const prices = [{ step: new ObjectId(), hourlyAmount: 60 }]; + const payload = { hourlyPaymentPlan: { hourlyPaymentPlanId, prices } }; + + await SubProgramHelper.updateSubProgram(subProgramId, payload); + + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, + { + $set: { 'hourlyPaymentPlans.$.prices': prices }, + $unset: { 'hourlyPaymentPlans.$.elearningPrice': '' }, + } + ); + sinon.assert.notCalled(findOne); + sinon.assert.notCalled(findOneAndUpdate); + }); + + it('should delete a plan if payload.hourlyPaymentPlan has an id and empty prices', async () => { + const subProgramId = new ObjectId(); + const hourlyPaymentPlanId = new ObjectId(); + const payload = { hourlyPaymentPlan: { hourlyPaymentPlanId, prices: [] } }; + + await SubProgramHelper.updateSubProgram(subProgramId, payload); + + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: subProgramId }, + { $pull: { hourlyPaymentPlans: { _id: hourlyPaymentPlanId } } } + ); + sinon.assert.notCalled(findOne); + sinon.assert.notCalled(findOneAndUpdate); + }); + }); + describe('update payment plan', () => { it('should add a new payment plan if payload.paymentPlan has no _id', async () => { const subProgramId = new ObjectId(); From 00a50f266318c28b184dccc9f68bf3e83292384f Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 12:38:33 +0100 Subject: [PATCH 03/53] COM-4314: fix bug --- src/helpers/translate.js | 2 ++ src/routes/preHandlers/courseBills.js | 13 ++++++++++++- src/routes/preHandlers/subPrograms.js | 4 ++++ tests/integration/courseBills.test.js | 13 +++++++++++++ tests/integration/seed/subProgramsSeed.js | 16 +++++++++++++++- tests/integration/subPrograms.test.js | 13 +++++++++++++ 6 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/helpers/translate.js b/src/helpers/translate.js index f719bb1413..6ea57f774e 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -106,6 +106,7 @@ module.exports = { paidSlotsBeforeSubProgramEffectiveDate: 'Forbidden: a slot is paid after effectiveDate.', subProgramPaymentPlanNotFound: 'This payment plan does not exist.', subProgramHourlyPaymentPlanNotFound: 'This hourly payment plan does not exist.', + 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.', subProgramHasPaymentPlan: 'Forbidden: this sub-program already has payment plans.', @@ -488,6 +489,7 @@ module.exports = { paidSlotsBeforeSubProgramEffectiveDate: 'Impossible: un créneau est noté réglé après la date d\'effet renseignée.', subProgramPaymentPlanNotFound: 'Cet échéancier n\'existe pas.', subProgramHourlyPaymentPlanNotFound: 'Cette tarification n\'existe pas.', + subProgramHourlyPaymentPlanUsed: 'Impossible : cette tarification est utilisée par une formation.', subProgramHourlyPaymentPlanAlreadyExists: 'Impossible : une tarification identique existe déjà.', subProgramHourlyPaymentPlanNoELearningStep: 'Impossible : ce sous-programme n\'a pas d\'étape e-learning.', subProgramHasPaymentPlan: 'Impossible : ce sous-programme a déjà des échéanciers.', diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 6014b269f4..26d2f22542 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -31,7 +31,14 @@ exports.authorizeCourseBillListCreation = async (req) => { } = req.payload; const course = await Course - .findOne({ _id: courseId }, { type: 1, expectedBillsCount: 1, companies: 1, prices: 1, interruptionDates: 1 }) + .findOne({ _id: courseId }, { + type: 1, + expectedBillsCount: 1, + companies: 1, + prices: 1, + interruptionDates: 1, + hourlyPaymentPlan: 1, + }) .populate({ path: 'subProgram', select: 'hourlyPaymentPlans' }) .lean(); @@ -44,6 +51,10 @@ exports.authorizeCourseBillListCreation = async (req) => { if (!UtilsHelper.doesArrayIncludeId(hourlyPaymentPlans.map(hpp => hpp._id), hourlyPaymentPlanId)) { throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); } + + if (course.hourlyPaymentPlan && !UtilsHelper.areObjectIdsEquals(course.hourlyPaymentPlan, hourlyPaymentPlanId)) { + throw Boom.forbidden(); + } } const isCourseInterrupted = UtilsHelper.isCourseInterrupted(course.interruptionDates); diff --git a/src/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 80a27ccbb4..68a0979c6f 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -185,6 +185,10 @@ exports.authorizeSubProgramUpdate = async (req) => { const hourlyPaymentPlanExists = UtilsHelper .doesArrayIncludeId((subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id), hourlyPaymentPlanId); if (!hourlyPaymentPlanExists) throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); + + const isUsedByCourse = !prices.length && subProgram.courses + .some(c => UtilsHelper.areObjectIdsEquals(c.hourlyPaymentPlan, hourlyPaymentPlanId)); + if (isUsedByCourse) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanUsed); } if (prices.length) { diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index 099ce16d3d..0436f26de0 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -911,6 +911,19 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(404); }); + it('should return 403 if the course already has another hourly payment plan', async () => { + await Course.updateOne({ _id: coursesList[12]._id }, { $set: { hourlyPaymentPlan: new ObjectId() } }); + + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 403 if hourly payment plan is sent for a non SINGLE course', async () => { const response = await app.inject({ method: 'POST', diff --git a/tests/integration/seed/subProgramsSeed.js b/tests/integration/seed/subProgramsSeed.js index 3eaa3c8c3f..f49544c093 100644 --- a/tests/integration/seed/subProgramsSeed.js +++ b/tests/integration/seed/subProgramsSeed.js @@ -12,7 +12,7 @@ const User = require('../../../src/models/User'); const UserCompany = require('../../../src/models/UserCompany'); const { vendorAdmin, trainer } = require('../../seed/authUsersSeed'); const { deleteNonAuthenticationSeeds } = require('../helpers/db'); -const { WEBAPP, INTRA, PUBLISHED, DRAFT, GLOBAL, PAID } = require('../../../src/helpers/constants'); +const { WEBAPP, INTRA, PUBLISHED, DRAFT, GLOBAL, PAID, MONTHLY } = require('../../../src/helpers/constants'); const { authCompany } = require('../../seed/authCompaniesSeed'); const tester = { @@ -242,6 +242,20 @@ const coursesList = [ accessRules: [], tradeName: 'program 5', }, + { // course using the hourly payment plan of subProgram 13 + _id: new ObjectId(), + format: 'blended', + subProgram: subProgramsList[13]._id, + hourlyPaymentPlan: hourlyPaymentPlanId, + type: INTRA, + trainees: [], + accessRules: [], + companies: [authCompany._id], + operationsRepresentative: vendorAdmin._id, + tradeName: 'hourly plan', + certificateGenerationMode: MONTHLY, + maxTrainees: 3, + }, ]; const trainerBillId = new ObjectId(); diff --git a/tests/integration/subPrograms.test.js b/tests/integration/subPrograms.test.js index 17e6ba18be..bef63abb11 100644 --- a/tests/integration/subPrograms.test.js +++ b/tests/integration/subPrograms.test.js @@ -522,6 +522,19 @@ describe('SUBPROGRAMS ROUTES - PUT /subprograms/{_id}', () => { expect(updatedSubProgram.hourlyPaymentPlans[0].prices[0].hourlyAmount).toBe(70); }); + it('should return 403 if deleting an hourly payment plan used by a course', async () => { + const payload = { hourlyPaymentPlan: { hourlyPaymentPlanId, prices: [] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._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 }] } }; From a55b67ed4c210ecdeeade729ba3a6328591209e4 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 28 Oct 2026 15:20:53 +0100 Subject: [PATCH 04/53] COM-4313 - review --- src/controllers/trainerBillController.js | 2 +- src/helpers/trainerBills.js | 4 +-- src/routes/preHandlers/trainerBills.js | 13 ---------- src/routes/trainerBills.js | 8 ++---- tests/integration/trainerBills.test.js | 31 ++++++++++++++---------- tests/unit/helpers/trainerBills.test.js | 9 ++++--- 6 files changed, 29 insertions(+), 38 deletions(-) diff --git a/src/controllers/trainerBillController.js b/src/controllers/trainerBillController.js index dcead18522..19c54f25f0 100644 --- a/src/controllers/trainerBillController.js +++ b/src/controllers/trainerBillController.js @@ -25,7 +25,7 @@ const create = async (req) => { const list = async (req) => { try { - const trainerBills = await TrainerBillsHelper.list(req.query); + const trainerBills = await TrainerBillsHelper.list(req.auth.credentials); return { message: trainerBills.length ? translate[language].trainerBillsFound : translate[language].trainerBillsNotFound, diff --git a/src/helpers/trainerBills.js b/src/helpers/trainerBills.js index 427681898e..63795d1f28 100644 --- a/src/helpers/trainerBills.js +++ b/src/helpers/trainerBills.js @@ -95,8 +95,8 @@ exports.createBill = async (payload, credentials) => { return trainerBill; }; -exports.list = async query => TrainerBill - .find({ trainer: query.trainer }, { number: 1, amount: 1, submittedAt: 1, file: 1 }) +exports.list = async credentials => TrainerBill + .find({ trainer: credentials._id }, { number: 1, amount: 1, submittedAt: 1, file: 1 }) .populate({ path: 'payment', select: 'status' }) .sort({ submittedAt: -1 }) .lean(); diff --git a/src/routes/preHandlers/trainerBills.js b/src/routes/preHandlers/trainerBills.js index 3ef6f294dc..d9f25de8d2 100644 --- a/src/routes/preHandlers/trainerBills.js +++ b/src/routes/preHandlers/trainerBills.js @@ -1,7 +1,6 @@ const Boom = require('@hapi/boom'); const CourseSlot = require('../../models/CourseSlot'); const TrainerBill = require('../../models/TrainerBill'); -const User = require('../../models/User'); const UtilsHelper = require('../../helpers/utils'); const translate = require('../../helpers/translate'); @@ -37,15 +36,3 @@ exports.authorizeTrainerBillCreation = async (req) => { return Boom.isBoom(e) ? e : Boom.badImplementation(e); } }; - -exports.authorizeTrainerBillsGet = async (req) => { - try { - const trainer = await User.countDocuments({ _id: req.query.trainer, 'role.vendor': { $exists: true } }); - if (!trainer) throw Boom.notFound(); - - return null; - } catch (e) { - req.log('error', e); - return Boom.isBoom(e) ? e : Boom.badImplementation(e); - } -}; diff --git a/src/routes/trainerBills.js b/src/routes/trainerBills.js index 7b29897f1b..68f4b9213d 100644 --- a/src/routes/trainerBills.js +++ b/src/routes/trainerBills.js @@ -1,7 +1,7 @@ const Joi = require('joi'); Joi.objectId = require('joi-objectid')(Joi); const { create, list } = require('../controllers/trainerBillController'); -const { authorizeTrainerBillCreation, authorizeTrainerBillsGet } = require('./preHandlers/trainerBills'); +const { authorizeTrainerBillCreation } = require('./preHandlers/trainerBills'); const { formDataPayload, objectIdOrArray } = require('./validations/utils'); exports.plugin = { @@ -30,11 +30,7 @@ exports.plugin = { method: 'GET', path: '/', options: { - auth: { scope: ['user:read-{query.trainer}'] }, - validate: { - query: Joi.object({ trainer: Joi.objectId().required() }), - }, - pre: [{ method: authorizeTrainerBillsGet }], + auth: { scope: ['trainerbills:create'] }, }, handler: list, }); diff --git a/tests/integration/trainerBills.test.js b/tests/integration/trainerBills.test.js index 24fc70a45b..c952195687 100644 --- a/tests/integration/trainerBills.test.js +++ b/tests/integration/trainerBills.test.js @@ -6,7 +6,7 @@ const TrainerBill = require('../../src/models/TrainerBill'); const TrainerPayment = require('../../src/models/TrainerPayment'); const CourseSlot = require('../../src/models/CourseSlot'); const GCloudStorageHelper = require('../../src/helpers/gCloudStorage'); -const { trainer, trainerAndCoach, coach } = require('../seed/authUsersSeed'); +const { trainer, trainerAndCoach } = require('../seed/authUsersSeed'); const { populateDB, courseSlotsList, paidTrainerBillId } = require('./seed/trainerBillsSeed'); const { PENDING } = require('../../src/helpers/constants'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); @@ -281,7 +281,7 @@ describe('TRAINER BILLS ROUTES - GET /trainerbills', () => { it('should get own trainer bills, sorted by submission date', async () => { const response = await app.inject({ method: 'GET', - url: `/trainerbills?trainer=${trainer._id}`, + url: '/trainerbills', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, }); @@ -289,36 +289,41 @@ describe('TRAINER BILLS ROUTES - GET /trainerbills', () => { expect(response.result.data.trainerBills.length).toBe(2); expect(response.result.data.trainerBills[0]._id).toEqual(paidTrainerBillId); }); + }); + + describe('Other trainer', () => { + it('should not get other trainer\'s bills', async () => { + authToken = await getTokenByCredentials(trainerAndCoach.local); - it('should return 403 if trying to get other trainer\'s bills', async () => { const response = await app.inject({ method: 'GET', - url: `/trainerbills?trainer=${trainerAndCoach._id}`, + url: '/trainerbills', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, }); - expect(response.statusCode).toBe(403); + expect(response.statusCode).toBe(200); + expect(response.result.data.trainerBills.length).toBe(0); }); - }); - describe('Other roles', () => { - it('should return 404 if user in query has no vendor role', async () => { - authToken = await getToken('coach'); + it('should not get other trainer\'s bills as user is training_organisation_manager', async () => { + authToken = await getToken('training_organisation_manager'); const response = await app.inject({ method: 'GET', - url: `/trainerbills?trainer=${coach._id}`, + url: '/trainerbills', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, }); - expect(response.statusCode).toBe(404); + expect(response.statusCode).toBe(200); + expect(response.result.data.trainerBills.length).toBe(0); }); + }); + describe('Other roles', () => { const roles = [ { name: 'helper', expectedCode: 403 }, { name: 'planning_referent', expectedCode: 403 }, { name: 'client_admin', expectedCode: 403 }, - { name: 'training_organisation_manager', expectedCode: 403 }, ]; roles.forEach((role) => { it(`should return ${role.expectedCode} as user is ${role.name}`, async () => { @@ -326,7 +331,7 @@ describe('TRAINER BILLS ROUTES - GET /trainerbills', () => { const response = await app.inject({ method: 'GET', - url: `/trainerbills?trainer=${trainer._id}`, + url: '/trainerbills', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, }); diff --git a/tests/unit/helpers/trainerBills.test.js b/tests/unit/helpers/trainerBills.test.js index 4048fd68fe..3562a6ac4b 100644 --- a/tests/unit/helpers/trainerBills.test.js +++ b/tests/unit/helpers/trainerBills.test.js @@ -310,16 +310,19 @@ describe('list', () => { it('should return the trainer bills', async () => { const trainerId = new ObjectId(); - const trainerBills = [{ _id: new ObjectId(), number: 'FACT_0001', payment: { status: PENDING } }]; + const credentials = { _id: trainerId }; + const trainerBills = [ + { _id: new ObjectId(), number: 'FACT_0001', payment: { status: PENDING }, trainer: trainerId }, + ]; trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'sort', 'lean'])); - const result = await TrainerBillsHelper.list({ trainer: trainerId }); + const result = await TrainerBillsHelper.list(credentials); expect(result).toEqual(trainerBills); SinonMongoose.calledOnceWithExactly( trainerBillFind, [ - { query: 'find', args: [{ trainer: trainerId }, { number: 1, amount: 1, submittedAt: 1, file: 1 }] }, + { query: 'find', args: [{ trainer: credentials._id }, { number: 1, amount: 1, submittedAt: 1, file: 1 }] }, { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, { query: 'sort', args: [{ submittedAt: -1 }] }, { query: 'lean' }, From e3e6601366737d945f053332d78c4db49c36d70d Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:40:51 +0100 Subject: [PATCH 05/53] COM-4318: mask infos function --- src/helpers/utils.js | 7 +++++++ tests/unit/helpers/utils.test.js | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/helpers/utils.js b/src/helpers/utils.js index f41feaa5e7..b6225682f8 100644 --- a/src/helpers/utils.js +++ b/src/helpers/utils.js @@ -194,6 +194,13 @@ exports.doesArrayIncludeId = (array, id) => !!array && array.some(item => export exports.isStringedObjectId = value => typeof value === 'string' && !!value.match(/^[0-9a-fA-F]{24}$/); +exports.maskBankInfo = (value) => { + if (!value) return undefined; + if (value.length <= 4) return '*'.repeat(value.length); + + return `${value.slice(0, 2)}${'*'.repeat(value.length - 4)}${value.slice(-2)}`; +}; + exports.formatPhone = contact => (contact.phone ? `${contact.countryCode} ${contact.phone.substring(1) .replace(/^(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1 $2 $3 $4 $5')}` diff --git a/tests/unit/helpers/utils.test.js b/tests/unit/helpers/utils.test.js index 3670e35ddc..64761fc62e 100644 --- a/tests/unit/helpers/utils.test.js +++ b/tests/unit/helpers/utils.test.js @@ -978,3 +978,18 @@ describe('getVAESupportConfigs', () => { expect(result).toEqual(undefined); }); }); + +describe('maskBankInfo', () => { + it('should keep the first and last two characters and mask the rest', () => { + expect(UtilsHelper.maskBankInfo('FR3514508000505917721779B12')).toEqual('FR***********************12'); + }); + + it('should mask everything if value is too short', () => { + expect(UtilsHelper.maskBankInfo('FR12')).toEqual('****'); + }); + + it('should return undefined if empty', () => { + expect(UtilsHelper.maskBankInfo(undefined)).toBeUndefined(); + expect(UtilsHelper.maskBankInfo('')).toBeUndefined(); + }); +}); From caeffa806366db71b670f1690afa33c82baeb494 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:42:49 +0100 Subject: [PATCH 06/53] COM-4318: vendorCompany --- src/controllers/vendorCompanyController.js | 2 +- src/helpers/vendorCompanies.js | 19 +++++++++++++++---- tests/integration/vendorCompanies.test.js | 8 ++++---- tests/unit/helpers/vendorCompanies.test.js | 13 ++++++++++++- 4 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/controllers/vendorCompanyController.js b/src/controllers/vendorCompanyController.js index 0df8085b5f..76e95d42a9 100644 --- a/src/controllers/vendorCompanyController.js +++ b/src/controllers/vendorCompanyController.js @@ -6,7 +6,7 @@ const { language } = translate; const get = async (req) => { try { - const vendorCompany = await VendorCompaniesHelper.get(); + const vendorCompany = await VendorCompaniesHelper.get(true); return { message: translate[language].vendorCompanyFound, diff --git a/src/helpers/vendorCompanies.js b/src/helpers/vendorCompanies.js index e04dd93704..84b931e486 100644 --- a/src/helpers/vendorCompanies.js +++ b/src/helpers/vendorCompanies.js @@ -1,11 +1,22 @@ const VendorCompany = require('../models/VendorCompany'); const drive = require('../models/Google/Drive'); const GDriveStorageHelper = require('./gDriveStorage'); +const UtilsHelper = require('./utils'); -exports.get = async () => VendorCompany - .findOne() - .populate({ path: 'billingRepresentative', select: '_id picture contact identity local' }) - .lean(); +exports.get = async (shouldMaskBankInfos = false) => { + const vendorCompany = await VendorCompany + .findOne() + .populate({ path: 'billingRepresentative', select: '_id picture contact identity local' }) + .lean(); + + if (!shouldMaskBankInfos) return vendorCompany; + + return { + ...vendorCompany, + iban: UtilsHelper.maskBankInfo(vendorCompany.iban), + bic: UtilsHelper.maskBankInfo(vendorCompany.bic), + }; +}; exports.update = async payload => VendorCompany.updateOne({}, { $set: payload }); diff --git a/tests/integration/vendorCompanies.test.js b/tests/integration/vendorCompanies.test.js index b81149524b..ed05ce1540 100644 --- a/tests/integration/vendorCompanies.test.js +++ b/tests/integration/vendorCompanies.test.js @@ -34,8 +34,8 @@ describe('VENDOR COMPANY ROUTES - GET /vendorcompanies', () => { expect(response.result.data.vendorCompany).toMatchObject({ name: 'Test Company', siret: '12345678901234', - iban: 'FR9210096000302523177152Q14', - bic: 'BPCEFRPP', + iban: 'FR***********************14', + bic: 'BP****PP', ics: 'FR1234567890D', address: { fullAddress: '12 rue du test 92160 Antony', @@ -70,8 +70,8 @@ describe('VENDOR COMPANY ROUTES - GET /vendorcompanies', () => { expect(response.result.data.vendorCompany).toMatchObject({ name: 'Test Company', siret: '12345678901234', - iban: 'FR9210096000302523177152Q14', - bic: 'BPCEFRPP', + iban: 'FR***********************14', + bic: 'BP****PP', address: { fullAddress: '12 rue du test 92160 Antony', street: '12 rue du test', diff --git a/tests/unit/helpers/vendorCompanies.test.js b/tests/unit/helpers/vendorCompanies.test.js index 9773480a3b..4884e75e57 100644 --- a/tests/unit/helpers/vendorCompanies.test.js +++ b/tests/unit/helpers/vendorCompanies.test.js @@ -1,3 +1,4 @@ +const { expect } = require('expect'); const { ObjectId } = require('mongodb'); const sinon = require('sinon'); const VendorCompany = require('../../../src/models/VendorCompany'); @@ -28,8 +29,9 @@ describe('get', () => { }; findOne.returns(SinonMongoose.stubChainedQueries(vendorCompany)); - await VendorCompaniesHelper.get(); + const result = await VendorCompaniesHelper.get(); + expect(result).toEqual(vendorCompany); SinonMongoose.calledOnceWithExactly( findOne, [ @@ -41,6 +43,15 @@ describe('get', () => { { query: 'lean' }, ]); }); + + it('should return vendor company infos with masked iban and bic', async () => { + const vendorCompany = { name: 'Company', iban: 'FR3514508000505917721779B12', bic: 'WERTFRPP' }; + findOne.returns(SinonMongoose.stubChainedQueries(vendorCompany)); + + const result = await VendorCompaniesHelper.get(true); + + expect(result).toEqual({ name: 'Company', iban: 'FR***********************12', bic: 'WE****PP' }); + }); }); describe('update', () => { From 3fd2baef5b29a9b1c7c3bf31e2c1318a765e7f5a Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:47:24 +0100 Subject: [PATCH 07/53] COM-4318: user --- src/helpers/users.js | 12 +++++++++--- tests/unit/helpers/users.test.js | 8 +++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/helpers/users.js b/src/helpers/users.js index e2fe9f2ccf..ac4d5de06a 100644 --- a/src/helpers/users.js +++ b/src/helpers/users.js @@ -102,7 +102,7 @@ exports.formatQueryForUsersList = async (query) => { exports.getUsersList = async (query, credentials) => { const params = await exports.formatQueryForUsersList(query); - return User.find(params, {}, { autopopulate: false }) + return User.find(params, { iban: 0, bic: 0 }, { autopopulate: false }) .populate({ path: 'role.client', select: '-__v -createdAt -updatedAt' }) .populate({ path: 'role.holding', select: '-__v -createdAt -updatedAt' }) .populate({ path: 'company', populate: { path: 'company' }, select: '-__v -createdAt -updatedAt' }) @@ -248,10 +248,16 @@ exports.getUser = async (userId, credentials) => { if (!user) throw Boom.notFound(translate[language].userNotFound); + const maskedUser = { + ...user, + ...user.iban && { iban: UtilsHelper.maskBankInfo(user.iban) }, + ...user.bic && { bic: UtilsHelper.maskBankInfo(user.bic) }, + }; + return isVendorUser || requestingOwnInfos - ? user + ? maskedUser : { - ...user, + ...maskedUser, userCompanyList: user.userCompanyList .filter(uc => UtilsHelper.hasUserAccessToCompany(credentials, get(uc, 'company'))), }; diff --git a/tests/unit/helpers/users.test.js b/tests/unit/helpers/users.test.js index 3b2bbc0bd7..395dadc2d6 100644 --- a/tests/unit/helpers/users.test.js +++ b/tests/unit/helpers/users.test.js @@ -386,7 +386,7 @@ describe('getUsersList', () => { SinonMongoose.calledOnceWithExactly( find, [ - { query: 'find', args: [{ ...query, company: companyId }, {}, { autopopulate: false }] }, + { query: 'find', args: [{ ...query, company: companyId }, { iban: 0, bic: 0 }, { autopopulate: false }] }, { query: 'populate', args: [{ path: 'role.client', select: '-__v -createdAt -updatedAt' }] }, { query: 'populate', args: [{ path: 'role.holding', select: '-__v -createdAt -updatedAt' }] }, { @@ -415,7 +415,7 @@ describe('getUsersList', () => { SinonMongoose.calledOnceWithExactly( find, [ - { query: 'find', args: [formattedQuery, {}, { autopopulate: false }] }, + { query: 'find', args: [formattedQuery, { iban: 0, bic: 0 }, { autopopulate: false }] }, { query: 'populate', args: [{ path: 'role.client', select: '-__v -createdAt -updatedAt' }] }, { query: 'populate', args: [{ path: 'role.holding', select: '-__v -createdAt -updatedAt' }] }, @@ -1052,13 +1052,15 @@ describe('getUser', () => { _id: userId, role: { vendor: 'trainer', rights: [] }, userCompanyList: [{ company: new ObjectId() }, { company: new ObjectId() }], + iban: 'FR3514508000505917721779B12', + bic: 'WERTFRPP', }; const credentials = { company: { _id: new ObjectId() }, _id: new ObjectId(), role: { vendor: 'trainer' } }; findOne.returns(SinonMongoose.stubChainedQueries(user)); const res = await UsersHelper.getUser(userId, credentials); - expect(res).toEqual(user); + expect(res).toEqual({ ...user, iban: 'FR***********************12', bic: 'WE****PP' }); SinonMongoose.calledOnceWithExactly( findOne, From 317cc3f55914f0cee8a81f5d0915610a1f65630e Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:57:42 +0100 Subject: [PATCH 08/53] COM-4318: company --- src/helpers/companies.js | 24 ++++++++++++++++++------ tests/unit/helpers/companies.test.js | 24 +++++++++++++++++------- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/helpers/companies.js b/src/helpers/companies.js index 12f117bcef..39a55c3d39 100644 --- a/src/helpers/companies.js +++ b/src/helpers/companies.js @@ -80,6 +80,12 @@ const getEditedField = (payload) => { return null; }; +const maskInfos = company => ({ + ...company, + ...company.iban && { iban: UtilsHelper.maskBankInfo(company.iban) }, + ...company.bic && { bic: UtilsHelper.maskBankInfo(company.bic) }, +}); + exports.updateCompany = async (companyId, payload) => { let debitMandate = {}; const company = await Company.findOne({ _id: companyId }).lean(); @@ -96,18 +102,24 @@ exports.updateCompany = async (companyId, payload) => { debitMandate = { _id: new ObjectId(), rum, createdAt: today.toISO() }; } - return Company.findOneAndUpdate( + const updatedCompany = await Company.findOneAndUpdate( { _id: companyId }, { $set: flat(payload), ...Object.keys(debitMandate).length && { $addToSet: { debitMandates: debitMandate } } }, { new: true } ).lean(); + + return updatedCompany && maskInfos(updatedCompany); }; -exports.getCompany = async companyId => Company - .findOne({ _id: companyId }) - .populate({ path: 'billingRepresentatives', select: '_id picture contact identity local' }) - .populate({ path: 'salesRepresentative', select: '_id picture contact identity local' }) - .lean(); +exports.getCompany = async (companyId) => { + const company = await Company + .findOne({ _id: companyId }) + .populate({ path: 'billingRepresentatives', select: '_id picture contact identity local' }) + .populate({ path: 'salesRepresentative', select: '_id picture contact identity local' }) + .lean(); + + return company && maskInfos(company); +}; exports.generateMandate = async (companyId, mandateId) => { const vendorCompany = await VendorCompany.findOne().lean(); diff --git a/tests/unit/helpers/companies.test.js b/tests/unit/helpers/companies.test.js index 7fbdb1c6ec..506a378c59 100644 --- a/tests/unit/helpers/companies.test.js +++ b/tests/unit/helpers/companies.test.js @@ -246,6 +246,8 @@ describe('getCompany', () => { const company = { _id: new ObjectId(), name: 'test', + bic: 'WERTFRPP', + iban: 'FR3514508000505917721779B12', billingRepresentatives: [{ _id: new ObjectId(), identity: { firstname: 'nono', lastname: 'toto' }, @@ -257,7 +259,7 @@ describe('getCompany', () => { const result = await CompanyHelper.getCompany(company._id); - expect(result).toEqual(company); + expect(result).toEqual({ ...company, bic: 'WE****PP', iban: 'FR***********************12' }); SinonMongoose.calledOnceWithExactly( findOne, [ @@ -301,7 +303,7 @@ describe('updateCompany', () => { const result = await CompanyHelper.updateCompany(companyId, payload); - expect(result).toEqual({ ...company, name: 'Nouveau nom' }); + expect(result).toEqual(({ ...company, name: 'Nouveau nom', bic: 'WE****PP' })); SinonMongoose.calledOnceWithExactly( findOne, @@ -325,8 +327,8 @@ describe('updateCompany', () => { }); const editedField = [ - { key: 'bic', value: 'QWERFRPP' }, - { key: 'iban', value: 'FR3514508000505917721779B12' }, + { key: 'bic', value: 'QWERFRPP', returnedValue: 'QW****PP' }, + { key: 'iban', value: 'FR3514508000505917721779B12', returnedValue: 'FR***********************12' }, { key: 'address', value: { @@ -360,7 +362,11 @@ describe('updateCompany', () => { const payload = { [param.key]: param.value }; const result = await CompanyHelper.updateCompany(companyId, payload); - expect(result).toEqual(updatedCompany); + expect(result).toEqual( + param.returnedValue + ? { ...updatedCompany, [param.key]: param.returnedValue } + : updatedCompany + ); SinonMongoose.calledOnceWithExactly( findOne, @@ -406,7 +412,11 @@ describe('updateCompany', () => { const payload = { [param.key]: param.value }; const result = await CompanyHelper.updateCompany(companyId, payload); - expect(result).toEqual(updatedCompany); + expect(result).toEqual( + param.returnedValue + ? { ...updatedCompany, [param.key]: param.returnedValue } + : updatedCompany + ); SinonMongoose.calledOnceWithExactly( findOne, @@ -452,7 +462,7 @@ describe('updateCompany', () => { const payload = { bic: 'DFGTFRPP' }; const result = await CompanyHelper.updateCompany(companyId, payload); - expect(result).toEqual(updatedCompany); + expect(result).toEqual({ ...updatedCompany, bic: 'DF****PP' }); SinonMongoose.calledOnceWithExactly( findOne, From 68377fa221f853840ad769cfeb87ef1f98ea1e55 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:59:28 +0100 Subject: [PATCH 09/53] COM-4318: coursepayment --- src/helpers/coursePayments.js | 51 ++++++++++++++--------- tests/unit/helpers/coursePayments.test.js | 42 +++++++++++++++++-- 2 files changed, 71 insertions(+), 22 deletions(-) diff --git a/src/helpers/coursePayments.js b/src/helpers/coursePayments.js index 720dc4a803..9b4ff1a06f 100644 --- a/src/helpers/coursePayments.js +++ b/src/helpers/coursePayments.js @@ -1,3 +1,5 @@ +const get = require('lodash/get'); +const omit = require('lodash/omit'); const CourseBill = require('../models/CourseBill'); const CoursePayment = require('../models/CoursePayment'); const CoursePaymentNumber = require('../models/CoursePaymentNumber'); @@ -28,25 +30,36 @@ exports.updateCoursePayment = async (coursePaymentId, payload) => { await CoursePayment.updateOne({ _id: coursePaymentId }, { $set: payload }); }; -exports.list = async query => CoursePayment - .find({ status: { $in: Array.isArray(query.status) ? query.status : [query.status] }, nature: PAYMENT }) - .populate({ - path: 'courseBill', - select: 'number payer course', - populate: [ - { - path: 'payer.company', - select: 'name bic iban debitMandates', - populate: { path: 'holding', populate: { path: 'holding', select: 'name' } }, - }, - { path: 'payer.fundingOrganisation', select: 'name' }, - { path: 'course', select: 'type' }, - ], - }) - .populate({ path: 'xmlSEPAFileInfos', select: 'name', options: { isVendorUser: true } }) - .setOptions({ isVendorUser: true }) - .sort({ updatedAt: -1 }) - .lean(); +exports.list = async (query) => { + const coursePayments = await CoursePayment + .find({ status: { $in: Array.isArray(query.status) ? query.status : [query.status] }, nature: PAYMENT }) + .populate({ + path: 'courseBill', + select: 'number payer course', + populate: [ + { + path: 'payer.company', + select: 'name bic iban debitMandates', + populate: { path: 'holding', populate: { path: 'holding', select: 'name' } }, + }, + { path: 'payer.fundingOrganisation', select: 'name' }, + { path: 'course', select: 'type' }, + ], + }) + .populate({ path: 'xmlSEPAFileInfos', select: 'name', options: { isVendorUser: true } }) + .setOptions({ isVendorUser: true }) + .sort({ updatedAt: -1 }) + .lean(); + + return coursePayments.map((payment) => { + const payer = get(payment, 'courseBill.payer'); + if (!payer) return payment; + + const formattedPayer = { ...omit(payer, ['bic', 'iban']), hasBankDetails: !!(payer.bic && payer.iban) }; + + return { ...payment, courseBill: { ...payment.courseBill, payer: formattedPayer } }; + }); +}; exports.updateList = async payload => CoursePayment .updateMany({ _id: { $in: payload._ids } }, { $set: { status: payload.status } }); diff --git a/tests/unit/helpers/coursePayments.test.js b/tests/unit/helpers/coursePayments.test.js index fd4cc2aab6..8c3b0ce24f 100644 --- a/tests/unit/helpers/coursePayments.test.js +++ b/tests/unit/helpers/coursePayments.test.js @@ -224,7 +224,12 @@ describe('list', () => { nature: PAYMENT, courseBill: { number: 'FACT_00001', - payer: { company: { name: 'Structure', holding: { _id: new ObjectId(), name: 'holding' } } }, + payer: { + name: 'Structure', + holding: { _id: new ObjectId(), name: 'holding' }, + bic: 'WERTFRPP', + iban: 'FR3514508000505917721779B12', + }, isPayerCompany: true, course: { type: INTRA }, }, @@ -257,7 +262,26 @@ describe('list', () => { const result = await CoursePaymentsHelper.list({ status: [RECEIVED, XML_GENERATED] }); - expect(result).toEqual(paymentList); + expect(result).toEqual([ + { + ...paymentList[0], + courseBill: { + ...paymentList[0].courseBill, + payer: { name: 'Structure', holding: paymentList[0].courseBill.payer.holding, hasBankDetails: true }, + }, + }, + { + ...paymentList[1], + courseBill: { + ...paymentList[1].courseBill, + payer: { fundingOrganisation: { name: 'Financeur', holding: null }, hasBankDetails: false }, + }, + }, + { + ...paymentList[2], + courseBill: { ...paymentList[2].courseBill, payer: { company: { name: 'Structure' }, hasBankDetails: false } }, + }, + ]); SinonMongoose.calledOnceWithExactly( find, @@ -335,7 +359,19 @@ describe('list', () => { const result = await CoursePaymentsHelper.list({ status: RECEIVED }); - expect(result).toEqual([paymentList[0], paymentList[1]]); + expect(result).toEqual([ + { + ...paymentList[0], + courseBill: { ...paymentList[0].courseBill, payer: { company: { name: 'Structure' }, hasBankDetails: false } }, + }, + { + ...paymentList[1], + courseBill: { + ...paymentList[1].courseBill, + payer: { company: { fundingOrganisation: 'Financeur' }, hasBankDetails: false }, + }, + }, + ]); SinonMongoose.calledOnceWithExactly( find, From 70a5e7b7d57201ead1a4c94d67ea2f203fb90ce3 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 14:59:53 +0100 Subject: [PATCH 10/53] COM-4318: trainerpayment --- src/helpers/trainerPayments.js | 12 +++++++++++- tests/unit/helpers/trainerPayments.test.js | 11 +++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index 547094bcfd..bab0ff776f 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -1,4 +1,5 @@ const get = require('lodash/get'); +const omit = require('lodash/omit'); const CourseSlot = require('../models/CourseSlot'); const TrainerBill = require('../models/TrainerBill'); const TrainerPayment = require('../models/TrainerPayment'); @@ -7,7 +8,7 @@ const GCloudStorageHelper = require('./gCloudStorage'); exports.list = async (query) => { const status = Array.isArray(query.status) ? query.status : [query.status]; - return TrainerPayment + const trainerPayments = await TrainerPayment .find({ status: { $in: status } }) .populate({ path: 'trainerBill', @@ -17,6 +18,15 @@ exports.list = async (query) => { .populate({ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }) .sort({ date: -1 }) .lean(); + + return trainerPayments.map((payment) => { + const trainer = get(payment, 'trainerBill.trainer'); + if (!trainer) return payment; + + const formattedTrainer = { ...omit(trainer, ['bic', 'iban']), hasBankDetails: !!(trainer.bic && trainer.iban) }; + + return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; + }); }; exports.update = async (trainerPaymentId, payload) => TrainerPayment diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index f6a7fbe7bb..cd1eb341db 100644 --- a/tests/unit/helpers/trainerPayments.test.js +++ b/tests/unit/helpers/trainerPayments.test.js @@ -86,12 +86,19 @@ describe('list', () => { }); it('should return the trainer payments with the given status', async () => { - const trainerPayments = [{ _id: new ObjectId(), status: PAID }]; + const trainerPayments = [{ + _id: new ObjectId(), + status: PAID, + trainerBill: { number: 'FACT', trainer: { identity: { lastname: 'Trainer' }, bic: 'WERTFRPP', iban: 'FR35' } }, + }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); const result = await TrainerPaymentsHelper.list({ status: PAID }); - expect(result).toEqual(trainerPayments); + expect(result).toEqual([{ + ...trainerPayments[0], + trainerBill: { number: 'FACT', trainer: { identity: { lastname: 'Trainer' }, hasBankDetails: true } }, + }]); SinonMongoose.calledOnceWithExactly( trainerPaymentFind, [ From d60bb89732ec591f4c184f868b1736c986a3c23e Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 28 Oct 2026 17:12:27 +0100 Subject: [PATCH 11/53] COM-4314: review --- src/helpers/courses.js | 13 ++++++++----- src/routes/preHandlers/courseBills.js | 3 ++- src/routes/preHandlers/subPrograms.js | 4 ++-- tests/unit/helpers/courses.test.js | 4 ++++ 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 7e9c7f7afe..bb7fab5df6 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -584,11 +584,14 @@ const getCourseForOperations = async (courseId, credentials, origin) => { populate: [ { path: 'program', select: 'learningGoals' }, ...(origin === WEBAPP - ? [{ - path: 'steps', - select: 'name type theoreticalDuration durationCountedPerTrainer', - populate: { path: 'activities', select: 'name type' }, - }] + ? [ + { + path: 'steps', + select: 'name type theoreticalDuration durationCountedPerTrainer', + populate: { path: 'activities', select: 'name type' }, + }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, + ] : [{ path: 'steps', select: 'name' }] ), ], diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 26d2f22542..b32af5d48a 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -48,7 +48,8 @@ exports.authorizeCourseBillListCreation = async (req) => { if (course.type !== SINGLE) throw Boom.forbidden(); const hourlyPaymentPlans = get(course, 'subProgram.hourlyPaymentPlans') || []; - if (!UtilsHelper.doesArrayIncludeId(hourlyPaymentPlans.map(hpp => hpp._id), hourlyPaymentPlanId)) { + const subProgramHppIds = hourlyPaymentPlans.map(hpp => hpp._id); + if (!UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId)) { throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); } diff --git a/src/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 68a0979c6f..b4cceec435 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -182,8 +182,8 @@ exports.authorizeSubProgramUpdate = async (req) => { const { hourlyPaymentPlanId, prices, elearningPrice } = req.payload.hourlyPaymentPlan; if (hourlyPaymentPlanId) { - const hourlyPaymentPlanExists = UtilsHelper - .doesArrayIncludeId((subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id), hourlyPaymentPlanId); + const subProgramHppIds = (subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id); + const hourlyPaymentPlanExists = UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId); if (!hourlyPaymentPlanExists) throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); const isUsedByCourse = !prices.length && subProgram.courses diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 935d9b41c5..32d43e1e26 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -2894,6 +2894,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -3009,6 +3010,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -3117,6 +3119,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -3299,6 +3302,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { From 1ba8e5da69633e6b350b86057a3a6f365c7fc982 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 28 Oct 2026 18:58:27 +0100 Subject: [PATCH 12/53] COM-4313 - remove useless seed --- tests/integration/seed/trainerBillsSeed.js | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/tests/integration/seed/trainerBillsSeed.js b/tests/integration/seed/trainerBillsSeed.js index ee2ec5ba69..edbf5c8ca0 100644 --- a/tests/integration/seed/trainerBillsSeed.js +++ b/tests/integration/seed/trainerBillsSeed.js @@ -2,14 +2,13 @@ const { ObjectId } = require('mongodb'); const Course = require('../../../src/models/Course'); const CourseSlot = require('../../../src/models/CourseSlot'); const TrainerBill = require('../../../src/models/TrainerBill'); -const TrainerPayment = require('../../../src/models/TrainerPayment'); const Program = require('../../../src/models/Program'); const Step = require('../../../src/models/Step'); const SubProgram = require('../../../src/models/SubProgram'); const { authCompany } = require('../../seed/authCompaniesSeed'); const { deleteNonAuthenticationSeeds } = require('../helpers/db'); const { vendorAdmin, trainer, trainerAndCoach } = require('../../seed/authUsersSeed'); -const { INTRA, PUBLISHED, GLOBAL, PENDING, PAID } = require('../../../src/helpers/constants'); +const { INTRA, PUBLISHED, GLOBAL } = require('../../../src/helpers/constants'); const step = { _id: new ObjectId(), type: 'on_site', name: 'étape', status: PUBLISHED, theoreticalDuration: 60 }; @@ -106,11 +105,6 @@ const trainerBillList = [ }, ]; -const trainerPaymentList = [ - { _id: new ObjectId(), number: 'REG-00098', trainerBill: trainerBillId, amount: 100, status: PENDING }, - { _id: new ObjectId(), number: 'REG-00099', trainerBill: paidTrainerBillId, amount: 100, status: PAID }, -]; - const populateDB = async () => { await deleteNonAuthenticationSeeds(); @@ -121,7 +115,6 @@ const populateDB = async () => { Step.create(step), CourseSlot.create(courseSlotsList), TrainerBill.create(trainerBillList), - TrainerPayment.create(trainerPaymentList), ]); }; From 5616ada7401b9934d851a52a1f61dd7813165fc2 Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 29 Oct 2026 11:03:58 +0100 Subject: [PATCH 13/53] COM-4318: review --- src/helpers/coursePayments.js | 4 +++- src/helpers/trainerPayments.js | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/helpers/coursePayments.js b/src/helpers/coursePayments.js index 9b4ff1a06f..14650b9dff 100644 --- a/src/helpers/coursePayments.js +++ b/src/helpers/coursePayments.js @@ -51,7 +51,7 @@ exports.list = async (query) => { .sort({ updatedAt: -1 }) .lean(); - return coursePayments.map((payment) => { + const formattedPayments = coursePayments.map((payment) => { const payer = get(payment, 'courseBill.payer'); if (!payer) return payment; @@ -59,6 +59,8 @@ exports.list = async (query) => { return { ...payment, courseBill: { ...payment.courseBill, payer: formattedPayer } }; }); + + return formattedPayments; }; exports.updateList = async payload => CoursePayment diff --git a/src/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index bab0ff776f..b450c0b6e5 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -19,7 +19,7 @@ exports.list = async (query) => { .sort({ date: -1 }) .lean(); - return trainerPayments.map((payment) => { + const formattedPayments = trainerPayments.map((payment) => { const trainer = get(payment, 'trainerBill.trainer'); if (!trainer) return payment; @@ -27,6 +27,8 @@ exports.list = async (query) => { return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; }); + + return formattedPayments; }; exports.update = async (trainerPaymentId, payload) => TrainerPayment From 54acf4f15d165213d4f632a331637fc542967f5c Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 29 Oct 2026 17:04:48 +0100 Subject: [PATCH 14/53] COM-4315: compute real price --- src/helpers/completionCertificates.js | 173 +++++++----- src/helpers/courseBills.js | 55 +++- src/helpers/courseSlots.js | 7 + src/helpers/courses.js | 40 +++ src/helpers/hourlyPaymentPlans.js | 18 ++ src/routes/courseBills.js | 7 +- src/routes/preHandlers/courseBills.js | 6 + .../completionCertificates.test.js | 36 ++- tests/integration/courseBills.test.js | 17 +- .../seed/completionCertificatesSeed.js | 58 +++- .../helpers/completionCertificates.test.js | 257 +++++++++++++----- tests/unit/helpers/courseBills.test.js | 125 ++++++++- tests/unit/helpers/courseSlots.test.js | 17 ++ tests/unit/helpers/courses.test.js | 71 +++++ tests/unit/helpers/hourlyPaymentPlans.test.js | 35 +++ 15 files changed, 778 insertions(+), 144 deletions(-) create mode 100644 src/helpers/hourlyPaymentPlans.js create mode 100644 tests/unit/helpers/hourlyPaymentPlans.test.js diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index b1ac314836..f5d9ea849a 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -1,17 +1,18 @@ const { ObjectId } = require('mongodb'); const get = require('lodash/get'); const has = require('lodash/has'); -const groupBy = require('lodash/groupBy'); const pick = require('lodash/pick'); const CompletionCertificatePdf = require('../data/pdf/completionCertificate'); const CompletionCertificate = require('../models/CompletionCertificate'); const TrainingContract = require('../models/TrainingContract'); -const ActivityHistory = require('../models/ActivityHistory'); -const Attendance = require('../models/Attendance'); +const Course = require('../models/Course'); +const CourseBill = require('../models/CourseBill'); const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); -const { MM_YYYY, MONTH, DD_MM_YYYY, E_LEARNING, SHORT_DURATION_H_MM, OFFICIAL, PRESENT } = require('./constants'); +const { MM_YYYY, MONTH, DD_MM_YYYY, SHORT_DURATION_H_MM, OFFICIAL } = require('./constants'); const UtilsHelper = require('./utils'); +const HourlyPaymentPlansHelper = require('./hourlyPaymentPlans'); +const CourseSlotsHelper = require('./courseSlots'); const CoursesHelper = require('./courses'); const GCloudStorageHelper = require('./gCloudStorage'); @@ -66,19 +67,39 @@ exports.list = async (query, credentials) => { return completionCertificates; }; +const computeMonthDurations = async (course, month, traineeId) => { + const startOfMonth = CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(); + const endOfMonth = CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(); + + const dates = { startDate: startOfMonth, endDate: endOfMonth }; + const { slotsWithAttendance, eLearningDuration } = await CoursesHelper.getTraineeDurations(course, traineeId, dates); + + const unsubscribedAttendances = await CoursesHelper.getUnsubscribedAttendances( + { ...pick(course, ['_id', 'trainees', 'companies']), subPrograms: get(course, 'subProgram.program.subPrograms') }, + true + ); + const slotsWithUnsubscribedAttendance = unsubscribedAttendances + .filter(a => CompaniDate(a.courseSlot.startDate).isSameOrBetween(startOfMonth, endOfMonth)) + .map(a => a.courseSlot); + + const allSlotsWithAttendance = [...slotsWithAttendance, ...slotsWithUnsubscribedAttendance]; + const durationPerStep = CourseSlotsHelper.getDurationPerStep(allSlotsWithAttendance); + const traineePresence = Object.values(durationPerStep) + .reduce((acc, duration) => acc.add(duration), CompaniDuration()); + + return { startOfMonth, endOfMonth, traineePresence, eLearningDuration, durationPerStep }; +}; + exports.generate = async (completionCertificateId) => { const VAEI_SUBPROGRAM_IDS = process.env.VAEI_SUBPROGRAM_IDS.split(',').map(id => new ObjectId(id)); const PRI_SUBPROGRAM_IDS = process.env.PRI_SUBPROGRAM_IDS.split(',').map(id => new ObjectId(id)); - const REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS - .split(',') - .map(id => new ObjectId(id)); const completionCertificate = await CompletionCertificate .findOne({ _id: completionCertificateId }) .populate([ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -88,13 +109,10 @@ exports.generate = async (completionCertificateId) => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -127,57 +145,8 @@ exports.generate = async (completionCertificateId) => { } } - const startOfMonth = CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(); - const endOfMonth = CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(); - - const courseSlotIdsOnMonth = course.slots - .filter(slot => CompaniDate(slot.startDate).isSameOrBetween(startOfMonth, endOfMonth)).map(s => s._id); - - const attendances = await Attendance - .find({ trainee: trainee._id, courseSlot: { $in: courseSlotIdsOnMonth }, status: PRESENT }) - .setOptions({ isVendorUser: true }) - .lean(); - - const slotsWithAttendanceIds = attendances.map(a => a.courseSlot); - - const slotsWithAttendance = course.slots - .filter(slot => UtilsHelper.doesArrayIncludeId(slotsWithAttendanceIds, slot._id)); - - const unsubscribedAttendances = await CoursesHelper.getUnsubscribedAttendances( - { ...pick(course, ['_id', 'trainees', 'companies']), subPrograms: get(course, 'subProgram.program.subPrograms') }, - true - ); - const slotsWithUnsubscribedAttendance = unsubscribedAttendances - .filter(a => CompaniDate(a.courseSlot.startDate).isSameOrBetween(startOfMonth, endOfMonth)) - .map(a => a.courseSlot); - - const allSlotsWithAttendance = [...slotsWithAttendance, ...slotsWithUnsubscribedAttendance]; - const traineePresence = UtilsHelper.getTotalDuration(allSlotsWithAttendance, false); - - const eLearningSteps = course.subProgram.steps.filter(step => step.type === E_LEARNING); - - const activitiesIds = eLearningSteps.flatMap(s => s.activities); - const activityHistories = await ActivityHistory - .find({ activity: { $in: activitiesIds }, user: trainee._id }) - .lean(); - const activityHistoriesGroupedByActivity = groupBy(activityHistories, 'activity'); - - const dates = { startDate: startOfMonth, endDate: endOfMonth }; - - let eLearningDuration; - if (UtilsHelper.doesArrayIncludeId(REAL_ELEARNING_DURATION_SUBPROGRAM_IDS, course.subProgram._id)) { - const filteredActivityHistories = activityHistories - .filter(aH => (CompaniDate(aH.date).isSameOrBetween(dates.startDate, dates.endDate))); - eLearningDuration = CoursesHelper.getRealELearningDuration(filteredActivityHistories); - } else { - const eLearningStepsWithAH = eLearningSteps - .map(s => ({ - ...s, - activities: s.activities - .map(a => ({ _id: a, activityHistories: activityHistoriesGroupedByActivity[a] || [] })), - })); - eLearningDuration = CoursesHelper.getELearningDuration(eLearningStepsWithAH, trainee._id, dates); - } + const durations = await computeMonthDurations(course, month, trainee._id); + const { startOfMonth, endOfMonth, traineePresence, durationPerStep, eLearningDuration } = durations; const formattedELearningDuration = CompaniDuration(eLearningDuration).format(SHORT_DURATION_H_MM); @@ -258,16 +227,88 @@ exports.generate = async (completionCertificateId) => { updatePayload.vaeSupportRemainingMinutes = newVAESupportRemainingMinutes; } await CompletionCertificate.updateOne({ _id: completionCertificateId }, { $set: updatePayload }); + + if (course.hourlyPaymentPlan) { + const billsToUpdate = await CourseBill + .find( + { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': 0 }, + { _id: 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); + + if (billsToUpdate.length) { + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); + const price = HourlyPaymentPlansHelper + .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + + await CourseBill + .updateMany({ _id: { $in: billsToUpdate.map(b => b._id) } }, { $set: { 'mainFee.price': price } }); + } + } }; exports.create = async payload => CompletionCertificate.create(payload); exports.deleteFile = async (completionCertificateId) => { - const completionCertificate = await CompletionCertificate.findOne({ _id: completionCertificateId }).lean(); + const completionCertificate = await CompletionCertificate + .findOne({ _id: completionCertificateId }) + .populate({ path: 'course', select: 'hourlyPaymentPlan' }) + .lean(); + + if (completionCertificate.course.hourlyPaymentPlan) { + const { month, trainee } = completionCertificate; + + const course = await Course + .findOne( + { _id: completionCertificate.course._id }, + { subProgram: 1, slots: 1, companies: 1, trainees: 1, hourlyPaymentPlan: 1 } + ) + .populate({ + path: 'slots', + select: 'startDate endDate trainers step', + populate: { path: 'step', select: 'durationCountedPerTrainer' }, + }) + .populate({ + path: 'subProgram', + select: 'program steps hourlyPaymentPlans', + populate: [ + { path: 'program', select: 'subPrograms' }, + { path: 'steps', select: 'activities type theoreticalDuration' }, + ], + }) + .lean(); + + const durations = await computeMonthDurations(course, month, trainee); + const { startOfMonth, endOfMonth, durationPerStep, eLearningDuration } = durations; + + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); + const price = HourlyPaymentPlansHelper + .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + + const billsToReset = await CourseBill + .find( + { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': price }, + { _id: 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); + + if (billsToReset.length) { + await CourseBill.updateMany({ _id: { $in: billsToReset.map(b => b._id) } }, { $set: { 'mainFee.price': 0 } }); + } + } + if (completionCertificate.vaeSupportRemainingMinutes) { const { course, trainee, vaeSupportRemainingMinutes } = completionCertificate; const completionCertificateWithRemainingMinutes = await CompletionCertificate - .find({ course, trainee, vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes } }) + .find({ + course: course._id, + trainee, + vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes }, + }) .setOptions({ isVendorUser: true }) .lean(); const certificateToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 005b328362..66bad1365b 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -15,6 +15,9 @@ const CoursePayment = require('../models/CoursePayment'); const SubProgram = require('../models/SubProgram'); const BalanceHelper = require('./balances'); const UtilsHelper = require('./utils'); +const HourlyPaymentPlansHelper = require('./hourlyPaymentPlans'); +const CoursesHelper = require('./courses'); +const CourseSlotsHelper = require('./courseSlots'); const CourseHistoriesHelper = require('./courseHistories'); const VendorCompaniesHelper = require('./vendorCompanies'); const CourseBillPdf = require('../data/pdf/courseBilling/courseBill'); @@ -33,6 +36,7 @@ const { BANK_TRANSFER, DIRECT_DEBIT, PRESENT, + GLOBAL, } = require('./constants'); const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); @@ -323,9 +327,45 @@ exports.list = async (query, credentials) => { }); }; +exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => { + const course = await Course + .findOne({ _id: courseId }, { subProgram: 1, slots: 1, trainees: 1 }) + .populate({ + path: 'slots', + select: 'startDate endDate trainers step', + populate: { path: 'step', select: 'durationCountedPerTrainer' }, + }) + .populate({ + path: 'subProgram', + select: 'steps hourlyPaymentPlans', + populate: { path: 'steps', select: 'activities type theoreticalDuration' }, + }) + .lean(); + + const { slotsWithAttendance, eLearningDuration } = await CoursesHelper + .getTraineeDurations(course, course.trainees[0]); + + const durationPerStep = CourseSlotsHelper.getDurationPerStep(slotsWithAttendance); + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId)); + + return HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); +}; + exports.createBillList = async (payload) => { const course = await Course - .findOne({ _id: payload.course }, { type: 1, prices: 1, trainees: 1, trainers: 1, subProgram: 1 }) + .findOne( + { _id: payload.course }, + { + type: 1, + prices: 1, + trainees: 1, + trainers: 1, + subProgram: 1, + hourlyPaymentPlan: 1, + certificateGenerationMode: 1, + } + ) .populate({ path: 'trainees', select: 'identity' }) .populate({ path: 'trainers', select: 'identity' }) .populate({ path: 'subProgram', select: 'subjectToVat' }) @@ -342,8 +382,17 @@ exports.createBillList = async (payload) => { } if (payload.quantity === 1) { - const billCreated = await CourseBill - .create({ ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), ...vat && { vat } }); + const isGlobalCertificationCourseWithPriceFromDurations = payload.hourlyPaymentPlanId && + course.certificateGenerationMode === GLOBAL; + const mainFee = isGlobalCertificationCourseWithPriceFromDurations + ? { ...payload.mainFee, price: await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId) } + : payload.mainFee; + + const billCreated = await CourseBill.create({ + ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), + mainFee, + ...vat && { vat }, + }); if (payload.mainFee.percentage) { const trainerFees = (course.prices || []).reduce((acc, price) => { diff --git a/src/helpers/courseSlots.js b/src/helpers/courseSlots.js index e75a1f2b6a..615507032d 100644 --- a/src/helpers/courseSlots.js +++ b/src/helpers/courseSlots.js @@ -3,6 +3,7 @@ const compact = require('lodash/compact'); const get = require('lodash/get'); const groupBy = require('lodash/groupBy'); const has = require('lodash/has'); +const mapValues = require('lodash/mapValues'); const pick = require('lodash/pick'); const omit = require('lodash/omit'); const uniqBy = require('lodash/uniqBy'); @@ -485,3 +486,9 @@ exports.formatSlotDates = (slots) => { return [...new Set(slotDatesWithDuplicate)]; }; + +exports.getDurationPerStep = (slots) => { + const slotsPerStep = groupBy(slots, slot => get(slot, 'step._id') || slot.step); + + return mapValues(slotsPerStep, stepSlots => UtilsHelper.getTotalDuration(stepSlots, false)); +}; diff --git a/src/helpers/courses.js b/src/helpers/courses.js index bb7fab5df6..58721f350c 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -23,6 +23,7 @@ const UserCompany = require('../models/UserCompany'); const Questionnaire = require('../models/Questionnaire'); const QuestionnaireHistory = require('../models/QuestionnaireHistory'); const CourseSmsHistory = require('../models/CourseSmsHistory'); +const ActivityHistory = require('../models/ActivityHistory'); const Attendance = require('../models/Attendance'); const SubProgram = require('../models/SubProgram'); const TrainingContract = require('../models/TrainingContract'); @@ -1409,6 +1410,45 @@ exports.getRealELearningDuration = (activityHistories) => { return eLearningDuration; }; +exports.getTraineeDurations = async (course, traineeId, dates) => { + const REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS + .split(',') + .map(id => new ObjectId(id)); + + const slots = dates + ? course.slots.filter(slot => CompaniDate(slot.startDate).isSameOrBetween(dates.startDate, dates.endDate)) + : course.slots; + + const attendances = await Attendance + .find({ trainee: traineeId, courseSlot: { $in: slots.map(s => s._id) }, status: PRESENT }) + .setOptions({ isVendorUser: true }) + .lean(); + 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); + } + + return { slotsWithAttendance, eLearningDuration }; +}; + const getTraineeInformations = ( trainee, courseAttendances, diff --git a/src/helpers/hourlyPaymentPlans.js b/src/helpers/hourlyPaymentPlans.js new file mode 100644 index 0000000000..db3635628b --- /dev/null +++ b/src/helpers/hourlyPaymentPlans.js @@ -0,0 +1,18 @@ +const NumbersHelper = require('./numbers'); +const UtilsHelper = require('./utils'); +const { CompaniDuration } = require('./dates/companiDurations'); + +exports.getPriceFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration) => { + const stepsPrice = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => { + const stepPrice = hourlyPaymentPlan.prices.find(p => UtilsHelper.areObjectIdsEquals(p.step, stepId)); + if (!stepPrice) return acc; + + return NumbersHelper.add(acc, NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount)); + }, 0); + + const eLearningPrice = hourlyPaymentPlan.elearningPrice + ? NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice) + : 0; + + return NumbersHelper.toFixedToFloat(NumbersHelper.add(stepsPrice, eLearningPrice)); +}; diff --git a/src/routes/courseBills.js b/src/routes/courseBills.js index 46d3ec223c..9c4eee0e8f 100644 --- a/src/routes/courseBills.js +++ b/src/routes/courseBills.js @@ -81,7 +81,12 @@ exports.plugin = { 'quantity', { is: 1, - then: Joi.object({ price: Joi.required() }), + then: Joi.object({ + price: Joi.when( + '/hourlyPaymentPlanId', + { is: Joi.exist(), then: Joi.any(), otherwise: Joi.required() } + ), + }), otherwise: Joi.object({ percentage: Joi.forbidden() }), } ), diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index b32af5d48a..a52d805b55 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -13,6 +13,7 @@ const { BALANCE, INTRA, GROUP, + GLOBAL, TRAINEE, SINGLE, } = require('../../helpers/constants'); @@ -38,6 +39,7 @@ exports.authorizeCourseBillListCreation = async (req) => { prices: 1, interruptionDates: 1, hourlyPaymentPlan: 1, + certificateGenerationMode: 1, }) .populate({ path: 'subProgram', select: 'hourlyPaymentPlans' }) .lean(); @@ -58,6 +60,10 @@ exports.authorizeCourseBillListCreation = async (req) => { } } + const shouldComputePriceFromDuration = hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; + if (quantity === 1 && !mainFee.price && !shouldComputePriceFromDuration) throw Boom.badRequest(); + if (shouldComputePriceFromDuration && mainFee.price) throw Boom.badRequest(); + const isCourseInterrupted = UtilsHelper.isCourseInterrupted(course.interruptionDates); if (isCourseInterrupted) throw Boom.forbidden(); diff --git a/tests/integration/completionCertificates.test.js b/tests/integration/completionCertificates.test.js index 38dbb115d3..a70dfe115e 100644 --- a/tests/integration/completionCertificates.test.js +++ b/tests/integration/completionCertificates.test.js @@ -4,10 +4,16 @@ const { ObjectId } = require('mongodb'); const GCloudStorageHelper = require('../../src/helpers/gCloudStorage'); const app = require('../../server'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); -const { populateDB, courseList, completionCertificateList } = require('./seed/completionCertificatesSeed'); +const { + populateDB, + courseList, + completionCertificateList, + courseBillsList, +} = require('./seed/completionCertificatesSeed'); const { auxiliary, noRole } = require('../seed/authUsersSeed'); const { GENERATION } = require('../../src/helpers/constants'); const CompletionCertificate = require('../../src/models/CompletionCertificate'); +const CourseBill = require('../../src/models/CourseBill'); const { authCompany, otherCompany, companyWithoutSubscription } = require('../seed/authCompaniesSeed'); const { holdingAdminFromOtherCompany } = require('../seed/authUsersSeed'); @@ -219,6 +225,22 @@ describe('COMPLETION CERTIFICATES ROUTES - PUT /completioncertificates/{_id}', ( sinon.assert.calledOnce(uploadCourseFile); }); + it('should generate completion certificates file and set the real price on the month bills', async () => { + const payload = { action: GENERATION }; + uploadCourseFile.returns({ publicId: '1234', link: 'https://test.com/completionCertificate.pdf' }); + + const response = await app.inject({ + method: 'PUT', + url: `/completioncertificates/${completionCertificateList[9]._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload, + }); + + expect(response.statusCode).toBe(200); + const billCount = await CourseBill.countDocuments({ _id: courseBillsList[0]._id, 'mainFee.price': 200 }); + expect(billCount).toBe(1); + }); + it('should return 404 if completion certificate does not exist', async () => { const payload = { action: GENERATION }; const response = await app.inject({ @@ -391,6 +413,18 @@ describe('COMPLETION CERTIFICATES ROUTES - DELETE /completioncertificates/{_id}/ sinon.assert.calledOnce(deleteCourseFile); }); + it('should delete completion certificate file and reset the real price of the month bills', async () => { + const response = await app.inject({ + method: 'DELETE', + url: `/completioncertificates/${completionCertificateList[10]._id}/file`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + const billCount = await CourseBill.countDocuments({ _id: courseBillsList[1]._id, 'mainFee.price': 0 }); + expect(billCount).toBe(1); + }); + it('should return 404 if completion certificate does not exist', async () => { const response = await app.inject({ method: 'DELETE', diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index 0436f26de0..251aaf2bd7 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -891,7 +891,11 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { method: 'POST', url: '/coursebills/list-creation', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, - payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + payload: { + ...singleCoursePayload, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, }); expect(response.statusCode).toBe(200); @@ -900,6 +904,17 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(course.hourlyPaymentPlan).toEqual(hourlyPaymentPlanId); }); + it('should return 400 if price sent with an hourly payment plan', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(400); + }); + it('should return 404 if hourly payment plan does not exist on the subProgram', async () => { const response = await app.inject({ method: 'POST', diff --git a/tests/integration/seed/completionCertificatesSeed.js b/tests/integration/seed/completionCertificatesSeed.js index 1c26c0c418..0d6494a9a7 100644 --- a/tests/integration/seed/completionCertificatesSeed.js +++ b/tests/integration/seed/completionCertificatesSeed.js @@ -7,12 +7,22 @@ const Card = require('../../../src/models/Card'); const Course = require('../../../src/models/Course'); const CourseSlot = require('../../../src/models/CourseSlot'); const CompletionCertificate = require('../../../src/models/CompletionCertificate'); +const CourseBill = require('../../../src/models/CourseBill'); const Step = require('../../../src/models/Step'); const SubProgram = require('../../../src/models/SubProgram'); const User = require('../../../src/models/User'); const UserCompany = require('../../../src/models/UserCompany'); const Program = require('../../../src/models/Program'); -const { INTER_B2B, PUBLISHED, MONTHLY, VIDEO, E_LEARNING, WEBAPP, PRESENT } = require('../../../src/helpers/constants'); +const { + INTER_B2B, + PUBLISHED, + MONTHLY, + VIDEO, + E_LEARNING, + WEBAPP, + PRESENT, + GROUP, +} = require('../../../src/helpers/constants'); const { authCompany, otherCompany, companyWithoutSubscription } = require('../../seed/authCompaniesSeed'); const { trainer, @@ -54,9 +64,17 @@ const stepList = [ }, ]; +const hourlyPaymentPlanId = new ObjectId(); + const subProgramList = [ { _id: new ObjectId(), name: 'Subprogram 1', steps: [stepList[0]._id], status: PUBLISHED }, - { _id: new ObjectId(), name: 'Subprogram 2', steps: [stepList[1]._id], status: PUBLISHED }, + { + _id: new ObjectId(), + name: 'Subprogram 2', + steps: [stepList[1]._id], + status: PUBLISHED, + hourlyPaymentPlans: [{ _id: hourlyPaymentPlanId, prices: [{ step: stepList[1]._id, hourlyAmount: 50 }] }], + }, { _id: new ObjectId(), name: 'Subprogram 3', steps: [stepList[2]._id], status: PUBLISHED }, ]; @@ -130,6 +148,7 @@ const courseList = [ operationsRepresentative: trainerOrganisationManager._id, trainers: [trainer._id], certificateGenerationMode: MONTHLY, + hourlyPaymentPlan: hourlyPaymentPlanId, tradeName: 'nom', }, { // 3 Archived course with monthly certificateGenerationMode @@ -275,6 +294,38 @@ const completionCertificateList = [ month: '12-2024', file: { publicId: 'certif12', link: 'https://test.com/certif1234' }, }, + { // 9 hourly payment plan + _id: new ObjectId(), + course: courseList[2]._id, + trainee: auxiliary._id, + month: '01-2020', + }, + { // 10 hourly payment plan, with file + _id: new ObjectId(), + course: courseList[2]._id, + trainee: auxiliary._id, + month: '01-2020', + file: { publicId: 'certif2020', link: 'https://test.com/certif2020' }, + }, +]; + +const courseBillsList = [ + { // 0 bill to update when the certificate is generated + _id: new ObjectId(), + course: courseList[2]._id, + companies: [authCompany._id], + payer: { company: authCompany._id }, + mainFee: { price: 0, count: 1, countUnit: GROUP }, + maturityDate: '2020-01-15T10:00:00.000Z', + }, + { // 1 bill with the real price, to reset when the certificate file is deleted + _id: new ObjectId(), + course: courseList[2]._id, + companies: [authCompany._id], + payer: { company: authCompany._id }, + mainFee: { price: 200, count: 1, countUnit: GROUP }, + maturityDate: '2020-01-20T10:00:00.000Z', + }, ]; const populateDB = async () => { @@ -288,6 +339,7 @@ const populateDB = async () => { Course.create(courseList), CourseSlot.create(slotsList), CompletionCertificate.create(completionCertificateList), + CourseBill.create(courseBillsList), Step.create(stepList), SubProgram.create(subProgramList), Program.create(programsList), @@ -296,4 +348,4 @@ const populateDB = async () => { ]); }; -module.exports = { populateDB, courseList, completionCertificateList }; +module.exports = { populateDB, courseList, completionCertificateList, courseBillsList }; diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index 242b65f089..5932fa5b53 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -7,12 +7,16 @@ const CompletionCertificate = require('../../../src/models/CompletionCertificate const TrainingContract = require('../../../src/models/TrainingContract'); const ActivityHistory = require('../../../src/models/ActivityHistory'); const Course = require('../../../src/models/Course'); +const CourseBill = require('../../../src/models/CourseBill'); const CompletionCertificatesHelper = require('../../../src/helpers/completionCertificates'); const GCloudStorageHelper = require('../../../src/helpers/gCloudStorage'); const CoursesHelper = require('../../../src/helpers/courses'); +const HourlyPaymentPlansHelper = require('../../../src/helpers/hourlyPaymentPlans'); +const CourseSlotsHelper = require('../../../src/helpers/courseSlots'); const CompletionCertificatePdf = require('../../../src/data/pdf/completionCertificate'); -const { OFFICIAL, BLENDED, E_LEARNING, PRESENT } = require('../../../src/helpers/constants'); +const { OFFICIAL, BLENDED, E_LEARNING, PRESENT, MM_YYYY, MONTH } = require('../../../src/helpers/constants'); const UtilsHelper = require('../../../src/helpers/utils'); +const { CompaniDate } = require('../../../src/helpers/dates/companiDates'); const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); const UtilsMock = require('../../utilsMock'); @@ -431,11 +435,15 @@ describe('generate', () => { let uploadCourseFile; let updateOne; let findActivityHistories; - let getTotalDuration; + let getDurationPerStep; let courseFind; let getELearningDuration; let getRealELearningDuration; + let findBills; + let updateManyBills; + let getPriceFromDurations; const PRI_SUBPROGRAM_IDS = new ObjectId(); + const stepId = new ObjectId(); const REAL_ELEARNING_DURATION_SUBPROGRAM_ID = new ObjectId(); beforeEach(() => { @@ -449,10 +457,13 @@ describe('generate', () => { updateOne = sinon.stub(CompletionCertificate, 'updateOne'); UtilsMock.mockCurrentDate('2025-03-24T10:00:00.000Z'); findActivityHistories = sinon.stub(ActivityHistory, 'find'); - getTotalDuration = sinon.stub(UtilsHelper, 'getTotalDuration'); + getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); courseFind = sinon.stub(Course, 'find'); getELearningDuration = sinon.stub(CoursesHelper, 'getELearningDuration'); getRealELearningDuration = sinon.stub(CoursesHelper, 'getRealELearningDuration'); + findBills = sinon.stub(CourseBill, 'find'); + updateManyBills = sinon.stub(CourseBill, 'updateMany'); + getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); process.env.VAEI_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; process.env.PRI_SUBPROGRAM_IDS = PRI_SUBPROGRAM_IDS; process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; @@ -470,22 +481,28 @@ describe('generate', () => { updateOne.restore(); UtilsMock.unmockCurrentDate(); findActivityHistories.restore(); - getTotalDuration.restore(); + getDurationPerStep.restore(); courseFind.restore(); getELearningDuration.restore(); getRealELearningDuration.restore(); + findBills.restore(); + updateManyBills.restore(); + getPriceFromDurations.restore(); process.env.VAEI_SUBPROGRAM_IDS = ''; process.env.PRI_SUBPROGRAM_IDS = ''; process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = ''; process.env.VAE_SUPPORT_CONFIGS = ''; }); - it('should generate completion certificate (with theoretical elearning duration)', async () => { + it('should generate completion certificate (with theoretical elearning duration) (and add bill price)', async () => { const completionCertificateId = new ObjectId(); const traineeId = new ObjectId(); const companyId = new ObjectId(); const courseId = new ObjectId(); const month = '03-2025'; + const hourlyPaymentPlan = { _id: new ObjectId(), prices: [{ step: stepId, hourlyAmount: 40 }] }; + const billId = new ObjectId(); + const durationPerStep = { [stepId]: CompaniDuration({ minutes: 390 }) }; const slotList = [ { _id: new ObjectId(), startDate: '2025-01-20T10:00:00.000Z', endDate: '2025-01-20T14:00:00.000Z' }, { _id: new ObjectId(), startDate: '2025-03-14T10:00:00.000Z', endDate: '2025-03-14T14:00:00.000Z' }, @@ -530,6 +547,7 @@ describe('generate', () => { subProgram: { _id: subProgramIds[0], program: { subPrograms: subProgramIds }, + hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ { type: E_LEARNING, @@ -540,6 +558,7 @@ describe('generate', () => { }, companies: [companyId], trainees: [traineeId], + hourlyPaymentPlan: hourlyPaymentPlan._id, }, month, trainee: { @@ -591,7 +610,9 @@ describe('generate', () => { SinonMongoose.stubChainedQueries({ startDate: '2025-01-01T00:00:00.000Z' }, ['sort', 'lean']) ); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getTotalDuration.returns(CompaniDuration({ minutes: 390 })); + getDurationPerStep.returns(durationPerStep); + findBills.returns(SinonMongoose.stubChainedQueries([{ _id: billId }], ['setOptions', 'lean'])); + getPriceFromDurations.returns(260); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getELearningDuration.returns('PT3H30M'); @@ -610,7 +631,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -620,13 +641,10 @@ describe('generate', () => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -658,9 +676,8 @@ describe('generate', () => { ] ); sinon.assert.calledOnceWithExactly( - getTotalDuration, - [slotList[1], { startDate: '2025-03-22T07:00:00.000Z', endDate: '2025-03-22T09:30:00.000Z' }], - false + getDurationPerStep, + [slotList[1], { startDate: '2025-03-22T07:00:00.000Z', endDate: '2025-03-22T09:30:00.000Z' }] ); SinonMongoose.calledWithExactly( courseFind, @@ -745,6 +762,33 @@ describe('generate', () => { { query: 'lean' }, ] ); + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), + }, + 'mainFee.price': 0, + }, + { _id: 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + sinon.assert.calledOnceWithExactly(getPriceFromDurations, hourlyPaymentPlan, durationPerStep, 'PT3H30M'); + sinon.assert.calledOnceWithExactly( + updateManyBills, + { _id: { $in: [billId] } }, + { $set: { 'mainFee.price': 260 } } + ); }); it('should generate completion certificate (with real elearning duration)', async () => { @@ -843,7 +887,7 @@ describe('generate', () => { ); findCompletionCertificate.returns(SinonMongoose.stubChainedQueries([{ month: '02-2025' }], ['setOptions', 'lean'])); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getTotalDuration.returns(CompaniDuration({ minutes: 390 })); + getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getRealELearningDuration.returns('PT200S'); @@ -862,7 +906,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -872,13 +916,10 @@ describe('generate', () => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -910,9 +951,8 @@ describe('generate', () => { ] ); sinon.assert.calledOnceWithExactly( - getTotalDuration, - [slotList[1], { startDate: '2025-03-22T07:00:00.000Z', endDate: '2025-03-22T09:30:00.000Z' }], - false + getDurationPerStep, + [slotList[1], { startDate: '2025-03-22T07:00:00.000Z', endDate: '2025-03-22T09:30:00.000Z' }] ); SinonMongoose.calledWithExactly( courseFind, @@ -987,6 +1027,9 @@ describe('generate', () => { ] ); sinon.assert.notCalled(findOneTrainingContract); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(getPriceFromDurations); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { @@ -1087,7 +1130,7 @@ describe('generate', () => { findCompletionCertificate.onCall(1).returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'sort', 'lean'])); findOneTrainingContract.returns(SinonMongoose.stubChainedQueries(null, ['sort', 'lean'])); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getTotalDuration.returns(CompaniDuration({ minutes: 390 })); + getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getRealELearningDuration.returns('PT200S'); @@ -1106,7 +1149,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -1116,13 +1159,10 @@ describe('generate', () => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -1195,9 +1235,8 @@ describe('generate', () => { ] ); sinon.assert.calledOnceWithExactly( - getTotalDuration, - [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }], - false + getDurationPerStep, + [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }] ); SinonMongoose.calledWithExactly( courseFind, @@ -1258,6 +1297,9 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 330 } } ); sinon.assert.notCalled(getELearningDuration); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(getPriceFromDurations); }); it('should generate completion certificate in VAE period (attendance exceeds remaining budget)', async () => { @@ -1363,7 +1405,7 @@ describe('generate', () => { ); findOneTrainingContract.returns(SinonMongoose.stubChainedQueries(null, ['sort', 'lean'])); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getTotalDuration.returns(CompaniDuration({ minutes: 390 })); + getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getRealELearningDuration.returns('PT200S'); @@ -1382,7 +1424,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -1392,13 +1434,10 @@ describe('generate', () => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -1471,9 +1510,8 @@ describe('generate', () => { ] ); sinon.assert.calledOnceWithExactly( - getTotalDuration, - [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }], - false + getDurationPerStep, + [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }] ); SinonMongoose.calledWithExactly( courseFind, @@ -1534,6 +1572,9 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 0 } } ); sinon.assert.notCalled(getELearningDuration); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(getPriceFromDurations); }); it('should generate completion certificate normally when VAE period budget is exhausted', async () => { @@ -1636,7 +1677,7 @@ describe('generate', () => { ); findOneTrainingContract.returns(SinonMongoose.stubChainedQueries(null, ['sort', 'lean'])); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getTotalDuration.returns(CompaniDuration({ minutes: 390 })); + getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getRealELearningDuration.returns('PT200S'); @@ -1655,7 +1696,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName', + select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', populate: [ { path: 'slots', @@ -1665,13 +1706,10 @@ describe('generate', () => { }, { path: 'subProgram', - select: 'program steps', + select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { - path: 'steps', - select: 'activities type theoreticalDuration', - }, + { path: 'steps', select: 'activities type theoreticalDuration' }, ], }, ], @@ -1744,9 +1782,8 @@ describe('generate', () => { ] ); sinon.assert.calledOnceWithExactly( - getTotalDuration, - [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }], - false + getDurationPerStep, + [slotList[1], { startDate: '2026-03-22T07:00:00.000Z', endDate: '2026-03-22T09:30:00.000Z' }] ); SinonMongoose.calledWithExactly( courseFind, @@ -1806,6 +1843,9 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' } } } ); sinon.assert.notCalled(getELearningDuration); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(getPriceFromDurations); }); }); @@ -1831,41 +1871,69 @@ describe('create', () => { describe('deleteFile', () => { let findOne; + let findOneCourse; let find; let updateOne; let updateMany; let deleteCourseFile; + let getUnsubscribedAttendances; + let getTraineeDurations; + let getDurationPerStep; + let getPriceFromDurations; + let findBills; + let updateManyBills; beforeEach(() => { findOne = sinon.stub(CompletionCertificate, 'findOne'); + findOneCourse = sinon.stub(Course, 'findOne'); find = sinon.stub(CompletionCertificate, 'find'); updateOne = sinon.stub(CompletionCertificate, 'updateOne'); updateMany = sinon.stub(CompletionCertificate, 'updateMany'); deleteCourseFile = sinon.stub(GCloudStorageHelper, 'deleteCourseFile'); + getUnsubscribedAttendances = sinon.stub(CoursesHelper, 'getUnsubscribedAttendances'); + getTraineeDurations = sinon.stub(CoursesHelper, 'getTraineeDurations'); + getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); + getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); + findBills = sinon.stub(CourseBill, 'find'); + updateManyBills = sinon.stub(CourseBill, 'updateMany'); }); afterEach(() => { findOne.restore(); + findOneCourse.restore(); find.restore(); updateOne.restore(); updateMany.restore(); deleteCourseFile.restore(); + getUnsubscribedAttendances.restore(); + getTraineeDurations.restore(); + getDurationPerStep.restore(); + getPriceFromDurations.restore(); + findBills.restore(); + updateManyBills.restore(); }); it('should remove the file of a completion certificat', async () => { const completionCertificateId = new ObjectId(); const completionCertificate = { _id: completionCertificateId, - trainee: new ObjectId(), - course: new ObjectId(), + trainee: { _id: new ObjectId() }, + course: { _id: new ObjectId() }, month: '03-2025', file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, }; - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); await CompletionCertificatesHelper.deleteFile(completionCertificateId); SinonMongoose.calledOnceWithExactly( findOne, - [{ query: 'findOne', args: [{ _id: completionCertificateId }] }, { query: 'lean' }] + [ + { query: 'findOne', args: [{ _id: completionCertificateId }] }, + { + query: 'populate', + args: [{ path: 'course', select: 'hourlyPaymentPlan' }], + }, + { query: 'lean' }, + ] ); sinon.assert.calledOnceWithExactly( updateOne, @@ -1875,6 +1943,13 @@ describe('deleteFile', () => { sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); sinon.assert.notCalled(find); sinon.assert.notCalled(updateMany); + sinon.assert.notCalled(findOneCourse); + sinon.assert.notCalled(getUnsubscribedAttendances); + sinon.assert.notCalled(getTraineeDurations); + sinon.assert.notCalled(getDurationPerStep); + sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); }); it('should remove the file of a completion certificat', async () => { @@ -1884,7 +1959,7 @@ describe('deleteFile', () => { const completionCertificate = { _id: completionCertificateIds[0], trainee: traineeId, - course: courseId, + course: { _id: courseId }, month: '03-2025', file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, vaeSupportRemainingMinutes: 100, @@ -1897,14 +1972,21 @@ describe('deleteFile', () => { file: { publicId: 'completionCertificateTest_2', link: 'test/completionCertificateTest_2' }, vaeSupportRemainingMinutes: 0, }]; - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); find.returns(SinonMongoose.stubChainedQueries(completionCertificatesWithRemaingMinutes, ['setOptions', 'lean'])); await CompletionCertificatesHelper.deleteFile(completionCertificateIds[0]); SinonMongoose.calledOnceWithExactly( findOne, - [{ query: 'findOne', args: [{ _id: completionCertificateIds[0] }] }, { query: 'lean' }] + [ + { query: 'findOne', args: [{ _id: completionCertificateIds[0] }] }, + { + query: 'populate', + args: [{ path: 'course', select: 'hourlyPaymentPlan' }], + }, + { query: 'lean' }, + ] ); SinonMongoose.calledOnceWithExactly( @@ -1923,5 +2005,56 @@ describe('deleteFile', () => { sinon.assert.calledWithExactly(deleteCourseFile.getCall(0), 'completionCertificateTest'); sinon.assert.calledWithExactly(deleteCourseFile.getCall(1), 'completionCertificateTest_2'); sinon.assert.notCalled(updateOne); + sinon.assert.notCalled(findOneCourse); + sinon.assert.notCalled(getUnsubscribedAttendances); + sinon.assert.notCalled(getTraineeDurations); + sinon.assert.notCalled(getDurationPerStep); + sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(findBills); + sinon.assert.notCalled(updateManyBills); + }); + + it('should remove the real price of the bills and the file of a completion certificat', async () => { + const completionCertificateId = new ObjectId(); + const courseId = new ObjectId(); + const traineeId = new ObjectId(); + const stepId = new ObjectId(); + const hourlyPaymentPlanId = new ObjectId(); + const hourlyPaymentPlan = { _id: hourlyPaymentPlanId, prices: [{ step: stepId, hourlyAmount: 50 }] }; + const completionCertificate = { + _id: completionCertificateId, + month: '03-2025', + file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, + trainee: traineeId, + course: { _id: courseId, hourlyPaymentPlan: hourlyPaymentPlanId }, + }; + const course = { + _id: courseId, + slots: [], + hourlyPaymentPlan: hourlyPaymentPlanId, + subProgram: { _id: new ObjectId(), steps: [], hourlyPaymentPlans: [hourlyPaymentPlan] }, + }; + const billId = new ObjectId(); + const eLearningDuration = CompaniDuration('PT3600S'); + const durationPerStep = { [stepId]: CompaniDuration('PT7200S') }; + + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); + getUnsubscribedAttendances.returns([]); + findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); + getTraineeDurations.returns({ slotsWithAttendance: [], eLearningDuration }); + getDurationPerStep.returns(durationPerStep); + getPriceFromDurations.returns(150); + findBills.returns(SinonMongoose.stubChainedQueries([{ _id: billId }], ['setOptions', 'lean'])); + + await CompletionCertificatesHelper.deleteFile(completionCertificateId); + + sinon.assert.calledOnceWithExactly(getPriceFromDurations, hourlyPaymentPlan, durationPerStep, eLearningDuration); + sinon.assert.calledOnceWithExactly(updateManyBills, { _id: { $in: [billId] } }, { $set: { 'mainFee.price': 0 } }); + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: completionCertificateId }, + { $unset: { file: '', vaeSupportRemainingMinutes: '' } } + ); + sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); }); }); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index 70204dbb13..14bfd10d78 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -6,6 +6,10 @@ const ActivityHistory = require('../../../src/models/ActivityHistory'); const Course = require('../../../src/models/Course'); const CourseBill = require('../../../src/models/CourseBill'); const SubProgram = require('../../../src/models/SubProgram'); +const CoursesHelper = require('../../../src/helpers/courses'); +const HourlyPaymentPlansHelper = require('../../../src/helpers/hourlyPaymentPlans'); +const CourseSlotsHelper = require('../../../src/helpers/courseSlots'); +const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); const CourseBillHelper = require('../../../src/helpers/courseBills'); const CourseHistoriesHelper = require('../../../src/helpers/courseHistories'); const VendorCompaniesHelper = require('../../../src/helpers/vendorCompanies'); @@ -25,6 +29,7 @@ const { TRAINEE, SINGLE, GROUP, + GLOBAL, INTER_B2B, RECEIVED, XML_GENERATED, @@ -1145,9 +1150,82 @@ describe('list', () => { }); }); +describe('computePriceFromDurations', () => { + let findOneCourse; + let getTraineeDurations; + let getDurationPerStep; + let getPriceFromDurations; + + beforeEach(() => { + findOneCourse = sinon.stub(Course, 'findOne'); + getTraineeDurations = sinon.stub(CoursesHelper, 'getTraineeDurations'); + getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); + getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); + }); + + afterEach(() => { + findOneCourse.restore(); + getTraineeDurations.restore(); + getDurationPerStep.restore(); + getPriceFromDurations.restore(); + }); + + it('should compute the price of the course from the chosen hourly payment plan', async () => { + const courseId = new ObjectId(); + const traineeId = new ObjectId(); + const hourlyPaymentPlans = [{ _id: new ObjectId(), prices: [] }, { _id: new ObjectId(), prices: [] }]; + const slotsWithAttendance = [{ _id: new ObjectId() }]; + const eLearningDuration = CompaniDuration({ minutes: 60 }); + const durationPerStep = { [new ObjectId()]: CompaniDuration({ minutes: 120 }) }; + + const course = { subProgram: { hourlyPaymentPlans }, slots: [], trainees: [traineeId] }; + + findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); + getTraineeDurations.returns({ slotsWithAttendance, eLearningDuration }); + getDurationPerStep.returns(durationPerStep); + getPriceFromDurations.returns(300); + + const result = await CourseBillHelper.computePriceFromDurations(courseId, hourlyPaymentPlans[1]._id); + + expect(result).toBe(300); + SinonMongoose.calledOnceWithExactly( + findOneCourse, + [ + { query: 'findOne', args: [{ _id: courseId }, { subProgram: 1, slots: 1, trainees: 1 }] }, + { + query: 'populate', + args: [{ + path: 'slots', + select: 'startDate endDate trainers step', + populate: { path: 'step', select: 'durationCountedPerTrainer' }, + }], + }, + { + query: 'populate', + args: [{ + path: 'subProgram', + select: 'steps hourlyPaymentPlans', + populate: { path: 'steps', select: 'activities type theoreticalDuration' }, + }], + }, + { query: 'lean' }, + ] + ); + sinon.assert.calledOnceWithExactly(getTraineeDurations, course, traineeId); + sinon.assert.calledOnceWithExactly(getDurationPerStep, slotsWithAttendance); + sinon.assert.calledOnceWithExactly( + getPriceFromDurations, + hourlyPaymentPlans[1], + durationPerStep, + eLearningDuration + ); + }); +}); + describe('createBillList', () => { let findOneCourse; let updateOneCourse; + let computePriceFromDurations; let createCourseBill; let insertManyCourseBills; let addBillingPurchase; @@ -1157,6 +1235,7 @@ describe('createBillList', () => { beforeEach(() => { findOneCourse = sinon.stub(Course, 'findOne'); updateOneCourse = sinon.stub(Course, 'updateOne'); + computePriceFromDurations = sinon.stub(CourseBillHelper, 'computePriceFromDurations'); createCourseBill = sinon.stub(CourseBill, 'create'); insertManyCourseBills = sinon.stub(CourseBill, 'insertMany'); addBillingPurchase = sinon.stub(CourseBillHelper, 'addBillingPurchase'); @@ -1167,6 +1246,7 @@ describe('createBillList', () => { afterEach(() => { findOneCourse.restore(); updateOneCourse.restore(); + computePriceFromDurations.restore(); createCourseBill.restore(); insertManyCourseBills.restore(); addBillingPurchase.restore(); @@ -1174,12 +1254,19 @@ describe('createBillList', () => { process.env.MANAGEMENT_FEES_BILLING_ITEM = ''; }); - it('should create one bill without percentage for INTER course', async () => { - const course = { type: INTER_B2B, prices: [], subProgram: { subjectToVat: false } }; + it('should create one bill with real price for a GLOBAL certification course', async () => { + const courseId = new ObjectId(); + const course = { + _id: courseId, + type: INTER_B2B, + prices: [], + subProgram: { subjectToVat: false }, + certificateGenerationMode: GLOBAL, + }; const payload = { - course: new ObjectId(), + course: courseId, quantity: 1, - mainFee: { price: 100, count: 1, countUnit: GROUP, description: 'test' }, + mainFee: { count: 1, countUnit: GROUP, description: 'test' }, companies: [new ObjectId()], payer: { fundingOrganisation: new ObjectId() }, maturityDate: '2025-04-29T22:00:00.000Z', @@ -1187,9 +1274,11 @@ describe('createBillList', () => { }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); + computePriceFromDurations.returns(250); await CourseBillHelper.createBillList(payload); + sinon.assert.calledOnceWithExactly(computePriceFromDurations, payload.course, payload.hourlyPaymentPlanId); sinon.assert.calledOnceWithExactly( updateOneCourse, { _id: payload.course }, @@ -1201,7 +1290,7 @@ describe('createBillList', () => { { course: payload.course, mainFee: { - price: 100, + price: 250, count: 1, countUnit: GROUP, description: 'test', @@ -1448,7 +1537,18 @@ describe('createBillList', () => { [ { query: 'findOne', - args: [{ _id: course._id }, { type: 1, prices: 1, trainees: 1, trainers: 1, subProgram: 1 }], + args: [ + { _id: course._id }, + { + type: 1, + prices: 1, + trainees: 1, + trainers: 1, + subProgram: 1, + hourlyPaymentPlan: 1, + certificateGenerationMode: 1, + }, + ], }, { query: 'populate', args: [{ path: 'trainees', select: 'identity' }] }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, @@ -1525,7 +1625,18 @@ describe('createBillList', () => { [ { query: 'findOne', - args: [{ _id: course._id }, { type: 1, prices: 1, trainees: 1, trainers: 1, subProgram: 1 }], + args: [ + { _id: course._id }, + { + type: 1, + prices: 1, + trainees: 1, + trainers: 1, + subProgram: 1, + hourlyPaymentPlan: 1, + certificateGenerationMode: 1, + }, + ], }, { query: 'populate', args: [{ path: 'trainees', select: 'identity' }] }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, diff --git a/tests/unit/helpers/courseSlots.test.js b/tests/unit/helpers/courseSlots.test.js index 59f1d4dadd..193e392506 100644 --- a/tests/unit/helpers/courseSlots.test.js +++ b/tests/unit/helpers/courseSlots.test.js @@ -1735,3 +1735,20 @@ describe('removeCourseSlot', () => { sinon.assert.calledOnceWithExactly(deleteOne, { _id: courseSlotId }); }); }); + +describe('getDurationPerStep', () => { + it('should return the total duration of the slots for each step', () => { + const steps = [{ _id: new ObjectId() }, { _id: new ObjectId() }]; + const slots = [ + { startDate: '2025-03-10T08:00:00.000Z', endDate: '2025-03-10T10:00:00.000Z', step: steps[0] }, + { startDate: '2025-03-11T08:00:00.000Z', endDate: '2025-03-11T09:30:00.000Z', step: steps[0] }, + { startDate: '2025-03-12T08:00:00.000Z', endDate: '2025-03-12T09:00:00.000Z', step: steps[1] }, + ]; + + const result = CourseSlotsHelper.getDurationPerStep(slots); + + expect(Object.keys(result)).toEqual([steps[0]._id.toString(), steps[1]._id.toString()]); + expect(result[steps[0]._id.toString()].asHours()).toBe(3.5); + expect(result[steps[1]._id.toString()].asHours()).toBe(1); + }); +}); diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 32d43e1e26..d26a69440f 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -12,6 +12,7 @@ const Company = require('../../../src/models/Company'); const Course = require('../../../src/models/Course'); const CourseBill = require('../../../src/models/CourseBill'); const SubProgram = require('../../../src/models/SubProgram'); +const ActivityHistory = require('../../../src/models/ActivityHistory'); const Attendance = require('../../../src/models/Attendance'); const User = require('../../../src/models/User'); const CourseHistory = require('../../../src/models/CourseHistory'); @@ -23,6 +24,7 @@ const Questionnaire = require('../../../src/models/Questionnaire'); const TrainingContract = require('../../../src/models/TrainingContract'); const CompanyHelper = require('../../../src/helpers/companies'); const CourseHelper = require('../../../src/helpers/courses'); +const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); const CourseBillHelper = require('../../../src/helpers/courseBills'); const CourseCreditNoteHelper = require('../../../src/helpers/courseCreditNotes'); const EmailHelper = require('../../../src/helpers/email'); @@ -11256,3 +11258,72 @@ describe('downloadAllDocuments', () => { ); }); }); + +describe('getTraineeDurations', () => { + let findAttendance; + let findActivityHistories; + let getELearningDuration; + + beforeEach(() => { + process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = new ObjectId().toHexString(); + findAttendance = sinon.stub(Attendance, 'find'); + findActivityHistories = sinon.stub(ActivityHistory, 'find'); + getELearningDuration = sinon.stub(CourseHelper, 'getELearningDuration'); + }); + + afterEach(() => { + findAttendance.restore(); + findActivityHistories.restore(); + getELearningDuration.restore(); + }); + + it('should return the slots with attendance on the period and the e-learning duration', async () => { + const traineeId = new ObjectId(); + const activityId = new ObjectId(); + const slots = [ + { _id: new ObjectId(), startDate: '2025-02-10T08:00:00.000Z', endDate: '2025-02-10T10:00:00.000Z' }, + { _id: new ObjectId(), startDate: '2025-03-10T08:00:00.000Z', endDate: '2025-03-10T10:00:00.000Z' }, + { _id: new ObjectId(), startDate: '2025-03-11T08:00:00.000Z', endDate: '2025-03-11T10:00:00.000Z' }, + ]; + const course = { + _id: new ObjectId(), + slots, + subProgram: { + _id: new ObjectId(), + steps: [{ type: 'e_learning', activities: [activityId] }, { type: 'on_site' }], + }, + }; + const dates = { startDate: '2025-03-01T00:00:00.000Z', endDate: '2025-03-31T23:59:59.000Z' }; + const activityHistories = [{ _id: new ObjectId(), activity: activityId, user: traineeId }]; + const eLearningDuration = CompaniDuration({ minutes: 90 }); + + findAttendance.returns(SinonMongoose.stubChainedQueries([{ courseSlot: slots[1]._id }], ['setOptions', 'lean'])); + findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + getELearningDuration.returns(eLearningDuration); + + const result = await CourseHelper.getTraineeDurations(course, traineeId, dates); + + expect(result).toEqual({ slotsWithAttendance: [slots[1]], eLearningDuration }); + SinonMongoose.calledOnceWithExactly( + findAttendance, + [ + { + query: 'find', + args: [{ trainee: traineeId, courseSlot: { $in: [slots[1]._id, slots[2]._id] }, status: 'present' }], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + SinonMongoose.calledOnceWithExactly( + findActivityHistories, + [{ query: 'find', args: [{ activity: { $in: [activityId] }, user: traineeId }] }, { query: 'lean' }] + ); + sinon.assert.calledOnceWithExactly( + getELearningDuration, + [{ type: 'e_learning', activities: [{ _id: activityId, activityHistories }] }], + traineeId, + dates + ); + }); +}); diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js new file mode 100644 index 0000000000..33a25015c9 --- /dev/null +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -0,0 +1,35 @@ +const { expect } = require('expect'); +const { ObjectId } = require('mongodb'); +const HourlyPaymentPlansHelper = require('../../../src/helpers/hourlyPaymentPlans'); +const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); + +describe('getPriceFromDurations', () => { + it('should compute price from on-site steps and e-learning durations', () => { + const stepIds = [new ObjectId(), new ObjectId()]; + const hourlyPaymentPlan = { + prices: [{ step: stepIds[0], hourlyAmount: 50 }, { step: stepIds[1], hourlyAmount: 80 }], + elearningPrice: 20, + }; + const durationPerStep = { + [stepIds[0]]: CompaniDuration({ minutes: 210 }), + [stepIds[1]]: CompaniDuration({ minutes: 60 }), + }; + + const result = HourlyPaymentPlansHelper + .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ minutes: 90 })); + + expect(result).toBe(50 * 3.5 + 80 + 20 * 1.5); + }); + + it('should ignore e-learning if there is no e-learning price', () => { + const stepId = new ObjectId(); + const hourlyPaymentPlan = { prices: [{ step: stepId, hourlyAmount: 40 }] }; + + const durationPerStep = { [stepId]: CompaniDuration({ minutes: 30 }) }; + + const result = HourlyPaymentPlansHelper + .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ hours: 2 })); + + expect(result).toBe(20); + }); +}); From bc222debb56f84a1a2fb3b63c868c09ff8f9b8fd Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 29 Oct 2026 17:16:11 +0100 Subject: [PATCH 15/53] COM-4315: fixes --- src/helpers/completionCertificates.js | 95 ++++++++++--------- .../helpers/completionCertificates.test.js | 66 ++++++++++++- 2 files changed, 115 insertions(+), 46 deletions(-) diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index f5d9ea849a..439c13d775 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -231,7 +231,11 @@ exports.generate = async (completionCertificateId) => { if (course.hourlyPaymentPlan) { const billsToUpdate = await CourseBill .find( - { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': 0 }, + { + course: course._id, + maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, + 'mainFee.price': { $in: [0, null] }, + }, { _id: 1 } ) .setOptions({ isVendorUser: true }) @@ -257,9 +261,35 @@ exports.deleteFile = async (completionCertificateId) => { .populate({ path: 'course', select: 'hourlyPaymentPlan' }) .lean(); - if (completionCertificate.course.hourlyPaymentPlan) { - const { month, trainee } = completionCertificate; + let certificatesToDelete = [completionCertificate]; + if (completionCertificate.vaeSupportRemainingMinutes) { + const { course, trainee, vaeSupportRemainingMinutes } = completionCertificate; + const completionCertificateWithRemainingMinutes = await CompletionCertificate + .find({ + course: course._id, + trainee, + vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes }, + }) + .setOptions({ isVendorUser: true }) + .lean(); + certificatesToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; + await CompletionCertificate.updateMany( + { _id: { $in: certificatesToDelete.map(c => c._id) } }, + { $unset: { file: '', vaeSupportRemainingMinutes: '' } } + ); + for (const certificate of certificatesToDelete) { + await GCloudStorageHelper.deleteCourseFile(certificate.file.publicId); + } + } else { + await CompletionCertificate.updateOne( + { _id: completionCertificateId }, + { $unset: { file: '', vaeSupportRemainingMinutes: '' } } + ); + + await GCloudStorageHelper.deleteCourseFile(completionCertificate.file.publicId); + } + if (completionCertificate.course.hourlyPaymentPlan) { const course = await Course .findOne( { _id: completionCertificate.course._id }, @@ -280,51 +310,26 @@ exports.deleteFile = async (completionCertificateId) => { }) .lean(); - const durations = await computeMonthDurations(course, month, trainee); - const { startOfMonth, endOfMonth, durationPerStep, eLearningDuration } = durations; - - const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans - .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); - const price = HourlyPaymentPlansHelper - .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + for (const certificate of certificatesToDelete) { + const durations = await computeMonthDurations(course, certificate.month, certificate.trainee); + const { startOfMonth, endOfMonth, durationPerStep, eLearningDuration } = durations; - const billsToReset = await CourseBill - .find( - { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': price }, - { _id: 1 } - ) - .setOptions({ isVendorUser: true }) - .lean(); + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); + const price = HourlyPaymentPlansHelper + .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); - if (billsToReset.length) { - await CourseBill.updateMany({ _id: { $in: billsToReset.map(b => b._id) } }, { $set: { 'mainFee.price': 0 } }); - } - } + const billsToReset = await CourseBill + .find( + { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': price }, + { _id: 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); - if (completionCertificate.vaeSupportRemainingMinutes) { - const { course, trainee, vaeSupportRemainingMinutes } = completionCertificate; - const completionCertificateWithRemainingMinutes = await CompletionCertificate - .find({ - course: course._id, - trainee, - vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes }, - }) - .setOptions({ isVendorUser: true }) - .lean(); - const certificateToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; - await CompletionCertificate.updateMany( - { _id: { $in: certificateToDelete.map(c => c._id) } }, - { $unset: { file: '', vaeSupportRemainingMinutes: '' } } - ); - for (const certificate of certificateToDelete) { - await GCloudStorageHelper.deleteCourseFile(certificate.file.publicId); + if (billsToReset.length) { + await CourseBill.updateMany({ _id: { $in: billsToReset.map(b => b._id) } }, { $set: { 'mainFee.price': 0 } }); + } } - } else { - await CompletionCertificate.updateOne( - { _id: completionCertificateId }, - { $unset: { file: '', vaeSupportRemainingMinutes: '' } } - ); - - await GCloudStorageHelper.deleteCourseFile(completionCertificate.file.publicId); } }; diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index 5932fa5b53..fd925d400d 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -774,7 +774,7 @@ describe('generate', () => { $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), }, - 'mainFee.price': 0, + 'mainFee.price': { $in: [0, null] }, }, { _id: 1 }, ], @@ -2056,5 +2056,69 @@ describe('deleteFile', () => { { $unset: { file: '', vaeSupportRemainingMinutes: '' } } ); sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); + sinon.assert.callOrder(deleteCourseFile, updateManyBills); + }); + + it('should remove the real price of the bills of every certificate deleted in cascade (VAE)', async () => { + const courseId = new ObjectId(); + const traineeId = new ObjectId(); + const stepId = new ObjectId(); + const hourlyPaymentPlan = { _id: new ObjectId(), prices: [{ step: stepId, hourlyAmount: 50 }] }; + const completionCertificates = [ + { + _id: new ObjectId(), + month: '03-2025', + trainee: traineeId, + course: { _id: courseId, hourlyPaymentPlan: hourlyPaymentPlan._id }, + file: { publicId: 'certif_03', link: 'test/certif_03' }, + vaeSupportRemainingMinutes: 100, + }, + { + _id: new ObjectId(), + month: '04-2025', + trainee: traineeId, + course: courseId, + file: { publicId: 'certif_04', link: 'test/certif_04' }, + vaeSupportRemainingMinutes: 0, + }, + ]; + const course = { + _id: courseId, + slots: [], + hourlyPaymentPlan: hourlyPaymentPlan._id, + subProgram: { _id: new ObjectId(), steps: [], hourlyPaymentPlans: [hourlyPaymentPlan] }, + }; + const bills = [{ _id: new ObjectId() }, { _id: new ObjectId() }]; + const eLearningDuration = CompaniDuration('PT3600S'); + const durationPerStep = { [stepId]: CompaniDuration('PT7200S') }; + + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificates[0], ['populate', 'lean'])); + find.returns(SinonMongoose.stubChainedQueries([completionCertificates[1]], ['setOptions', 'lean'])); + findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); + getUnsubscribedAttendances.returns([]); + getTraineeDurations.returns({ slotsWithAttendance: [], eLearningDuration }); + getDurationPerStep.returns(durationPerStep); + getPriceFromDurations.onFirstCall().returns(150); + getPriceFromDurations.onSecondCall().returns(90); + findBills.onFirstCall().returns(SinonMongoose.stubChainedQueries([bills[0]], ['setOptions', 'lean'])); + findBills.onSecondCall().returns(SinonMongoose.stubChainedQueries([bills[1]], ['setOptions', 'lean'])); + + await CompletionCertificatesHelper.deleteFile(completionCertificates[0]._id); + + sinon.assert.calledTwice(getPriceFromDurations); + sinon.assert.calledTwice(findBills); + sinon.assert.calledTwice(updateManyBills); + sinon.assert.calledWithExactly( + updateManyBills.getCall(0), + { _id: { $in: [bills[0]._id] } }, + { $set: { 'mainFee.price': 0 } } + ); + sinon.assert.calledWithExactly( + updateManyBills.getCall(1), + { _id: { $in: [bills[1]._id] } }, + { $set: { 'mainFee.price': 0 } } + ); + sinon.assert.calledTwice(deleteCourseFile); + sinon.assert.callOrder(deleteCourseFile, updateManyBills); }); }); From 0a0e0fb0e61c3bc7778e75eee2050defd0427fbd Mon Sep 17 00:00:00 2001 From: ulysse Date: Fri, 30 Oct 2026 11:35:18 +0100 Subject: [PATCH 16/53] COM-4315: block if course not over --- src/helpers/translate.js | 2 + src/routes/preHandlers/courseBills.js | 22 +++ tests/integration/courseBills.test.js | 69 +++++++-- tests/integration/seed/courseBillsSeed.js | 138 ++++++++++++++++++ .../seed/seedsVerification.test.js | 10 +- 5 files changed, 226 insertions(+), 15 deletions(-) diff --git a/src/helpers/translate.js b/src/helpers/translate.js index f39d3fa77d..c1214b5f5d 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -268,6 +268,7 @@ module.exports = { someSlotsAreLinkedToCompletionCertificate: 'Edition forbidden : some slots are linked to completion certificate.', traineeNotConcernedBySlot: 'Operation forbidden : trainee not concerned by slot.', someAttendancesAreEmpty: 'Operation forbidden : some attendances are empty.', + courseNotOver: 'Operation forbidden : the course is not over.', slotIsLinkedToTrainerBill: 'Operation forbidden : slot is paid and linked to a trainerBill.', /* Questionnaires */ questionnairesFound: 'Questionnaires found.', @@ -662,6 +663,7 @@ module.exports = { + 'certificat de réalisation.', traineeNotConcernedBySlot: 'Opération impossible : l\'apprenant n\'est pas concerné par le créneau.', someAttendancesAreEmpty: 'Opération impossible : certains émargements n\'ont pas été remplis.', + courseNotOver: 'Opération impossible : la formation n\'est pas terminée.', slotIsLinkedToTrainerBill: 'Opération impossible : le créneau est réglé et relié à une facture d\'un intervenant.', /* Questionnaires */ questionnairesFound: 'Liste des questionnaires trouvée.', diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index a52d805b55..33568f98ca 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -3,9 +3,12 @@ const { get, omit, has } = require('lodash'); const Company = require('../../models/Company'); const Course = require('../../models/Course'); const CourseBill = require('../../models/CourseBill'); +const Attendance = require('../../models/Attendance'); +const CourseSlot = require('../../models/CourseSlot'); const CourseBillingItem = require('../../models/CourseBillingItem'); const CourseFundingOrganisation = require('../../models/CourseFundingOrganisation'); const UtilsHelper = require('../../helpers/utils'); +const { CompaniDate } = require('../../helpers/dates/companiDates'); const translate = require('../../helpers/translate'); const { TRAINING_ORGANISATION_MANAGER, @@ -40,6 +43,7 @@ exports.authorizeCourseBillListCreation = async (req) => { interruptionDates: 1, hourlyPaymentPlan: 1, certificateGenerationMode: 1, + trainees: 1, }) .populate({ path: 'subProgram', select: 'hourlyPaymentPlans' }) .lean(); @@ -64,6 +68,24 @@ exports.authorizeCourseBillListCreation = async (req) => { if (quantity === 1 && !mainFee.price && !shouldComputePriceFromDuration) throw Boom.badRequest(); if (shouldComputePriceFromDuration && mainFee.price) throw Boom.badRequest(); + if (shouldComputePriceFromDuration) { + if (quantity !== 1) throw Boom.badRequest(); + + const slots = await CourseSlot + .find({ course: courseId, startDate: { $exists: true } }, { endDate: 1 }) + .sort({ endDate: 1 }) + .lean(); + if (!slots.length) throw Boom.forbidden(translate[language].courseNotOver); + + if (CompaniDate(slots[slots.length - 1].endDate).isAfter(CompaniDate())) { + throw Boom.forbidden(translate[language].courseNotOver); + } + + const attendancesCount = await Attendance + .countDocuments({ courseSlot: { $in: slots.map(slot => slot._id) }, trainee: course.trainees[0] }); + if (attendancesCount !== slots.length) throw Boom.forbidden(translate[language].someAttendancesAreEmpty); + } + const isCourseInterrupted = UtilsHelper.isCourseInterrupted(course.interruptionDates); if (isCourseInterrupted) throw Boom.forbidden(); diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index 251aaf2bd7..10f5cdc0f5 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -802,6 +802,49 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(409); }); + + it('should return 400 if price sent with an hourly payment plan', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 403 if the last slot of the course is not over', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { + ...singleCoursePayload, + course: coursesList[18]._id, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, + }); + + expect(response.statusCode).toBe(403); + }); + + it('should return 403 if some slots of the course have no attendance', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { + ...singleCoursePayload, + course: coursesList[19]._id, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, + }); + + expect(response.statusCode).toBe(403); + }); }); describe('Quantity > 1', () => { @@ -886,30 +929,32 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(billsCountAfter).toBe(billsCountBefore + 2); }); - it('should create a bill and link the hourly payment plan to a SINGLE course', async () => { + it('should create several bills and link the hourly payment plan (MONTHLY certification)', async () => { const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, - payload: { - ...singleCoursePayload, - mainFee: omit(singleCoursePayload.mainFee, 'price'), - hourlyPaymentPlanId, - }, + payload: { ...singleCoursePayload, course: coursesList[17]._id, hourlyPaymentPlanId }, }); expect(response.statusCode).toBe(200); - const course = await Course.findOne({ _id: coursesList[12]._id }, { hourlyPaymentPlan: 1 }).lean(); - expect(course.hourlyPaymentPlan).toEqual(hourlyPaymentPlanId); + const courseCount = await Course + .countDocuments({ _id: coursesList[17]._id, hourlyPaymentPlan: hourlyPaymentPlanId }); + expect(courseCount).toBe(1); }); - it('should return 400 if price sent with an hourly payment plan', async () => { + it('should return 400 if several bills are created with an hourly payment plan (GLOBAL)', async () => { const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, - payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + payload: { + ...singleCoursePayload, + quantity: 2, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, }); expect(response.statusCode).toBe(400); @@ -927,13 +972,11 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { }); it('should return 403 if the course already has another hourly payment plan', async () => { - await Course.updateOne({ _id: coursesList[12]._id }, { $set: { hourlyPaymentPlan: new ObjectId() } }); - const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, - payload: { ...singleCoursePayload, hourlyPaymentPlanId }, + payload: { ...singleCoursePayload, course: coursesList[20]._id, hourlyPaymentPlanId }, }); expect(response.statusCode).toBe(403); diff --git a/tests/integration/seed/courseBillsSeed.js b/tests/integration/seed/courseBillsSeed.js index ed9cb860ba..773db8dc0c 100644 --- a/tests/integration/seed/courseBillsSeed.js +++ b/tests/integration/seed/courseBillsSeed.js @@ -7,12 +7,16 @@ const { PUBLISHED, GROUP, GLOBAL, + MONTHLY, SINGLE, TRAINEE, COURSE_BILL, + PRESENT, } = require('../../../src/helpers/constants'); const Company = require('../../../src/models/Company'); +const Attendance = require('../../../src/models/Attendance'); const Course = require('../../../src/models/Course'); +const CourseSlot = require('../../../src/models/CourseSlot'); const CourseBill = require('../../../src/models/CourseBill'); const CourseBillingItem = require('../../../src/models/CourseBillingItem'); const CourseBillsNumber = require('../../../src/models/CourseBillsNumber'); @@ -382,6 +386,78 @@ const coursesList = [ folderId: 'folderId', gSheetId: 'gSheetId', tradeName: 'nom', + }, { // 17 - single course with monthly certificates, expectedBillsCount is 4 + _id: new ObjectId(), + type: SINGLE, + maxTrainees: 1, + subProgram: subProgramList[0]._id, + misc: 'group 4', + trainers: [trainer._id], + operationsRepresentative: vendorAdmin._id, + contact: vendorAdmin._id, + trainees: [traineeFromOtherCompany._id], + expectedBillsCount: 4, + companies: [otherCompany._id], + certificateGenerationMode: MONTHLY, + prices: [{ company: otherCompany._id, global: 15000, trainerFee: 1500 }], + folderId: 'folderId', + gSheetId: 'gSheetId', + tradeName: 'nom', + }, + { // 18 - single course with global certificate, last slot not over + _id: new ObjectId(), + type: SINGLE, + maxTrainees: 1, + subProgram: subProgramList[0]._id, + misc: 'group 5', + trainers: [trainer._id], + operationsRepresentative: vendorAdmin._id, + contact: vendorAdmin._id, + trainees: [traineeFromOtherCompany._id], + expectedBillsCount: 4, + companies: [otherCompany._id], + certificateGenerationMode: GLOBAL, + prices: [{ company: otherCompany._id, global: 15000, trainerFee: 1500 }], + folderId: 'folderId', + gSheetId: 'gSheetId', + tradeName: 'nom', + }, + { // 19 - single course with global certificate, with a slot without attendance + _id: new ObjectId(), + type: SINGLE, + maxTrainees: 1, + subProgram: subProgramList[0]._id, + misc: 'group 7', + trainers: [trainer._id], + operationsRepresentative: vendorAdmin._id, + contact: vendorAdmin._id, + trainees: [traineeFromOtherCompany._id], + expectedBillsCount: 4, + companies: [otherCompany._id], + certificateGenerationMode: GLOBAL, + prices: [{ company: otherCompany._id, global: 15000, trainerFee: 1500 }], + folderId: 'folderId', + gSheetId: 'gSheetId', + tradeName: 'nom', + }, + { // 20 - single course with global certificate, already linked to another hourly payment plan + _id: new ObjectId(), + type: SINGLE, + maxTrainees: 1, + subProgram: subProgramList[0]._id, + misc: 'group 8', + trainers: [trainer._id], + operationsRepresentative: vendorAdmin._id, + contact: vendorAdmin._id, + trainees: [traineeFromOtherCompany._id], + expectedBillsCount: 4, + companies: [otherCompany._id], + certificateGenerationMode: GLOBAL, + hourlyPaymentPlan: new ObjectId(), + prices: [{ company: otherCompany._id, global: 15000, trainerFee: 1500 }], + folderId: 'folderId', + gSheetId: 'gSheetId', + tradeName: 'nom', }, ]; @@ -611,12 +687,73 @@ const courseCreditNoteList = [ const courseCreditNoteNumber = { _id: new ObjectId(), seq: 2 }; +const slotsList = [ + { // course 12 (single), over + _id: new ObjectId(), + course: coursesList[12]._id, + startDate: '2024-01-10T09:00:00.000Z', + endDate: '2024-01-10T12:00:00.000Z', + step: steps[0]._id, + trainers: [trainer._id], + }, + { // 1 course 18, not over + _id: new ObjectId(), + course: coursesList[18]._id, + startDate: '2999-01-10T09:00:00.000Z', + endDate: '2999-01-10T12:00:00.000Z', + step: steps[0]._id, + trainers: [trainer._id], + }, + { // 2 course 19, over + _id: new ObjectId(), + course: coursesList[19]._id, + startDate: '2024-01-10T09:00:00.000Z', + endDate: '2024-01-10T12:00:00.000Z', + step: steps[0]._id, + trainers: [trainer._id], + }, + { // 3 course 19, over, without attendance + _id: new ObjectId(), + course: coursesList[19]._id, + startDate: '2023-01-10T09:00:00.000Z', + endDate: '2023-01-10T12:00:00.000Z', + step: steps[0]._id, + trainers: [trainer._id], + }, +]; + +const attendancesList = [ + { + _id: new ObjectId(), + courseSlot: slotsList[0]._id, + trainee: traineeFromOtherCompany._id, + company: otherCompany._id, + status: PRESENT, + }, + { + _id: new ObjectId(), + courseSlot: slotsList[1]._id, + trainee: traineeFromOtherCompany._id, + company: otherCompany._id, + status: PRESENT, + }, + { + _id: new ObjectId(), + courseSlot: slotsList[2]._id, + trainee: traineeFromOtherCompany._id, + company: otherCompany._id, + status: PRESENT, + }, +]; + const populateDB = async () => { await deleteNonAuthenticationSeeds(); await Promise.all([ Company.create(companyWithoutAddress), + Attendance.create(attendancesList), Course.create(coursesList), + CourseSlot.create(slotsList), CourseBill.create(courseBillsList), CourseBillingItem.create(billingItemList), CourseBillsNumber.create(courseBillNumber), @@ -639,4 +776,5 @@ module.exports = { coursesList, billingItemList, hourlyPaymentPlanId, + slotsList, }; diff --git a/tests/integration/seed/seedsVerification.test.js b/tests/integration/seed/seedsVerification.test.js index a103b5cfb0..c409fc4be2 100644 --- a/tests/integration/seed/seedsVerification.test.js +++ b/tests/integration/seed/seedsVerification.test.js @@ -1232,7 +1232,11 @@ describe('SEEDS VERIFICATION', () => { before(async () => { courseBillList = await CourseBill .find() - .populate({ path: 'course', select: 'type format companies type expectedBillsCount prices', transform }) + .populate({ + path: 'course', + select: 'type format companies type expectedBillsCount prices hourlyPaymentPlan', + transform, + }) .populate({ path: 'companies', transform }) .populate({ path: 'payer.company', transform }) .populate({ path: 'payer.fundingOrganisation', transform }) @@ -1253,7 +1257,9 @@ describe('SEEDS VERIFICATION', () => { }); it('should pass if every price is positive', () => { - const everyPriceIsValid = courseBillList.every(bill => !has(bill, 'mainFee.price') || bill.mainFee.price > 0); + const everyPriceIsValid = courseBillList.every(bill => + !has(bill, 'mainFee.price') || bill.mainFee.price > 0 || + (bill.mainFee.price === 0 && has(bill, 'course.hourlyPaymentPlan'))); expect(everyPriceIsValid).toBeTruthy(); }); From 01145cee7d1cdf24848e1c1d05f37bf3f9a50ddc Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Mon, 2 Nov 2026 14:48:25 +0100 Subject: [PATCH 17/53] COM-4322 - fix bug --- src/helpers/courseBills.js | 3 ++- tests/unit/helpers/courseBills.test.js | 32 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 66bad1365b..04becd96d4 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -387,10 +387,11 @@ exports.createBillList = async (payload) => { const mainFee = isGlobalCertificationCourseWithPriceFromDurations ? { ...payload.mainFee, price: await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId) } : payload.mainFee; + const { price: mainFeePrice } = mainFee; const billCreated = await CourseBill.create({ ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), - mainFee, + mainFee: { ...mainFee, ...Array.isArray(mainFeePrice) && { price: mainFeePrice[0] } }, ...vat && { vat }, }); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index 14bfd10d78..3bce99d9e6 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -1771,6 +1771,38 @@ describe('createBillList', () => { sinon.assert.notCalled(insertManyCourseBills); sinon.assert.notCalled(getVendorCompany); }); + + it('should create one bill for SINGLE course with prices array', async () => { + const companyId = new ObjectId(); + const payerId = new ObjectId(); + const course = { _id: new ObjectId(), type: SINGLE, prices: [], subProgram: { subjectToVat: false } }; + const payload = { + course: course._id, + quantity: 1, + mainFee: { count: 1, countUnit: TRAINEE, price: [9000], description: 'test' }, + companies: [companyId], + payer: { fundingOrganisation: payerId }, + maturityDate: '2025-04-29T22:00:00.000Z', + }; + + findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); + + await CourseBillHelper.createBillList(payload); + + sinon.assert.calledOnceWithExactly( + createCourseBill, + { + course: course._id, + mainFee: { count: 1, countUnit: TRAINEE, price: 9000, description: 'test' }, + companies: [companyId], + payer: { fundingOrganisation: payerId }, + maturityDate: '2025-04-29T22:00:00.000Z', + } + ); + sinon.assert.notCalled(addBillingPurchase); + sinon.assert.notCalled(insertManyCourseBills); + sinon.assert.notCalled(getVendorCompany); + }); }); describe('updateCourseBill', () => { From 71d4df8dab38f04437a0c0af8da635c5b16ba444 Mon Sep 17 00:00:00 2001 From: ulysse Date: Fri, 30 Oct 2026 16:13:17 +0100 Subject: [PATCH 18/53] COM-4317: display collective bills --- src/controllers/courseController.js | 15 +++ src/helpers/constants.js | 1 + src/helpers/courses.js | 89 +++++++++++++ src/helpers/trainerBills.js | 1 + src/helpers/users.js | 1 + src/models/TrainerBill.js | 1 + src/models/User.js | 10 ++ src/routes/courses.js | 13 ++ src/routes/preHandlers/courses.js | 14 ++ src/routes/preHandlers/trainerBills.js | 6 + src/routes/trainerBills.js | 3 +- tests/integration/courses.test.js | 61 +++++++++ tests/integration/seed/usersSeed.js | 1 + tests/integration/trainerBills.test.js | 55 +++++++- tests/integration/users.test.js | 1 + tests/unit/helpers/courses.test.js | 167 ++++++++++++++++++++++++ tests/unit/helpers/trainerBills.test.js | 4 +- tests/unit/helpers/users.test.js | 5 + 18 files changed, 445 insertions(+), 3 deletions(-) diff --git a/src/controllers/courseController.js b/src/controllers/courseController.js index 4e6f839798..5a53292ac0 100644 --- a/src/controllers/courseController.js +++ b/src/controllers/courseController.js @@ -22,6 +22,20 @@ const list = async (req) => { } }; +const listTrainersBilling = async (req) => { + try { + const trainers = await CoursesHelper.listTrainersBilling(req.query); + + return { + message: trainers.length ? translate[language].coursesFound : translate[language].coursesNotFound, + data: { trainers }, + }; + } catch (e) { + req.log('error', e); + return Boom.isBoom(e) ? e : Boom.badImplementation(e); + } +}; + const create = async (req) => { try { const course = await CoursesHelper.createCourse(req.payload, req.auth.credentials); @@ -457,4 +471,5 @@ module.exports = { uploadSingleCourseCSV, uploadCollectiveCourseCSV, downloadAllDocuments, + listTrainersBilling, }; diff --git a/src/helpers/constants.js b/src/helpers/constants.js index 6cce8c8048..6a40fe2185 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -229,6 +229,7 @@ module.exports = { NOT_INVOICED: 'not_invoiced', INVOICED: 'invoiced', PAID: 'paid', + PARTIALLY_INVOICED: 'partially_invoiced', get SLOT_STATUS() { return { [this.NOT_INVOICED]: 'Non facturé', diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 58721f350c..cd6955e934 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -34,6 +34,7 @@ const DatesUtilsHelper = require('./dates/utils'); const ZipHelper = require('./zip'); const SmsHelper = require('./sms'); const CourseBillsHelper = require('./courseBills'); +const CourseSlotsHelper = require('./courseSlots'); const CourseCreditNotesHelper = require('./courseCreditNotes'); const DocxHelper = require('./docx'); const FileHelper = require('./file'); @@ -89,6 +90,11 @@ const { SECOND, MONTH, TRAINER_SALARY, + MINUTE, + PARTIALLY_INVOICED, + NOT_INVOICED, + INVOICED, + PAID, VAEI_COACH, ARCHITECT, } = require('./constants'); @@ -106,6 +112,7 @@ const CompletionCertificatePdf = require('../data/pdf/completionCertificate'); const TrainingContractPdf = require('../data/pdf/trainingContract'); const CourseBill = require('../models/CourseBill'); const CourseSlot = require('../models/CourseSlot'); +const TrainerBill = require('../models/TrainerBill'); const CourseHistory = require('../models/CourseHistory'); const CompletionCertificate = require('../models/CompletionCertificate'); const CourseBillingItem = require('../models/CourseBillingItem'); @@ -2303,3 +2310,85 @@ exports.deleteBillingPurchase = async (courseId, billingPurchaseId) => Course.up { _id: courseId }, { $pull: { billingPurchaseList: { _id: billingPurchaseId } } } ); + +exports.getCourseTrainerSalary = async (course, trainerId) => { + if (course.trainers.length === 1) { + const salaryItem = (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); + if (salaryItem) return NumbersHelper.toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)); + } + + const slots = await CourseSlot + .find({ course: course._id, trainers: trainerId }, { step: 1, startDate: 1, endDate: 1 }) + .lean(); + + const salary = slots.reduce((acc, slot) => { + const hourlyAmount = CourseSlotsHelper + .getHourlyAmount({ step: { _id: slot.step }, startDate: course.createdAt, course }, trainerId); + if (!hourlyAmount) return acc; + + const duration = CompaniDate(slot.endDate).diff(slot.startDate, MINUTE); + const slotAmount = NumbersHelper.toFixedToFloat( + NumbersHelper.multiply(hourlyAmount, CompaniDuration(duration).asHours()) + ); + + return NumbersHelper.add(acc, slotAmount); + }, 0); + + return NumbersHelper.toNumber(salary); +}; + +exports.listTrainersBilling = async (query) => { + const courses = await Course + .find( + { trainers: query.trainer, type: { $ne: SINGLE } }, + { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } + ) + .populate({ path: 'companies', select: 'name' }) + .populate({ + path: 'subProgram', + select: 'program trainerPriceVersions', + populate: { path: 'program', select: 'name' }, + }) + .populate({ path: 'trainers', select: 'identity' }) + .populate({ path: 'billingPurchaseList.billingItem', select: 'type' }) + .lean(); + if (!courses.length) return []; + + const trainerBills = await TrainerBill + .find({ course: { $in: courses.map(c => c._id) }, trainer: query.trainer }, { course: 1, amount: 1 }) + .populate({ path: 'payment', select: 'status' }) + .lean(); + + const billsByCourse = groupBy(trainerBills, bill => bill.course); + + const trainerCourses = []; + for (const course of courses) { + const plannedSalary = await exports.getCourseTrainerSalary(course, query.trainer); + const courseBills = billsByCourse[course._id] || []; + let invoicedAmount = 0; + let paidAmount = 0; + for (const bill of courseBills) { + invoicedAmount = NumbersHelper.add(invoicedAmount, bill.amount); + if (bill.payment?.status === PAID) paidAmount = NumbersHelper.add(paidAmount, bill.amount); + } + invoicedAmount = NumbersHelper.toNumber(invoicedAmount); + paidAmount = NumbersHelper.toNumber(paidAmount); + + let status = INVOICED; + if (invoicedAmount === 0) status = NOT_INVOICED; + else if (invoicedAmount < plannedSalary) status = PARTIALLY_INVOICED; + else if (invoicedAmount === paidAmount) status = PAID; + + trainerCourses.push({ + ...omit(course, ['billingPurchaseList', 'rolesPerTrainer']), + plannedSalary, + invoicedAmount, + paidAmount, + status, + }); + } + + const trainer = courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer)); + + return [{ ...trainer, courses: trainerCourses }]; +}; diff --git a/src/helpers/trainerBills.js b/src/helpers/trainerBills.js index 63795d1f28..ed1ca34e76 100644 --- a/src/helpers/trainerBills.js +++ b/src/helpers/trainerBills.js @@ -65,6 +65,7 @@ exports.createBill = async (payload, credentials) => { trainer: credentials._id, number: payload.number, ...(courseSlotIds.length && { courseSlots: courseSlotIds }), + ...(payload.course && { course: payload.course }), amount, submittedAt: CompaniDate().toISO(), file: fileUploaded, diff --git a/src/helpers/users.js b/src/helpers/users.js index ac4d5de06a..d0f5589444 100644 --- a/src/helpers/users.js +++ b/src/helpers/users.js @@ -244,6 +244,7 @@ exports.getUser = async (userId, credentials) => { .populate({ path: 'companyLinkRequest', populate: { path: 'company', select: '_id name' } }) .populate({ path: 'userCompanyList' }) .populate({ path: 'isSingleCourseTrainer' }) + .populate({ path: 'isCollectiveCourseTrainer' }) .lean({ autopopulate: true, virtuals: true }); if (!user) throw Boom.notFound(translate[language].userNotFound); diff --git a/src/models/TrainerBill.js b/src/models/TrainerBill.js index a3b2036098..0f992b3e67 100644 --- a/src/models/TrainerBill.js +++ b/src/models/TrainerBill.js @@ -5,6 +5,7 @@ const TrainerBillSchema = mongoose.Schema({ trainer: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, number: { type: String, required: true }, courseSlots: { type: [mongoose.Schema.Types.ObjectId], ref: 'CourseSlot', default: undefined }, + course: { type: mongoose.Schema.Types.ObjectId, ref: 'Course' }, amount: { type: Number, required: true }, submittedAt: { type: Date, required: true }, file: { diff --git a/src/models/User.js b/src/models/User.js index 0f896a527f..d45a78b1f0 100644 --- a/src/models/User.js +++ b/src/models/User.js @@ -402,6 +402,16 @@ UserSchema.virtual( match: { type: SINGLE }, }); +UserSchema.virtual( + 'isCollectiveCourseTrainer', + { + ref: 'Course', + localField: '_id', + foreignField: 'trainers', + count: true, + match: { type: { $ne: SINGLE } }, + }); + UserSchema.pre('validate', validate); UserSchema.pre('save', save); UserSchema.pre('findOneAndUpdate', findOneAndUpdate); diff --git a/src/routes/courses.js b/src/routes/courses.js index 872439861b..877b02bda5 100644 --- a/src/routes/courses.js +++ b/src/routes/courses.js @@ -37,6 +37,7 @@ const { uploadSingleCourseCSV, uploadCollectiveCourseCSV, downloadAllDocuments, + listTrainersBilling, } = require('../controllers/courseController'); const { MESSAGE_TYPE } = require('../models/CourseSmsHistory'); const { COURSE_TYPES, COURSE_FORMATS, CERTIFICATE_GENERATION_MODE } = require('../models/Course'); @@ -72,6 +73,7 @@ const { authorizeUploadSingleCourseCSV, authorizeUploadCollectiveCourseCSV, authorizeGetAllDocuments, + authorizeTrainerBillsGet, } = require('./preHandlers/courses'); const { INTRA, @@ -134,6 +136,17 @@ exports.plugin = { handler: list, }); + server.route({ + method: 'GET', + path: '/trainers-billing', + options: { + auth: { scope: ['user:read-{query.trainer}'] }, + validate: { query: Joi.object({ trainer: Joi.objectId().required() }) }, + pre: [{ method: authorizeTrainerBillsGet }], + }, + handler: listTrainersBilling, + }); + server.route({ method: 'POST', path: '/', diff --git a/src/routes/preHandlers/courses.js b/src/routes/preHandlers/courses.js index 487836d3b2..b11ad29cb9 100644 --- a/src/routes/preHandlers/courses.js +++ b/src/routes/preHandlers/courses.js @@ -1658,3 +1658,17 @@ exports.authorizeCourseBillingPurchaseEdition = async (req) => { return null; }; + +exports.authorizeTrainerBillsGet = async (req) => { + try { + const { trainer: trainerId } = req.query; + + const trainer = await User.countDocuments({ _id: trainerId, 'role.vendor': { $exists: true } }); + if (!trainer) throw Boom.notFound(); + + return null; + } catch (e) { + req.log('error', e); + return Boom.isBoom(e) ? e : Boom.badImplementation(e); + } +}; diff --git a/src/routes/preHandlers/trainerBills.js b/src/routes/preHandlers/trainerBills.js index d9f25de8d2..025847e362 100644 --- a/src/routes/preHandlers/trainerBills.js +++ b/src/routes/preHandlers/trainerBills.js @@ -1,4 +1,5 @@ const Boom = require('@hapi/boom'); +const Course = require('../../models/Course'); const CourseSlot = require('../../models/CourseSlot'); const TrainerBill = require('../../models/TrainerBill'); const UtilsHelper = require('../../helpers/utils'); @@ -10,6 +11,11 @@ exports.authorizeTrainerBillCreation = async (req) => { try { const { credentials } = req.auth; + if (req.payload.course) { + const courseCount = await Course.countDocuments({ _id: req.payload.course, trainers: credentials._id }); + if (!courseCount) throw Boom.notFound(); + } + if (req.payload.courseSlots) { const courseSlotIds = Array.isArray(req.payload.courseSlots) ? req.payload.courseSlots diff --git a/src/routes/trainerBills.js b/src/routes/trainerBills.js index 68f4b9213d..32d0ac254d 100644 --- a/src/routes/trainerBills.js +++ b/src/routes/trainerBills.js @@ -19,7 +19,8 @@ exports.plugin = { number: Joi.string().required(), file: Joi.any().required(), amount: Joi.number().positive(), - }).xor('amount', 'courseSlots'), + course: Joi.objectId(), + }).xor('amount', 'courseSlots').oxor('course', 'courseSlots'), }, pre: [{ method: authorizeTrainerBillCreation }], }, diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index f6222106bb..0504c6432c 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10092,3 +10092,64 @@ describe('COURSES ROUTES - GET /{_id}/all-documents', () => { }); }); }); + +describe('COURSES ROUTES - GET /courses/trainers-billing', () => { + let authToken; + beforeEach(populateDB); + + describe('TRAINER', () => { + beforeEach(async () => { + authToken = await getToken('trainer'); + }); + + it('should return trainer\'s collective courses with billing infos', async () => { + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${trainer._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + expect(response.result.data.trainers.length).toBe(1); + const { courses } = response.result.data.trainers[0]; + expect(courses.length).toBeGreaterThan(0); + expect(courses.every(c => c.type !== SINGLE)).toBeTruthy(); + expect(courses[0]).toEqual(expect.objectContaining({ + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + })); + }); + + it('should return 403 if trainer is not the logged user', async () => { + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${trainerAndCoach._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(403); + }); + }); + + describe('Other roles', () => { + const roles = [ + { name: 'helper', expectedCode: 403 }, + { name: 'planning_referent', expectedCode: 403 }, + { name: 'coach', expectedCode: 403 }, + ]; + roles.forEach((role) => { + it(`should return ${role.expectedCode} as user is ${role.name}`, async () => { + authToken = await getToken(role.name); + + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${trainer._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(role.expectedCode); + }); + }); + }); +}); diff --git a/tests/integration/seed/usersSeed.js b/tests/integration/seed/usersSeed.js index 618f8db253..b73aca8dbf 100644 --- a/tests/integration/seed/usersSeed.js +++ b/tests/integration/seed/usersSeed.js @@ -407,6 +407,7 @@ const coursesList = [ operationsRepresentative: vendorAdmin._id, certificateGenerationMode: GLOBAL, tradeName: 'nom', + trainers: [trainer._id], }, { _id: new ObjectId(), diff --git a/tests/integration/trainerBills.test.js b/tests/integration/trainerBills.test.js index c952195687..b7ddc33255 100644 --- a/tests/integration/trainerBills.test.js +++ b/tests/integration/trainerBills.test.js @@ -7,7 +7,7 @@ const TrainerPayment = require('../../src/models/TrainerPayment'); const CourseSlot = require('../../src/models/CourseSlot'); const GCloudStorageHelper = require('../../src/helpers/gCloudStorage'); const { trainer, trainerAndCoach } = require('../seed/authUsersSeed'); -const { populateDB, courseSlotsList, paidTrainerBillId } = require('./seed/trainerBillsSeed'); +const { populateDB, course, courseSlotsList, paidTrainerBillId } = require('./seed/trainerBillsSeed'); const { PENDING } = require('../../src/helpers/constants'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); const { generateFormData, getStream } = require('./utils'); @@ -109,6 +109,30 @@ describe('TRAINER BILLS ROUTES - POST /trainerbills', () => { expect(trainerBillCount).toBe(1); }); + it('should create a trainer bill with course, using the given amount', async () => { + const form = generateFormData({ number: 'FACT_0010', file: 'test', amount: 80 }); + form.append('course', course._id.toHexString()); + + const response = await app.inject({ + method: 'POST', + url: '/trainerbills', + headers: { ...form.getHeaders(), Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: getStream(form), + }); + + expect(response.statusCode).toBe(200); + + const trainerBillCount = await TrainerBill + .countDocuments({ + trainer: trainer._id, + number: 'FACT_0010', + amount: 80, + course: course._id, + courseSlots: { $exists: false }, + }); + expect(trainerBillCount).toBe(1); + }); + it('should return 400 if both courseSlots and amount are provided', async () => { const form = generateFormData({ number: 'FACT_0011', file: 'test', amount: 80 }); form.append('courseSlots', courseSlotsList[0]._id.toHexString()); @@ -123,6 +147,35 @@ describe('TRAINER BILLS ROUTES - POST /trainerbills', () => { expect(response.statusCode).toBe(400); }); + it('should return 400 if both course and courseSlots are provided', async () => { + const form = generateFormData({ number: 'FACT_0013', file: 'test' }); + form.append('course', course._id.toHexString()); + form.append('courseSlots', courseSlotsList[0]._id.toHexString()); + + const response = await app.inject({ + method: 'POST', + url: '/trainerbills', + headers: { ...form.getHeaders(), Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: getStream(form), + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 404 if course does not exist', async () => { + const form = generateFormData({ number: 'FACT_0014', file: 'test', amount: 80 }); + form.append('course', new ObjectId().toHexString()); + + const response = await app.inject({ + method: 'POST', + url: '/trainerbills', + headers: { ...form.getHeaders(), Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: getStream(form), + }); + + expect(response.statusCode).toBe(404); + }); + it('should return 400 if neither courseSlots nor amount are provided', async () => { const form = generateFormData({ number: 'FACT_0012', file: 'test' }); diff --git a/tests/integration/users.test.js b/tests/integration/users.test.js index 26afa1e0e3..bfcaa5fc19 100644 --- a/tests/integration/users.test.js +++ b/tests/integration/users.test.js @@ -1170,6 +1170,7 @@ describe('USERS ROUTES - GET /users/:id', () => { expect(UtilsHelper.areObjectIdsEquals(res.result.data.user._id, trainer._id)).toBeTruthy(); expect(res.result.data.user.role.vendor).toBeDefined(); expect(res.result.data.user.isSingleCourseTrainer).toBeTruthy(); + expect(res.result.data.user.isCollectiveCourseTrainer).toBeTruthy(); }); }); diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index d26a69440f..690a22be01 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -17,6 +17,7 @@ const Attendance = require('../../../src/models/Attendance'); const User = require('../../../src/models/User'); const CourseHistory = require('../../../src/models/CourseHistory'); const CourseSlot = require('../../../src/models/CourseSlot'); +const TrainerBill = require('../../../src/models/TrainerBill'); const CourseSmsHistory = require('../../../src/models/CourseSmsHistory'); const Drive = require('../../../src/models/Google/Drive'); const Sheet = require('../../../src/models/Google/Sheets'); @@ -25,6 +26,7 @@ const TrainingContract = require('../../../src/models/TrainingContract'); const CompanyHelper = require('../../../src/helpers/companies'); const CourseHelper = require('../../../src/helpers/courses'); const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); +const CourseSlotsHelper = require('../../../src/helpers/courseSlots'); const CourseBillHelper = require('../../../src/helpers/courseBills'); const CourseCreditNoteHelper = require('../../../src/helpers/courseCreditNotes'); const EmailHelper = require('../../../src/helpers/email'); @@ -11327,3 +11329,168 @@ describe('getTraineeDurations', () => { ); }); }); + +describe('getCourseTrainerSalary', () => { + let courseSlotFind; + let getHourlyAmount; + + beforeEach(() => { + courseSlotFind = sinon.stub(CourseSlot, 'find'); + getHourlyAmount = sinon.stub(CourseSlotsHelper, 'getHourlyAmount'); + }); + + afterEach(() => { + courseSlotFind.restore(); + getHourlyAmount.restore(); + }); + + it('should return trainer salary billing purchase amount if only one trainer', async () => { + const trainerId = new ObjectId(); + const course = { + _id: new ObjectId(), + trainers: [trainerId], + billingPurchaseList: [ + { billingItem: { type: 'course' }, price: 1000, count: 1 }, + { billingItem: { type: 'trainer_salary' }, price: 100, count: 2 }, + ], + }; + + const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); + + expect(result).toEqual(200); + sinon.assert.notCalled(courseSlotFind); + }); + + it('should compute salary from slots if only one trainer and no trainer salary billing purchase', async () => { + const trainerId = new ObjectId(); + const course = { + _id: new ObjectId(), + trainers: [trainerId], + billingPurchaseList: [{ billingItem: { type: 'course' }, price: 1000, count: 1 }], + createdAt: '2024-01-01T00:00:00.000Z', + }; + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); + + const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); + + expect(result).toEqual(0); + sinon.assert.calledOnce(courseSlotFind); + }); + + it('should compute salary from slots if several trainers', async () => { + const trainerId = new ObjectId(); + const stepId = new ObjectId(); + const course = { + _id: new ObjectId(), + trainers: [trainerId, new ObjectId()], + createdAt: '2024-01-01T00:00:00.000Z', + }; + const slots = [ + { step: stepId, startDate: new Date('2024-02-01T08:00:00.000Z'), endDate: new Date('2024-02-01T10:00:00.000Z') }, + { step: stepId, startDate: new Date('2024-02-02T08:00:00.000Z'), endDate: new Date('2024-02-02T09:30:00.000Z') }, + ]; + courseSlotFind.returns(SinonMongoose.stubChainedQueries(slots, ['lean'])); + getHourlyAmount.onCall(0).returns(40); + getHourlyAmount.onCall(1).returns(60); + + const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); + + expect(result).toEqual(170); + sinon.assert.calledWithExactly( + getHourlyAmount.getCall(0), + { step: { _id: stepId }, startDate: course.createdAt, course }, + trainerId + ); + sinon.assert.calledWithExactly( + getHourlyAmount.getCall(1), + { step: { _id: stepId }, startDate: course.createdAt, course }, + trainerId + ); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [{ course: course._id, trainers: trainerId }, { step: 1, startDate: 1, endDate: 1 }], + }, + { query: 'lean' }, + ] + ); + }); +}); + +describe('listTrainersBilling', () => { + let courseFind; + let trainerBillFind; + let getCourseTrainerSalary; + + beforeEach(() => { + courseFind = sinon.stub(Course, 'find'); + trainerBillFind = sinon.stub(TrainerBill, 'find'); + getCourseTrainerSalary = sinon.stub(CourseHelper, 'getCourseTrainerSalary'); + }); + + afterEach(() => { + courseFind.restore(); + trainerBillFind.restore(); + getCourseTrainerSalary.restore(); + }); + + it('should return an empty array if no course found', async () => { + const trainerId = new ObjectId(); + courseFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([]); + sinon.assert.notCalled(trainerBillFind); + sinon.assert.notCalled(getCourseTrainerSalary); + }); + + it('should return trainer with its courses and billing status', async () => { + const trainerId = new ObjectId(); + const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const courses = [ + { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, + ]; + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'lean'])); + getCourseTrainerSalary.returns(100); + const trainerBills = [ + { course: courses[1]._id, amount: 40, payment: { status: 'pending' } }, + { course: courses[2]._id, amount: 100, payment: { status: 'pending' } }, + { course: courses[3]._id, amount: 60, payment: { status: 'paid' } }, + { course: courses[3]._id, amount: 40, payment: { status: 'paid' } }, + ]; + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([{ + ...trainer, + courses: [ + { ...courses[0], plannedSalary: 100, invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, + { ...courses[1], plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced' }, + { ...courses[2], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, + { ...courses[3], plannedSalary: 100, invoicedAmount: 100, paidAmount: 100, status: 'paid' }, + ], + }]); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courses[0], trainerId); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courses[1], trainerId); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(2), courses[2], trainerId); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(3), courses[3], trainerId); + SinonMongoose.calledOnceWithExactly( + trainerBillFind, + [ + { + query: 'find', + args: [{ course: { $in: courses.map(c => c._id) }, trainer: trainerId }, { course: 1, amount: 1 }], + }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'lean' }, + ] + ); + }); +}); diff --git a/tests/unit/helpers/trainerBills.test.js b/tests/unit/helpers/trainerBills.test.js index 3562a6ac4b..1f6021de2d 100644 --- a/tests/unit/helpers/trainerBills.test.js +++ b/tests/unit/helpers/trainerBills.test.js @@ -269,7 +269,8 @@ describe('createBill', () => { it('should create a trainer bill with no course slots, using the given amount', async () => { const credentials = { _id: new ObjectId(), identity: { firstname: 'Jean', lastname: 'Dupont' } }; const trainerBillId = new ObjectId(); - const payload = { number: 'FACT_0006', file: 'file', amount: 80 }; + const courseId = new ObjectId(); + const payload = { number: 'FACT_0006', file: 'file', amount: 80, course: courseId }; trainerBillCreate.returns({ _id: trainerBillId }); @@ -285,6 +286,7 @@ describe('createBill', () => { { trainer: credentials._id, number: 'FACT_0006', + course: courseId, amount: 80, submittedAt: '2025-09-29T13:45:25.437Z', file: { link: 'link', publicId: 'publicId' }, diff --git a/tests/unit/helpers/users.test.js b/tests/unit/helpers/users.test.js index 395dadc2d6..82b1df6464 100644 --- a/tests/unit/helpers/users.test.js +++ b/tests/unit/helpers/users.test.js @@ -991,6 +991,7 @@ describe('getUser', () => { }, { query: 'populate', args: [{ path: 'userCompanyList' }] }, { query: 'populate', args: [{ path: 'isSingleCourseTrainer' }] }, + { query: 'populate', args: [{ path: 'isCollectiveCourseTrainer' }] }, { query: 'lean', args: [{ autopopulate: true, virtuals: true }] }, ] ); @@ -1041,6 +1042,7 @@ describe('getUser', () => { }, { query: 'populate', args: [{ path: 'userCompanyList' }] }, { query: 'populate', args: [{ path: 'isSingleCourseTrainer' }] }, + { query: 'populate', args: [{ path: 'isCollectiveCourseTrainer' }] }, { query: 'lean', args: [{ autopopulate: true, virtuals: true }] }, ] ); @@ -1088,6 +1090,7 @@ describe('getUser', () => { }, { query: 'populate', args: [{ path: 'userCompanyList' }] }, { query: 'populate', args: [{ path: 'isSingleCourseTrainer' }] }, + { query: 'populate', args: [{ path: 'isCollectiveCourseTrainer' }] }, { query: 'lean', args: [{ autopopulate: true, virtuals: true }] }, ] ); @@ -1129,6 +1132,7 @@ describe('getUser', () => { }, { query: 'populate', args: [{ path: 'userCompanyList' }] }, { query: 'populate', args: [{ path: 'isSingleCourseTrainer' }] }, + { query: 'populate', args: [{ path: 'isCollectiveCourseTrainer' }] }, { query: 'lean', args: [{ autopopulate: true, virtuals: true }] }, ] ); @@ -1175,6 +1179,7 @@ describe('getUser', () => { }, { query: 'populate', args: [{ path: 'userCompanyList' }] }, { query: 'populate', args: [{ path: 'isSingleCourseTrainer' }] }, + { query: 'populate', args: [{ path: 'isCollectiveCourseTrainer' }] }, { query: 'lean', args: [{ autopopulate: true, virtuals: true }] }, ] ); From 0688aaab92b4a0f6c547cfc18322b853b94c36cb Mon Sep 17 00:00:00 2001 From: ulysse Date: Fri, 30 Oct 2026 16:56:27 +0100 Subject: [PATCH 19/53] COM-4317: sort courses --- src/helpers/courses.js | 1 + tests/unit/helpers/courses.test.js | 4 ++-- tests/unit/helpers/trainerBills.test.js | 30 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index cd6955e934..7dc69a4514 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2351,6 +2351,7 @@ exports.listTrainersBilling = async (query) => { }) .populate({ path: 'trainers', select: 'identity' }) .populate({ path: 'billingPurchaseList.billingItem', select: 'type' }) + .sort({ createdAt: -1 }) .lean(); if (!courses.length) return []; diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 690a22be01..bfccb955d6 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11438,7 +11438,7 @@ describe('listTrainersBilling', () => { it('should return an empty array if no course found', async () => { const trainerId = new ObjectId(); - courseFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + courseFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'sort', 'lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11456,7 +11456,7 @@ describe('listTrainersBilling', () => { { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, ]; - courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'lean'])); + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); getCourseTrainerSalary.returns(100); const trainerBills = [ { course: courses[1]._id, amount: 40, payment: { status: 'pending' } }, diff --git a/tests/unit/helpers/trainerBills.test.js b/tests/unit/helpers/trainerBills.test.js index 1f6021de2d..9fce059768 100644 --- a/tests/unit/helpers/trainerBills.test.js +++ b/tests/unit/helpers/trainerBills.test.js @@ -267,6 +267,36 @@ describe('createBill', () => { }); it('should create a trainer bill with no course slots, using the given amount', async () => { + const credentials = { _id: new ObjectId(), identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const trainerBillId = new ObjectId(); + const payload = { number: 'FACT_0006', file: 'file', amount: 80 }; + + trainerBillCreate.returns({ _id: trainerBillId }); + + const result = await TrainerBillsHelper.createBill(payload, credentials); + + expect(result).toEqual({ _id: trainerBillId }); + + sinon.assert.notCalled(courseSlotFind); + sinon.assert.notCalled(getHourlyAmount); + sinon.assert.notCalled(courseSlotUpdateMany); + sinon.assert.calledOnceWithExactly( + trainerBillCreate, + { + trainer: credentials._id, + number: 'FACT_0006', + amount: 80, + submittedAt: '2025-09-29T13:45:25.437Z', + file: { link: 'link', publicId: 'publicId' }, + } + ); + sinon.assert.calledOnceWithExactly( + trainerPaymentCreate, + { number: 'REG-00007', trainerBill: trainerBillId, amount: 80, status: PENDING } + ); + }); + + it('should create a trainer bill with course, using the given amount', async () => { const credentials = { _id: new ObjectId(), identity: { firstname: 'Jean', lastname: 'Dupont' } }; const trainerBillId = new ObjectId(); const courseId = new ObjectId(); From 359c3943d5a88422f17318ff58924f13470e3ff8 Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 2 Nov 2026 15:05:57 +0100 Subject: [PATCH 20/53] COM-4317: review --- tests/integration/courses.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 0504c6432c..b4b2e76bb0 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10112,7 +10112,7 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { expect(response.statusCode).toBe(200); expect(response.result.data.trainers.length).toBe(1); const { courses } = response.result.data.trainers[0]; - expect(courses.length).toBeGreaterThan(0); + expect(courses.length).toEqual(15); expect(courses.every(c => c.type !== SINGLE)).toBeTruthy(); expect(courses[0]).toEqual(expect.objectContaining({ invoicedAmount: 0, From b893c11f3da5faca1bcd630cc99758d61f213266 Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 3 Nov 2026 15:03:31 +0100 Subject: [PATCH 21/53] COM-4318: stop returning bic --- src/helpers/users.js | 12 +++++++-- tests/unit/helpers/users.test.js | 42 ++++++++++++++++++++++++++------ 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/helpers/users.js b/src/helpers/users.js index d0f5589444..20fd462120 100644 --- a/src/helpers/users.js +++ b/src/helpers/users.js @@ -105,7 +105,11 @@ exports.getUsersList = async (query, credentials) => { return User.find(params, { iban: 0, bic: 0 }, { autopopulate: false }) .populate({ path: 'role.client', select: '-__v -createdAt -updatedAt' }) .populate({ path: 'role.holding', select: '-__v -createdAt -updatedAt' }) - .populate({ path: 'company', populate: { path: 'company' }, select: '-__v -createdAt -updatedAt' }) + .populate({ + path: 'company', + populate: { path: 'company', select: '_id name' }, + select: '-__v -createdAt -updatedAt', + }) .setOptions({ isVendorUser: has(credentials, 'role.vendor') }) .lean({ virtuals: true, autopopulate: true }); }; @@ -233,7 +237,11 @@ exports.getUser = async (userId, credentials) => { const user = await User.findOne({ _id: userId }) .populate({ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }) .populate({ diff --git a/tests/unit/helpers/users.test.js b/tests/unit/helpers/users.test.js index 82b1df6464..5deb765b97 100644 --- a/tests/unit/helpers/users.test.js +++ b/tests/unit/helpers/users.test.js @@ -391,7 +391,11 @@ describe('getUsersList', () => { { query: 'populate', args: [{ path: 'role.holding', select: '-__v -createdAt -updatedAt' }] }, { query: 'populate', - args: [{ path: 'company', populate: { path: 'company' }, select: '-__v -createdAt -updatedAt' }], + args: [{ + path: 'company', + populate: { path: 'company', select: '_id name' }, + select: '-__v -createdAt -updatedAt', + }], }, { query: 'setOptions', args: [{ isVendorUser: false }] }, { query: 'lean', args: [{ virtuals: true, autopopulate: true }] }, @@ -421,7 +425,11 @@ describe('getUsersList', () => { { query: 'populate', - args: [{ path: 'company', populate: { path: 'company' }, select: '-__v -createdAt -updatedAt' }], + args: [{ + path: 'company', + populate: { path: 'company', select: '_id name' }, + select: '-__v -createdAt -updatedAt', + }], }, { query: 'setOptions', args: [{ isVendorUser: false }] }, { query: 'lean', args: [{ virtuals: true, autopopulate: true }] }, @@ -973,7 +981,11 @@ describe('getUser', () => { query: 'populate', args: [{ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }], }, @@ -1024,7 +1036,11 @@ describe('getUser', () => { query: 'populate', args: [{ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }], }, @@ -1072,7 +1088,11 @@ describe('getUser', () => { query: 'populate', args: [{ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }], }, @@ -1114,7 +1134,11 @@ describe('getUser', () => { query: 'populate', args: [{ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }], }, @@ -1161,7 +1185,11 @@ describe('getUser', () => { query: 'populate', args: [{ path: 'company', - populate: { path: 'company', populate: { path: 'billingRepresentatives salesRepresentative' } }, + populate: { + path: 'company', + select: '-iban -bic', + populate: { path: 'billingRepresentatives salesRepresentative', select: '-iban -bic' }, + }, select: '-__v -createdAt -updatedAt', }], }, From 5ed4ed1cb50724a386ecc57117dd9002c55bde4c Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 3 Nov 2026 15:15:07 +0100 Subject: [PATCH 22/53] COM-4321 - allow ROF to get trainerBills linked to courses --- src/helpers/courses.js | 75 +++++++++++++--------- src/routes/courses.js | 4 +- src/routes/preHandlers/courses.js | 6 +- tests/integration/courses.test.js | 52 +++++++++++++++ tests/integration/seed/coursesSeed.js | 15 +++++ tests/unit/helpers/courses.test.js | 91 ++++++++++++++++++++++++--- 6 files changed, 201 insertions(+), 42 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 7dc69a4514..235157bdda 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2340,7 +2340,7 @@ exports.getCourseTrainerSalary = async (course, trainerId) => { exports.listTrainersBilling = async (query) => { const courses = await Course .find( - { trainers: query.trainer, type: { $ne: SINGLE } }, + { ...(query.trainer && { trainers: query.trainer }), type: { $ne: SINGLE } }, { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } ) .populate({ path: 'companies', select: 'name' }) @@ -2356,40 +2356,53 @@ exports.listTrainersBilling = async (query) => { if (!courses.length) return []; const trainerBills = await TrainerBill - .find({ course: { $in: courses.map(c => c._id) }, trainer: query.trainer }, { course: 1, amount: 1 }) + .find( + { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, + { course: 1, amount: 1, trainer: 1 } + ) .populate({ path: 'payment', select: 'status' }) .lean(); - const billsByCourse = groupBy(trainerBills, bill => bill.course); - - const trainerCourses = []; - for (const course of courses) { - const plannedSalary = await exports.getCourseTrainerSalary(course, query.trainer); - const courseBills = billsByCourse[course._id] || []; - let invoicedAmount = 0; - let paidAmount = 0; - for (const bill of courseBills) { - invoicedAmount = NumbersHelper.add(invoicedAmount, bill.amount); - if (bill.payment?.status === PAID) paidAmount = NumbersHelper.add(paidAmount, bill.amount); + const trainers = query.trainer + ? [courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer))] + : uniqBy(courses.flatMap(c => c.trainers), t => t._id.toHexString()); + + const trainersBilling = []; + for (const trainer of trainers) { + const filteredTrainerBills = trainerBills.filter(bill => UtilsHelper.areObjectIdsEquals(bill.trainer, trainer._id)); + const trainerBillsByCourse = groupBy(filteredTrainerBills, bill => bill.course); + const filteredTrainerCourses = courses + .filter(course => UtilsHelper.doesArrayIncludeId(course.trainers.map(t => t._id), trainer._id)); + + const trainerCourses = []; + for (const course of filteredTrainerCourses) { + const plannedSalary = await exports.getCourseTrainerSalary(course, trainer._id); + const courseBills = trainerBillsByCourse[course._id] || []; + let invoicedAmount = 0; + let paidAmount = 0; + for (const bill of courseBills) { + invoicedAmount = NumbersHelper.add(invoicedAmount, bill.amount); + if (bill.payment?.status === PAID) paidAmount = NumbersHelper.add(paidAmount, bill.amount); + } + invoicedAmount = NumbersHelper.toNumber(invoicedAmount); + paidAmount = NumbersHelper.toNumber(paidAmount); + + let status = INVOICED; + if (invoicedAmount === 0) status = NOT_INVOICED; + else if (invoicedAmount < plannedSalary) status = PARTIALLY_INVOICED; + else if (invoicedAmount === paidAmount) status = PAID; + + trainerCourses.push({ + ...omit(course, ['billingPurchaseList', 'rolesPerTrainer']), + plannedSalary, + invoicedAmount, + paidAmount, + status, + }); } - invoicedAmount = NumbersHelper.toNumber(invoicedAmount); - paidAmount = NumbersHelper.toNumber(paidAmount); - - let status = INVOICED; - if (invoicedAmount === 0) status = NOT_INVOICED; - else if (invoicedAmount < plannedSalary) status = PARTIALLY_INVOICED; - else if (invoicedAmount === paidAmount) status = PAID; - - trainerCourses.push({ - ...omit(course, ['billingPurchaseList', 'rolesPerTrainer']), - plannedSalary, - invoicedAmount, - paidAmount, - status, - }); - } - const trainer = courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer)); + trainersBilling.push({ ...trainer, courses: trainerCourses }); + } - return [{ ...trainer, courses: trainerCourses }]; + return trainersBilling; }; diff --git a/src/routes/courses.js b/src/routes/courses.js index 877b02bda5..27fb1f5c9a 100644 --- a/src/routes/courses.js +++ b/src/routes/courses.js @@ -140,8 +140,8 @@ exports.plugin = { method: 'GET', path: '/trainers-billing', options: { - auth: { scope: ['user:read-{query.trainer}'] }, - validate: { query: Joi.object({ trainer: Joi.objectId().required() }) }, + auth: { scope: ['trainerbills:edit', 'user:read-{query.trainer}'] }, + validate: { query: Joi.object({ trainer: Joi.objectId() }) }, pre: [{ method: authorizeTrainerBillsGet }], }, handler: listTrainersBilling, diff --git a/src/routes/preHandlers/courses.js b/src/routes/preHandlers/courses.js index b11ad29cb9..dc4cb9ed84 100644 --- a/src/routes/preHandlers/courses.js +++ b/src/routes/preHandlers/courses.js @@ -1663,8 +1663,10 @@ exports.authorizeTrainerBillsGet = async (req) => { try { const { trainer: trainerId } = req.query; - const trainer = await User.countDocuments({ _id: trainerId, 'role.vendor': { $exists: true } }); - if (!trainer) throw Boom.notFound(); + if (trainerId) { + const trainer = await User.countDocuments({ _id: trainerId, 'role.vendor': { $exists: true } }); + if (!trainer) throw Boom.notFound(); + } return null; } catch (e) { diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index b4b2e76bb0..3c07de0085 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10097,6 +10097,48 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { let authToken; beforeEach(populateDB); + describe('TRAINING_ORGANISATION_MANAGER', () => { + beforeEach(async () => { + authToken = await getToken('training_organisation_manager'); + }); + + it('should return all trainers with their collective courses and billing infos #tag', async () => { + const response = await app.inject({ + method: 'GET', + url: '/courses/trainers-billing', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + const { trainers } = response.result.data; + expect(trainers.length).toBe(2); + expect(trainers.every(t => t.courses.every(c => c.type !== SINGLE))).toBeTruthy(); + expect(trainers.some(t => t.courses.some(c => c.status === 'invoiced'))).toBeTruthy(); + }); + + it('should return a specific trainer with its collective courses and billing infos', async () => { + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${trainer._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + expect(response.result.data.trainers.length).toBe(1); + expect(response.result.data.trainers[0].courses.length).toEqual(15); + }); + + it('should return 404 if trainer does not exist', async () => { + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${new ObjectId()}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(404); + }); + }); + describe('TRAINER', () => { beforeEach(async () => { authToken = await getToken('trainer'); @@ -10130,6 +10172,16 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { expect(response.statusCode).toBe(403); }); + + it('should return 403 if no trainer in query', async () => { + const response = await app.inject({ + method: 'GET', + url: '/courses/trainers-billing', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(403); + }); }); describe('Other roles', () => { diff --git a/tests/integration/seed/coursesSeed.js b/tests/integration/seed/coursesSeed.js index 5e2870a4ea..836bbf72b6 100644 --- a/tests/integration/seed/coursesSeed.js +++ b/tests/integration/seed/coursesSeed.js @@ -9,6 +9,7 @@ const SubProgram = require('../../../src/models/SubProgram'); const CourseSlot = require('../../../src/models/CourseSlot'); const CourseSmsHistory = require('../../../src/models/CourseSmsHistory'); const CourseHistory = require('../../../src/models/CourseHistory'); +const TrainerBill = require('../../../src/models/TrainerBill'); const TrainerMission = require('../../../src/models/TrainerMission'); const User = require('../../../src/models/User'); const Step = require('../../../src/models/Step'); @@ -1537,6 +1538,18 @@ const trainerMissionList = [ }, ]; +const trainerBillList = [ + { + _id: new ObjectId(), + trainer: trainer._id, + number: 'FACT_0001', + course: coursesList[0]._id, + amount: 100, + submittedAt: '2025-01-01T10:00:00.000Z', + file: { publicId: 'publicId', link: 'link' }, + }, +]; + const populateDB = async () => { await deleteNonAuthenticationSeeds(); @@ -1563,6 +1576,7 @@ const populateDB = async () => { QuestionnaireHistory.create(questionnaireHistory), Step.create(stepList), SubProgram.create(subProgramsList), + TrainerBill.create(trainerBillList), TrainerMission.create(trainerMissionList), User.create(userList), UserCompany.create(userCompanies), @@ -1591,4 +1605,5 @@ module.exports = { traineeWithoutCompany, ROFAndCoach, slots, + trainerBillList, }; diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index bfccb955d6..5b886a4416 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11456,14 +11456,15 @@ describe('listTrainersBilling', () => { { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, ]; - courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - getCourseTrainerSalary.returns(100); const trainerBills = [ - { course: courses[1]._id, amount: 40, payment: { status: 'pending' } }, - { course: courses[2]._id, amount: 100, payment: { status: 'pending' } }, - { course: courses[3]._id, amount: 60, payment: { status: 'paid' } }, - { course: courses[3]._id, amount: 40, payment: { status: 'paid' } }, + { course: courses[1]._id, trainer: trainerId, amount: 40, payment: { status: 'pending' } }, + { course: courses[2]._id, trainer: trainerId, amount: 100, payment: { status: 'pending' } }, + { course: courses[3]._id, trainer: trainerId, amount: 60, payment: { status: 'paid' } }, + { course: courses[3]._id, trainer: trainerId, amount: 40, payment: { status: 'paid' } }, ]; + + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + getCourseTrainerSalary.returns(100); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11486,8 +11487,84 @@ describe('listTrainersBilling', () => { [ { query: 'find', - args: [{ course: { $in: courses.map(c => c._id) }, trainer: trainerId }, { course: 1, amount: 1 }], + args: [ + { course: { $in: courses.map(c => c._id) }, trainer: trainerId }, + { course: 1, amount: 1, trainer: 1 }, + ], + }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'lean' }, + ] + ); + }); + + it('should return all trainers with their courses and billing status if no trainer in query', async () => { + const firstTrainerId = new ObjectId(); + const secondTrainerId = new ObjectId(); + const firstTrainer = { _id: firstTrainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const secondTrainer = { _id: secondTrainerId, identity: { firstname: 'Paul', lastname: 'Martin' } }; + const courses = [ + { _id: new ObjectId(), trainers: [firstTrainer, secondTrainer], tradeName: 'prog' }, + { _id: new ObjectId(), trainers: [secondTrainer], tradeName: 'prog' }, + ]; + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + getCourseTrainerSalary.returns(100); + const trainerBills = [ + { course: courses[0]._id, trainer: firstTrainerId, amount: 100, payment: { status: 'paid' } }, + { course: courses[0]._id, trainer: secondTrainerId, amount: 40, payment: { status: 'pending' } }, + { course: courses[1]._id, trainer: secondTrainerId, amount: 100, payment: { status: 'pending' } }, + ]; + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({}); + + expect(result).toEqual([ + { + ...firstTrainer, + courses: [ + { ...courses[0], plannedSalary: 100, invoicedAmount: 100, paidAmount: 100, status: 'paid' }, + ], + }, + { + ...secondTrainer, + courses: [ + { ...courses[0], plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced' }, + { ...courses[1], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, + ], + }, + ]); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courses[0], firstTrainerId); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courses[0], secondTrainerId); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(2), courses[1], secondTrainerId); + SinonMongoose.calledOnceWithExactly( + courseFind, + [ + { + query: 'find', + args: [ + { type: { $ne: 'single' } }, + { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + ], }, + { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, + { + query: 'populate', + args: [{ + path: 'subProgram', + select: 'program trainerPriceVersions', + populate: { path: 'program', select: 'name' }, + }], + }, + { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, + { query: 'populate', args: [{ path: 'billingPurchaseList.billingItem', select: 'type' }] }, + { query: 'sort', args: [{ createdAt: -1 }] }, + { query: 'lean' }, + ] + ); + SinonMongoose.calledOnceWithExactly( + trainerBillFind, + [ + { query: 'find', args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, amount: 1, trainer: 1 }] }, { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, { query: 'lean' }, ] From 79188341b4602942a70849582dc33e379e0be38a Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 3 Nov 2026 16:10:02 +0100 Subject: [PATCH 23/53] COM-4321 - ignores courses without trainers --- src/helpers/courses.js | 5 ++++- tests/unit/helpers/courses.test.js | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 235157bdda..b5c48b3caa 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2340,7 +2340,10 @@ exports.getCourseTrainerSalary = async (course, trainerId) => { exports.listTrainersBilling = async (query) => { const courses = await Course .find( - { ...(query.trainer && { trainers: query.trainer }), type: { $ne: SINGLE } }, + { + ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), + type: { $ne: SINGLE }, + }, { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } ) .populate({ path: 'companies', select: 'name' }) diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 5b886a4416..bbcd5bd8cc 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11542,7 +11542,7 @@ describe('listTrainersBilling', () => { { query: 'find', args: [ - { type: { $ne: 'single' } }, + { 'trainers.0': { $exists: true }, type: { $ne: 'single' } }, { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, ], }, From 1ad79d139a2d8a68342eaa6f346f50aa4fee5c98 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 3 Nov 2026 16:19:04 +0100 Subject: [PATCH 24/53] COM-4321 - fix seedsVerif error + add new tests --- .../seed/seedsVerification.test.js | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/integration/seed/seedsVerification.test.js b/tests/integration/seed/seedsVerification.test.js index c409fc4be2..9f4a453326 100644 --- a/tests/integration/seed/seedsVerification.test.js +++ b/tests/integration/seed/seedsVerification.test.js @@ -2561,10 +2561,16 @@ describe('SEEDS VERIFICATION', () => { describe('Collection TrainerBill', () => { let trainerBillList; + let courseTrainerBillList; before(async () => { + courseTrainerBillList = await TrainerBill + .find({ course: { $exists: true } }, { course: 1, courseSlots: 1, trainer: 1, amount: 1 }) + .populate({ path: 'course', select: 'trainers' }) + .lean(); + trainerBillList = await TrainerBill - .find() + .find({ courseSlots: { $exists: true } }) .populate({ path: 'courseSlots', select: 'startDate endDate step trainerBillings', @@ -2613,6 +2619,19 @@ describe('SEEDS VERIFICATION', () => { expect(everyAmountIsCorrect).toBeTruthy(); }); + + it('should pass if no trainerBill is linked to both a course and course slots', () => { + const noTrainerBillHasCourseAndCourseSlots = courseTrainerBillList.every(tb => !tb.courseSlots); + + expect(noTrainerBillHasCourseAndCourseSlots).toBeTruthy(); + }); + + it('should pass if every trainerBill linked to a course has its trainer in course trainers', () => { + const everyTrainerIsInCourseTrainers = courseTrainerBillList + .every(tb => tb.course && UtilsHelper.doesArrayIncludeId(tb.course.trainers, tb.trainer)); + + expect(everyTrainerIsInCourseTrainers).toBeTruthy(); + }); }); describe('Collection TrainerMission', () => { From 18b4c5f0d7f22ff3a12c7d7cadb916f2264db574 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 4 Nov 2026 12:02:32 +0100 Subject: [PATCH 25/53] COM-4321 - fix reviews --- src/helpers/courses.js | 58 +++++--- tests/integration/courses.test.js | 2 +- tests/unit/helpers/courses.test.js | 227 +++++++++++++++++++++-------- 3 files changed, 203 insertions(+), 84 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index b5c48b3caa..bebf467f30 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -97,6 +97,7 @@ const { PAID, VAEI_COACH, ARCHITECT, + INTER_B2C, } = require('./constants'); const CompaniesHelper = require('./companies'); const CourseHistoriesHelper = require('./courseHistories'); @@ -2311,15 +2312,8 @@ exports.deleteBillingPurchase = async (courseId, billingPurchaseId) => Course.up { $pull: { billingPurchaseList: { _id: billingPurchaseId } } } ); -exports.getCourseTrainerSalary = async (course, trainerId) => { - if (course.trainers.length === 1) { - const salaryItem = (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); - if (salaryItem) return NumbersHelper.toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)); - } - - const slots = await CourseSlot - .find({ course: course._id, trainers: trainerId }, { step: 1, startDate: 1, endDate: 1 }) - .lean(); +exports.getCourseTrainerSalaryFromSlots = (course, trainerId, courseSlots) => { + const slots = courseSlots.filter(slot => UtilsHelper.doesArrayIncludeId(slot.trainers, trainerId)); const salary = slots.reduce((acc, slot) => { const hourlyAmount = CourseSlotsHelper @@ -2342,7 +2336,7 @@ exports.listTrainersBilling = async (query) => { .find( { ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), - type: { $ne: SINGLE }, + type: { $nin: [SINGLE, INTER_B2C] }, }, { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } ) @@ -2358,13 +2352,35 @@ exports.listTrainersBilling = async (query) => { .lean(); if (!courses.length) return []; - const trainerBills = await TrainerBill - .find( - { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, - { course: 1, amount: 1, trainer: 1 } - ) - .populate({ path: 'payment', select: 'status' }) - .lean(); + const trainerSalaryByCourse = {}; + const courseIdsWithoutTrainerSalary = []; + for (const course of courses) { + const salaryItem = course.trainers.length === 1 && + (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); + if (salaryItem) { + trainerSalaryByCourse[course._id] = NumbersHelper + .toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)); + } else courseIdsWithoutTrainerSalary.push(course._id); + } + const [trainerBills, courseSlots] = await Promise.all([ + TrainerBill + .find( + { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, + { course: 1, amount: 1, trainer: 1 } + ) + .populate({ path: 'payment', select: 'status' }) + .lean(), + courseIdsWithoutTrainerSalary.length + ? CourseSlot + .find( + { course: { $in: courseIdsWithoutTrainerSalary }, ...(query.trainer && { trainers: query.trainer }) }, + { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 } + ) + .lean() + : [], + ]); + const billsByTrainerAndCourse = groupBy(trainerBills, bill => `${bill.trainer}-${bill.course}`); + const courseSlotsByCourse = groupBy(courseSlots, slot => slot.course); const trainers = query.trainer ? [courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer))] @@ -2372,15 +2388,15 @@ exports.listTrainersBilling = async (query) => { const trainersBilling = []; for (const trainer of trainers) { - const filteredTrainerBills = trainerBills.filter(bill => UtilsHelper.areObjectIdsEquals(bill.trainer, trainer._id)); - const trainerBillsByCourse = groupBy(filteredTrainerBills, bill => bill.course); const filteredTrainerCourses = courses .filter(course => UtilsHelper.doesArrayIncludeId(course.trainers.map(t => t._id), trainer._id)); const trainerCourses = []; for (const course of filteredTrainerCourses) { - const plannedSalary = await exports.getCourseTrainerSalary(course, trainer._id); - const courseBills = trainerBillsByCourse[course._id] || []; + const plannedSalary = trainerSalaryByCourse[course._id] + ? trainerSalaryByCourse[course._id] + : exports.getCourseTrainerSalaryFromSlots(course, trainer._id, courseSlotsByCourse[course._id] || []); + const courseBills = billsByTrainerAndCourse[`${trainer._id}-${course._id}`] || []; let invoicedAmount = 0; let paidAmount = 0; for (const bill of courseBills) { diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 3c07de0085..eb7c63c943 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10102,7 +10102,7 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { authToken = await getToken('training_organisation_manager'); }); - it('should return all trainers with their collective courses and billing infos #tag', async () => { + it('should return all trainers with their collective courses and billing infos', async () => { const response = await app.inject({ method: 'GET', url: '/courses/trainers-billing', diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index bbcd5bd8cc..f8a370c948 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11330,72 +11330,67 @@ describe('getTraineeDurations', () => { }); }); -describe('getCourseTrainerSalary', () => { - let courseSlotFind; +describe('getCourseTrainerSalaryFromSlots', () => { let getHourlyAmount; beforeEach(() => { - courseSlotFind = sinon.stub(CourseSlot, 'find'); getHourlyAmount = sinon.stub(CourseSlotsHelper, 'getHourlyAmount'); }); afterEach(() => { - courseSlotFind.restore(); getHourlyAmount.restore(); }); - it('should return trainer salary billing purchase amount if only one trainer', async () => { - const trainerId = new ObjectId(); - const course = { - _id: new ObjectId(), - trainers: [trainerId], - billingPurchaseList: [ - { billingItem: { type: 'course' }, price: 1000, count: 1 }, - { billingItem: { type: 'trainer_salary' }, price: 100, count: 2 }, - ], - }; - - const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); - - expect(result).toEqual(200); - sinon.assert.notCalled(courseSlotFind); - }); - - it('should compute salary from slots if only one trainer and no trainer salary billing purchase', async () => { + it('should return 0 if no slot', () => { const trainerId = new ObjectId(); const course = { _id: new ObjectId(), trainers: [trainerId], - billingPurchaseList: [{ billingItem: { type: 'course' }, price: 1000, count: 1 }], createdAt: '2024-01-01T00:00:00.000Z', }; - courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); - const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); + const result = CourseHelper.getCourseTrainerSalaryFromSlots(course, trainerId, []); expect(result).toEqual(0); - sinon.assert.calledOnce(courseSlotFind); + sinon.assert.notCalled(getHourlyAmount); }); - it('should compute salary from slots if several trainers', async () => { + it('should compute salary from trainer slots', () => { const trainerId = new ObjectId(); + const otherTrainerId = new ObjectId(); const stepId = new ObjectId(); const course = { _id: new ObjectId(), - trainers: [trainerId, new ObjectId()], + trainers: [trainerId, otherTrainerId], createdAt: '2024-01-01T00:00:00.000Z', }; - const slots = [ - { step: stepId, startDate: new Date('2024-02-01T08:00:00.000Z'), endDate: new Date('2024-02-01T10:00:00.000Z') }, - { step: stepId, startDate: new Date('2024-02-02T08:00:00.000Z'), endDate: new Date('2024-02-02T09:30:00.000Z') }, + const courseSlots = [ + { + step: stepId, + trainers: [trainerId], + startDate: new Date('2024-02-01T08:00:00.000Z'), + endDate: new Date('2024-02-01T10:00:00.000Z'), + }, + { + step: stepId, + trainers: [otherTrainerId], + startDate: new Date('2024-02-01T14:00:00.000Z'), + endDate: new Date('2024-02-01T16:00:00.000Z'), + }, + { + step: stepId, + trainers: [trainerId, otherTrainerId], + startDate: new Date('2024-02-02T08:00:00.000Z'), + endDate: new Date('2024-02-02T09:30:00.000Z'), + }, ]; - courseSlotFind.returns(SinonMongoose.stubChainedQueries(slots, ['lean'])); getHourlyAmount.onCall(0).returns(40); getHourlyAmount.onCall(1).returns(60); - const result = await CourseHelper.getCourseTrainerSalary(course, trainerId); + const result = CourseHelper.getCourseTrainerSalaryFromSlots(course, trainerId, courseSlots); expect(result).toEqual(170); + sinon.assert.calledTwice(getHourlyAmount); sinon.assert.calledWithExactly( getHourlyAmount.getCall(0), { step: { _id: stepId }, startDate: course.createdAt, course }, @@ -11406,34 +11401,27 @@ describe('getCourseTrainerSalary', () => { { step: { _id: stepId }, startDate: course.createdAt, course }, trainerId ); - SinonMongoose.calledOnceWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [{ course: course._id, trainers: trainerId }, { step: 1, startDate: 1, endDate: 1 }], - }, - { query: 'lean' }, - ] - ); }); }); describe('listTrainersBilling', () => { let courseFind; let trainerBillFind; - let getCourseTrainerSalary; + let courseSlotFind; + let getCourseTrainerSalaryFromSlots; beforeEach(() => { courseFind = sinon.stub(Course, 'find'); trainerBillFind = sinon.stub(TrainerBill, 'find'); - getCourseTrainerSalary = sinon.stub(CourseHelper, 'getCourseTrainerSalary'); + courseSlotFind = sinon.stub(CourseSlot, 'find'); + getCourseTrainerSalaryFromSlots = sinon.stub(CourseHelper, 'getCourseTrainerSalaryFromSlots'); }); afterEach(() => { courseFind.restore(); trainerBillFind.restore(); - getCourseTrainerSalary.restore(); + courseSlotFind.restore(); + getCourseTrainerSalaryFromSlots.restore(); }); it('should return an empty array if no course found', async () => { @@ -11444,7 +11432,8 @@ describe('listTrainersBilling', () => { expect(result).toEqual([]); sinon.assert.notCalled(trainerBillFind); - sinon.assert.notCalled(getCourseTrainerSalary); + sinon.assert.notCalled(courseSlotFind); + sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); }); it('should return trainer with its courses and billing status', async () => { @@ -11454,7 +11443,12 @@ describe('listTrainersBilling', () => { { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, - { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 40, count: 2 }], + }, ]; const trainerBills = [ { course: courses[1]._id, trainer: trainerId, amount: 40, payment: { status: 'pending' } }, @@ -11464,8 +11458,14 @@ describe('listTrainersBilling', () => { ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - getCourseTrainerSalary.returns(100); + getCourseTrainerSalaryFromSlots.returns(100); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + const courseSlots = [ + { course: courses[0]._id, trainers: [trainerId] }, + { course: courses[0]._id, trainers: [trainerId] }, + { course: courses[2]._id, trainers: [trainerId] }, + ]; + courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11475,13 +11475,24 @@ describe('listTrainersBilling', () => { { ...courses[0], plannedSalary: 100, invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, { ...courses[1], plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced' }, { ...courses[2], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, - { ...courses[3], plannedSalary: 100, invoicedAmount: 100, paidAmount: 100, status: 'paid' }, + { + ...omit(courses[3], ['billingPurchaseList']), + plannedSalary: 80, + invoicedAmount: 100, + paidAmount: 100, + status: 'paid', + }, ], }]); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courses[0], trainerId); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courses[1], trainerId); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(2), courses[2], trainerId); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(3), courses[3], trainerId); + sinon.assert.calledWithExactly( + getCourseTrainerSalaryFromSlots.getCall(0), + courses[0], + trainerId, + [courseSlots[0], courseSlots[1]] + ); + sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(1), courses[1], trainerId, []); + sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(2), courses[2], trainerId, [courseSlots[2]]); + sinon.assert.calledThrice(getCourseTrainerSalaryFromSlots); SinonMongoose.calledOnceWithExactly( trainerBillFind, [ @@ -11496,6 +11507,48 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courses[0]._id, courses[1]._id, courses[2]._id] }, trainers: trainerId }, + { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, + ], + }, + { query: 'lean' }, + ] + ); + }); + + it('should not get slots if all courses have a trainer salary billing purchase', async () => { + const trainerId = new ObjectId(); + const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const courses = [{ + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 60, count: 2 }], + }]; + + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([{ + ...trainer, + courses: [{ + ...omit(courses[0], ['billingPurchaseList']), + plannedSalary: 120, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }], + }]); + sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); + sinon.assert.notCalled(courseSlotFind); }); it('should return all trainers with their courses and billing status if no trainer in query', async () => { @@ -11504,17 +11557,27 @@ describe('listTrainersBilling', () => { const firstTrainer = { _id: firstTrainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; const secondTrainer = { _id: secondTrainerId, identity: { firstname: 'Paul', lastname: 'Martin' } }; const courses = [ - { _id: new ObjectId(), trainers: [firstTrainer, secondTrainer], tradeName: 'prog' }, + { + _id: new ObjectId(), + trainers: [firstTrainer, secondTrainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 40, count: 2 }], + }, { _id: new ObjectId(), trainers: [secondTrainer], tradeName: 'prog' }, ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - getCourseTrainerSalary.returns(100); + getCourseTrainerSalaryFromSlots.returns(100); const trainerBills = [ { course: courses[0]._id, trainer: firstTrainerId, amount: 100, payment: { status: 'paid' } }, { course: courses[0]._id, trainer: secondTrainerId, amount: 40, payment: { status: 'pending' } }, { course: courses[1]._id, trainer: secondTrainerId, amount: 100, payment: { status: 'pending' } }, ]; trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + const courseSlots = [ + { course: courses[0]._id, trainers: [firstTrainerId, secondTrainerId] }, + { course: courses[1]._id, trainers: [secondTrainerId] }, + ]; + courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); const result = await CourseHelper.listTrainersBilling({}); @@ -11522,27 +11585,54 @@ describe('listTrainersBilling', () => { { ...firstTrainer, courses: [ - { ...courses[0], plannedSalary: 100, invoicedAmount: 100, paidAmount: 100, status: 'paid' }, + { + ...omit(courses[0], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 100, + paidAmount: 100, + status: 'paid', + }, ], }, { ...secondTrainer, courses: [ - { ...courses[0], plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced' }, + { + ...omit(courses[0], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 40, + paidAmount: 0, + status: 'partially_invoiced', + }, { ...courses[1], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, ], }, ]); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courses[0], firstTrainerId); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courses[0], secondTrainerId); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(2), courses[1], secondTrainerId); + sinon.assert.calledWithExactly( + getCourseTrainerSalaryFromSlots.getCall(0), + courses[0], + firstTrainerId, + [courseSlots[0]] + ); + sinon.assert.calledWithExactly( + getCourseTrainerSalaryFromSlots.getCall(1), + courses[0], + secondTrainerId, + [courseSlots[0]] + ); + sinon.assert.calledWithExactly( + getCourseTrainerSalaryFromSlots.getCall(2), + courses[1], + secondTrainerId, + [courseSlots[1]] + ); SinonMongoose.calledOnceWithExactly( courseFind, [ { query: 'find', args: [ - { 'trainers.0': { $exists: true }, type: { $ne: 'single' } }, + { 'trainers.0': { $exists: true }, type: { $nin: ['single', 'inter_b2c'] } }, { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, ], }, @@ -11569,5 +11659,18 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { course: { $in: courses.map(c => c._id) } }, + { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, + ], + }, + { query: 'lean' }, + ] + ); }); }); From 77c5771546d34f9f067c3ee0d114481cbdc3dd74 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 4 Nov 2026 13:11:09 +0100 Subject: [PATCH 26/53] COM-4321 - add date input to filter courses on dashboard --- src/helpers/courses.js | 9 +++ src/routes/courses.js | 15 +++- tests/integration/courses.test.js | 44 +++++++++++ tests/unit/helpers/courses.test.js | 114 +++++++++++++++++++++++++++++ 4 files changed, 181 insertions(+), 1 deletion(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index bebf467f30..176a9a4af7 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2332,9 +2332,18 @@ exports.getCourseTrainerSalaryFromSlots = (course, trainerId, courseSlots) => { }; exports.listTrainersBilling = async (query) => { + let courseIdsWithSlotsInPeriod; + if (query.startDate) { + const slotsInPeriod = await CourseSlot + .find({ startDate: { $gte: query.startDate }, endDate: { $lte: query.endDate } }, { course: 1 }) + .lean(); + courseIdsWithSlotsInPeriod = uniqBy(slotsInPeriod.map(slot => slot.course), id => id.toHexString()); + } + const courses = await Course .find( { + ...(courseIdsWithSlotsInPeriod && { _id: { $in: courseIdsWithSlotsInPeriod } }), ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), type: { $nin: [SINGLE, INTER_B2C] }, }, diff --git a/src/routes/courses.js b/src/routes/courses.js index 27fb1f5c9a..2811290771 100644 --- a/src/routes/courses.js +++ b/src/routes/courses.js @@ -141,7 +141,20 @@ exports.plugin = { path: '/trainers-billing', options: { auth: { scope: ['trainerbills:edit', 'user:read-{query.trainer}'] }, - validate: { query: Joi.object({ trainer: Joi.objectId() }) }, + validate: { + query: Joi.object({ + trainer: Joi.objectId(), + startDate: dateToISOString, + endDate: Joi.when( + 'startDate', + { + is: Joi.exist(), + then: dateToISOString && Joi.date().required().min(Joi.ref('startDate')), + otherwise: Joi.forbidden(), + } + ), + }), + }, pre: [{ method: authorizeTrainerBillsGet }], }, handler: listTrainersBilling, diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index eb7c63c943..70037dbff5 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10128,6 +10128,50 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { expect(response.result.data.trainers[0].courses.length).toEqual(15); }); + it('should return trainer\'s courses with slots in period', async () => { + const startDate = '2020-03-01T00:00:00.000Z'; + const endDate = '2020-03-05T23:59:59.999Z'; + const response = await app.inject({ + method: 'GET', + url: `/courses/trainers-billing?trainer=${trainer._id}&startDate=${startDate}&endDate=${endDate}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + const { courses } = response.result.data.trainers[0]; + expect(courses.length).toBe(2); + }); + + it('should return 400 if endDate without startDate', async () => { + const response = await app.inject({ + method: 'GET', + url: '/courses/trainers-billing?endDate=2020-03-05T23:59:59.999Z', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 400 if startDate without endDate', async () => { + const response = await app.inject({ + method: 'GET', + url: '/courses/trainers-billing?startDate=2020-03-01T00:00:00.000Z', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 400 if endDate is before startDate', async () => { + const response = await app.inject({ + method: 'GET', + url: '/courses/trainers-billing?startDate=2020-03-05T00:00:00.000Z&endDate=2020-03-01T00:00:00.000Z', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(400); + }); + it('should return 404 if trainer does not exist', async () => { const response = await app.inject({ method: 'GET', diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index f8a370c948..d6f45604a4 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11551,6 +11551,120 @@ describe('listTrainersBilling', () => { sinon.assert.notCalled(courseSlotFind); }); + it('should only return courses with slots in period', async () => { + const trainerId = new ObjectId(); + const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const query = { trainer: trainerId, startDate: '2024-02-01T00:00:00.000Z', endDate: '2024-02-29T23:59:59.999Z' }; + const courses = [ + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 100, count: 1 }], + }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog 2' }, + ]; + const courseSlotsInPeriod = [ + { + course: courses[0]._id, + startDate: '2024-02-01T08:00:00.000Z', + endDate: '2024-02-01T10:00:00.000Z', + trainers: [trainerId], + }, + { + course: courses[1]._id, + startDate: '2024-02-06T08:00:00.000Z', + endDate: '2024-02-06T10:00:00.000Z', + trainers: [trainerId], + }, + ]; + + courseSlotFind.onCall(0).returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + courseSlotFind.onCall(1).returns(SinonMongoose.stubChainedQueries([courseSlotsInPeriod[1]], ['lean'])); + getCourseTrainerSalaryFromSlots.returns(50); + + const result = await CourseHelper.listTrainersBilling(query); + + expect(result).toEqual([{ + ...trainer, + courses: [ + { + ...omit(courses[0], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }, + { ...courses[1], plannedSalary: 50, invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, + ], + }]); + sinon.assert.calledOnceWithExactly( + getCourseTrainerSalaryFromSlots, + courses[1], + trainerId, + [courseSlotsInPeriod[1]] + ); + SinonMongoose.calledWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { startDate: { $gte: query.startDate }, endDate: { $lte: query.endDate } }, + { course: 1 }, + ], + }, + { query: 'lean' }, + ], + 0 + ); + SinonMongoose.calledWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courses[1]._id] }, trainers: trainerId }, + { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, + ], + }, + { query: 'lean' }, + ], + 1 + ); + SinonMongoose.calledOnceWithExactly( + courseFind, + [ + { + query: 'find', + args: [ + { + _id: { $in: [courses[0]._id, courses[1]._id] }, + trainers: trainerId, + type: { $nin: ['single', 'inter_b2c'] }, + }, + { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + ], + }, + { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, + { + query: 'populate', + args: [{ + path: 'subProgram', + select: 'program trainerPriceVersions', + populate: { path: 'program', select: 'name' }, + }], + }, + { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, + { query: 'populate', args: [{ path: 'billingPurchaseList.billingItem', select: 'type' }] }, + { query: 'sort', args: [{ createdAt: -1 }] }, + { query: 'lean' }, + ] + ); + }); + it('should return all trainers with their courses and billing status if no trainer in query', async () => { const firstTrainerId = new ObjectId(); const secondTrainerId = new ObjectId(); From 9e0cab4c3f9457a735827d331c116a71505997fd Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 3 Nov 2026 17:10:31 +0100 Subject: [PATCH 27/53] COM-4324: refacto --- src/helpers/completionCertificates.js | 108 ++---- src/helpers/courseBills.js | 9 +- src/models/Course.js | 1 - src/models/CourseBill.js | 1 + src/routes/preHandlers/courseBills.js | 5 - src/routes/preHandlers/subPrograms.js | 8 +- tests/integration/courseBills.test.js | 29 +- .../seed/completionCertificatesSeed.js | 3 +- tests/integration/seed/courseBillsSeed.js | 33 +- .../seed/seedsVerification.test.js | 8 +- tests/integration/seed/subProgramsSeed.js | 26 +- .../helpers/completionCertificates.test.js | 354 +++++++++--------- tests/unit/helpers/courseBills.test.js | 14 +- 13 files changed, 267 insertions(+), 332 deletions(-) diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index 439c13d775..ddb512d448 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -2,10 +2,10 @@ const { ObjectId } = require('mongodb'); const get = require('lodash/get'); const has = require('lodash/has'); const pick = require('lodash/pick'); +const groupBy = require('lodash/groupBy'); const CompletionCertificatePdf = require('../data/pdf/completionCertificate'); const CompletionCertificate = require('../models/CompletionCertificate'); const TrainingContract = require('../models/TrainingContract'); -const Course = require('../models/Course'); const CourseBill = require('../models/CourseBill'); const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); @@ -99,7 +99,7 @@ exports.generate = async (completionCertificateId) => { .populate([ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -228,48 +228,39 @@ exports.generate = async (completionCertificateId) => { } await CompletionCertificate.updateOne({ _id: completionCertificateId }, { $set: updatePayload }); - if (course.hourlyPaymentPlan) { - const billsToUpdate = await CourseBill - .find( - { - course: course._id, - maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, - 'mainFee.price': { $in: [0, null] }, - }, - { _id: 1 } - ) - .setOptions({ isVendorUser: true }) - .lean(); + const billsToUpdate = await CourseBill + .find( + { + course: course._id, + maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); - if (billsToUpdate.length) { - const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans - .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); - const price = HourlyPaymentPlansHelper - .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + const billsGroupedByPlan = groupBy(billsToUpdate, 'hourlyPaymentPlan'); + for (const [planId, bills] of Object.entries(billsGroupedByPlan)) { + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, planId)); + const price = HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); - await CourseBill - .updateMany({ _id: { $in: billsToUpdate.map(b => b._id) } }, { $set: { 'mainFee.price': price } }); - } + await CourseBill.updateMany({ _id: { $in: bills.map(b => b._id) } }, { $set: { 'mainFee.price': price } }); } }; exports.create = async payload => CompletionCertificate.create(payload); exports.deleteFile = async (completionCertificateId) => { - const completionCertificate = await CompletionCertificate - .findOne({ _id: completionCertificateId }) - .populate({ path: 'course', select: 'hourlyPaymentPlan' }) - .lean(); + const completionCertificate = await CompletionCertificate.findOne({ _id: completionCertificateId }).lean(); let certificatesToDelete = [completionCertificate]; if (completionCertificate.vaeSupportRemainingMinutes) { const { course, trainee, vaeSupportRemainingMinutes } = completionCertificate; const completionCertificateWithRemainingMinutes = await CompletionCertificate - .find({ - course: course._id, - trainee, - vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes }, - }) + .find({ course, trainee, vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes } }) .setOptions({ isVendorUser: true }) .lean(); certificatesToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; @@ -289,47 +280,18 @@ exports.deleteFile = async (completionCertificateId) => { await GCloudStorageHelper.deleteCourseFile(completionCertificate.file.publicId); } - if (completionCertificate.course.hourlyPaymentPlan) { - const course = await Course - .findOne( - { _id: completionCertificate.course._id }, - { subProgram: 1, slots: 1, companies: 1, trainees: 1, hourlyPaymentPlan: 1 } - ) - .populate({ - path: 'slots', - select: 'startDate endDate trainers step', - populate: { path: 'step', select: 'durationCountedPerTrainer' }, - }) - .populate({ - path: 'subProgram', - select: 'program steps hourlyPaymentPlans', - populate: [ - { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, - ], - }) - .lean(); - - for (const certificate of certificatesToDelete) { - const durations = await computeMonthDurations(course, certificate.month, certificate.trainee); - const { startOfMonth, endOfMonth, durationPerStep, eLearningDuration } = durations; - - const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans - .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, course.hourlyPaymentPlan)); - const price = HourlyPaymentPlansHelper - .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); - - const billsToReset = await CourseBill - .find( - { course: course._id, maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, 'mainFee.price': price }, - { _id: 1 } - ) - .setOptions({ isVendorUser: true }) - .lean(); - - if (billsToReset.length) { - await CourseBill.updateMany({ _id: { $in: billsToReset.map(b => b._id) } }, { $set: { 'mainFee.price': 0 } }); - } - } + for (const certificate of certificatesToDelete) { + await CourseBill.updateMany( + { + course: certificate.course, + maturityDate: { + $gte: CompaniDate(certificate.month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(certificate.month, MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, + { $set: { 'mainFee.price': 0 } } + ); } }; diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 04becd96d4..62175b3db0 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -362,7 +362,6 @@ exports.createBillList = async (payload) => { trainees: 1, trainers: 1, subProgram: 1, - hourlyPaymentPlan: 1, certificateGenerationMode: 1, } ) @@ -377,10 +376,6 @@ exports.createBillList = async (payload) => { vat = vendorCompany.vat; } - if (payload.hourlyPaymentPlanId) { - await Course.updateOne({ _id: payload.course }, { $set: { hourlyPaymentPlan: payload.hourlyPaymentPlanId } }); - } - if (payload.quantity === 1) { const isGlobalCertificationCourseWithPriceFromDurations = payload.hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; @@ -392,6 +387,7 @@ exports.createBillList = async (payload) => { const billCreated = await CourseBill.create({ ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), mainFee: { ...mainFee, ...Array.isArray(mainFeePrice) && { price: mainFeePrice[0] } }, + ...payload.hourlyPaymentPlanId && { hourlyPaymentPlan: payload.hourlyPaymentPlanId }, ...vat && { vat }, }); @@ -453,8 +449,9 @@ exports.createBillList = async (payload) => { .formatSingleCourseBillDescription(billMaturityDate, course.trainees, get(course, 'trainers', [])); await CourseBill.create({ - ...omit(payload, ['quantity', 'maturityDate']), + ...omit(payload, ['quantity', 'maturityDate', 'hourlyPaymentPlanId']), mainFee: { ...payload.mainFee, description, ...payload.mainFee.price && { price: payload.mainFee.price[i] } }, + ...payload.hourlyPaymentPlanId && { hourlyPaymentPlan: payload.hourlyPaymentPlanId }, maturityDate: billMaturityDate.toISO(), ...vat && { vat }, }); diff --git a/src/models/Course.js b/src/models/Course.js index e5ff9198c4..fb8bc587b2 100644 --- a/src/models/Course.js +++ b/src/models/Course.js @@ -129,7 +129,6 @@ const CourseSchema = mongoose.Schema({ })], default: undefined, }, - hourlyPaymentPlan: { type: mongoose.Schema.Types.ObjectId }, }, { timestamps: true }); CourseSchema.virtual('slots', { diff --git a/src/models/CourseBill.js b/src/models/CourseBill.js index 908700629d..d1a12aa9fe 100644 --- a/src/models/CourseBill.js +++ b/src/models/CourseBill.js @@ -12,6 +12,7 @@ const CourseBillSchema = mongoose.Schema({ countUnit: { type: String, enum: [GROUP, TRAINEE], required: true }, description: { type: String }, }, + hourlyPaymentPlan: { type: mongoose.Schema.Types.ObjectId }, companies: { type: [mongoose.Schema.Types.ObjectId], ref: 'Company', required: true }, payer: { type: mongoose.Schema({ diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 33568f98ca..1f6cd45d2e 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -41,7 +41,6 @@ exports.authorizeCourseBillListCreation = async (req) => { companies: 1, prices: 1, interruptionDates: 1, - hourlyPaymentPlan: 1, certificateGenerationMode: 1, trainees: 1, }) @@ -58,10 +57,6 @@ exports.authorizeCourseBillListCreation = async (req) => { if (!UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId)) { throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); } - - if (course.hourlyPaymentPlan && !UtilsHelper.areObjectIdsEquals(course.hourlyPaymentPlan, hourlyPaymentPlanId)) { - throw Boom.forbidden(); - } } const shouldComputePriceFromDuration = hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; diff --git a/src/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index b4cceec435..958895db0b 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -7,6 +7,7 @@ const Program = require('../../models/Program'); const Company = require('../../models/Company'); const Step = require('../../models/Step'); const CourseSlot = require('../../models/CourseSlot'); +const CourseBill = require('../../models/CourseBill'); const { PUBLISHED, DRAFT, @@ -186,9 +187,10 @@ exports.authorizeSubProgramUpdate = async (req) => { const hourlyPaymentPlanExists = UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId); if (!hourlyPaymentPlanExists) throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); - const isUsedByCourse = !prices.length && subProgram.courses - .some(c => UtilsHelper.areObjectIdsEquals(c.hourlyPaymentPlan, hourlyPaymentPlanId)); - if (isUsedByCourse) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanUsed); + if (!prices.length) { + const isUsedByBill = await CourseBill.countDocuments({ hourlyPaymentPlan: hourlyPaymentPlanId }, { limit: 1 }); + if (isUsedByBill) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanUsed); + } } if (prices.length) { diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index 10f5cdc0f5..f43dc38ebc 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -3,7 +3,6 @@ const { expect } = require('expect'); const { ObjectId } = require('mongodb'); const set = require('lodash/set'); const omit = require('lodash/omit'); -const Course = require('../../src/models/Course'); const CourseBill = require('../../src/models/CourseBill'); const app = require('../../server'); const { @@ -814,7 +813,7 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(400); }); - it('should return 403 if the last slot of the course is not over', async () => { + it('should return 403 if the last slot of the course is not over (GLOBAL)', async () => { const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', @@ -830,7 +829,7 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(403); }); - it('should return 403 if some slots of the course have no attendance', async () => { + it('should return 403 if some slots of the course have no attendance (GLOBAL)', async () => { const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', @@ -929,7 +928,7 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(billsCountAfter).toBe(billsCountBefore + 2); }); - it('should create several bills and link the hourly payment plan (MONTHLY certification)', async () => { + it('should create bills with hourly payment plan even if other bills have another plan (MONTHLY)', async () => { const response = await app.inject({ method: 'POST', url: '/coursebills/list-creation', @@ -939,9 +938,14 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(200); - const courseCount = await Course - .countDocuments({ _id: coursesList[17]._id, hourlyPaymentPlan: hourlyPaymentPlanId }); - expect(courseCount).toBe(1); + const billsWithPlanCount = await CourseBill + .countDocuments({ course: coursesList[17]._id, hourlyPaymentPlan: hourlyPaymentPlanId }); + expect(billsWithPlanCount).toBe(2); + const billsWithAnotherPlanCount = await CourseBill.countDocuments({ + course: coursesList[17]._id, + hourlyPaymentPlan: { $exists: true, $ne: hourlyPaymentPlanId }, + }); + expect(billsWithAnotherPlanCount).toBe(1); }); it('should return 400 if several bills are created with an hourly payment plan (GLOBAL)', async () => { @@ -971,17 +975,6 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(404); }); - it('should return 403 if the course already has another hourly payment plan', async () => { - const response = await app.inject({ - method: 'POST', - url: '/coursebills/list-creation', - headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, - payload: { ...singleCoursePayload, course: coursesList[20]._id, hourlyPaymentPlanId }, - }); - - expect(response.statusCode).toBe(403); - }); - it('should return 403 if hourly payment plan is sent for a non SINGLE course', async () => { const response = await app.inject({ method: 'POST', diff --git a/tests/integration/seed/completionCertificatesSeed.js b/tests/integration/seed/completionCertificatesSeed.js index 0d6494a9a7..8d03f44877 100644 --- a/tests/integration/seed/completionCertificatesSeed.js +++ b/tests/integration/seed/completionCertificatesSeed.js @@ -148,7 +148,6 @@ const courseList = [ operationsRepresentative: trainerOrganisationManager._id, trainers: [trainer._id], certificateGenerationMode: MONTHLY, - hourlyPaymentPlan: hourlyPaymentPlanId, tradeName: 'nom', }, { // 3 Archived course with monthly certificateGenerationMode @@ -316,6 +315,7 @@ const courseBillsList = [ companies: [authCompany._id], payer: { company: authCompany._id }, mainFee: { price: 0, count: 1, countUnit: GROUP }, + hourlyPaymentPlan: hourlyPaymentPlanId, maturityDate: '2020-01-15T10:00:00.000Z', }, { // 1 bill with the real price, to reset when the certificate file is deleted @@ -324,6 +324,7 @@ const courseBillsList = [ companies: [authCompany._id], payer: { company: authCompany._id }, mainFee: { price: 200, count: 1, countUnit: GROUP }, + hourlyPaymentPlan: hourlyPaymentPlanId, maturityDate: '2020-01-20T10:00:00.000Z', }, ]; diff --git a/tests/integration/seed/courseBillsSeed.js b/tests/integration/seed/courseBillsSeed.js index 773db8dc0c..90a41637bb 100644 --- a/tests/integration/seed/courseBillsSeed.js +++ b/tests/integration/seed/courseBillsSeed.js @@ -44,7 +44,10 @@ const subProgramList = [ name: 'subProgram 1', steps: [steps[0]._id], status: PUBLISHED, - hourlyPaymentPlans: [{ _id: hourlyPaymentPlanId, prices: [{ step: steps[0]._id, hourlyAmount: 50 }] }], + hourlyPaymentPlans: [ + { _id: hourlyPaymentPlanId, prices: [{ step: steps[0]._id, hourlyAmount: 50 }] }, + { _id: new ObjectId(), prices: [{ step: steps[0]._id, hourlyAmount: 60 }] }, + ], }, ]; @@ -440,25 +443,6 @@ const coursesList = [ gSheetId: 'gSheetId', tradeName: 'nom', }, - { // 20 - single course with global certificate, already linked to another hourly payment plan - _id: new ObjectId(), - type: SINGLE, - maxTrainees: 1, - subProgram: subProgramList[0]._id, - misc: 'group 8', - trainers: [trainer._id], - operationsRepresentative: vendorAdmin._id, - contact: vendorAdmin._id, - trainees: [traineeFromOtherCompany._id], - expectedBillsCount: 4, - companies: [otherCompany._id], - certificateGenerationMode: GLOBAL, - hourlyPaymentPlan: new ObjectId(), - prices: [{ company: otherCompany._id, global: 15000, trainerFee: 1500 }], - folderId: 'folderId', - gSheetId: 'gSheetId', - tradeName: 'nom', - }, ]; const courseFundingOrganisationList = [ @@ -664,6 +648,15 @@ const courseBillsList = [ payer: { company: otherCompany._id }, maturityDate: '2025-08-14T22:00:00.000+00:00', }, + { // 18 - bill linked with hourly payment plan + _id: new ObjectId(), + course: coursesList[17]._id, + companies: [otherCompany._id], + mainFee: { price: 100, count: 1, countUnit: TRAINEE, description: 'test' }, + payer: { company: otherCompany._id }, + hourlyPaymentPlan: subProgramList[0].hourlyPaymentPlans[1]._id, + maturityDate: '2025-09-14T22:00:00.000+00:00', + }, ]; const courseCreditNoteList = [ diff --git a/tests/integration/seed/seedsVerification.test.js b/tests/integration/seed/seedsVerification.test.js index c409fc4be2..c8ff378293 100644 --- a/tests/integration/seed/seedsVerification.test.js +++ b/tests/integration/seed/seedsVerification.test.js @@ -1232,11 +1232,7 @@ describe('SEEDS VERIFICATION', () => { before(async () => { courseBillList = await CourseBill .find() - .populate({ - path: 'course', - select: 'type format companies type expectedBillsCount prices hourlyPaymentPlan', - transform, - }) + .populate({ path: 'course', select: 'type format companies type expectedBillsCount prices', transform }) .populate({ path: 'companies', transform }) .populate({ path: 'payer.company', transform }) .populate({ path: 'payer.fundingOrganisation', transform }) @@ -1259,7 +1255,7 @@ describe('SEEDS VERIFICATION', () => { it('should pass if every price is positive', () => { const everyPriceIsValid = courseBillList.every(bill => !has(bill, 'mainFee.price') || bill.mainFee.price > 0 || - (bill.mainFee.price === 0 && has(bill, 'course.hourlyPaymentPlan'))); + (bill.mainFee.price === 0 && has(bill, 'hourlyPaymentPlan'))); expect(everyPriceIsValid).toBeTruthy(); }); diff --git a/tests/integration/seed/subProgramsSeed.js b/tests/integration/seed/subProgramsSeed.js index f49544c093..58c3734c8f 100644 --- a/tests/integration/seed/subProgramsSeed.js +++ b/tests/integration/seed/subProgramsSeed.js @@ -5,6 +5,7 @@ const SubProgram = require('../../../src/models/SubProgram'); const Step = require('../../../src/models/Step'); const Activity = require('../../../src/models/Activity'); const Course = require('../../../src/models/Course'); +const CourseBill = require('../../../src/models/CourseBill'); const Card = require('../../../src/models/Card'); const CourseSlot = require('../../../src/models/CourseSlot'); const TrainerBill = require('../../../src/models/TrainerBill'); @@ -12,7 +13,16 @@ const User = require('../../../src/models/User'); const UserCompany = require('../../../src/models/UserCompany'); const { vendorAdmin, trainer } = require('../../seed/authUsersSeed'); const { deleteNonAuthenticationSeeds } = require('../helpers/db'); -const { WEBAPP, INTRA, PUBLISHED, DRAFT, GLOBAL, PAID, MONTHLY } = require('../../../src/helpers/constants'); +const { + WEBAPP, + INTRA, + PUBLISHED, + DRAFT, + GLOBAL, + PAID, + MONTHLY, + GROUP, +} = require('../../../src/helpers/constants'); const { authCompany } = require('../../seed/authCompaniesSeed'); const tester = { @@ -246,18 +256,29 @@ const coursesList = [ _id: new ObjectId(), format: 'blended', subProgram: subProgramsList[13]._id, - hourlyPaymentPlan: hourlyPaymentPlanId, type: INTRA, trainees: [], accessRules: [], companies: [authCompany._id], operationsRepresentative: vendorAdmin._id, tradeName: 'hourly plan', + expectedBillsCount: 1, certificateGenerationMode: MONTHLY, maxTrainees: 3, }, ]; +const courseBillsList = [ + { + _id: new ObjectId(), + course: coursesList[3]._id, + companies: [authCompany._id], + payer: { company: authCompany._id }, + mainFee: { price: 0, count: 1, countUnit: GROUP }, + hourlyPaymentPlan: hourlyPaymentPlanId, + }, +]; + const trainerBillId = new ObjectId(); const courseSlotsList = [ @@ -299,6 +320,7 @@ const populateDB = async () => { Activity.create(activitiesList), Card.create(cardsList), Course.create(coursesList), + CourseBill.create(courseBillsList), CourseSlot.create(courseSlotsList), Program.create(programsList), Step.create(stepsList), diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index fd925d400d..1371c68c7f 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -558,7 +558,6 @@ describe('generate', () => { }, companies: [companyId], trainees: [traineeId], - hourlyPaymentPlan: hourlyPaymentPlan._id, }, month, trainee: { @@ -611,7 +610,10 @@ describe('generate', () => { ); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); getDurationPerStep.returns(durationPerStep); - findBills.returns(SinonMongoose.stubChainedQueries([{ _id: billId }], ['setOptions', 'lean'])); + findBills.returns(SinonMongoose.stubChainedQueries( + [{ _id: billId, hourlyPaymentPlan: hourlyPaymentPlan._id }], + ['setOptions', 'lean'] + )); getPriceFromDurations.returns(260); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); @@ -631,7 +633,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -774,9 +776,10 @@ describe('generate', () => { $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), }, + hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { _id: 1 }, + { hourlyPaymentPlan: 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, @@ -890,6 +893,7 @@ describe('generate', () => { getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -906,7 +910,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -1027,7 +1031,28 @@ describe('generate', () => { ] ); sinon.assert.notCalled(findOneTrainingContract); - sinon.assert.notCalled(findBills); + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); sinon.assert.notCalled(updateManyBills); sinon.assert.notCalled(getPriceFromDurations); }); @@ -1133,6 +1158,7 @@ describe('generate', () => { getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1149,7 +1175,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -1297,7 +1323,28 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 330 } } ); sinon.assert.notCalled(getELearningDuration); - sinon.assert.notCalled(findBills); + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); sinon.assert.notCalled(updateManyBills); sinon.assert.notCalled(getPriceFromDurations); }); @@ -1408,6 +1455,7 @@ describe('generate', () => { getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1424,7 +1472,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -1572,7 +1620,28 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 0 } } ); sinon.assert.notCalled(getELearningDuration); - sinon.assert.notCalled(findBills); + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); sinon.assert.notCalled(updateManyBills); sinon.assert.notCalled(getPriceFromDurations); }); @@ -1680,6 +1749,7 @@ describe('generate', () => { getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1696,7 +1766,7 @@ describe('generate', () => { args: [[ { path: 'course', - select: 'subProgram slots companies trainees tradeName hourlyPaymentPlan', + select: 'subProgram slots companies trainees tradeName', populate: [ { path: 'slots', @@ -1843,7 +1913,28 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' } } } ); sinon.assert.notCalled(getELearningDuration); - sinon.assert.notCalled(findBills); + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate(month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(month, MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); sinon.assert.notCalled(updateManyBills); sinon.assert.notCalled(getPriceFromDurations); }); @@ -1871,95 +1962,79 @@ describe('create', () => { describe('deleteFile', () => { let findOne; - let findOneCourse; let find; let updateOne; let updateMany; let deleteCourseFile; - let getUnsubscribedAttendances; - let getTraineeDurations; - let getDurationPerStep; - let getPriceFromDurations; - let findBills; let updateManyBills; beforeEach(() => { findOne = sinon.stub(CompletionCertificate, 'findOne'); - findOneCourse = sinon.stub(Course, 'findOne'); find = sinon.stub(CompletionCertificate, 'find'); updateOne = sinon.stub(CompletionCertificate, 'updateOne'); updateMany = sinon.stub(CompletionCertificate, 'updateMany'); deleteCourseFile = sinon.stub(GCloudStorageHelper, 'deleteCourseFile'); - getUnsubscribedAttendances = sinon.stub(CoursesHelper, 'getUnsubscribedAttendances'); - getTraineeDurations = sinon.stub(CoursesHelper, 'getTraineeDurations'); - getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); - getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); - findBills = sinon.stub(CourseBill, 'find'); updateManyBills = sinon.stub(CourseBill, 'updateMany'); }); afterEach(() => { findOne.restore(); - findOneCourse.restore(); find.restore(); updateOne.restore(); updateMany.restore(); deleteCourseFile.restore(); - getUnsubscribedAttendances.restore(); - getTraineeDurations.restore(); - getDurationPerStep.restore(); - getPriceFromDurations.restore(); - findBills.restore(); updateManyBills.restore(); }); - it('should remove the file of a completion certificat', async () => { - const completionCertificateId = new ObjectId(); - const completionCertificate = { - _id: completionCertificateId, - trainee: { _id: new ObjectId() }, - course: { _id: new ObjectId() }, - month: '03-2025', - file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, - }; - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); - - await CompletionCertificatesHelper.deleteFile(completionCertificateId); - - SinonMongoose.calledOnceWithExactly( - findOne, - [ - { query: 'findOne', args: [{ _id: completionCertificateId }] }, + it('should remove the file of a completion certificat and the price of the bills with a hourly payment plan', + async () => { + const completionCertificateId = new ObjectId(); + const courseId = new ObjectId(); + const completionCertificate = { + _id: completionCertificateId, + trainee: new ObjectId(), + course: courseId, + month: '03-2025', + file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, + }; + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); + + await CompletionCertificatesHelper.deleteFile(completionCertificateId); + + SinonMongoose.calledOnceWithExactly( + findOne, + [{ query: 'findOne', args: [{ _id: completionCertificateId }] }, { query: 'lean' }] + ); + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: completionCertificateId }, + { $unset: { file: '', vaeSupportRemainingMinutes: '' } } + ); + sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); + sinon.assert.calledOnceWithExactly( + updateManyBills, { - query: 'populate', - args: [{ path: 'course', select: 'hourlyPaymentPlan' }], + course: courseId, + maturityDate: { + $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, }, - { query: 'lean' }, - ] - ); - sinon.assert.calledOnceWithExactly( - updateOne, - { _id: completionCertificateId }, - { $unset: { file: '', vaeSupportRemainingMinutes: '' } } - ); - sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); - sinon.assert.notCalled(find); - sinon.assert.notCalled(updateMany); - sinon.assert.notCalled(findOneCourse); - sinon.assert.notCalled(getUnsubscribedAttendances); - sinon.assert.notCalled(getTraineeDurations); - sinon.assert.notCalled(getDurationPerStep); - sinon.assert.notCalled(getPriceFromDurations); - sinon.assert.notCalled(findBills); - sinon.assert.notCalled(updateManyBills); - }); - - it('should remove the file of a completion certificat', async () => { + { $set: { 'mainFee.price': 0 } } + ); + sinon.assert.callOrder(deleteCourseFile, updateManyBills); + sinon.assert.notCalled(find); + sinon.assert.notCalled(updateMany); + }); + + it('should remove the file and the price of the bills of every certificate deleted in cascade (VAE)', async () => { const completionCertificateIds = [new ObjectId(), new ObjectId()]; const traineeId = new ObjectId(); const courseId = new ObjectId(); const completionCertificate = { _id: completionCertificateIds[0], trainee: traineeId, - course: { _id: courseId }, + course: courseId, month: '03-2025', file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, vaeSupportRemainingMinutes: 100, @@ -1972,23 +2047,15 @@ describe('deleteFile', () => { file: { publicId: 'completionCertificateTest_2', link: 'test/completionCertificateTest_2' }, vaeSupportRemainingMinutes: 0, }]; - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); find.returns(SinonMongoose.stubChainedQueries(completionCertificatesWithRemaingMinutes, ['setOptions', 'lean'])); await CompletionCertificatesHelper.deleteFile(completionCertificateIds[0]); SinonMongoose.calledOnceWithExactly( findOne, - [ - { query: 'findOne', args: [{ _id: completionCertificateIds[0] }] }, - { - query: 'populate', - args: [{ path: 'course', select: 'hourlyPaymentPlan' }], - }, - { query: 'lean' }, - ] + [{ query: 'findOne', args: [{ _id: completionCertificateIds[0] }] }, { query: 'lean' }] ); - SinonMongoose.calledOnceWithExactly( find, [ @@ -2004,121 +2071,34 @@ describe('deleteFile', () => { ); sinon.assert.calledWithExactly(deleteCourseFile.getCall(0), 'completionCertificateTest'); sinon.assert.calledWithExactly(deleteCourseFile.getCall(1), 'completionCertificateTest_2'); - sinon.assert.notCalled(updateOne); - sinon.assert.notCalled(findOneCourse); - sinon.assert.notCalled(getUnsubscribedAttendances); - sinon.assert.notCalled(getTraineeDurations); - sinon.assert.notCalled(getDurationPerStep); - sinon.assert.notCalled(getPriceFromDurations); - sinon.assert.notCalled(findBills); - sinon.assert.notCalled(updateManyBills); - }); - - it('should remove the real price of the bills and the file of a completion certificat', async () => { - const completionCertificateId = new ObjectId(); - const courseId = new ObjectId(); - const traineeId = new ObjectId(); - const stepId = new ObjectId(); - const hourlyPaymentPlanId = new ObjectId(); - const hourlyPaymentPlan = { _id: hourlyPaymentPlanId, prices: [{ step: stepId, hourlyAmount: 50 }] }; - const completionCertificate = { - _id: completionCertificateId, - month: '03-2025', - file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, - trainee: traineeId, - course: { _id: courseId, hourlyPaymentPlan: hourlyPaymentPlanId }, - }; - const course = { - _id: courseId, - slots: [], - hourlyPaymentPlan: hourlyPaymentPlanId, - subProgram: { _id: new ObjectId(), steps: [], hourlyPaymentPlans: [hourlyPaymentPlan] }, - }; - const billId = new ObjectId(); - const eLearningDuration = CompaniDuration('PT3600S'); - const durationPerStep = { [stepId]: CompaniDuration('PT7200S') }; - - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['populate', 'lean'])); - getUnsubscribedAttendances.returns([]); - findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); - getTraineeDurations.returns({ slotsWithAttendance: [], eLearningDuration }); - getDurationPerStep.returns(durationPerStep); - getPriceFromDurations.returns(150); - findBills.returns(SinonMongoose.stubChainedQueries([{ _id: billId }], ['setOptions', 'lean'])); - - await CompletionCertificatesHelper.deleteFile(completionCertificateId); - - sinon.assert.calledOnceWithExactly(getPriceFromDurations, hourlyPaymentPlan, durationPerStep, eLearningDuration); - sinon.assert.calledOnceWithExactly(updateManyBills, { _id: { $in: [billId] } }, { $set: { 'mainFee.price': 0 } }); - sinon.assert.calledOnceWithExactly( - updateOne, - { _id: completionCertificateId }, - { $unset: { file: '', vaeSupportRemainingMinutes: '' } } - ); - sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); - sinon.assert.callOrder(deleteCourseFile, updateManyBills); - }); - - it('should remove the real price of the bills of every certificate deleted in cascade (VAE)', async () => { - const courseId = new ObjectId(); - const traineeId = new ObjectId(); - const stepId = new ObjectId(); - const hourlyPaymentPlan = { _id: new ObjectId(), prices: [{ step: stepId, hourlyAmount: 50 }] }; - const completionCertificates = [ - { - _id: new ObjectId(), - month: '03-2025', - trainee: traineeId, - course: { _id: courseId, hourlyPaymentPlan: hourlyPaymentPlan._id }, - file: { publicId: 'certif_03', link: 'test/certif_03' }, - vaeSupportRemainingMinutes: 100, - }, - { - _id: new ObjectId(), - month: '04-2025', - trainee: traineeId, - course: courseId, - file: { publicId: 'certif_04', link: 'test/certif_04' }, - vaeSupportRemainingMinutes: 0, - }, - ]; - const course = { - _id: courseId, - slots: [], - hourlyPaymentPlan: hourlyPaymentPlan._id, - subProgram: { _id: new ObjectId(), steps: [], hourlyPaymentPlans: [hourlyPaymentPlan] }, - }; - const bills = [{ _id: new ObjectId() }, { _id: new ObjectId() }]; - const eLearningDuration = CompaniDuration('PT3600S'); - const durationPerStep = { [stepId]: CompaniDuration('PT7200S') }; - - findOne.returns(SinonMongoose.stubChainedQueries(completionCertificates[0], ['populate', 'lean'])); - find.returns(SinonMongoose.stubChainedQueries([completionCertificates[1]], ['setOptions', 'lean'])); - findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); - getUnsubscribedAttendances.returns([]); - getTraineeDurations.returns({ slotsWithAttendance: [], eLearningDuration }); - getDurationPerStep.returns(durationPerStep); - getPriceFromDurations.onFirstCall().returns(150); - getPriceFromDurations.onSecondCall().returns(90); - findBills.onFirstCall().returns(SinonMongoose.stubChainedQueries([bills[0]], ['setOptions', 'lean'])); - findBills.onSecondCall().returns(SinonMongoose.stubChainedQueries([bills[1]], ['setOptions', 'lean'])); - - await CompletionCertificatesHelper.deleteFile(completionCertificates[0]._id); - - sinon.assert.calledTwice(getPriceFromDurations); - sinon.assert.calledTwice(findBills); sinon.assert.calledTwice(updateManyBills); sinon.assert.calledWithExactly( updateManyBills.getCall(0), - { _id: { $in: [bills[0]._id] } }, + { + course: courseId, + maturityDate: { + $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, { $set: { 'mainFee.price': 0 } } ); sinon.assert.calledWithExactly( updateManyBills.getCall(1), - { _id: { $in: [bills[1]._id] } }, + { + course: courseId, + maturityDate: { + $gte: CompaniDate('04-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('04-2025', MM_YYYY).endOf(MONTH).toISO(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, { $set: { 'mainFee.price': 0 } } ); - sinon.assert.calledTwice(deleteCourseFile); sinon.assert.callOrder(deleteCourseFile, updateManyBills); + sinon.assert.notCalled(updateOne); }); }); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index 3bce99d9e6..b8a43dbd86 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -1224,7 +1224,6 @@ describe('computePriceFromDurations', () => { describe('createBillList', () => { let findOneCourse; - let updateOneCourse; let computePriceFromDurations; let createCourseBill; let insertManyCourseBills; @@ -1234,7 +1233,6 @@ describe('createBillList', () => { beforeEach(() => { findOneCourse = sinon.stub(Course, 'findOne'); - updateOneCourse = sinon.stub(Course, 'updateOne'); computePriceFromDurations = sinon.stub(CourseBillHelper, 'computePriceFromDurations'); createCourseBill = sinon.stub(CourseBill, 'create'); insertManyCourseBills = sinon.stub(CourseBill, 'insertMany'); @@ -1245,7 +1243,6 @@ describe('createBillList', () => { afterEach(() => { findOneCourse.restore(); - updateOneCourse.restore(); computePriceFromDurations.restore(); createCourseBill.restore(); insertManyCourseBills.restore(); @@ -1279,11 +1276,6 @@ describe('createBillList', () => { await CourseBillHelper.createBillList(payload); sinon.assert.calledOnceWithExactly(computePriceFromDurations, payload.course, payload.hourlyPaymentPlanId); - sinon.assert.calledOnceWithExactly( - updateOneCourse, - { _id: payload.course }, - { $set: { hourlyPaymentPlan: payload.hourlyPaymentPlanId } } - ); sinon.assert.calledOnceWithExactly( createCourseBill, @@ -1295,6 +1287,7 @@ describe('createBillList', () => { countUnit: GROUP, description: 'test', }, + hourlyPaymentPlan: payload.hourlyPaymentPlanId, companies: payload.companies, payer: payload.payer, maturityDate: payload.maturityDate, @@ -1526,6 +1519,7 @@ describe('createBillList', () => { companies: [companyId], payer: { fundingOrganisation: payerId }, maturityDate: '2025-04-29T22:00:00.000Z', + hourlyPaymentPlanId: new ObjectId(), }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); @@ -1545,7 +1539,6 @@ describe('createBillList', () => { trainees: 1, trainers: 1, subProgram: 1, - hourlyPaymentPlan: 1, certificateGenerationMode: 1, }, ], @@ -1569,6 +1562,7 @@ describe('createBillList', () => { + 'Nom de l\'apprenant·e: Sarah PEL \r\n' + 'Nom du / des intervenants: toto TEST', }, + hourlyPaymentPlan: payload.hourlyPaymentPlanId, companies: [companyId], payer: { fundingOrganisation: payerId }, maturityDate: '2025-04-29T22:00:00.000Z', @@ -1587,6 +1581,7 @@ describe('createBillList', () => { + 'Nom de l\'apprenant·e: Sarah PEL \r\n' + 'Nom du / des intervenants: toto TEST', }, + hourlyPaymentPlan: payload.hourlyPaymentPlanId, companies: [companyId], payer: { fundingOrganisation: payerId }, maturityDate: '2025-05-29T22:00:00.000Z', @@ -1633,7 +1628,6 @@ describe('createBillList', () => { trainees: 1, trainers: 1, subProgram: 1, - hourlyPaymentPlan: 1, certificateGenerationMode: 1, }, ], From 42d94b90eaf77b062ce820ff4e3ee434375a66dc Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 3 Nov 2026 17:21:22 +0100 Subject: [PATCH 28/53] COM-4324: can create single bill --- src/helpers/courseBills.js | 9 +-------- src/helpers/translate.js | 2 +- src/routes/preHandlers/courseBills.js | 5 +++-- tests/integration/courseBills.test.js | 23 +++++++++++++++++++++++ 4 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 62175b3db0..f9f108ee05 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -356,14 +356,7 @@ exports.createBillList = async (payload) => { const course = await Course .findOne( { _id: payload.course }, - { - type: 1, - prices: 1, - trainees: 1, - trainers: 1, - subProgram: 1, - certificateGenerationMode: 1, - } + { type: 1, prices: 1, trainees: 1, trainers: 1, subProgram: 1, certificateGenerationMode: 1 } ) .populate({ path: 'trainees', select: 'identity' }) .populate({ path: 'trainers', select: 'identity' }) diff --git a/src/helpers/translate.js b/src/helpers/translate.js index c1214b5f5d..37a4ed9b9f 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -492,7 +492,7 @@ module.exports = { paidSlotsBeforeSubProgramEffectiveDate: 'Impossible: un créneau est noté réglé après la date d\'effet renseignée.', subProgramPaymentPlanNotFound: 'Cet échéancier n\'existe pas.', subProgramHourlyPaymentPlanNotFound: 'Cette tarification n\'existe pas.', - subProgramHourlyPaymentPlanUsed: 'Impossible : cette tarification est utilisée par une formation.', + 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.', subProgramHasPaymentPlan: 'Impossible : ce sous-programme a déjà des échéanciers.', diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 1f6cd45d2e..5fda62de1d 100644 --- a/src/routes/preHandlers/courseBills.js +++ b/src/routes/preHandlers/courseBills.js @@ -59,9 +59,10 @@ exports.authorizeCourseBillListCreation = async (req) => { } } + if (quantity === 1 && !mainFee.price && !hourlyPaymentPlanId) throw Boom.badRequest(); + if (hourlyPaymentPlanId && mainFee.price) throw Boom.badRequest(); + const shouldComputePriceFromDuration = hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; - if (quantity === 1 && !mainFee.price && !shouldComputePriceFromDuration) throw Boom.badRequest(); - if (shouldComputePriceFromDuration && mainFee.price) throw Boom.badRequest(); if (shouldComputePriceFromDuration) { if (quantity !== 1) throw Boom.badRequest(); diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index f43dc38ebc..addd6d5d22 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -539,6 +539,29 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(billsCountAfter).toBe(billsCountBefore + 1); }); + it('should create a bill without price when an hourly payment plan is sent (MONTHLY)', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { + ...singleCoursePayload, + course: coursesList[17]._id, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, + }); + + expect(response.statusCode).toBe(200); + + const billsWithPlanAndWithoutPriceCount = await CourseBill.countDocuments({ + course: coursesList[17]._id, + hourlyPaymentPlan: hourlyPaymentPlanId, + 'mainFee.price': { $exists: false }, + }); + expect(billsWithPlanAndWithoutPriceCount).toBe(1); + }); + it('should return 403 if payload has percentage but some companies have no price', async () => { const response = await app.inject({ method: 'POST', From 3e08da146481192f9367570cad1f1848717a0ebf Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 4 Nov 2026 12:12:11 +0100 Subject: [PATCH 29/53] COM-4324: select fields for bills --- src/helpers/courses.js | 6 +++++- tests/unit/helpers/courses.test.js | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 7dc69a4514..b8b2f855c7 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -645,7 +645,11 @@ const getCourseForOperations = async (courseId, credentials, origin) => { ...(isRofOrAdmin ? [ { path: 'trainerMissions', select: '_id trainer', options: { isVendorUser: true } }, - { path: 'bills', select: '_id companies', options: { isVendorUser: true } }, + { + path: 'bills', + select: '_id companies hourlyPaymentPlan maturityDate', + options: { isVendorUser: true }, + }, ] : []), ] diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index bfccb955d6..cfa023da14 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -2936,7 +2936,11 @@ describe('getCourse', () => { { path: 'contact', select: 'identity.firstname identity.lastname contact' }, { path: 'questionnaires' }, { path: 'trainerMissions', select: '_id trainer', options: { isVendorUser: true } }, - { path: 'bills', select: '_id companies', options: { isVendorUser: true } }, + { + path: 'bills', + select: '_id companies hourlyPaymentPlan maturityDate', + options: { isVendorUser: true }, + }, ]], }, { query: 'lean' }, From c6aa84c13ca6adc8496e7b33e3972c5fb518e1f0 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Thu, 5 Nov 2026 09:48:36 +0100 Subject: [PATCH 30/53] COM-4321 - fix reviews --- src/helpers/courses.js | 2 +- tests/integration/courses.test.js | 14 +++++++------- tests/unit/helpers/courses.test.js | 4 +--- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 176a9a4af7..ca106e49a8 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2402,7 +2402,7 @@ exports.listTrainersBilling = async (query) => { const trainerCourses = []; for (const course of filteredTrainerCourses) { - const plannedSalary = trainerSalaryByCourse[course._id] + const plannedSalary = has(trainerSalaryByCourse, course._id) ? trainerSalaryByCourse[course._id] : exports.getCourseTrainerSalaryFromSlots(course, trainer._id, courseSlotsByCourse[course._id] || []); const courseBills = billsByTrainerAndCourse[`${trainer._id}-${course._id}`] || []; diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 70037dbff5..c3a1c3f9bb 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10113,7 +10113,6 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { const { trainers } = response.result.data; expect(trainers.length).toBe(2); expect(trainers.every(t => t.courses.every(c => c.type !== SINGLE))).toBeTruthy(); - expect(trainers.some(t => t.courses.some(c => c.status === 'invoiced'))).toBeTruthy(); }); it('should return a specific trainer with its collective courses and billing infos', async () => { @@ -10124,22 +10123,23 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { }); expect(response.statusCode).toBe(200); - expect(response.result.data.trainers.length).toBe(1); - expect(response.result.data.trainers[0].courses.length).toEqual(15); + const { trainers } = response.result.data; + expect(trainers.length).toEqual(1); + expect(trainers[0].courses.length).toEqual(15); }); - it('should return trainer\'s courses with slots in period', async () => { + it('should return all trainer\'s courses with slots in period', async () => { const startDate = '2020-03-01T00:00:00.000Z'; const endDate = '2020-03-05T23:59:59.999Z'; const response = await app.inject({ method: 'GET', - url: `/courses/trainers-billing?trainer=${trainer._id}&startDate=${startDate}&endDate=${endDate}`, + url: `/courses/trainers-billing?startDate=${startDate}&endDate=${endDate}`, headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, }); expect(response.statusCode).toBe(200); - const { courses } = response.result.data.trainers[0]; - expect(courses.length).toBe(2); + expect(response.result.data.trainers.length).toEqual(1); + expect(response.result.data.trainers[0].courses.length).toEqual(5); }); it('should return 400 if endDate without startDate', async () => { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index d6f45604a4..5e37bf6251 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11390,7 +11390,6 @@ describe('getCourseTrainerSalaryFromSlots', () => { const result = CourseHelper.getCourseTrainerSalaryFromSlots(course, trainerId, courseSlots); expect(result).toEqual(170); - sinon.assert.calledTwice(getHourlyAmount); sinon.assert.calledWithExactly( getHourlyAmount.getCall(0), { step: { _id: stepId }, startDate: course.createdAt, course }, @@ -11492,7 +11491,6 @@ describe('listTrainersBilling', () => { ); sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(1), courses[1], trainerId, []); sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(2), courses[2], trainerId, [courseSlots[2]]); - sinon.assert.calledThrice(getCourseTrainerSalaryFromSlots); SinonMongoose.calledOnceWithExactly( trainerBillFind, [ @@ -11522,7 +11520,7 @@ describe('listTrainersBilling', () => { ); }); - it('should not get slots if all courses have a trainer salary billing purchase', async () => { + it('should return trainer salary from course billing purchase', async () => { const trainerId = new ObjectId(); const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; const courses = [{ From 098565688378bbc9893d1f3ad209416dd8a67e98 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Fri, 6 Nov 2026 16:46:15 +0100 Subject: [PATCH 31/53] COM-4321 - fix plannedSalary calculate --- .github/workflows/integration.js.yml | 2 + src/helpers/courses.js | 80 ++----- tests/integration/courses.test.js | 6 +- tests/unit/helpers/courses.test.js | 321 ++++++++++----------------- 4 files changed, 146 insertions(+), 263 deletions(-) diff --git a/.github/workflows/integration.js.yml b/.github/workflows/integration.js.yml index df32c5271f..ff49e03b01 100644 --- a/.github/workflows/integration.js.yml +++ b/.github/workflows/integration.js.yml @@ -41,3 +41,5 @@ jobs: MAX_CSV_COURSE_SIZE: ${{ secrets.MAX_CSV_COURSE_SIZE }} ALENVI_TOKEN: ${{ secrets.ALENVI_TOKEN }} REFRESH_TOKEN: ${{ secrets.REFRESH_TOKEN }} + CONSULTING_PROGRAM_IDS: ${{ secrets.CONSULTING_PROGRAM_IDS }} + CONSULTING_BILLING_ITEM: ${{ secrets.CONSULTING_BILLING_ITEM }} diff --git a/src/helpers/courses.js b/src/helpers/courses.js index ca106e49a8..126fa4ea64 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -34,7 +34,6 @@ const DatesUtilsHelper = require('./dates/utils'); const ZipHelper = require('./zip'); const SmsHelper = require('./sms'); const CourseBillsHelper = require('./courseBills'); -const CourseSlotsHelper = require('./courseSlots'); const CourseCreditNotesHelper = require('./courseCreditNotes'); const DocxHelper = require('./docx'); const FileHelper = require('./file'); @@ -90,7 +89,6 @@ const { SECOND, MONTH, TRAINER_SALARY, - MINUTE, PARTIALLY_INVOICED, NOT_INVOICED, INVOICED, @@ -2312,23 +2310,20 @@ exports.deleteBillingPurchase = async (courseId, billingPurchaseId) => Course.up { $pull: { billingPurchaseList: { _id: billingPurchaseId } } } ); -exports.getCourseTrainerSalaryFromSlots = (course, trainerId, courseSlots) => { - const slots = courseSlots.filter(slot => UtilsHelper.doesArrayIncludeId(slot.trainers, trainerId)); +exports.getCourseTrainerSalary = (course) => { + if (course.trainers.length !== 1) return undefined; - const salary = slots.reduce((acc, slot) => { - const hourlyAmount = CourseSlotsHelper - .getHourlyAmount({ step: { _id: slot.step }, startDate: course.createdAt, course }, trainerId); - if (!hourlyAmount) return acc; - - const duration = CompaniDate(slot.endDate).diff(slot.startDate, MINUTE); - const slotAmount = NumbersHelper.toFixedToFloat( - NumbersHelper.multiply(hourlyAmount, CompaniDuration(duration).asHours()) - ); - - return NumbersHelper.add(acc, slotAmount); - }, 0); + const billingPurchaseList = course.billingPurchaseList || []; + let salary = billingPurchaseList.find(item => item.billingItem?.type === TRAINER_SALARY); + if (!salary) { + const CONSULTING_PROGRAM_IDS = (process.env.CONSULTING_PROGRAM_IDS || '').split(','); + if (UtilsHelper.doesArrayIncludeId(CONSULTING_PROGRAM_IDS, get(course, 'subProgram.program._id'))) { + salary = billingPurchaseList + .find(item => UtilsHelper.areObjectIdsEquals(item.billingItem?._id, process.env.CONSULTING_BILLING_ITEM)); + } + } - return NumbersHelper.toNumber(salary); + return salary ? NumbersHelper.toNumber(NumbersHelper.multiply(salary.price, salary.count)) : undefined; }; exports.listTrainersBilling = async (query) => { @@ -2347,49 +2342,24 @@ exports.listTrainersBilling = async (query) => { ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), type: { $nin: [SINGLE, INTER_B2C] }, }, - { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } ) .populate({ path: 'companies', select: 'name' }) - .populate({ - path: 'subProgram', - select: 'program trainerPriceVersions', - populate: { path: 'program', select: 'name' }, - }) + .populate({ path: 'subProgram', select: 'program', populate: { path: 'program', select: 'name' } }) .populate({ path: 'trainers', select: 'identity' }) .populate({ path: 'billingPurchaseList.billingItem', select: 'type' }) .sort({ createdAt: -1 }) .lean(); if (!courses.length) return []; - const trainerSalaryByCourse = {}; - const courseIdsWithoutTrainerSalary = []; - for (const course of courses) { - const salaryItem = course.trainers.length === 1 && - (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); - if (salaryItem) { - trainerSalaryByCourse[course._id] = NumbersHelper - .toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)); - } else courseIdsWithoutTrainerSalary.push(course._id); - } - const [trainerBills, courseSlots] = await Promise.all([ - TrainerBill - .find( - { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, - { course: 1, amount: 1, trainer: 1 } - ) - .populate({ path: 'payment', select: 'status' }) - .lean(), - courseIdsWithoutTrainerSalary.length - ? CourseSlot - .find( - { course: { $in: courseIdsWithoutTrainerSalary }, ...(query.trainer && { trainers: query.trainer }) }, - { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 } - ) - .lean() - : [], - ]); + const trainerBills = await TrainerBill + .find( + { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, + { course: 1, amount: 1, trainer: 1 } + ) + .populate({ path: 'payment', select: 'status' }) + .lean(); const billsByTrainerAndCourse = groupBy(trainerBills, bill => `${bill.trainer}-${bill.course}`); - const courseSlotsByCourse = groupBy(courseSlots, slot => slot.course); const trainers = query.trainer ? [courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer))] @@ -2402,9 +2372,7 @@ exports.listTrainersBilling = async (query) => { const trainerCourses = []; for (const course of filteredTrainerCourses) { - const plannedSalary = has(trainerSalaryByCourse, course._id) - ? trainerSalaryByCourse[course._id] - : exports.getCourseTrainerSalaryFromSlots(course, trainer._id, courseSlotsByCourse[course._id] || []); + const plannedSalary = exports.getCourseTrainerSalary(course); const courseBills = billsByTrainerAndCourse[`${trainer._id}-${course._id}`] || []; let invoicedAmount = 0; let paidAmount = 0; @@ -2421,8 +2389,8 @@ exports.listTrainersBilling = async (query) => { else if (invoicedAmount === paidAmount) status = PAID; trainerCourses.push({ - ...omit(course, ['billingPurchaseList', 'rolesPerTrainer']), - plannedSalary, + ...omit(course, ['billingPurchaseList']), + ...(plannedSalary !== undefined && { plannedSalary }), invoicedAmount, paidAmount, status, diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index c3a1c3f9bb..1e236e07be 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10138,8 +10138,10 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { }); expect(response.statusCode).toBe(200); - expect(response.result.data.trainers.length).toEqual(1); - expect(response.result.data.trainers[0].courses.length).toEqual(5); + const { trainers } = response.result.data; + expect(trainers.length).toEqual(2); + expect(trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainer._id)).courses.length).toEqual(2); + expect(trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainerAndCoach._id)).courses.length).toEqual(4); }); it('should return 400 if endDate without startDate', async () => { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 5e37bf6251..0d333fdeba 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -26,7 +26,6 @@ const TrainingContract = require('../../../src/models/TrainingContract'); const CompanyHelper = require('../../../src/helpers/companies'); const CourseHelper = require('../../../src/helpers/courses'); const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); -const CourseSlotsHelper = require('../../../src/helpers/courseSlots'); const CourseBillHelper = require('../../../src/helpers/courseBills'); const CourseCreditNoteHelper = require('../../../src/helpers/courseCreditNotes'); const EmailHelper = require('../../../src/helpers/email'); @@ -11330,76 +11329,72 @@ describe('getTraineeDurations', () => { }); }); -describe('getCourseTrainerSalaryFromSlots', () => { - let getHourlyAmount; +describe('getCourseTrainerSalary', () => { + const consultingProgramId = new ObjectId(); + const consultingBillingItemId = new ObjectId(); + const trainerSalaryItem = { billingItem: { _id: new ObjectId(), type: TRAINER_SALARY }, price: 40, count: 2 }; + const consultingItem = { billingItem: { _id: consultingBillingItemId, type: 'other' }, price: 300, count: 1 }; beforeEach(() => { - getHourlyAmount = sinon.stub(CourseSlotsHelper, 'getHourlyAmount'); + process.env.CONSULTING_PROGRAM_IDS = `${new ObjectId()},${consultingProgramId}`; + process.env.CONSULTING_BILLING_ITEM = consultingBillingItemId.toHexString(); }); afterEach(() => { - getHourlyAmount.restore(); + process.env.CONSULTING_PROGRAM_IDS = ''; + process.env.CONSULTING_BILLING_ITEM = ''; }); - it('should return 0 if no slot', () => { - const trainerId = new ObjectId(); + it('should return undefined if course has several trainers', () => { + const course = { trainers: [{ _id: new ObjectId() }, { _id: new ObjectId() }] }; + + const result = CourseHelper.getCourseTrainerSalary(course); + + expect(result).toBeUndefined(); + }); + + it('should return trainer salary from course billingPurchaseList', () => { const course = { - _id: new ObjectId(), - trainers: [trainerId], - createdAt: '2024-01-01T00:00:00.000Z', + trainers: [{ _id: new ObjectId() }], + subProgram: { program: { _id: new ObjectId() } }, + billingPurchaseList: [trainerSalaryItem], }; - const result = CourseHelper.getCourseTrainerSalaryFromSlots(course, trainerId, []); + const result = CourseHelper.getCourseTrainerSalary(course); - expect(result).toEqual(0); - sinon.assert.notCalled(getHourlyAmount); + expect(result).toEqual(80); }); - it('should compute salary from trainer slots', () => { - const trainerId = new ObjectId(); - const otherTrainerId = new ObjectId(); - const stepId = new ObjectId(); + it('should return consulting billing item if no trainer salary and program is consulting', () => { const course = { - _id: new ObjectId(), - trainers: [trainerId, otherTrainerId], - createdAt: '2024-01-01T00:00:00.000Z', + trainers: [{ _id: new ObjectId() }], + subProgram: { program: { _id: consultingProgramId } }, + billingPurchaseList: [consultingItem], }; - const courseSlots = [ - { - step: stepId, - trainers: [trainerId], - startDate: new Date('2024-02-01T08:00:00.000Z'), - endDate: new Date('2024-02-01T10:00:00.000Z'), - }, - { - step: stepId, - trainers: [otherTrainerId], - startDate: new Date('2024-02-01T14:00:00.000Z'), - endDate: new Date('2024-02-01T16:00:00.000Z'), - }, - { - step: stepId, - trainers: [trainerId, otherTrainerId], - startDate: new Date('2024-02-02T08:00:00.000Z'), - endDate: new Date('2024-02-02T09:30:00.000Z'), - }, - ]; - getHourlyAmount.onCall(0).returns(40); - getHourlyAmount.onCall(1).returns(60); - const result = CourseHelper.getCourseTrainerSalaryFromSlots(course, trainerId, courseSlots); + const result = CourseHelper.getCourseTrainerSalary(course); - expect(result).toEqual(170); - sinon.assert.calledWithExactly( - getHourlyAmount.getCall(0), - { step: { _id: stepId }, startDate: course.createdAt, course }, - trainerId - ); - sinon.assert.calledWithExactly( - getHourlyAmount.getCall(1), - { step: { _id: stepId }, startDate: course.createdAt, course }, - trainerId - ); + expect(result).toEqual(300); + }); + + it('should return undefined if no trainer salary and program is not consulting', () => { + const course = { + trainers: [{ _id: new ObjectId() }], + subProgram: { program: { _id: new ObjectId() } }, + billingPurchaseList: [consultingItem], + }; + + const result = CourseHelper.getCourseTrainerSalary(course); + + expect(result).toBeUndefined(); + }); + + it('should return undefined if no billing purchase list', () => { + const course = { trainers: [{ _id: new ObjectId() }], subProgram: { program: { _id: consultingProgramId } } }; + + const result = CourseHelper.getCourseTrainerSalary(course); + + expect(result).toBeUndefined(); }); }); @@ -11407,20 +11402,17 @@ describe('listTrainersBilling', () => { let courseFind; let trainerBillFind; let courseSlotFind; - let getCourseTrainerSalaryFromSlots; beforeEach(() => { courseFind = sinon.stub(Course, 'find'); trainerBillFind = sinon.stub(TrainerBill, 'find'); courseSlotFind = sinon.stub(CourseSlot, 'find'); - getCourseTrainerSalaryFromSlots = sinon.stub(CourseHelper, 'getCourseTrainerSalaryFromSlots'); }); afterEach(() => { courseFind.restore(); trainerBillFind.restore(); courseSlotFind.restore(); - getCourseTrainerSalaryFromSlots.restore(); }); it('should return an empty array if no course found', async () => { @@ -11432,21 +11424,30 @@ describe('listTrainersBilling', () => { expect(result).toEqual([]); sinon.assert.notCalled(trainerBillFind); sinon.assert.notCalled(courseSlotFind); - sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); }); it('should return trainer with its courses and billing status', async () => { const trainerId = new ObjectId(); const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; const courses = [ - { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, - { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog' }, { _id: new ObjectId(), trainers: [trainer], tradeName: 'prog', - billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 40, count: 2 }], + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 2 }], + }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 100, count: 1 }], + }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 2 }], }, ]; const trainerBills = [ @@ -11457,23 +11458,28 @@ describe('listTrainersBilling', () => { ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - getCourseTrainerSalaryFromSlots.returns(100); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); - const courseSlots = [ - { course: courses[0]._id, trainers: [trainerId] }, - { course: courses[0]._id, trainers: [trainerId] }, - { course: courses[2]._id, trainers: [trainerId] }, - ]; - courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); expect(result).toEqual([{ ...trainer, courses: [ - { ...courses[0], plannedSalary: 100, invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, - { ...courses[1], plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced' }, - { ...courses[2], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, + { ...courses[0], invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, + { + ...omit(courses[1], ['billingPurchaseList']), + plannedSalary: 80, + invoicedAmount: 40, + paidAmount: 0, + status: 'partially_invoiced', + }, + { + ...omit(courses[2], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 100, + paidAmount: 0, + status: 'invoiced', + }, { ...omit(courses[3], ['billingPurchaseList']), plannedSalary: 80, @@ -11483,69 +11489,41 @@ describe('listTrainersBilling', () => { }, ], }]); - sinon.assert.calledWithExactly( - getCourseTrainerSalaryFromSlots.getCall(0), - courses[0], - trainerId, - [courseSlots[0], courseSlots[1]] - ); - sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(1), courses[1], trainerId, []); - sinon.assert.calledWithExactly(getCourseTrainerSalaryFromSlots.getCall(2), courses[2], trainerId, [courseSlots[2]]); SinonMongoose.calledOnceWithExactly( - trainerBillFind, + courseFind, [ { query: 'find', args: [ - { course: { $in: courses.map(c => c._id) }, trainer: trainerId }, - { course: 1, amount: 1, trainer: 1 }, + { trainers: trainerId, type: { $nin: ['single', 'inter_b2c'] } }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, ], }, - { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, + { + query: 'populate', + args: [{ path: 'subProgram', select: 'program', populate: { path: 'program', select: 'name' } }], + }, + { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, + { query: 'populate', args: [{ path: 'billingPurchaseList.billingItem', select: 'type' }] }, + { query: 'sort', args: [{ createdAt: -1 }] }, { query: 'lean' }, ] ); SinonMongoose.calledOnceWithExactly( - courseSlotFind, + trainerBillFind, [ { query: 'find', args: [ - { course: { $in: [courses[0]._id, courses[1]._id, courses[2]._id] }, trainers: trainerId }, - { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, + { course: { $in: courses.map(c => c._id) }, trainer: trainerId }, + { course: 1, amount: 1, trainer: 1 }, ], }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, { query: 'lean' }, ] ); - }); - - it('should return trainer salary from course billing purchase', async () => { - const trainerId = new ObjectId(); - const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; - const courses = [{ - _id: new ObjectId(), - trainers: [trainer], - tradeName: 'prog', - billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 60, count: 2 }], - }]; - - courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - trainerBillFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); - - const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); - - expect(result).toEqual([{ - ...trainer, - courses: [{ - ...omit(courses[0], ['billingPurchaseList']), - plannedSalary: 120, - invoicedAmount: 0, - paidAmount: 0, - status: 'not_invoiced', - }], - }]); - sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); sinon.assert.notCalled(courseSlotFind); }); @@ -11577,11 +11555,9 @@ describe('listTrainersBilling', () => { }, ]; - courseSlotFind.onCall(0).returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); - courseSlotFind.onCall(1).returns(SinonMongoose.stubChainedQueries([courseSlotsInPeriod[1]], ['lean'])); - getCourseTrainerSalaryFromSlots.returns(50); const result = await CourseHelper.listTrainersBilling(query); @@ -11595,16 +11571,10 @@ describe('listTrainersBilling', () => { paidAmount: 0, status: 'not_invoiced', }, - { ...courses[1], plannedSalary: 50, invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, + { ...courses[1], invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, ], }]); - sinon.assert.calledOnceWithExactly( - getCourseTrainerSalaryFromSlots, - courses[1], - trainerId, - [courseSlotsInPeriod[1]] - ); - SinonMongoose.calledWithExactly( + SinonMongoose.calledOnceWithExactly( courseSlotFind, [ { @@ -11615,22 +11585,7 @@ describe('listTrainersBilling', () => { ], }, { query: 'lean' }, - ], - 0 - ); - SinonMongoose.calledWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [ - { course: { $in: [courses[1]._id] }, trainers: trainerId }, - { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, - ], - }, - { query: 'lean' }, - ], - 1 + ] ); SinonMongoose.calledOnceWithExactly( courseFind, @@ -11643,17 +11598,13 @@ describe('listTrainersBilling', () => { trainers: trainerId, type: { $nin: ['single', 'inter_b2c'] }, }, - { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, ], }, { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, { query: 'populate', - args: [{ - path: 'subProgram', - select: 'program trainerPriceVersions', - populate: { path: 'program', select: 'name' }, - }], + args: [{ path: 'subProgram', select: 'program', populate: { path: 'program', select: 'name' } }], }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, { query: 'populate', args: [{ path: 'billingPurchaseList.billingItem', select: 'type' }] }, @@ -11663,7 +11614,7 @@ describe('listTrainersBilling', () => { ); }); - it('should return all trainers with their courses and billing status if no trainer in query', async () => { + it('should return all trainers without planned salary for courses with several trainers', async () => { const firstTrainerId = new ObjectId(); const secondTrainerId = new ObjectId(); const firstTrainer = { _id: firstTrainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; @@ -11673,23 +11624,23 @@ describe('listTrainersBilling', () => { _id: new ObjectId(), trainers: [firstTrainer, secondTrainer], tradeName: 'prog', - billingPurchaseList: [{ billingItem: { type: 'trainer_salary' }, price: 40, count: 2 }], + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 2 }], + }, + { + _id: new ObjectId(), + trainers: [secondTrainer], + tradeName: 'prog', + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 100, count: 1 }], }, - { _id: new ObjectId(), trainers: [secondTrainer], tradeName: 'prog' }, ]; - courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - getCourseTrainerSalaryFromSlots.returns(100); const trainerBills = [ { course: courses[0]._id, trainer: firstTrainerId, amount: 100, payment: { status: 'paid' } }, { course: courses[0]._id, trainer: secondTrainerId, amount: 40, payment: { status: 'pending' } }, { course: courses[1]._id, trainer: secondTrainerId, amount: 100, payment: { status: 'pending' } }, ]; + + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); - const courseSlots = [ - { course: courses[0]._id, trainers: [firstTrainerId, secondTrainerId] }, - { course: courses[1]._id, trainers: [secondTrainerId] }, - ]; - courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); const result = await CourseHelper.listTrainersBilling({}); @@ -11697,47 +11648,23 @@ describe('listTrainersBilling', () => { { ...firstTrainer, courses: [ - { - ...omit(courses[0], ['billingPurchaseList']), - plannedSalary: 100, - invoicedAmount: 100, - paidAmount: 100, - status: 'paid', - }, + { ...omit(courses[0], ['billingPurchaseList']), invoicedAmount: 100, paidAmount: 100, status: 'paid' }, ], }, { ...secondTrainer, courses: [ + { ...omit(courses[0], ['billingPurchaseList']), invoicedAmount: 40, paidAmount: 0, status: 'invoiced' }, { - ...omit(courses[0], ['billingPurchaseList']), + ...omit(courses[1], ['billingPurchaseList']), plannedSalary: 100, - invoicedAmount: 40, + invoicedAmount: 100, paidAmount: 0, - status: 'partially_invoiced', + status: 'invoiced', }, - { ...courses[1], plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced' }, ], }, ]); - sinon.assert.calledWithExactly( - getCourseTrainerSalaryFromSlots.getCall(0), - courses[0], - firstTrainerId, - [courseSlots[0]] - ); - sinon.assert.calledWithExactly( - getCourseTrainerSalaryFromSlots.getCall(1), - courses[0], - secondTrainerId, - [courseSlots[0]] - ); - sinon.assert.calledWithExactly( - getCourseTrainerSalaryFromSlots.getCall(2), - courses[1], - secondTrainerId, - [courseSlots[1]] - ); SinonMongoose.calledOnceWithExactly( courseFind, [ @@ -11745,17 +11672,13 @@ describe('listTrainersBilling', () => { query: 'find', args: [ { 'trainers.0': { $exists: true }, type: { $nin: ['single', 'inter_b2c'] } }, - { trainers: 1, rolesPerTrainer: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, ], }, { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, { query: 'populate', - args: [{ - path: 'subProgram', - select: 'program trainerPriceVersions', - populate: { path: 'program', select: 'name' }, - }], + args: [{ path: 'subProgram', select: 'program', populate: { path: 'program', select: 'name' } }], }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, { query: 'populate', args: [{ path: 'billingPurchaseList.billingItem', select: 'type' }] }, @@ -11771,18 +11694,6 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); - SinonMongoose.calledOnceWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [ - { course: { $in: courses.map(c => c._id) } }, - { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, - ], - }, - { query: 'lean' }, - ] - ); + sinon.assert.notCalled(courseSlotFind); }); }); From 02ab05fc721fc37bc13a653ae5113aaf3421bf26 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Mon, 9 Nov 2026 15:09:09 +0100 Subject: [PATCH 32/53] COM-4321 - use bignumber --- src/helpers/courses.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 126fa4ea64..1c2a477330 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2384,9 +2384,12 @@ exports.listTrainersBilling = async (query) => { paidAmount = NumbersHelper.toNumber(paidAmount); let status = INVOICED; - if (invoicedAmount === 0) status = NOT_INVOICED; - else if (invoicedAmount < plannedSalary) status = PARTIALLY_INVOICED; - else if (invoicedAmount === paidAmount) status = PAID; + if (NumbersHelper.isEqualTo(invoicedAmount, 0)) status = NOT_INVOICED; + else if (plannedSalary !== undefined && NumbersHelper.isLessThan(invoicedAmount, plannedSalary)) { + status = PARTIALLY_INVOICED; + } else if (NumbersHelper.isEqualTo(invoicedAmount, paidAmount)) { + status = PAID; + } trainerCourses.push({ ...omit(course, ['billingPurchaseList']), From a7de4049e1bbe34dab8113f863a7efebb7e43154 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 4 Nov 2026 15:49:57 +0100 Subject: [PATCH 33/53] COM-4323 - display trainerSalary on paymentDashboard for collective slots --- src/helpers/trainerPayments.js | 45 ++++++++- tests/unit/helpers/trainerPayments.test.js | 108 ++++++++++++++++++++- 2 files changed, 145 insertions(+), 8 deletions(-) diff --git a/src/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index b450c0b6e5..961ace29c4 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -1,9 +1,13 @@ const get = require('lodash/get'); +const groupBy = require('lodash/groupBy'); const omit = require('lodash/omit'); const CourseSlot = require('../models/CourseSlot'); const TrainerBill = require('../models/TrainerBill'); const TrainerPayment = require('../models/TrainerPayment'); +const CoursesHelper = require('./courses'); const GCloudStorageHelper = require('./gCloudStorage'); +const NumbersHelper = require('./numbers'); +const { TRAINER_SALARY } = require('./constants'); exports.list = async (query) => { const status = Array.isArray(query.status) ? query.status : [query.status]; @@ -12,20 +16,53 @@ exports.list = async (query) => { .find({ status: { $in: status } }) .populate({ path: 'trainerBill', - select: 'number file', - populate: { path: 'trainer', select: 'identity bic iban' }, + select: 'number file course', + populate: [ + { path: 'trainer', select: 'identity bic iban' }, + { + path: 'course', + select: 'trainers billingPurchaseList rolesPerTrainer subProgram createdAt', + populate: [ + { path: 'subProgram', select: 'name trainerPriceVersions' }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], }) .populate({ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }) .sort({ date: -1 }) .lean(); + const courseIds = trainerPayments + .filter(payment => payment.trainerBill?.course) + .map(payment => payment.trainerBill.course._id); + const courseSlots = await CourseSlot + .find({ course: { $in: courseIds } }, { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }) + .lean(); + const courseSlotsByCourse = groupBy(courseSlots, slot => slot.course); + const formattedPayments = trainerPayments.map((payment) => { - const trainer = get(payment, 'trainerBill.trainer'); + const { trainer, course } = payment.trainerBill || {}; if (!trainer) return payment; const formattedTrainer = { ...omit(trainer, ['bic', 'iban']), hasBankDetails: !!(trainer.bic && trainer.iban) }; + let plannedSalary; + if (course) { + const salaryItem = course.trainers.length === 1 && + (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); + plannedSalary = salaryItem + ? NumbersHelper.toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)) + : CoursesHelper.getCourseTrainerSalaryFromSlots(course, trainer._id, courseSlotsByCourse[course._id] || []); + } - return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; + return { + ...payment, + trainerBill: { + ...payment.trainerBill, + trainer: formattedTrainer, + ...(course && { course: { _id: course._id, plannedSalary } }), + }, + }; }); return formattedPayments; diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index cd1eb341db..ef9c6ccaab 100644 --- a/tests/unit/helpers/trainerPayments.test.js +++ b/tests/unit/helpers/trainerPayments.test.js @@ -5,9 +5,10 @@ const CourseSlot = require('../../../src/models/CourseSlot'); const TrainerBill = require('../../../src/models/TrainerBill'); const TrainerPayment = require('../../../src/models/TrainerPayment'); const TrainerPaymentsHelper = require('../../../src/helpers/trainerPayments'); +const CoursesHelper = require('../../../src/helpers/courses'); const GCloudStorageHelper = require('../../../src/helpers/gCloudStorage'); const SinonMongoose = require('../sinonMongoose'); -const { PENDING, PAID } = require('../../../src/helpers/constants'); +const { PENDING, PAID, TRAINER_SALARY } = require('../../../src/helpers/constants'); describe('update', () => { let trainerPaymentUpdateOne; @@ -76,13 +77,19 @@ describe('remove', () => { describe('list', () => { let trainerPaymentFind; + let courseSlotFind; + let getCourseTrainerSalaryFromSlots; beforeEach(() => { trainerPaymentFind = sinon.stub(TrainerPayment, 'find'); + courseSlotFind = sinon.stub(CourseSlot, 'find'); + getCourseTrainerSalaryFromSlots = sinon.stub(CoursesHelper, 'getCourseTrainerSalaryFromSlots'); }); afterEach(() => { trainerPaymentFind.restore(); + courseSlotFind.restore(); + getCourseTrainerSalaryFromSlots.restore(); }); it('should return the trainer payments with the given status', async () => { @@ -92,6 +99,7 @@ describe('list', () => { trainerBill: { number: 'FACT', trainer: { identity: { lastname: 'Trainer' }, bic: 'WERTFRPP', iban: 'FR35' } }, }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await TrainerPaymentsHelper.list({ status: PAID }); @@ -105,9 +113,21 @@ describe('list', () => { { query: 'find', args: [{ status: { $in: [PAID] } }] }, { query: 'populate', - args: [ - { path: 'trainerBill', select: 'number file', populate: { path: 'trainer', select: 'identity bic iban' } }, - ], + args: [{ + path: 'trainerBill', + select: 'number file course', + populate: [ + { path: 'trainer', select: 'identity bic iban' }, + { + path: 'course', + select: 'trainers billingPurchaseList rolesPerTrainer subProgram createdAt', + populate: [ + { path: 'subProgram', select: 'name trainerPriceVersions' }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], + }], }, { query: 'populate', @@ -117,12 +137,92 @@ describe('list', () => { { query: 'lean' }, ] ); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [{ course: { $in: [] } }, { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }], + }, + { query: 'lean' }, + ] + ); + sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); + }); + + it('should return the planned salary of the course from billing purchase list or from slots', async () => { + const trainerId = new ObjectId(); + const trainer = { _id: trainerId, identity: { lastname: 'Trainer' }, bic: 'WERTFRPP', iban: 'FR35' }; + const courseWithSalaryItem = { + _id: new ObjectId(), + trainers: [trainerId], + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 1 }], + }; + const courseWithoutSalaryItem = { _id: new ObjectId(), trainers: [trainerId, new ObjectId()] }; + const trainerPayments = [ + { _id: new ObjectId(), status: PAID, trainerBill: { number: 'FACT_1', trainer, course: courseWithSalaryItem } }, + { + _id: new ObjectId(), + status: PAID, + trainerBill: { number: 'FACT_2', trainer, course: courseWithoutSalaryItem }, + }, + ]; + const courseSlots = [ + { _id: new ObjectId(), course: courseWithoutSalaryItem._id, trainers: [trainerId] }, + { _id: new ObjectId(), course: courseWithoutSalaryItem._id, trainers: [trainerId] }, + ]; + + trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); + getCourseTrainerSalaryFromSlots.returns(120); + + const result = await TrainerPaymentsHelper.list({ status: PAID }); + + const formattedTrainer = { _id: trainerId, identity: { lastname: 'Trainer' }, hasBankDetails: true }; + expect(result).toEqual([ + { + ...trainerPayments[0], + trainerBill: { + number: 'FACT_1', + trainer: formattedTrainer, + course: { _id: courseWithSalaryItem._id, plannedSalary: 40 }, + }, + }, + { + ...trainerPayments[1], + trainerBill: { + number: 'FACT_2', + trainer: formattedTrainer, + course: { _id: courseWithoutSalaryItem._id, plannedSalary: 120 }, + }, + }, + ]); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courseWithSalaryItem._id, courseWithoutSalaryItem._id] } }, + { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, + ], + }, + { query: 'lean' }, + ] + ); + sinon.assert.calledOnceWithExactly( + getCourseTrainerSalaryFromSlots, + courseWithoutSalaryItem, + trainerId, + courseSlots + ); }); it('should query every status when status is an array', async () => { const trainerPayments = [{ _id: new ObjectId(), status: PAID }, { _id: new ObjectId(), status: PENDING }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await TrainerPaymentsHelper.list({ status: [PENDING, PAID] }); expect(result).toEqual(trainerPayments); From bc4f34d91808b3df33efeb9eed8b9300e95a3873 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Mon, 9 Nov 2026 16:27:09 +0100 Subject: [PATCH 34/53] COM-4323 - simplify code --- src/helpers/trainerPayments.js | 31 ++--- tests/unit/helpers/trainerPayments.test.js | 131 ++++++++++++--------- 2 files changed, 86 insertions(+), 76 deletions(-) diff --git a/src/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index 961ace29c4..51bbc322ec 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -1,13 +1,10 @@ const get = require('lodash/get'); -const groupBy = require('lodash/groupBy'); const omit = require('lodash/omit'); const CourseSlot = require('../models/CourseSlot'); const TrainerBill = require('../models/TrainerBill'); const TrainerPayment = require('../models/TrainerPayment'); -const CoursesHelper = require('./courses'); const GCloudStorageHelper = require('./gCloudStorage'); -const NumbersHelper = require('./numbers'); -const { TRAINER_SALARY } = require('./constants'); +const CoursesHelper = require('./courses'); exports.list = async (query) => { const status = Array.isArray(query.status) ? query.status : [query.status]; @@ -21,9 +18,9 @@ exports.list = async (query) => { { path: 'trainer', select: 'identity bic iban' }, { path: 'course', - select: 'trainers billingPurchaseList rolesPerTrainer subProgram createdAt', + select: 'trainers billingPurchaseList subProgram', populate: [ - { path: 'subProgram', select: 'name trainerPriceVersions' }, + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, { path: 'billingPurchaseList.billingItem', select: 'type' }, ], }, @@ -33,34 +30,22 @@ exports.list = async (query) => { .sort({ date: -1 }) .lean(); - const courseIds = trainerPayments - .filter(payment => payment.trainerBill?.course) - .map(payment => payment.trainerBill.course._id); - const courseSlots = await CourseSlot - .find({ course: { $in: courseIds } }, { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }) - .lean(); - const courseSlotsByCourse = groupBy(courseSlots, slot => slot.course); - const formattedPayments = trainerPayments.map((payment) => { const { trainer, course } = payment.trainerBill || {}; if (!trainer) return payment; const formattedTrainer = { ...omit(trainer, ['bic', 'iban']), hasBankDetails: !!(trainer.bic && trainer.iban) }; - let plannedSalary; - if (course) { - const salaryItem = course.trainers.length === 1 && - (course.billingPurchaseList || []).find(item => item.billingItem?.type === TRAINER_SALARY); - plannedSalary = salaryItem - ? NumbersHelper.toNumber(NumbersHelper.multiply(salaryItem.price, salaryItem.count)) - : CoursesHelper.getCourseTrainerSalaryFromSlots(course, trainer._id, courseSlotsByCourse[course._id] || []); - } + if (!course) return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; + + const plannedSalary = CoursesHelper.getCourseTrainerSalary(course); + const formattedCourse = { _id: course._id, ...(plannedSalary && { plannedSalary }) }; return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer, - ...(course && { course: { _id: course._id, plannedSalary } }), + course: formattedCourse, }, }; }); diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index ef9c6ccaab..5a6c09ac52 100644 --- a/tests/unit/helpers/trainerPayments.test.js +++ b/tests/unit/helpers/trainerPayments.test.js @@ -77,29 +77,25 @@ describe('remove', () => { describe('list', () => { let trainerPaymentFind; - let courseSlotFind; - let getCourseTrainerSalaryFromSlots; + let getCourseTrainerSalary; beforeEach(() => { trainerPaymentFind = sinon.stub(TrainerPayment, 'find'); - courseSlotFind = sinon.stub(CourseSlot, 'find'); - getCourseTrainerSalaryFromSlots = sinon.stub(CoursesHelper, 'getCourseTrainerSalaryFromSlots'); + getCourseTrainerSalary = sinon.stub(CoursesHelper, 'getCourseTrainerSalary'); }); afterEach(() => { trainerPaymentFind.restore(); - courseSlotFind.restore(); - getCourseTrainerSalaryFromSlots.restore(); + getCourseTrainerSalary.restore(); }); - it('should return the trainer payments with the given status', async () => { + it('should return PAID trainer payments', async () => { const trainerPayments = [{ _id: new ObjectId(), status: PAID, trainerBill: { number: 'FACT', trainer: { identity: { lastname: 'Trainer' }, bic: 'WERTFRPP', iban: 'FR35' } }, }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); - courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await TrainerPaymentsHelper.list({ status: PAID }); @@ -120,9 +116,9 @@ describe('list', () => { { path: 'trainer', select: 'identity bic iban' }, { path: 'course', - select: 'trainers billingPurchaseList rolesPerTrainer subProgram createdAt', + select: 'trainers billingPurchaseList subProgram', populate: [ - { path: 'subProgram', select: 'name trainerPriceVersions' }, + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, { path: 'billingPurchaseList.billingItem', select: 'type' }, ], }, @@ -137,44 +133,34 @@ describe('list', () => { { query: 'lean' }, ] ); - SinonMongoose.calledOnceWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [{ course: { $in: [] } }, { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }], - }, - { query: 'lean' }, - ] - ); - sinon.assert.notCalled(getCourseTrainerSalaryFromSlots); + sinon.assert.notCalled(getCourseTrainerSalary); }); - it('should return the planned salary of the course from billing purchase list or from slots', async () => { + it('should return trainer payments formatted with trainer\'s planned salary', async () => { const trainerId = new ObjectId(); const trainer = { _id: trainerId, identity: { lastname: 'Trainer' }, bic: 'WERTFRPP', iban: 'FR35' }; - const courseWithSalaryItem = { + const courseWithTrainerSalary = { _id: new ObjectId(), trainers: [trainerId], billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 1 }], }; - const courseWithoutSalaryItem = { _id: new ObjectId(), trainers: [trainerId, new ObjectId()] }; + const courseWithoutTrainerSalary = { _id: new ObjectId(), trainers: [trainerId, new ObjectId()] }; const trainerPayments = [ - { _id: new ObjectId(), status: PAID, trainerBill: { number: 'FACT_1', trainer, course: courseWithSalaryItem } }, { _id: new ObjectId(), status: PAID, - trainerBill: { number: 'FACT_2', trainer, course: courseWithoutSalaryItem }, + trainerBill: { number: 'FACT_1', trainer, course: courseWithTrainerSalary }, + }, + { + _id: new ObjectId(), + status: PAID, + trainerBill: { number: 'FACT_2', trainer, course: courseWithoutTrainerSalary }, }, - ]; - const courseSlots = [ - { _id: new ObjectId(), course: courseWithoutSalaryItem._id, trainers: [trainerId] }, - { _id: new ObjectId(), course: courseWithoutSalaryItem._id, trainers: [trainerId] }, ]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); - courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); - getCourseTrainerSalaryFromSlots.returns(120); + getCourseTrainerSalary.onCall(0).returns(40); + getCourseTrainerSalary.onCall(1).returns(undefined); const result = await TrainerPaymentsHelper.list({ status: PAID }); @@ -185,48 +171,87 @@ describe('list', () => { trainerBill: { number: 'FACT_1', trainer: formattedTrainer, - course: { _id: courseWithSalaryItem._id, plannedSalary: 40 }, + course: { _id: courseWithTrainerSalary._id, plannedSalary: 40 }, }, }, { ...trainerPayments[1], - trainerBill: { - number: 'FACT_2', - trainer: formattedTrainer, - course: { _id: courseWithoutSalaryItem._id, plannedSalary: 120 }, - }, + trainerBill: { number: 'FACT_2', trainer: formattedTrainer, course: { _id: courseWithoutTrainerSalary._id } }, }, ]); + SinonMongoose.calledOnceWithExactly( - courseSlotFind, + trainerPaymentFind, [ + { query: 'find', args: [{ status: { $in: [PAID] } }] }, + { + query: 'populate', + args: [{ + path: 'trainerBill', + select: 'number file course', + populate: [ + { path: 'trainer', select: 'identity bic iban' }, + { + path: 'course', + select: 'trainers billingPurchaseList subProgram', + populate: [ + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], + }], + }, { - query: 'find', - args: [ - { course: { $in: [courseWithSalaryItem._id, courseWithoutSalaryItem._id] } }, - { course: 1, step: 1, startDate: 1, endDate: 1, trainers: 1 }, - ], + query: 'populate', + args: [{ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }], }, + { query: 'sort', args: [{ date: -1 }] }, { query: 'lean' }, ] ); - sinon.assert.calledOnceWithExactly( - getCourseTrainerSalaryFromSlots, - courseWithoutSalaryItem, - trainerId, - courseSlots - ); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courseWithTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courseWithoutTrainerSalary); }); - it('should query every status when status is an array', async () => { + it('should return PAID and PENDING trainer payments', async () => { const trainerPayments = [{ _id: new ObjectId(), status: PAID }, { _id: new ObjectId(), status: PENDING }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); - courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await TrainerPaymentsHelper.list({ status: [PENDING, PAID] }); expect(result).toEqual(trainerPayments); - sinon.assert.calledOnceWithExactly(trainerPaymentFind, { status: { $in: [PENDING, PAID] } }); + SinonMongoose.calledOnceWithExactly( + trainerPaymentFind, + [ + { query: 'find', args: [{ status: { $in: [PENDING, PAID] } }] }, + { + query: 'populate', + args: [{ + path: 'trainerBill', + select: 'number file course', + populate: [ + { path: 'trainer', select: 'identity bic iban' }, + { + path: 'course', + select: 'trainers billingPurchaseList subProgram', + populate: [ + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], + }], + }, + { + query: 'populate', + args: [{ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }], + }, + { query: 'sort', args: [{ date: -1 }] }, + { query: 'lean' }, + ] + ); + sinon.assert.notCalled(getCourseTrainerSalary); }); }); From 4aeb52d8b7386898bd7adc213c0911093462b009 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 10 Nov 2026 12:34:37 +0100 Subject: [PATCH 35/53] COM-4326 - add billSubmissionDates in trainerBills list + return courses with trainerBills on period --- src/helpers/courses.js | 21 +++-- tests/integration/courses.test.js | 12 ++- tests/integration/seed/coursesSeed.js | 10 +++ tests/unit/helpers/courses.test.js | 117 ++++++++++++++++++++++---- 4 files changed, 134 insertions(+), 26 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 4634c71f31..8420b00376 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2331,18 +2331,24 @@ exports.getCourseTrainerSalary = (course) => { }; exports.listTrainersBilling = async (query) => { - let courseIdsWithSlotsInPeriod; + let courseIdsWithSlotsOrBillsInPeriod; if (query.startDate) { const slotsInPeriod = await CourseSlot .find({ startDate: { $gte: query.startDate }, endDate: { $lte: query.endDate } }, { course: 1 }) .lean(); - courseIdsWithSlotsInPeriod = uniqBy(slotsInPeriod.map(slot => slot.course), id => id.toHexString()); + const billsInPeriod = await TrainerBill + .find({ submittedAt: { $gte: query.startDate, $lte: query.endDate }, course: { $exists: true } }, { course: 1 }) + .lean(); + courseIdsWithSlotsOrBillsInPeriod = uniqBy( + [...slotsInPeriod.map(slot => slot.course), ...billsInPeriod.map(bill => bill.course)], + id => id.toHexString() + ); } const courses = await Course .find( { - ...(courseIdsWithSlotsInPeriod && { _id: { $in: courseIdsWithSlotsInPeriod } }), + ...(courseIdsWithSlotsOrBillsInPeriod && { _id: { $in: courseIdsWithSlotsOrBillsInPeriod } }), ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), type: { $nin: [SINGLE, INTER_B2C] }, }, @@ -2359,7 +2365,7 @@ exports.listTrainersBilling = async (query) => { const trainerBills = await TrainerBill .find( { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, - { course: 1, amount: 1, trainer: 1 } + { course: 1, amount: 1, trainer: 1, submittedAt: 1 } ) .populate({ path: 'payment', select: 'status' }) .lean(); @@ -2380,9 +2386,13 @@ exports.listTrainersBilling = async (query) => { const courseBills = billsByTrainerAndCourse[`${trainer._id}-${course._id}`] || []; let invoicedAmount = 0; let paidAmount = 0; + const billsSubmissionDates = []; for (const bill of courseBills) { invoicedAmount = NumbersHelper.add(invoicedAmount, bill.amount); - if (bill.payment?.status === PAID) paidAmount = NumbersHelper.add(paidAmount, bill.amount); + if (bill.payment?.status === PAID) { + paidAmount = NumbersHelper.add(paidAmount, bill.amount); + } + billsSubmissionDates.push(bill.submittedAt); } invoicedAmount = NumbersHelper.toNumber(invoicedAmount); paidAmount = NumbersHelper.toNumber(paidAmount); @@ -2401,6 +2411,7 @@ exports.listTrainersBilling = async (query) => { invoicedAmount, paidAmount, status, + ...(status === INVOICED && { billsSubmissionDates }), }); } diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 1e236e07be..0990e9695c 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10128,7 +10128,7 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { expect(trainers[0].courses.length).toEqual(15); }); - it('should return all trainer\'s courses with slots in period', async () => { + it('should return all trainer\'s courses with slots or trainer bills in period', async () => { const startDate = '2020-03-01T00:00:00.000Z'; const endDate = '2020-03-05T23:59:59.999Z'; const response = await app.inject({ @@ -10140,8 +10140,13 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { expect(response.statusCode).toBe(200); const { trainers } = response.result.data; expect(trainers.length).toEqual(2); - expect(trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainer._id)).courses.length).toEqual(2); + const trainerCourses = trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainer._id)).courses; + expect(trainerCourses.length).toEqual(3); expect(trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainerAndCoach._id)).courses.length).toEqual(4); + const trainerCourseBilledInPeriod = trainerCourses + .find(c => UtilsHelper.areObjectIdsEquals(c._id, coursesList[7]._id)); + expect(trainerCourseBilledInPeriod.billsSubmissionDates) + .toEqual([CompaniDate('2020-03-02T10:00:00.000Z').toDate()]); }); it('should return 400 if endDate without startDate', async () => { @@ -10202,7 +10207,8 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { const { courses } = response.result.data.trainers[0]; expect(courses.length).toEqual(15); expect(courses.every(c => c.type !== SINGLE)).toBeTruthy(); - expect(courses[0]).toEqual(expect.objectContaining({ + const notInvoicedCourse = courses.find(c => UtilsHelper.areObjectIdsEquals(c._id, coursesList[4]._id)); + expect(notInvoicedCourse).toEqual(expect.objectContaining({ invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced', diff --git a/tests/integration/seed/coursesSeed.js b/tests/integration/seed/coursesSeed.js index 836bbf72b6..c6ba003827 100644 --- a/tests/integration/seed/coursesSeed.js +++ b/tests/integration/seed/coursesSeed.js @@ -1548,6 +1548,16 @@ const trainerBillList = [ submittedAt: '2025-01-01T10:00:00.000Z', file: { publicId: 'publicId', link: 'link' }, }, + { + _id: new ObjectId(), + trainer: trainer._id, + number: 'FACT_0002', + course: coursesList[7]._id, + amount: 50, + submittedAt: '2020-03-02T10:00:00.000Z', + createdAt: '2020-03-02T10:00:00.000Z', + file: { publicId: 'publicId2', link: 'link2' }, + }, ]; const populateDB = async () => { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index b6f95af63f..5934d4a24b 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11455,10 +11455,34 @@ describe('listTrainersBilling', () => { }, ]; const trainerBills = [ - { course: courses[1]._id, trainer: trainerId, amount: 40, payment: { status: 'pending' } }, - { course: courses[2]._id, trainer: trainerId, amount: 100, payment: { status: 'pending' } }, - { course: courses[3]._id, trainer: trainerId, amount: 60, payment: { status: 'paid' } }, - { course: courses[3]._id, trainer: trainerId, amount: 40, payment: { status: 'paid' } }, + { + course: courses[1]._id, + trainer: trainerId, + amount: 40, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + { + course: courses[2]._id, + trainer: trainerId, + amount: 100, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + { + course: courses[3]._id, + trainer: trainerId, + amount: 60, + payment: { status: 'paid' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + { + course: courses[3]._id, + trainer: trainerId, + amount: 40, + payment: { status: 'paid' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); @@ -11483,6 +11507,7 @@ describe('listTrainersBilling', () => { invoicedAmount: 100, paidAmount: 0, status: 'invoiced', + billsSubmissionDates: ['2024-01-01T08:00:00.000Z'], }, { ...omit(courses[3], ['billingPurchaseList']), @@ -11521,7 +11546,7 @@ describe('listTrainersBilling', () => { query: 'find', args: [ { course: { $in: courses.map(c => c._id) }, trainer: trainerId }, - { course: 1, amount: 1, trainer: 1 }, + { course: 1, amount: 1, trainer: 1, submittedAt: 1 }, ], }, { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, @@ -11531,7 +11556,7 @@ describe('listTrainersBilling', () => { sinon.assert.notCalled(courseSlotFind); }); - it('should only return courses with slots in period', async () => { + it('should only return courses with slots or trainer bills in period', async () => { const trainerId = new ObjectId(); const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; const query = { trainer: trainerId, startDate: '2024-02-01T00:00:00.000Z', endDate: '2024-02-29T23:59:59.999Z' }; @@ -11551,17 +11576,16 @@ describe('listTrainersBilling', () => { endDate: '2024-02-01T10:00:00.000Z', trainers: [trainerId], }, - { - course: courses[1]._id, - startDate: '2024-02-06T08:00:00.000Z', - endDate: '2024-02-06T10:00:00.000Z', - trainers: [trainerId], - }, + { course: courses[0]._id, startDate: '2024-02-06T08:00:00.000Z', endDate: '2024-02-06T10:00:00.000Z' }, + ]; + const trainerBillsInPeriod = [ + { course: courses[1]._id, submittedAt: '2024-02-15T08:00:00.000Z', trainer: trainerId, amount: 100 }, ]; courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); + trainerBillFind.onCall(0).returns(SinonMongoose.stubChainedQueries(trainerBillsInPeriod, ['lean'])); courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - trainerBillFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + trainerBillFind.onCall(1).returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); const result = await CourseHelper.listTrainersBilling(query); @@ -11591,6 +11615,20 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); + SinonMongoose.calledWithExactly( + trainerBillFind, + [ + { + query: 'find', + args: [ + { submittedAt: { $gte: query.startDate, $lte: query.endDate }, course: { $exists: true } }, + { course: 1 }, + ], + }, + { query: 'lean' }, + ], + 0 + ); SinonMongoose.calledOnceWithExactly( courseFind, [ @@ -11616,6 +11654,21 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); + SinonMongoose.calledWithExactly( + trainerBillFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courses[0]._id, courses[1]._id] }, trainer: trainerId }, + { course: 1, amount: 1, trainer: 1, submittedAt: 1 }, + ], + }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'lean' }, + ], + 1 + ); }); it('should return all trainers without planned salary for courses with several trainers', async () => { @@ -11638,9 +11691,27 @@ describe('listTrainersBilling', () => { }, ]; const trainerBills = [ - { course: courses[0]._id, trainer: firstTrainerId, amount: 100, payment: { status: 'paid' } }, - { course: courses[0]._id, trainer: secondTrainerId, amount: 40, payment: { status: 'pending' } }, - { course: courses[1]._id, trainer: secondTrainerId, amount: 100, payment: { status: 'pending' } }, + { + course: courses[0]._id, + trainer: firstTrainerId, + amount: 100, + payment: { status: 'paid' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + { + course: courses[0]._id, + trainer: secondTrainerId, + amount: 40, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + { + course: courses[1]._id, + trainer: secondTrainerId, + amount: 100, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); @@ -11658,13 +11729,20 @@ describe('listTrainersBilling', () => { { ...secondTrainer, courses: [ - { ...omit(courses[0], ['billingPurchaseList']), invoicedAmount: 40, paidAmount: 0, status: 'invoiced' }, + { + ...omit(courses[0], ['billingPurchaseList']), + invoicedAmount: 40, + paidAmount: 0, + status: 'invoiced', + billsSubmissionDates: ['2024-01-01T08:00:00.000Z'], + }, { ...omit(courses[1], ['billingPurchaseList']), plannedSalary: 100, invoicedAmount: 100, paidAmount: 0, status: 'invoiced', + billsSubmissionDates: ['2024-01-01T08:00:00.000Z'], }, ], }, @@ -11693,7 +11771,10 @@ describe('listTrainersBilling', () => { SinonMongoose.calledOnceWithExactly( trainerBillFind, [ - { query: 'find', args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, amount: 1, trainer: 1 }] }, + { + query: 'find', + args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, amount: 1, trainer: 1, submittedAt: 1 }], + }, { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, { query: 'lean' }, ] From 23bc9795fa134ad37bb19e6fa54742c463a7ab55 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Tue, 10 Nov 2026 16:05:02 +0100 Subject: [PATCH 36/53] COM-4323 - fix bug on computing totalPayment amount by course and by trainer --- src/helpers/trainerPayments.js | 35 +++++++++++++++++++- tests/unit/helpers/trainerPayments.test.js | 37 +++++++++++++++++++--- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/src/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index 51bbc322ec..fa5e8cc6ff 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -1,10 +1,31 @@ const get = require('lodash/get'); +const groupBy = require('lodash/groupBy'); +const mapValues = require('lodash/mapValues'); const omit = require('lodash/omit'); const CourseSlot = require('../models/CourseSlot'); const TrainerBill = require('../models/TrainerBill'); const TrainerPayment = require('../models/TrainerPayment'); const GCloudStorageHelper = require('./gCloudStorage'); const CoursesHelper = require('./courses'); +const NumbersHelper = require('./numbers'); + +const getTotalPaymentsAmountByCourseAndTrainer = async (courseIds) => { + if (!courseIds.length) return {}; + + const trainerBills = await TrainerBill + .find({ course: { $in: courseIds } }, { course: 1, trainer: 1 }) + .populate({ path: 'payment', select: 'amount' }) + .lean(); + + const billsWithPayment = trainerBills.filter(bill => bill.payment); + const billsWithPaymentByCourseAndTrainer = groupBy(billsWithPayment, bill => `${bill.course}-${bill.trainer}`); + + return mapValues(billsWithPaymentByCourseAndTrainer, (bills) => { + const paymentAmounts = bills.map(bill => bill.payment.amount); + + return NumbersHelper.toNumber(NumbersHelper.add(...paymentAmounts)); + }); +}; exports.list = async (query) => { const status = Array.isArray(query.status) ? query.status : [query.status]; @@ -30,6 +51,12 @@ exports.list = async (query) => { .sort({ date: -1 }) .lean(); + const courseIds = trainerPayments + .map(p => get(p, 'trainerBill.course')) + .filter(course => course && CoursesHelper.getCourseTrainerSalary(course)) + .map(course => course._id); + const totalPaymentsAmounts = await getTotalPaymentsAmountByCourseAndTrainer(courseIds); + const formattedPayments = trainerPayments.map((payment) => { const { trainer, course } = payment.trainerBill || {}; if (!trainer) return payment; @@ -38,7 +65,13 @@ exports.list = async (query) => { if (!course) return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; const plannedSalary = CoursesHelper.getCourseTrainerSalary(course); - const formattedCourse = { _id: course._id, ...(plannedSalary && { plannedSalary }) }; + const formattedCourse = { + _id: course._id, + ...(plannedSalary && { + plannedSalary, + totalPaymentsAmount: totalPaymentsAmounts[`${course._id}-${trainer._id}`] || 0, + }), + }; return { ...payment, diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index 5a6c09ac52..d55ae8952e 100644 --- a/tests/unit/helpers/trainerPayments.test.js +++ b/tests/unit/helpers/trainerPayments.test.js @@ -77,15 +77,18 @@ describe('remove', () => { describe('list', () => { let trainerPaymentFind; + let trainerBillFind; let getCourseTrainerSalary; beforeEach(() => { trainerPaymentFind = sinon.stub(TrainerPayment, 'find'); + trainerBillFind = sinon.stub(TrainerBill, 'find'); getCourseTrainerSalary = sinon.stub(CoursesHelper, 'getCourseTrainerSalary'); }); afterEach(() => { trainerPaymentFind.restore(); + trainerBillFind.restore(); getCourseTrainerSalary.restore(); }); @@ -134,6 +137,7 @@ describe('list', () => { ] ); sinon.assert.notCalled(getCourseTrainerSalary); + sinon.assert.notCalled(trainerBillFind); }); it('should return trainer payments formatted with trainer\'s planned salary', async () => { @@ -158,9 +162,18 @@ describe('list', () => { }, ]; + const otherTrainerId = new ObjectId(); + const trainerBills = [ + { _id: new ObjectId(), course: courseWithTrainerSalary._id, trainer: trainerId, payment: { amount: 30 } }, + { _id: new ObjectId(), course: courseWithTrainerSalary._id, trainer: trainerId, payment: { amount: 20.1 } }, + { _id: new ObjectId(), course: courseWithTrainerSalary._id, trainer: otherTrainerId, payment: { amount: 50 } }, + { _id: new ObjectId(), course: courseWithTrainerSalary._id, trainer: trainerId }, + ]; + trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); - getCourseTrainerSalary.onCall(0).returns(40); - getCourseTrainerSalary.onCall(1).returns(undefined); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + getCourseTrainerSalary.withArgs(courseWithTrainerSalary).returns(40); + getCourseTrainerSalary.withArgs(courseWithoutTrainerSalary).returns(undefined); const result = await TrainerPaymentsHelper.list({ status: PAID }); @@ -171,7 +184,7 @@ describe('list', () => { trainerBill: { number: 'FACT_1', trainer: formattedTrainer, - course: { _id: courseWithTrainerSalary._id, plannedSalary: 40 }, + course: { _id: courseWithTrainerSalary._id, plannedSalary: 40, totalPaymentsAmount: 50.1 }, }, }, { @@ -210,8 +223,22 @@ describe('list', () => { { query: 'lean' }, ] ); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courseWithTrainerSalary); - sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courseWithoutTrainerSalary); + SinonMongoose.calledOnceWithExactly( + trainerBillFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courseWithTrainerSalary._id] } }, + { course: 1, trainer: 1 }, + ], + }, + { query: 'populate', args: [{ path: 'payment', select: 'amount' }] }, + { query: 'lean' }, + ] + ); + sinon.assert.calledWithExactly(getCourseTrainerSalary, courseWithTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary, courseWithoutTrainerSalary); }); it('should return PAID and PENDING trainer payments', async () => { From 616ea81d183284c2f855c4e431297b0ebfa63406 Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 12 Nov 2026 11:29:52 +0100 Subject: [PATCH 37/53] COM-4323: review --- tests/unit/helpers/trainerPayments.test.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index d55ae8952e..3b777b48e0 100644 --- a/tests/unit/helpers/trainerPayments.test.js +++ b/tests/unit/helpers/trainerPayments.test.js @@ -171,7 +171,7 @@ describe('list', () => { ]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); - trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills)); getCourseTrainerSalary.withArgs(courseWithTrainerSalary).returns(40); getCourseTrainerSalary.withArgs(courseWithoutTrainerSalary).returns(undefined); @@ -237,8 +237,10 @@ describe('list', () => { { query: 'lean' }, ] ); - sinon.assert.calledWithExactly(getCourseTrainerSalary, courseWithTrainerSalary); - sinon.assert.calledWithExactly(getCourseTrainerSalary, courseWithoutTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(0), courseWithTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(1), courseWithoutTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(2), courseWithTrainerSalary); + sinon.assert.calledWithExactly(getCourseTrainerSalary.getCall(3), courseWithoutTrainerSalary); }); it('should return PAID and PENDING trainer payments', async () => { @@ -280,5 +282,6 @@ describe('list', () => { ] ); sinon.assert.notCalled(getCourseTrainerSalary); + sinon.assert.notCalled(trainerBillFind); }); }); From e7b31b0fc04783d99addd488301d506d6f3af99b Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 12 Nov 2026 14:17:25 +0100 Subject: [PATCH 38/53] COM-4326: review --- src/helpers/courses.js | 4 +--- tests/integration/courses.test.js | 8 +++++--- tests/unit/helpers/courses.test.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 8420b00376..6d428c5496 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2389,9 +2389,7 @@ exports.listTrainersBilling = async (query) => { const billsSubmissionDates = []; for (const bill of courseBills) { invoicedAmount = NumbersHelper.add(invoicedAmount, bill.amount); - if (bill.payment?.status === PAID) { - paidAmount = NumbersHelper.add(paidAmount, bill.amount); - } + if (bill.payment?.status === PAID) paidAmount = NumbersHelper.add(paidAmount, bill.amount); billsSubmissionDates.push(bill.submittedAt); } invoicedAmount = NumbersHelper.toNumber(invoicedAmount); diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 0990e9695c..29c24e7d43 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -10141,12 +10141,14 @@ describe('COURSES ROUTES - GET /courses/trainers-billing', () => { const { trainers } = response.result.data; expect(trainers.length).toEqual(2); const trainerCourses = trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainer._id)).courses; + const trainerAndCoachCourses = trainers + .find(t => UtilsHelper.areObjectIdsEquals(t._id, trainerAndCoach._id)).courses; expect(trainerCourses.length).toEqual(3); - expect(trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, trainerAndCoach._id)).courses.length).toEqual(4); + expect(trainerAndCoachCourses.length).toEqual(4); const trainerCourseBilledInPeriod = trainerCourses .find(c => UtilsHelper.areObjectIdsEquals(c._id, coursesList[7]._id)); - expect(trainerCourseBilledInPeriod.billsSubmissionDates) - .toEqual([CompaniDate('2020-03-02T10:00:00.000Z').toDate()]); + expect(CompaniDate(trainerCourseBilledInPeriod.billsSubmissionDates[0]).toISO()) + .toEqual('2020-03-02T10:00:00.000Z'); }); it('should return 400 if endDate without startDate', async () => { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 5934d4a24b..0ce3540e33 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11585,7 +11585,7 @@ describe('listTrainersBilling', () => { courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); trainerBillFind.onCall(0).returns(SinonMongoose.stubChainedQueries(trainerBillsInPeriod, ['lean'])); courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); - trainerBillFind.onCall(1).returns(SinonMongoose.stubChainedQueries([], ['populate', 'lean'])); + trainerBillFind.onCall(1).returns(SinonMongoose.stubChainedQueries([])); const result = await CourseHelper.listTrainersBilling(query); From f1be20c5f54fadb6da0b86b12da4679eca5b2a4e Mon Sep 17 00:00:00 2001 From: ulysse Date: Fri, 13 Nov 2026 16:09:44 +0100 Subject: [PATCH 39/53] COM-4327: edit description --- src/helpers/completionCertificates.js | 70 ++++++++- src/helpers/courseBills.js | 20 ++- src/helpers/hourlyPaymentPlans.js | 27 +++- .../completionCertificates.test.js | 11 +- tests/integration/courseBills.test.js | 23 +++ .../seed/completionCertificatesSeed.js | 9 +- .../helpers/completionCertificates.test.js | 146 +++++++++++++++--- tests/unit/helpers/courseBills.test.js | 30 ++-- tests/unit/helpers/hourlyPaymentPlans.test.js | 71 +++++++-- 9 files changed, 341 insertions(+), 66 deletions(-) diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index ddb512d448..186d843a56 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -11,6 +11,7 @@ const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); const { MM_YYYY, MONTH, DD_MM_YYYY, SHORT_DURATION_H_MM, OFFICIAL } = require('./constants'); const UtilsHelper = require('./utils'); +const NumbersHelper = require('./numbers'); const HourlyPaymentPlansHelper = require('./hourlyPaymentPlans'); const CourseSlotsHelper = require('./courseSlots'); const CoursesHelper = require('./courses'); @@ -112,7 +113,7 @@ exports.generate = async (completionCertificateId) => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -245,9 +246,47 @@ 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 price = HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + const priceDetails = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps); + const descriptionDetails = HourlyPaymentPlansHelper.getPriceDetails(priceDetails); + const price = NumbersHelper + .toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price))); - await CourseBill.updateMany({ _id: { $in: bills.map(b => b._id) } }, { $set: { 'mainFee.price': price } }); + await CourseBill.updateMany( + { _id: { $in: bills.map(b => b._id) } }, + [{ + $set: { + 'mainFee.price': price, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [ + { $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, + 0, + ], + }, + chars: '\r\n ', + }, + }, + }, + in: { + $concat: descriptionDetails + ? [ + '$$base', + { $cond: [{ $eq: ['$$base', ''] }, '', '\r\n'] }, + `--- Détail ---\r\n${descriptionDetails}`, + ] + : ['$$base'], + }, + }, + }, + }, + }], + { updatePipeline: true } + ); } }; @@ -291,7 +330,30 @@ exports.deleteFile = async (completionCertificateId) => { hourlyPaymentPlan: { $exists: true }, billedAt: { $exists: false }, }, - { $set: { 'mainFee.price': 0 } } + [{ + $set: { + 'mainFee.price': 0, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [ + { $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, + 0, + ], + }, + chars: '\r\n ', + }, + }, + }, + in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + }, + }, + }, + }], + { updatePipeline: true } ); } }; diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index f9f108ee05..dc15c71b53 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -338,7 +338,7 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => { .populate({ path: 'subProgram', select: 'steps hourlyPaymentPlans', - populate: { path: 'steps', select: 'activities type theoreticalDuration' }, + populate: { path: 'steps', select: 'name activities type theoreticalDuration' }, }) .lean(); @@ -349,7 +349,13 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => { const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId)); - return HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration); + const priceDetails = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps); + + return { + price: NumbersHelper.toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price))), + details: HourlyPaymentPlansHelper.getPriceDetails(priceDetails), + }; }; exports.createBillList = async (payload) => { @@ -372,9 +378,13 @@ exports.createBillList = async (payload) => { if (payload.quantity === 1) { const isGlobalCertificationCourseWithPriceFromDurations = payload.hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; - const mainFee = isGlobalCertificationCourseWithPriceFromDurations - ? { ...payload.mainFee, price: await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId) } - : payload.mainFee; + let { mainFee } = payload; + if (isGlobalCertificationCourseWithPriceFromDurations) { + const { price, details } = await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId); + const descriptionDetails = details && `--- Détail ---\r\n${details}`; + const description = [payload.mainFee.description, descriptionDetails].filter(Boolean).join('\r\n'); + mainFee = { ...payload.mainFee, price, ...description && { description } }; + } const { price: mainFeePrice } = mainFee; const billCreated = await CourseBill.create({ diff --git a/src/helpers/hourlyPaymentPlans.js b/src/helpers/hourlyPaymentPlans.js index db3635628b..e17432947e 100644 --- a/src/helpers/hourlyPaymentPlans.js +++ b/src/helpers/hourlyPaymentPlans.js @@ -1,18 +1,29 @@ const NumbersHelper = require('./numbers'); const UtilsHelper = require('./utils'); const { CompaniDuration } = require('./dates/companiDurations'); +const { SHORT_DURATION_H_MM } = require('./constants'); -exports.getPriceFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration) => { - const stepsPrice = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => { +exports.getPricesFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration, steps) => { + const stepsPrices = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => { const stepPrice = hourlyPaymentPlan.prices.find(p => UtilsHelper.areObjectIdsEquals(p.step, stepId)); if (!stepPrice) return acc; - return NumbersHelper.add(acc, NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount)); - }, 0); + const { name: stepName } = steps.find(step => UtilsHelper.areObjectIdsEquals(step._id, stepId)); - const eLearningPrice = hourlyPaymentPlan.elearningPrice - ? NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice) - : 0; + const price = NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount); - return NumbersHelper.toFixedToFloat(NumbersHelper.add(stepsPrice, eLearningPrice)); + return { ...acc, [stepId]: { stepId, stepName, duration, price } }; + }, {}); + + const eLearning = hourlyPaymentPlan.elearningPrice && { + duration: CompaniDuration(eLearningDuration), + price: NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice), + }; + + return { ...stepsPrices, ...eLearning && { elearning: eLearning } }; }; + +exports.getPriceDetails = priceDetails => Object.values(priceDetails) + .map(line => `${line.stepName || 'E-learning'} - ${line.duration.format(SHORT_DURATION_H_MM)}` + + ` - ${UtilsHelper.formatPrice(line.price)}`) + .join('\r\n'); diff --git a/tests/integration/completionCertificates.test.js b/tests/integration/completionCertificates.test.js index a70dfe115e..0dc01e57a8 100644 --- a/tests/integration/completionCertificates.test.js +++ b/tests/integration/completionCertificates.test.js @@ -237,8 +237,10 @@ describe('COMPLETION CERTIFICATES ROUTES - PUT /completioncertificates/{_id}', ( }); expect(response.statusCode).toBe(200); - const billCount = await CourseBill.countDocuments({ _id: courseBillsList[0]._id, 'mainFee.price': 200 }); - expect(billCount).toBe(1); + const bill = await CourseBill.findOne({ _id: courseBillsList[0]._id }).setOptions({ isVendorUser: true }).lean(); + expect(bill.mainFee.price).toBe(200); + expect(bill.mainFee.description) + .toBe('Facture test\r\n--- Détail ---\r\nautre étape - 4h - 200,00\u00a0€'); }); it('should return 404 if completion certificate does not exist', async () => { @@ -421,8 +423,9 @@ describe('COMPLETION CERTIFICATES ROUTES - DELETE /completioncertificates/{_id}/ }); expect(response.statusCode).toBe(200); - const billCount = await CourseBill.countDocuments({ _id: courseBillsList[1]._id, 'mainFee.price': 0 }); - expect(billCount).toBe(1); + const bill = await CourseBill.findOne({ _id: courseBillsList[1]._id }).setOptions({ isVendorUser: true }).lean(); + expect(bill.mainFee.price).toBe(0); + expect(bill.mainFee.description).toBe('Facture test'); }); it('should return 404 if completion certificate does not exist', async () => { diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index addd6d5d22..9b686612b9 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -825,6 +825,29 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(response.statusCode).toBe(409); }); + it('should create a bill with the price and the details of the hourly payment plan (GLOBAL)', async () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { + ...singleCoursePayload, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + hourlyPaymentPlanId, + }, + }); + + expect(response.statusCode).toBe(200); + + const createdBill = await CourseBill + .findOne({ course: coursesList[12]._id, hourlyPaymentPlan: hourlyPaymentPlanId }) + .setOptions({ isVendorUser: true }) + .lean(); + expect(createdBill.mainFee.price).toBe(150); + expect(createdBill.mainFee.description) + .toBe('test\r\n--- Détail ---\r\nétape - 3h - 150,00\u00a0€'); + }); + it('should return 400 if price sent with an hourly payment plan', async () => { const response = await app.inject({ method: 'POST', diff --git a/tests/integration/seed/completionCertificatesSeed.js b/tests/integration/seed/completionCertificatesSeed.js index 8d03f44877..17bbda5742 100644 --- a/tests/integration/seed/completionCertificatesSeed.js +++ b/tests/integration/seed/completionCertificatesSeed.js @@ -314,7 +314,7 @@ const courseBillsList = [ course: courseList[2]._id, companies: [authCompany._id], payer: { company: authCompany._id }, - mainFee: { price: 0, count: 1, countUnit: GROUP }, + mainFee: { price: 0, count: 1, countUnit: GROUP, description: 'Facture test' }, hourlyPaymentPlan: hourlyPaymentPlanId, maturityDate: '2020-01-15T10:00:00.000Z', }, @@ -323,7 +323,12 @@ const courseBillsList = [ course: courseList[2]._id, companies: [authCompany._id], payer: { company: authCompany._id }, - mainFee: { price: 200, count: 1, countUnit: GROUP }, + mainFee: { + price: 200, + count: 1, + countUnit: GROUP, + description: 'Facture test \r\n--- Détail ---\r\nautre étape - 4h - 200,00\u00a0€', + }, hourlyPaymentPlan: hourlyPaymentPlanId, maturityDate: '2020-01-20T10:00:00.000Z', }, diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index 1371c68c7f..b1468a1266 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -441,7 +441,8 @@ describe('generate', () => { let getRealELearningDuration; let findBills; let updateManyBills; - let getPriceFromDurations; + let getPricesFromDurations; + let getPriceDetails; const PRI_SUBPROGRAM_IDS = new ObjectId(); const stepId = new ObjectId(); const REAL_ELEARNING_DURATION_SUBPROGRAM_ID = new ObjectId(); @@ -463,7 +464,8 @@ describe('generate', () => { getRealELearningDuration = sinon.stub(CoursesHelper, 'getRealELearningDuration'); findBills = sinon.stub(CourseBill, 'find'); updateManyBills = sinon.stub(CourseBill, 'updateMany'); - getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); + getPricesFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPricesFromDurations'); + getPriceDetails = sinon.stub(HourlyPaymentPlansHelper, 'getPriceDetails'); process.env.VAEI_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; process.env.PRI_SUBPROGRAM_IDS = PRI_SUBPROGRAM_IDS; process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; @@ -487,7 +489,8 @@ describe('generate', () => { getRealELearningDuration.restore(); findBills.restore(); updateManyBills.restore(); - getPriceFromDurations.restore(); + getPricesFromDurations.restore(); + getPriceDetails.restore(); process.env.VAEI_SUBPROGRAM_IDS = ''; process.env.PRI_SUBPROGRAM_IDS = ''; process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = ''; @@ -503,6 +506,9 @@ describe('generate', () => { const hourlyPaymentPlan = { _id: new ObjectId(), prices: [{ step: stepId, hourlyAmount: 40 }] }; const billId = new ObjectId(); const durationPerStep = { [stepId]: CompaniDuration({ minutes: 390 }) }; + const priceDetails = { + [stepId]: { stepId, stepName: 'étape 1', duration: CompaniDuration({ minutes: 390 }), price: '260' }, + }; const slotList = [ { _id: new ObjectId(), startDate: '2025-01-20T10:00:00.000Z', endDate: '2025-01-20T14:00:00.000Z' }, { _id: new ObjectId(), startDate: '2025-03-14T10:00:00.000Z', endDate: '2025-03-14T14:00:00.000Z' }, @@ -549,6 +555,12 @@ describe('generate', () => { program: { subPrograms: subProgramIds }, hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ + { + _id: stepId, + name: 'étape 1', + type: 'on_site', + theoreticalDuration: '1h', + }, { type: E_LEARNING, theoreticalDuration: '3h30', @@ -614,7 +626,8 @@ describe('generate', () => { [{ _id: billId, hourlyPaymentPlan: hourlyPaymentPlan._id }], ['setOptions', 'lean'] )); - getPriceFromDurations.returns(260); + getPricesFromDurations.returns(priceDetails); + getPriceDetails.returns('étape 1 - 6h30 - 260,00 €'); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getELearningDuration.returns('PT3H30M'); @@ -646,7 +659,7 @@ describe('generate', () => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -786,11 +799,44 @@ describe('generate', () => { { query: 'lean' }, ] ); - sinon.assert.calledOnceWithExactly(getPriceFromDurations, hourlyPaymentPlan, durationPerStep, 'PT3H30M'); + sinon.assert.calledOnceWithExactly( + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT3H30M', + completionCertificate.course.subProgram.steps + ); + sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); sinon.assert.calledOnceWithExactly( updateManyBills, { _id: { $in: [billId] } }, - { $set: { 'mainFee.price': 260 } } + [{ + $set: { + 'mainFee.price': 260, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], + }, + chars: '\r\n ', + }, + }, + }, + in: { + $concat: [ + '$$base', + { $cond: [{ $eq: ['$$base', ''] }, '', '\r\n'] }, + '--- Détail ---\r\nétape 1 - 6h30 - 260,00 €', + ], + }, + }, + }, + }, + }], + { updatePipeline: true } ); }); @@ -923,7 +969,7 @@ describe('generate', () => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -1054,7 +1100,8 @@ describe('generate', () => { ] ); sinon.assert.notCalled(updateManyBills); - sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { @@ -1188,7 +1235,7 @@ describe('generate', () => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -1346,7 +1393,8 @@ describe('generate', () => { ] ); sinon.assert.notCalled(updateManyBills); - sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); it('should generate completion certificate in VAE period (attendance exceeds remaining budget)', async () => { @@ -1485,7 +1533,7 @@ describe('generate', () => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -1643,7 +1691,8 @@ describe('generate', () => { ] ); sinon.assert.notCalled(updateManyBills); - sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); it('should generate completion certificate normally when VAE period budget is exhausted', async () => { @@ -1779,7 +1828,7 @@ describe('generate', () => { select: 'program steps hourlyPaymentPlans', populate: [ { path: 'program', select: 'subPrograms' }, - { path: 'steps', select: 'activities type theoreticalDuration' }, + { path: 'steps', select: 'name activities type theoreticalDuration' }, ], }, ], @@ -1936,7 +1985,8 @@ describe('generate', () => { ] ); sinon.assert.notCalled(updateManyBills); - sinon.assert.notCalled(getPriceFromDurations); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); }); @@ -2020,7 +2070,27 @@ describe('deleteFile', () => { hourlyPaymentPlan: { $exists: true }, billedAt: { $exists: false }, }, - { $set: { 'mainFee.price': 0 } } + [{ + $set: { + 'mainFee.price': 0, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], + }, + chars: '\r\n ', + }, + }, + }, + in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + }, + }, + }, + }], + { updatePipeline: true } ); sinon.assert.callOrder(deleteCourseFile, updateManyBills); sinon.assert.notCalled(find); @@ -2083,7 +2153,27 @@ describe('deleteFile', () => { hourlyPaymentPlan: { $exists: true }, billedAt: { $exists: false }, }, - { $set: { 'mainFee.price': 0 } } + [{ + $set: { + 'mainFee.price': 0, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], + }, + chars: '\r\n ', + }, + }, + }, + in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + }, + }, + }, + }], + { updatePipeline: true } ); sinon.assert.calledWithExactly( updateManyBills.getCall(1), @@ -2096,7 +2186,27 @@ describe('deleteFile', () => { hourlyPaymentPlan: { $exists: true }, billedAt: { $exists: false }, }, - { $set: { 'mainFee.price': 0 } } + [{ + $set: { + 'mainFee.price': 0, + 'mainFee.description': { + $let: { + vars: { + base: { + $rtrim: { + input: { + $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], + }, + chars: '\r\n ', + }, + }, + }, + in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + }, + }, + }, + }], + { updatePipeline: true } ); sinon.assert.callOrder(deleteCourseFile, updateManyBills); sinon.assert.notCalled(updateOne); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index b8a43dbd86..29b602c9ca 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -1154,20 +1154,23 @@ describe('computePriceFromDurations', () => { let findOneCourse; let getTraineeDurations; let getDurationPerStep; - let getPriceFromDurations; + let getPricesFromDurations; + let getPriceDetails; beforeEach(() => { findOneCourse = sinon.stub(Course, 'findOne'); getTraineeDurations = sinon.stub(CoursesHelper, 'getTraineeDurations'); getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); - getPriceFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPriceFromDurations'); + getPricesFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPricesFromDurations'); + getPriceDetails = sinon.stub(HourlyPaymentPlansHelper, 'getPriceDetails'); }); afterEach(() => { findOneCourse.restore(); getTraineeDurations.restore(); getDurationPerStep.restore(); - getPriceFromDurations.restore(); + getPricesFromDurations.restore(); + getPriceDetails.restore(); }); it('should compute the price of the course from the chosen hourly payment plan', async () => { @@ -1177,17 +1180,20 @@ describe('computePriceFromDurations', () => { const slotsWithAttendance = [{ _id: new ObjectId() }]; const eLearningDuration = CompaniDuration({ minutes: 60 }); const durationPerStep = { [new ObjectId()]: CompaniDuration({ minutes: 120 }) }; + const priceDetails = { stepId: { stepName: 'étape', duration: CompaniDuration({ minutes: 120 }), price: '300' } }; - const course = { subProgram: { hourlyPaymentPlans }, slots: [], trainees: [traineeId] }; + const steps = [{ _id: new ObjectId(), name: 'étape' }]; + const course = { subProgram: { hourlyPaymentPlans, steps }, slots: [], trainees: [traineeId] }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course, ['populate', 'lean'])); getTraineeDurations.returns({ slotsWithAttendance, eLearningDuration }); getDurationPerStep.returns(durationPerStep); - getPriceFromDurations.returns(300); + getPricesFromDurations.returns(priceDetails); + getPriceDetails.returns('étape - 2h - 300,00 €'); const result = await CourseBillHelper.computePriceFromDurations(courseId, hourlyPaymentPlans[1]._id); - expect(result).toBe(300); + expect(result).toEqual({ price: 300, details: 'étape - 2h - 300,00 €' }); SinonMongoose.calledOnceWithExactly( findOneCourse, [ @@ -1205,7 +1211,7 @@ describe('computePriceFromDurations', () => { args: [{ path: 'subProgram', select: 'steps hourlyPaymentPlans', - populate: { path: 'steps', select: 'activities type theoreticalDuration' }, + populate: { path: 'steps', select: 'name activities type theoreticalDuration' }, }], }, { query: 'lean' }, @@ -1214,11 +1220,13 @@ describe('computePriceFromDurations', () => { sinon.assert.calledOnceWithExactly(getTraineeDurations, course, traineeId); sinon.assert.calledOnceWithExactly(getDurationPerStep, slotsWithAttendance); sinon.assert.calledOnceWithExactly( - getPriceFromDurations, + getPricesFromDurations, hourlyPaymentPlans[1], durationPerStep, - eLearningDuration + eLearningDuration, + steps ); + sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); }); }); @@ -1271,7 +1279,7 @@ describe('createBillList', () => { }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); - computePriceFromDurations.returns(250); + computePriceFromDurations.returns({ price: 250, details: 'étape - 2h - 250,00 €' }); await CourseBillHelper.createBillList(payload); @@ -1285,7 +1293,7 @@ describe('createBillList', () => { price: 250, count: 1, countUnit: GROUP, - description: 'test', + description: 'test\r\n--- Détail ---\r\nétape - 2h - 250,00 €', }, hourlyPaymentPlan: payload.hourlyPaymentPlanId, companies: payload.companies, diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js index 33a25015c9..8a9c05cd14 100644 --- a/tests/unit/helpers/hourlyPaymentPlans.test.js +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -3,33 +3,76 @@ const { ObjectId } = require('mongodb'); const HourlyPaymentPlansHelper = require('../../../src/helpers/hourlyPaymentPlans'); const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); -describe('getPriceFromDurations', () => { - it('should compute price from on-site steps and e-learning durations', () => { - const stepIds = [new ObjectId(), new ObjectId()]; +describe('getPricesFromDurations', () => { + it('should return a price line per priced step and one for e-learning', () => { + const steps = [{ _id: new ObjectId(), name: 'étape A' }, { _id: new ObjectId(), name: 'étape B' }]; const hourlyPaymentPlan = { - prices: [{ step: stepIds[0], hourlyAmount: 50 }, { step: stepIds[1], hourlyAmount: 80 }], + prices: [{ step: steps[0]._id, hourlyAmount: 50 }, { step: steps[1]._id, hourlyAmount: 80 }], elearningPrice: 20, }; const durationPerStep = { - [stepIds[0]]: CompaniDuration({ minutes: 210 }), - [stepIds[1]]: CompaniDuration({ minutes: 60 }), + [steps[0]._id]: CompaniDuration({ minutes: 210 }), + [steps[1]._id]: CompaniDuration({ minutes: 60 }), }; + const eLearningDuration = CompaniDuration({ minutes: 90 }); const result = HourlyPaymentPlansHelper - .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ minutes: 90 })); + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, steps); - expect(result).toBe(50 * 3.5 + 80 + 20 * 1.5); + expect(Object.keys(result)).toEqual([steps[0]._id.toHexString(), steps[1]._id.toHexString(), 'elearning']); + expect(result[steps[0]._id]).toEqual({ + stepId: steps[0]._id.toHexString(), + stepName: 'étape A', + duration: durationPerStep[steps[0]._id], + price: '175', + }); + expect(result[steps[1]._id]).toEqual({ + stepId: steps[1]._id.toHexString(), + stepName: 'étape B', + duration: durationPerStep[steps[1]._id], + price: '80', + }); + expect(result.elearning.price).toBe('30'); + expect(result.elearning.duration.asMinutes()).toBe(90); }); - it('should ignore e-learning if there is no e-learning price', () => { - const stepId = new ObjectId(); - const hourlyPaymentPlan = { prices: [{ step: stepId, hourlyAmount: 40 }] }; + 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 }] }; + const durationPerStep = { [steps[0]._id]: CompaniDuration({ minutes: 30 }) }; - const durationPerStep = { [stepId]: CompaniDuration({ minutes: 30 }) }; + const result = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ hours: 2 }), steps); + + expect(Object.keys(result)).toEqual([steps[0]._id.toHexString()]); + }); + + it('should ignore steps without price in the plan', () => { + const steps = [{ _id: new ObjectId(), name: 'étape A' }]; + const hourlyPaymentPlan = { prices: [] }; + const durationPerStep = { [steps[0]._id]: CompaniDuration({ minutes: 30 }) }; const result = HourlyPaymentPlansHelper - .getPriceFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ hours: 2 })); + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, CompaniDuration({ hours: 2 }), steps); + + expect(result).toEqual({}); + }); +}); + +describe('getPriceDetails', () => { + it('should return one line per price line (name - duration - price)', () => { + const priceDetails = { + [new ObjectId()]: { stepName: 'étape A', duration: CompaniDuration({ minutes: 210 }), price: '175' }, + [new ObjectId()]: { stepName: 'étape B', duration: CompaniDuration({ minutes: 60 }), price: '80' }, + elearning: { duration: CompaniDuration({ minutes: 90 }), price: '30' }, + }; + + const result = HourlyPaymentPlansHelper.getPriceDetails(priceDetails); - expect(result).toBe(20); + expect(result).toBe( + 'étape A - 3h30 - 175,00\u00a0€\r\n' + + 'étape B - 1h - 80,00\u00a0€\r\n' + + 'E-learning - 1h30 - 30,00\u00a0€' + ); }); }); From 3097d9ece5a519057d2d8810b538c4f60789707c Mon Sep 17 00:00:00 2001 From: ulysse Date: Fri, 13 Nov 2026 16:18:23 +0100 Subject: [PATCH 40/53] COM-4327: no bill if no elearning --- src/helpers/completionCertificates.js | 3 +++ .../helpers/completionCertificates.test.js | 22 +++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index 186d843a56..fa7cb3a6a2 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -248,6 +248,9 @@ exports.generate = async (completionCertificateId) => { .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, planId)); const priceDetails = HourlyPaymentPlansHelper .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps); + const hasPricedStep = Object.values(priceDetails).some(line => line.stepId); + if (!hasPricedStep && CompaniDuration(eLearningDuration).isShorterThan('PT900S')) continue; + const descriptionDetails = HourlyPaymentPlansHelper.getPriceDetails(priceDetails); const price = NumbersHelper .toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price))); diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index b1468a1266..907f1c69c0 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -846,6 +846,9 @@ describe('generate', () => { const companyId = new ObjectId(); const courseId = new ObjectId(); const month = '03-2025'; + const hourlyPaymentPlan = { _id: new ObjectId(), prices: [], elearningPrice: 20 }; + const billId = new ObjectId(); + const durationPerStep = { [stepId]: CompaniDuration({ minutes: 390 }) }; const slotList = [ { _id: new ObjectId(), startDate: '2025-01-20T10:00:00.000Z', endDate: '2025-01-20T14:00:00.000Z' }, { _id: new ObjectId(), startDate: '2025-03-14T10:00:00.000Z', endDate: '2025-03-14T14:00:00.000Z' }, @@ -878,6 +881,7 @@ describe('generate', () => { subProgram: { _id: subProgramIds[0], program: { subPrograms: subProgramIds }, + hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ { type: E_LEARNING, @@ -936,10 +940,14 @@ describe('generate', () => { ); findCompletionCertificate.returns(SinonMongoose.stubChainedQueries([{ month: '02-2025' }], ['setOptions', 'lean'])); findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); - getDurationPerStep.returns({ [stepId]: CompaniDuration({ minutes: 390 }) }); + getDurationPerStep.returns(durationPerStep); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); - findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', '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'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1099,9 +1107,15 @@ describe('generate', () => { { query: 'lean' }, ] ); - sinon.assert.notCalled(updateManyBills); - sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.calledOnceWithExactly( + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT200S', + completionCertificate.course.subProgram.steps + ); sinon.assert.notCalled(getPriceDetails); + sinon.assert.notCalled(updateManyBills); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { From c3c47f7e0d3b4d331b59df7b860097f6d05d712e Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 16 Nov 2026 14:42:03 +0100 Subject: [PATCH 41/53] COM-4327: review --- src/helpers/completionCertificates.js | 105 +++----- .../helpers/completionCertificates.test.js | 249 ++++++++---------- 2 files changed, 153 insertions(+), 201 deletions(-) diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index fa7cb3a6a2..cb11d50a1c 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -237,7 +237,7 @@ exports.generate = async (completionCertificateId) => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 } + { hourlyPaymentPlan: 1, 'mainFee.description': 1 } ) .setOptions({ isVendorUser: true }) .lean(); @@ -255,41 +255,17 @@ exports.generate = async (completionCertificateId) => { const price = NumbersHelper .toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price))); - await CourseBill.updateMany( - { _id: { $in: bills.map(b => b._id) } }, - [{ - $set: { - 'mainFee.price': price, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [ - { $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, - 0, - ], - }, - chars: '\r\n ', - }, - }, - }, - in: { - $concat: descriptionDetails - ? [ - '$$base', - { $cond: [{ $eq: ['$$base', ''] }, '', '\r\n'] }, - `--- Détail ---\r\n${descriptionDetails}`, - ] - : ['$$base'], - }, - }, - }, - }, - }], - { updatePipeline: true } - ); + await Promise.all(bills.map((bill) => { + const base = (get(bill, 'mainFee.description') || '').split('--- Détail ---')[0].trimEnd(); + const description = descriptionDetails + ? `${base ? `${base}\r\n` : ''}--- Détail ---\r\n${descriptionDetails}` + : base; + + return CourseBill.updateOne( + { _id: bill._id }, + { $set: { 'mainFee.price': price, 'mainFee.description': description } } + ); + })); } }; @@ -323,40 +299,31 @@ exports.deleteFile = async (completionCertificateId) => { } for (const certificate of certificatesToDelete) { - await CourseBill.updateMany( - { - course: certificate.course, - maturityDate: { - $gte: CompaniDate(certificate.month, MM_YYYY).startOf(MONTH).toISO(), - $lte: CompaniDate(certificate.month, MM_YYYY).endOf(MONTH).toISO(), - }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - [{ - $set: { - 'mainFee.price': 0, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [ - { $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, - 0, - ], - }, - chars: '\r\n ', - }, - }, - }, - in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, - }, + const bills = await CourseBill + .find( + { + course: certificate.course, + maturityDate: { + $gte: CompaniDate(certificate.month, MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate(certificate.month, MM_YYYY).endOf(MONTH).toISO(), }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, }, - }], - { updatePipeline: true } - ); + { 'mainFee.description': 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); + + await Promise.all(bills.map((bill) => { + const base = (get(bill, 'mainFee.description') || '').split('--- Détail ---')[0].trimEnd(); + + return CourseBill.updateOne( + { _id: bill._id }, + base + ? { $set: { 'mainFee.price': 0, 'mainFee.description': base } } + : { $set: { 'mainFee.price': 0 }, $unset: { 'mainFee.description': '' } } + ); + })); } }; diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index 907f1c69c0..cbe7a43941 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -440,7 +440,7 @@ describe('generate', () => { let getELearningDuration; let getRealELearningDuration; let findBills; - let updateManyBills; + let updateOneBill; let getPricesFromDurations; let getPriceDetails; const PRI_SUBPROGRAM_IDS = new ObjectId(); @@ -463,7 +463,7 @@ describe('generate', () => { getELearningDuration = sinon.stub(CoursesHelper, 'getELearningDuration'); getRealELearningDuration = sinon.stub(CoursesHelper, 'getRealELearningDuration'); findBills = sinon.stub(CourseBill, 'find'); - updateManyBills = sinon.stub(CourseBill, 'updateMany'); + updateOneBill = sinon.stub(CourseBill, 'updateOne'); getPricesFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPricesFromDurations'); getPriceDetails = sinon.stub(HourlyPaymentPlansHelper, 'getPriceDetails'); process.env.VAEI_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; @@ -488,7 +488,7 @@ describe('generate', () => { getELearningDuration.restore(); getRealELearningDuration.restore(); findBills.restore(); - updateManyBills.restore(); + updateOneBill.restore(); getPricesFromDurations.restore(); getPriceDetails.restore(); process.env.VAEI_SUBPROGRAM_IDS = ''; @@ -623,7 +623,7 @@ describe('generate', () => { findAttendance.returns(SinonMongoose.stubChainedQueries(attendances, ['setOptions', 'lean'])); getDurationPerStep.returns(durationPerStep); findBills.returns(SinonMongoose.stubChainedQueries( - [{ _id: billId, hourlyPaymentPlan: hourlyPaymentPlan._id }], + [{ _id: billId, hourlyPaymentPlan: hourlyPaymentPlan._id, mainFee: { description: 'Facture test' } }], ['setOptions', 'lean'] )); getPricesFromDurations.returns(priceDetails); @@ -792,7 +792,7 @@ describe('generate', () => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, @@ -808,35 +808,14 @@ describe('generate', () => { ); sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); sinon.assert.calledOnceWithExactly( - updateManyBills, - { _id: { $in: [billId] } }, - [{ + updateOneBill, + { _id: billId }, + { $set: { 'mainFee.price': 260, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], - }, - chars: '\r\n ', - }, - }, - }, - in: { - $concat: [ - '$$base', - { $cond: [{ $eq: ['$$base', ''] }, '', '\r\n'] }, - '--- Détail ---\r\nétape 1 - 6h30 - 260,00 €', - ], - }, - }, - }, + 'mainFee.description': 'Facture test\r\n--- Détail ---\r\nétape 1 - 6h30 - 260,00 €', }, - }], - { updatePipeline: true } + } ); }); @@ -1100,7 +1079,7 @@ describe('generate', () => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, @@ -1115,7 +1094,7 @@ describe('generate', () => { completionCertificate.course.subProgram.steps ); sinon.assert.notCalled(getPriceDetails); - sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(updateOneBill); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { @@ -1399,14 +1378,14 @@ describe('generate', () => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, { query: 'lean' }, ] ); - sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(updateOneBill); sinon.assert.notCalled(getPricesFromDurations); sinon.assert.notCalled(getPriceDetails); }); @@ -1697,14 +1676,14 @@ describe('generate', () => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, { query: 'lean' }, ] ); - sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(updateOneBill); sinon.assert.notCalled(getPricesFromDurations); sinon.assert.notCalled(getPriceDetails); }); @@ -1991,14 +1970,14 @@ describe('generate', () => { hourlyPaymentPlan: { $exists: true }, 'mainFee.price': { $in: [0, null] }, }, - { hourlyPaymentPlan: 1 }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, ], }, { query: 'setOptions', args: [{ isVendorUser: true }] }, { query: 'lean' }, ] ); - sinon.assert.notCalled(updateManyBills); + sinon.assert.notCalled(updateOneBill); sinon.assert.notCalled(getPricesFromDurations); sinon.assert.notCalled(getPriceDetails); }); @@ -2030,14 +2009,16 @@ describe('deleteFile', () => { let updateOne; let updateMany; let deleteCourseFile; - let updateManyBills; + let findBills; + let updateOneBill; beforeEach(() => { findOne = sinon.stub(CompletionCertificate, 'findOne'); find = sinon.stub(CompletionCertificate, 'find'); updateOne = sinon.stub(CompletionCertificate, 'updateOne'); updateMany = sinon.stub(CompletionCertificate, 'updateMany'); deleteCourseFile = sinon.stub(GCloudStorageHelper, 'deleteCourseFile'); - updateManyBills = sinon.stub(CourseBill, 'updateMany'); + findBills = sinon.stub(CourseBill, 'find'); + updateOneBill = sinon.stub(CourseBill, 'updateOne'); }); afterEach(() => { findOne.restore(); @@ -2045,13 +2026,21 @@ describe('deleteFile', () => { updateOne.restore(); updateMany.restore(); deleteCourseFile.restore(); - updateManyBills.restore(); + findBills.restore(); + updateOneBill.restore(); }); it('should remove the file of a completion certificat and the price of the bills with a hourly payment plan', async () => { const completionCertificateId = new ObjectId(); const courseId = new ObjectId(); + const bills = [ + { + _id: new ObjectId(), + mainFee: { description: 'Facture test\r\n--- Détail ---\r\nétape - 4h - 200,00 €' }, + }, + { _id: new ObjectId(), mainFee: { description: '--- Détail ---\r\nétape - 4h - 200,00 €' } }, + ]; const completionCertificate = { _id: completionCertificateId, trainee: new ObjectId(), @@ -2060,6 +2049,7 @@ describe('deleteFile', () => { file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, }; findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries(bills, ['setOptions', 'lean'])); await CompletionCertificatesHelper.deleteFile(completionCertificateId); @@ -2073,40 +2063,39 @@ describe('deleteFile', () => { { $unset: { file: '', vaeSupportRemainingMinutes: '' } } ); sinon.assert.calledOnceWithExactly(deleteCourseFile, 'completionCertificateTest'); - sinon.assert.calledOnceWithExactly( - updateManyBills, - { - course: courseId, - maturityDate: { - $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), - $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), - }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - [{ - $set: { - 'mainFee.price': 0, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], - }, - chars: '\r\n ', - }, - }, + SinonMongoose.calledOnceWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), }, - in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, }, - }, + { 'mainFee.description': 1 }, + ], }, - }], - { updatePipeline: true } + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + sinon.assert.calledWithExactly( + updateOneBill.getCall(0), + { _id: bills[0]._id }, + { $set: { 'mainFee.price': 0, 'mainFee.description': 'Facture test' } } ); - sinon.assert.callOrder(deleteCourseFile, updateManyBills); + sinon.assert.calledWithExactly( + updateOneBill.getCall(1), + { _id: bills[1]._id }, + { $set: { 'mainFee.price': 0 }, $unset: { 'mainFee.description': '' } } + ); + sinon.assert.callOrder(deleteCourseFile, updateOneBill); sinon.assert.notCalled(find); sinon.assert.notCalled(updateMany); }); @@ -2115,6 +2104,10 @@ describe('deleteFile', () => { const completionCertificateIds = [new ObjectId(), new ObjectId()]; const traineeId = new ObjectId(); const courseId = new ObjectId(); + const bills = [ + { _id: new ObjectId(), mainFee: { description: 'Facture mars\r\n--- Détail ---\r\nétape - 4h - 200,00 €' } }, + { _id: new ObjectId(), mainFee: { description: 'Facture avril\r\n--- Détail ---\r\nétape - 2h - 100,00 €' } }, + ]; const completionCertificate = { _id: completionCertificateIds[0], trainee: traineeId, @@ -2133,6 +2126,8 @@ describe('deleteFile', () => { }]; findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); find.returns(SinonMongoose.stubChainedQueries(completionCertificatesWithRemaingMinutes, ['setOptions', 'lean'])); + findBills.onCall(0).returns(SinonMongoose.stubChainedQueries([bills[0]], ['setOptions', 'lean'])); + findBills.onCall(1).returns(SinonMongoose.stubChainedQueries([bills[1]], ['setOptions', 'lean'])); await CompletionCertificatesHelper.deleteFile(completionCertificateIds[0]); @@ -2155,74 +2150,64 @@ describe('deleteFile', () => { ); sinon.assert.calledWithExactly(deleteCourseFile.getCall(0), 'completionCertificateTest'); sinon.assert.calledWithExactly(deleteCourseFile.getCall(1), 'completionCertificateTest_2'); - sinon.assert.calledTwice(updateManyBills); - sinon.assert.calledWithExactly( - updateManyBills.getCall(0), - { - course: courseId, - maturityDate: { - $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), - $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), - }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - [{ - $set: { - 'mainFee.price': 0, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], - }, - chars: '\r\n ', - }, - }, + sinon.assert.calledTwice(findBills); + SinonMongoose.calledWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate('03-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('03-2025', MM_YYYY).endOf(MONTH).toISO(), }, - in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, }, - }, + { 'mainFee.description': 1 }, + ], }, - }], - { updatePipeline: true } + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ], + 0 ); - sinon.assert.calledWithExactly( - updateManyBills.getCall(1), - { - course: courseId, - maturityDate: { - $gte: CompaniDate('04-2025', MM_YYYY).startOf(MONTH).toISO(), - $lte: CompaniDate('04-2025', MM_YYYY).endOf(MONTH).toISO(), - }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - [{ - $set: { - 'mainFee.price': 0, - 'mainFee.description': { - $let: { - vars: { - base: { - $rtrim: { - input: { - $arrayElemAt: [{ $split: [{ $ifNull: ['$mainFee.description', ''] }, '--- Détail ---'] }, 0], - }, - chars: '\r\n ', - }, - }, + SinonMongoose.calledWithExactly( + findBills, + [ + { + query: 'find', + args: [ + { + course: courseId, + maturityDate: { + $gte: CompaniDate('04-2025', MM_YYYY).startOf(MONTH).toISO(), + $lte: CompaniDate('04-2025', MM_YYYY).endOf(MONTH).toISO(), }, - in: { $cond: [{ $eq: ['$$base', ''] }, '$$REMOVE', '$$base'] }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, }, - }, + { 'mainFee.description': 1 }, + ], }, - }], - { updatePipeline: true } + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ], + 1 + ); + sinon.assert.calledWithExactly( + updateOneBill.getCall(0), + { _id: bills[0]._id }, + { $set: { 'mainFee.price': 0, 'mainFee.description': 'Facture mars' } } + ); + sinon.assert.calledWithExactly( + updateOneBill.getCall(1), + { _id: bills[1]._id }, + { $set: { 'mainFee.price': 0, 'mainFee.description': 'Facture avril' } } ); - sinon.assert.callOrder(deleteCourseFile, updateManyBills); + sinon.assert.callOrder(deleteCourseFile, updateOneBill); sinon.assert.notCalled(updateOne); }); }); From 15910320d0a99f345c5cb2e0f4bb8b203b7c1859 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Mon, 16 Nov 2026 15:13:14 +0100 Subject: [PATCH 42/53] COM-4329 - flag old courses to paid --- src/helpers/courses.js | 15 +++- tests/unit/helpers/courses.test.js | 116 +++++++++++++++++++++++++++-- 2 files changed, 125 insertions(+), 6 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 6d428c5496..7f6787cea5 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2330,6 +2330,10 @@ exports.getCourseTrainerSalary = (course) => { return salary ? NumbersHelper.toNumber(NumbersHelper.multiply(salary.price, salary.count)) : undefined; }; +// Trainer billing was not tracked in the app before October 1st, 2026: +// courses ended before this date are considered as paid +const TRAINER_PAYMENTS_START_DATE = '2026-09-30T22:00:00.000Z'; + exports.listTrainersBilling = async (query) => { let courseIdsWithSlotsOrBillsInPeriod; if (query.startDate) { @@ -2371,6 +2375,14 @@ exports.listTrainersBilling = async (query) => { .lean(); const billsByTrainerAndCourse = groupBy(trainerBills, bill => `${bill.trainer}-${bill.course}`); + const courseSlots = await CourseSlot + .find({ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }) + .lean(); + const isCourseEndedBeforePaymentsStart = mapValues( + groupBy(courseSlots, 'course'), + slots => slots.every(slot => slot.endDate && CompaniDate(slot.endDate).isBefore(TRAINER_PAYMENTS_START_DATE)) + ); + const trainers = query.trainer ? [courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer))] : uniqBy(courses.flatMap(c => c.trainers), t => t._id.toHexString()); @@ -2396,7 +2408,8 @@ exports.listTrainersBilling = async (query) => { paidAmount = NumbersHelper.toNumber(paidAmount); let status = INVOICED; - if (NumbersHelper.isEqualTo(invoicedAmount, 0)) status = NOT_INVOICED; + if (isCourseEndedBeforePaymentsStart[course._id]) status = PAID; + else if (NumbersHelper.isEqualTo(invoicedAmount, 0)) status = NOT_INVOICED; else if (plannedSalary !== undefined && NumbersHelper.isLessThan(invoicedAmount, plannedSalary)) { status = PARTIALLY_INVOICED; } else if (NumbersHelper.isEqualTo(invoicedAmount, paidAmount)) { diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 0ce3540e33..4b7669a984 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11487,6 +11487,7 @@ describe('listTrainersBilling', () => { courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11553,7 +11554,86 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); - sinon.assert.notCalled(courseSlotFind); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }], + }, + { query: 'lean' }, + ] + ); + }); + + it('should consider courses ended before trainer payments start as paid', async () => { + const trainerId = new ObjectId(); + const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; + const billingPurchaseList = [{ billingItem: { type: TRAINER_SALARY }, price: 100, count: 1 }]; + const courses = [ + { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended before', billingPurchaseList }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended after with bill', billingPurchaseList }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended after', billingPurchaseList }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'with slot to plan', billingPurchaseList }, + ]; + const trainerBills = [ + { + course: courses[1]._id, + trainer: trainerId, + amount: 40, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + ]; + const courseSlots = [ + { course: courses[0]._id, endDate: '2026-09-01T10:00:00.000Z' }, + { course: courses[0]._id, endDate: '2026-09-30T21:00:00.000Z' }, + { course: courses[1]._id, endDate: '2026-11-01T10:00:00.000Z' }, + { course: courses[2]._id, endDate: '2026-09-01T10:00:00.000Z' }, + { course: courses[2]._id, endDate: '2026-10-01T08:00:00.000Z' }, + { course: courses[3]._id, endDate: '2026-09-01T10:00:00.000Z' }, + { course: courses[3]._id }, + ]; + + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([{ + ...trainer, + courses: [ + { + ...omit(courses[0], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'paid', + }, + { + ...omit(courses[1], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 40, + paidAmount: 0, + status: 'partially_invoiced', + }, + { + ...omit(courses[2], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }, + { + ...omit(courses[3], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }, + ], + }]); }); it('should only return courses with slots or trainer bills in period', async () => { @@ -11582,10 +11662,11 @@ describe('listTrainersBilling', () => { { course: courses[1]._id, submittedAt: '2024-02-15T08:00:00.000Z', trainer: trainerId, amount: 100 }, ]; - courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); + courseSlotFind.onCall(0).returns(SinonMongoose.stubChainedQueries(courseSlotsInPeriod, ['lean'])); trainerBillFind.onCall(0).returns(SinonMongoose.stubChainedQueries(trainerBillsInPeriod, ['lean'])); courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.onCall(1).returns(SinonMongoose.stubChainedQueries([])); + courseSlotFind.onCall(1).returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await CourseHelper.listTrainersBilling(query); @@ -11602,7 +11683,7 @@ describe('listTrainersBilling', () => { { ...courses[1], invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, ], }]); - SinonMongoose.calledOnceWithExactly( + SinonMongoose.calledWithExactly( courseSlotFind, [ { @@ -11613,7 +11694,22 @@ describe('listTrainersBilling', () => { ], }, { query: 'lean' }, - ] + ], + 0 + ); + SinonMongoose.calledWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { course: { $in: [courses[0]._id, courses[1]._id] } }, + { course: 1, endDate: 1 }, + ], + }, + { query: 'lean' }, + ], + 1 ); SinonMongoose.calledWithExactly( trainerBillFind, @@ -11716,6 +11812,7 @@ describe('listTrainersBilling', () => { courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await CourseHelper.listTrainersBilling({}); @@ -11779,6 +11876,15 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); - sinon.assert.notCalled(courseSlotFind); + SinonMongoose.calledOnceWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }], + }, + { query: 'lean' }, + ] + ); }); }); From c0899d79f5d497182855545035c63e796b098abe Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 17 Nov 2026 16:34:54 +0100 Subject: [PATCH 43/53] COM-4331: cap elearning --- src/helpers/completionCertificates.js | 27 +++++++++-- src/helpers/courseBills.js | 4 +- src/helpers/courses.js | 45 ++++++++++--------- src/helpers/hourlyPaymentPlans.js | 22 +++++++-- src/helpers/subPrograms.js | 28 ++++++++++-- src/models/SubProgram.js | 25 ++++++++++- src/routes/preHandlers/subPrograms.js | 6 ++- src/routes/subPrograms.js | 3 ++ tests/integration/subPrograms.test.js | 15 +++++++ .../helpers/completionCertificates.test.js | 31 +++++++++---- tests/unit/helpers/courseBills.test.js | 14 +++++- tests/unit/helpers/hourlyPaymentPlans.test.js | 20 +++++++++ tests/unit/helpers/subPrograms.test.js | 24 +++++++--- 13 files changed, 215 insertions(+), 49 deletions(-) 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..151584a476 100644 --- a/src/helpers/courseBills.js +++ b/src/helpers/courseBills.js @@ -333,6 +333,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 +343,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..08b50da0f2 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,22 @@ 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 fieldsToUnset = { + ...!elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': '' }, + ...!elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': '' }, + }; + const updateQuery = { + $set: { + 'hourlyPaymentPlans.$.prices': prices, + ...elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': elearningPrice }, + ...elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': elearningLimit }, + }, + ...!isEmpty(fieldsToUnset) && { $unset: fieldsToUnset }, + }; return SubProgram.updateOne({ _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, updateQuery); } @@ -145,7 +157,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/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..86d000b4f9 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,6 +204,9 @@ 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))); diff --git a/src/routes/subPrograms.js b/src/routes/subPrograms.js index f0705d5f3e..86ea596fe5 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', { not: Joi.exist(), then: Joi.forbidden() }), }).required(), }), Joi.object({ archivedAt: Joi.date().allow('') }) diff --git a/tests/integration/subPrograms.test.js b/tests/integration/subPrograms.test.js index bef63abb11..d82855039b 100644 --- a/tests/integration/subPrograms.test.js +++ b/tests/integration/subPrograms.test.js @@ -535,6 +535,21 @@ 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 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..9b2ab845cb 100644 --- a/tests/unit/helpers/courseBills.test.js +++ b/tests/unit/helpers/courseBills.test.js @@ -1183,7 +1183,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 +1207,7 @@ describe('computePriceFromDurations', () => { args: [{ path: 'slots', select: 'startDate endDate trainers step', + options: { sort: { startDate: 1 } }, populate: { path: 'step', select: 'durationCountedPerTrainer' }, }], }, @@ -1217,7 +1222,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..07fc1ab070 100644 --- a/tests/unit/helpers/hourlyPaymentPlans.test.js +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -36,6 +36,26 @@ describe('getPricesFromDurations', () => { expect(result.elearning.duration.asMinutes()).toBe(90); }); + it('should cap the billed e-learning with the limit of the plan (real duration, capped price)', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const noPreviousDuration = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, []); + const limitNotReached = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 6 })); + const limitReachedThisMonth = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 8 })); + const limitAlreadyReached = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 12 })); + + expect(noPreviousDuration.elearning.price).toBe('60'); + expect(limitNotReached.elearning.price).toBe('60'); + expect(limitReachedThisMonth.elearning.price).toBe('40'); + expect(limitReachedThisMonth.elearning.duration.asHours()).toBe(3); + 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); From 9eeddbf932645ca97ce8246db4a6434507722a4f Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 17 Nov 2026 16:56:54 +0100 Subject: [PATCH 44/53] COM-4331: bills sum --- src/helpers/courseBills.js | 46 +++++++++++++----- tests/unit/helpers/courseBills.test.js | 66 ++++++++++++++++++++++++-- 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/src/helpers/courseBills.js b/src/helpers/courseBills.js index 151584a476..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), diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index 9b2ab845cb..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', From a4f73a5bb3ca07117257fa36fd3fb69b171d62b0 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 18 Nov 2026 13:01:49 +0100 Subject: [PATCH 45/53] COM-4331: review --- src/helpers/subPrograms.js | 6 +----- src/helpers/translate.js | 2 ++ src/routes/preHandlers/subPrograms.js | 6 +++++- src/routes/subPrograms.js | 2 +- tests/integration/seed/subProgramsSeed.js | 6 ++++++ tests/integration/subPrograms.test.js | 13 +++++++++++++ 6 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 08b50da0f2..79409fe5e0 100644 --- a/src/helpers/subPrograms.js +++ b/src/helpers/subPrograms.js @@ -132,17 +132,13 @@ exports.updateSubProgram = async (subProgramId, payload) => { CompaniDuration(payload.hourlyPaymentPlan.elearningLimit).asSeconds(); if (hourlyPaymentPlanId && prices.length) { - const fieldsToUnset = { - ...!elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': '' }, - ...!elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': '' }, - }; const updateQuery = { $set: { 'hourlyPaymentPlans.$.prices': prices, ...elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': elearningPrice }, ...elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': elearningLimit }, }, - ...!isEmpty(fieldsToUnset) && { $unset: fieldsToUnset }, + ...!elearningLimit && { $unset: { 'hourlyPaymentPlans.$.elearningLimit': '' } }, }; return SubProgram.updateOne({ _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, updateQuery); 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/routes/preHandlers/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 86d000b4f9..449a122fe4 100644 --- a/src/routes/preHandlers/subPrograms.js +++ b/src/routes/preHandlers/subPrograms.js @@ -213,9 +213,13 @@ exports.authorizeSubProgramUpdate = async (req) => { 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 86ea596fe5..50f21e8984 100644 --- a/src/routes/subPrograms.js +++ b/src/routes/subPrograms.js @@ -85,7 +85,7 @@ exports.plugin = { }), elearningPrice: Joi.number().positive(), elearningLimit: durationStrictlyPositive - .when('elearningPrice', { not: Joi.exist(), then: Joi.forbidden() }), + .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 d82855039b..10cfe0aa7b 100644 --- a/tests/integration/subPrograms.test.js +++ b/tests/integration/subPrograms.test.js @@ -550,6 +550,19 @@ describe('SUBPROGRAMS ROUTES - PUT /subprograms/{_id}', () => { 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 }] } }; From 41f936051df8e527dbbcfeddc8aff3bf34d06a29 Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 16 Nov 2026 11:12:22 +0100 Subject: [PATCH 46/53] COM-4328 : notifications --- src/helpers/notifications.js | 25 ++++++++------ tests/unit/helpers/notifications.test.js | 43 ++++++++++++------------ 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/src/helpers/notifications.js b/src/helpers/notifications.js index 31dc77d083..1a8c2cc4b2 100644 --- a/src/helpers/notifications.js +++ b/src/helpers/notifications.js @@ -11,6 +11,7 @@ const { TRAINER_ATTENDANCE_REMINDER, } = require('./constants'); +const EXPO_BATCH_SIZE = 100; const EXPO_NOTIFICATION_API_URL = 'https://exp.host/--/api/v2/push/send/'; exports.sendNotificationToAPI = async payload => axios.post(`${EXPO_NOTIFICATION_API_URL}`, payload); @@ -54,21 +55,25 @@ exports.sendNewElearningCourseNotification = async (courseId, query) => { const courseName = getCourseName(course); - const notifications = []; + const messages = []; for (const trainee of trainees) { for (const expoToken of trainee.formationExpoTokenList) { - notifications.push( - this.sendNotificationToUser({ - title: 'Une nouvelle formation est disponible', - body: `Découvrez notre nouvelle formation : ${courseName}.`, - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken, - }) - ); + messages.push({ + to: expoToken, + title: 'Une nouvelle formation est disponible', + body: `Découvrez notre nouvelle formation : ${courseName}.`, + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }); } } - await Promise.all(notifications); + for (let i = 0; i < messages.length; i += EXPO_BATCH_SIZE) { + try { + await this.sendNotificationToAPI(messages.slice(i, i + EXPO_BATCH_SIZE)); + } catch (e) { + console.error(e); + } + } }; exports.sendAttendanceSheetSignatureRequestNotification = diff --git a/tests/unit/helpers/notifications.test.js b/tests/unit/helpers/notifications.test.js index 5203aa8f64..d7d148e8a6 100644 --- a/tests/unit/helpers/notifications.test.js +++ b/tests/unit/helpers/notifications.test.js @@ -153,23 +153,23 @@ describe('sendBlendedCourseRegistrationNotification', () => { }); describe('sendNewElearningCourseNotification', () => { - let sendNotificationToUser; + let sendNotificationToAPI; let courseFindOne; let userFind; beforeEach(() => { - sendNotificationToUser = sinon.stub(NotificationHelper, 'sendNotificationToUser'); + sendNotificationToAPI = sinon.stub(NotificationHelper, 'sendNotificationToAPI'); courseFindOne = sinon.stub(Course, 'findOne'); userFind = sinon.stub(User, 'find'); }); afterEach(() => { - sendNotificationToUser.restore(); + sendNotificationToAPI.restore(); courseFindOne.restore(); userFind.restore(); }); - it('should format payload and call sendNotificationToUser', async () => { + it('should format payload and call sendNotificationToAPI', async () => { const trainees = [{ formationExpoTokenList: ['ExponentPushToken[jeSuisUnTokenExpo]', 'ExponentPushToken[jeSuisUnAutreTokenExpo]'], }]; @@ -212,23 +212,22 @@ describe('sendNewElearningCourseNotification', () => { { query: 'lean', args: [] }, ] ); - sinon.assert.calledWithExactly( - sendNotificationToUser.getCall(0), - { - title: 'Une nouvelle formation est disponible', - body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken: 'ExponentPushToken[jeSuisUnTokenExpo]', - } - ); - sinon.assert.calledWithExactly( - sendNotificationToUser.getCall(1), - { - title: 'Une nouvelle formation est disponible', - body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken: 'ExponentPushToken[jeSuisUnAutreTokenExpo]', - } + sinon.assert.calledOnceWithExactly( + sendNotificationToAPI, + [ + { + to: 'ExponentPushToken[jeSuisUnTokenExpo]', + title: 'Une nouvelle formation est disponible', + body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }, + { + to: 'ExponentPushToken[jeSuisUnAutreTokenExpo]', + title: 'Une nouvelle formation est disponible', + body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }, + ] ); }); @@ -271,7 +270,7 @@ describe('sendNewElearningCourseNotification', () => { { query: 'lean', args: [] }, ] ); - sinon.assert.notCalled(sendNotificationToUser); + sinon.assert.notCalled(sendNotificationToAPI); }); }); From f04d855ff6dc4cb6f393a363748fa6288dab1eac Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 16 Nov 2026 11:12:36 +0100 Subject: [PATCH 47/53] COM-4328 : access rules --- src/helpers/subPrograms.js | 5 +++-- tests/unit/helpers/subPrograms.test.js | 22 +++++++++++++++++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 394ee4e411..c16dd3a3ad 100644 --- a/src/helpers/subPrograms.js +++ b/src/helpers/subPrograms.js @@ -162,6 +162,7 @@ exports.updateSubProgram = async (subProgramId, payload) => { .findOne({ subProgram: { $in: otherSubProgramList }, type: INTER_B2C, format: STRICTLY_E_LEARNING }) .lean(); let courseId; + const accessCompanies = existingCourse ? existingCourse.accessRules : payload.accessCompanies; if (existingCourse) { courseId = existingCourse._id; await updateExistingElearningCourse(existingCourse._id, subProgramId); @@ -176,11 +177,11 @@ exports.updateSubProgram = async (subProgramId, payload) => { courseId = course._id; } query = { formationExpoTokenList: { $exists: true, $not: { $size: 0 } } }; - if (payload.accessCompanies) { + if (accessCompanies && accessCompanies.length) { const userCompanies = await UserCompany .find( { - company: { $in: payload.accessCompanies }, + company: { $in: accessCompanies }, $or: [{ endDate: { $gt: CompaniDate().toISO() } }, { endDate: { $exists: false } }], }, { user: 1 } diff --git a/tests/unit/helpers/subPrograms.test.js b/tests/unit/helpers/subPrograms.test.js index aa82ae32dc..84b3000e9d 100644 --- a/tests/unit/helpers/subPrograms.test.js +++ b/tests/unit/helpers/subPrograms.test.js @@ -472,11 +472,13 @@ describe('updateSubProgram', () => { ], program: { name: 'nom', subPrograms: programSubPrograms }, }; + const userId = new ObjectId(); const existingCourse = { _id: new ObjectId(), subProgram: otherSubProgramId, accessRules: [new ObjectId()] }; findOneAndUpdate.returns(SinonMongoose.stubChainedQueries(updatedSubProgram)); stepUpdateManyStub.returns({ activities }); courseFindOne.returns(SinonMongoose.stubChainedQueries(existingCourse, ['lean'])); + userCompanyFind.returns(SinonMongoose.stubChainedQueries([{ user: userId }], ['lean'])); await SubProgramHelper.updateSubProgram(subProgram._id, payload); @@ -496,14 +498,28 @@ describe('updateSubProgram', () => { { $set: { subProgram: subProgram._id } } ); sinon.assert.notCalled(courseCreateStub); - sinon.assert.notCalled(find); sinon.assert.notCalled(updateOne); + SinonMongoose.calledOnceWithExactly( + userCompanyFind, + [ + { + query: 'find', + args: [ + { + company: { $in: existingCourse.accessRules }, + $or: [{ endDate: { $gt: '2025-03-31T14:00:00.000Z' } }, { endDate: { $exists: false } }], + }, + { user: 1 }, + ], + }, + { query: 'lean' }, + ] + ); sinon.assert.calledWithExactly( sendNewElearningCourseNotification, existingCourse._id, - { formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } + { _id: { $in: [userId] }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); - sinon.assert.notCalled(userCompanyFind); sinon.assert.notCalled(getLastVersion); sinon.assert.notCalled(findOne); }); From e7c41909aaca54c11a046cb13a4a470407bfea73 Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 17 Nov 2026 17:52:53 +0100 Subject: [PATCH 48/53] COM-4328: fix bug --- src/helpers/courses.js | 10 +++++++- tests/unit/helpers/courses.test.js | 38 ++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 6d428c5496..cf258b2661 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -1869,7 +1869,15 @@ exports.generateCompletionCertificates = async (courseId, credentials, query) => }; exports.addAccessRule = async (courseId, payload) => { - await Course.updateOne({ _id: courseId }, { $addToSet: { accessRules: payload.companies } }); + const course = await Course + .findOneAndUpdate( + { _id: courseId }, + { $addToSet: { accessRules: payload.companies } }, + { projection: { subProgram: 1 } } + ) + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); + if (course.subProgram.archivedAt) return; const userCompanies = await UserCompany .find( diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 0ce3540e33..ac25274421 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -9003,17 +9003,17 @@ describe('generateCompletionCertificates', () => { }); describe('addAccessRule', () => { - let updateOne; + let findOneAndUpdate; let userCompanyFind; let sendNewElearningCourseNotification; beforeEach(() => { - updateOne = sinon.stub(Course, 'updateOne'); + findOneAndUpdate = sinon.stub(Course, 'findOneAndUpdate'); userCompanyFind = sinon.stub(UserCompany, 'find'); sendNewElearningCourseNotification = sinon.stub(NotificationHelper, 'sendNewElearningCourseNotification'); }); afterEach(() => { - updateOne.restore(); + findOneAndUpdate.restore(); userCompanyFind.restore(); sendNewElearningCourseNotification.restore(); }); @@ -9026,10 +9026,25 @@ describe('addAccessRule', () => { { user: userIds[0], company: payload.companies[0] }, { user: userIds[1], company: payload.companies[1] }, ]; + findOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId() } })); userCompanyFind.returns(SinonMongoose.stubChainedQueries(userCompanies, ['lean'])); await CourseHelper.addAccessRule(courseId, payload); - sinon.assert.calledOnceWithExactly(updateOne, { _id: courseId }, { $addToSet: { accessRules: payload.companies } }); + SinonMongoose.calledOnceWithExactly( + findOneAndUpdate, + [ + { + query: 'findOneAndUpdate', + args: [ + { _id: courseId }, + { $addToSet: { accessRules: payload.companies } }, + { projection: { subProgram: 1 } }, + ], + }, + { query: 'populate', args: [{ path: 'subProgram', select: 'archivedAt' }] }, + { query: 'lean' }, + ] + ); SinonMongoose.calledOnceWithExactly( userCompanyFind, [ @@ -9051,6 +9066,21 @@ describe('addAccessRule', () => { { _id: { $in: userIds }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); }); + + it('should add access rule but not notify if subProgram is archived', async () => { + const courseId = new ObjectId(); + const payload = { companies: [new ObjectId()] }; + findOneAndUpdate.returns( + SinonMongoose + .stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId(), archivedAt: '2025-01-01T12:30:00' } }) + ); + + await CourseHelper.addAccessRule(courseId, payload); + + sinon.assert.calledOnce(findOneAndUpdate); + sinon.assert.notCalled(userCompanyFind); + sinon.assert.notCalled(sendNewElearningCourseNotification); + }); }); describe('deleteAccessRule', () => { From 43e0bc3e469c402d1a5fe3ee6fce1e2ce609f4aa Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 18 Nov 2026 15:01:11 +0100 Subject: [PATCH 49/53] COM-4331: detail tests --- tests/unit/helpers/hourlyPaymentPlans.test.js | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js index 07fc1ab070..4886a22480 100644 --- a/tests/unit/helpers/hourlyPaymentPlans.test.js +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -36,23 +36,43 @@ describe('getPricesFromDurations', () => { expect(result.elearning.duration.asMinutes()).toBe(90); }); - it('should cap the billed e-learning with the limit of the plan (real duration, capped price)', () => { + 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 })); - const limitAlreadyReached = HourlyPaymentPlansHelper - .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 12 })); - expect(noPreviousDuration.elearning.price).toBe('60'); - expect(limitNotReached.elearning.price).toBe('60'); 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'); }); From 137dbfb47dc777239e23d6bcebc6f4902eb3c763 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 18 Nov 2026 14:22:01 +0100 Subject: [PATCH 50/53] COM-4328: review --- src/helpers/courses.js | 12 ++----- src/routes/preHandlers/courses.js | 11 +++++-- tests/integration/courses.test.js | 23 +++++++++++++- tests/integration/seed/coursesSeed.js | 16 ++++++++++ tests/unit/helpers/courses.test.js | 46 +++++---------------------- 5 files changed, 57 insertions(+), 51 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index cf258b2661..7725dcca36 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -587,7 +587,7 @@ const getCourseForOperations = async (courseId, credentials, origin) => { }, { path: 'subProgram', - select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans' : 'program steps', + select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans archivedAt' : 'program steps', populate: [ { path: 'program', select: 'learningGoals' }, ...(origin === WEBAPP @@ -1869,15 +1869,7 @@ exports.generateCompletionCertificates = async (courseId, credentials, query) => }; exports.addAccessRule = async (courseId, payload) => { - const course = await Course - .findOneAndUpdate( - { _id: courseId }, - { $addToSet: { accessRules: payload.companies } }, - { projection: { subProgram: 1 } } - ) - .populate({ path: 'subProgram', select: 'archivedAt' }) - .lean(); - if (course.subProgram.archivedAt) return; + await Course.updateOne({ _id: courseId }, { $addToSet: { accessRules: payload.companies } }); const userCompanies = await UserCompany .find( diff --git a/src/routes/preHandlers/courses.js b/src/routes/preHandlers/courses.js index dc4cb9ed84..a892245220 100644 --- a/src/routes/preHandlers/courses.js +++ b/src/routes/preHandlers/courses.js @@ -601,8 +601,11 @@ exports.authorizeGetCourse = async (req) => { }; exports.authorizeAccessRuleAddition = async (req) => { - const course = await Course.findById(req.params._id, 'accessRules').lean(); + const course = await Course.findById(req.params._id, 'accessRules subProgram') + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); if (!course) throw Boom.notFound(); + if (course.subProgram.archivedAt) throw Boom.forbidden(); const accessRuleAlreadyExist = req.payload.companies .some(companyId => UtilsHelper.doesArrayIncludeId(course.accessRules, companyId)); @@ -615,9 +618,13 @@ exports.authorizeAccessRuleAddition = async (req) => { }; exports.authorizeAccessRuleDeletion = async (req) => { - const course = await Course.countDocuments({ _id: req.params._id, accessRules: req.params.accessRuleId }); + const course = await Course + .findOne({ _id: req.params._id, accessRules: req.params.accessRuleId }, 'subProgram') + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); if (!course) throw Boom.notFound(); + if (course.subProgram.archivedAt) throw Boom.forbidden(); return null; }; diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 29c24e7d43..06ab7d2f6c 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -1020,7 +1020,7 @@ describe('COURSES ROUTES - GET /courses', () => { }); expect(response.statusCode).toBe(200); - expect(response.result.data.courses.length).toEqual(4); + expect(response.result.data.courses.length).toEqual(5); }); it('should get all trainee courses (pedagogy webapp)', async () => { @@ -5092,6 +5092,17 @@ describe('COURSES ROUTES - POST /:_id/accessrules', () => { expect(response.statusCode).toBe(409); }); + it('should return 403 if subProgram is archived', async () => { + const response = await app.inject({ + method: 'POST', + url: `/courses/${coursesList[28]._id}/accessrules`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { companies: [otherCompany._id] }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 404 if company does not exist', async () => { const response = await app.inject({ method: 'POST', @@ -5172,6 +5183,16 @@ describe('COURSES ROUTES - DELETE /:_id/accessrules/:accessRuleId', () => { expect(response.statusCode).toBe(404); }); + it('should return 403 if subProgram is archived', async () => { + const response = await app.inject({ + method: 'DELETE', + url: `/courses/${coursesList[28]._id}/accessrules/${authCompany._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 404 if accessRules doesn\'t exist', async () => { const response = await app.inject({ method: 'DELETE', diff --git a/tests/integration/seed/coursesSeed.js b/tests/integration/seed/coursesSeed.js index c6ba003827..21c8aba662 100644 --- a/tests/integration/seed/coursesSeed.js +++ b/tests/integration/seed/coursesSeed.js @@ -369,6 +369,13 @@ const subProgramsList = [ sheetTemplateId: 'templateId', folderId: 'parent_folderId', }, + { + _id: new ObjectId(), + name: 'sous-programme archivé', + steps: [stepList[1]._id], + status: PUBLISHED, + archivedAt: '2021-01-01T00:00:00.000Z', + }, ]; const programsList = [ @@ -832,6 +839,15 @@ const coursesList = [ }, ], }, + { // 28 eLearning course with archived subProgram + _id: new ObjectId(), + subProgram: subProgramsList[5]._id, + type: INTER_B2C, + format: STRICTLY_E_LEARNING, + trainees: [], + accessRules: [authCompany._id], + tradeName: 'nom', + }, ]; const courseBillsList = [ diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index ac25274421..50827cb716 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -2889,7 +2889,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3009,7 +3009,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3118,7 +3118,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3301,7 +3301,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -9003,17 +9003,17 @@ describe('generateCompletionCertificates', () => { }); describe('addAccessRule', () => { - let findOneAndUpdate; + let updateOne; let userCompanyFind; let sendNewElearningCourseNotification; beforeEach(() => { - findOneAndUpdate = sinon.stub(Course, 'findOneAndUpdate'); + updateOne = sinon.stub(Course, 'updateOne'); userCompanyFind = sinon.stub(UserCompany, 'find'); sendNewElearningCourseNotification = sinon.stub(NotificationHelper, 'sendNewElearningCourseNotification'); }); afterEach(() => { - findOneAndUpdate.restore(); + updateOne.restore(); userCompanyFind.restore(); sendNewElearningCourseNotification.restore(); }); @@ -9026,25 +9026,10 @@ describe('addAccessRule', () => { { user: userIds[0], company: payload.companies[0] }, { user: userIds[1], company: payload.companies[1] }, ]; - findOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId() } })); userCompanyFind.returns(SinonMongoose.stubChainedQueries(userCompanies, ['lean'])); await CourseHelper.addAccessRule(courseId, payload); - SinonMongoose.calledOnceWithExactly( - findOneAndUpdate, - [ - { - query: 'findOneAndUpdate', - args: [ - { _id: courseId }, - { $addToSet: { accessRules: payload.companies } }, - { projection: { subProgram: 1 } }, - ], - }, - { query: 'populate', args: [{ path: 'subProgram', select: 'archivedAt' }] }, - { query: 'lean' }, - ] - ); + sinon.assert.calledOnceWithExactly(updateOne, { _id: courseId }, { $addToSet: { accessRules: payload.companies } }); SinonMongoose.calledOnceWithExactly( userCompanyFind, [ @@ -9066,21 +9051,6 @@ describe('addAccessRule', () => { { _id: { $in: userIds }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); }); - - it('should add access rule but not notify if subProgram is archived', async () => { - const courseId = new ObjectId(); - const payload = { companies: [new ObjectId()] }; - findOneAndUpdate.returns( - SinonMongoose - .stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId(), archivedAt: '2025-01-01T12:30:00' } }) - ); - - await CourseHelper.addAccessRule(courseId, payload); - - sinon.assert.calledOnce(findOneAndUpdate); - sinon.assert.notCalled(userCompanyFind); - sinon.assert.notCalled(sendNewElearningCourseNotification); - }); }); describe('deleteAccessRule', () => { From a86ccee0f06abf5d494b34cd3c3061f0e3d99dd7 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Wed, 18 Nov 2026 18:33:15 +0100 Subject: [PATCH 51/53] COM-4333 - fix status in paymentExport --- src/helpers/constants.js | 1 + tests/integration/exports.test.js | 1 + tests/integration/seed/exportsSeed.js | 13 +++++++++++- .../unit/helpers/vendorHistoryExport.test.js | 21 ++++++++++++++++++- 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/helpers/constants.js b/src/helpers/constants.js index 6a40fe2185..788bbe2b93 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -224,6 +224,7 @@ module.exports = { [this.RECEIVED]: 'Reçu', [this.XML_GENERATED]: 'Fichier XML associé', [this.PAID]: 'Réglé', + [this.CANCELLED]: 'Annulé', }; }, NOT_INVOICED: 'not_invoiced', diff --git a/tests/integration/exports.test.js b/tests/integration/exports.test.js index 70650b5344..6820071232 100644 --- a/tests/integration/exports.test.js +++ b/tests/integration/exports.test.js @@ -200,6 +200,7 @@ const vendorHistoryExportTypes = [ `"Paiement";"REG-00001";"09/03/2022";"FACT-00001";${authCompany._id};1;"Prélèvement";"1100,00";"Fichier XML associé";"Prélèvements Septembre 2025";"14/03/2022";`, `"Paiement";"REG-00003";"09/03/2022";"FACT-00005";${courseFundingOrganisation._id};1;"Espèces";"300,00";"Reçu";;;`, `"Paiement";"REG-00006";"01/04/2022";"FACT-00001";${authCompany._id};2;"Prélèvement";"50,00";"En attente";;;`, + `"Paiement";"REG-00007";"10/03/2022";"FACT-00002";${courseFundingOrganisation._id};1;"Prélèvement";"1200,00";"Annulé";;;`, `"Remboursement";"REMB-00001";"11/03/2022";"FACT-00005";${courseFundingOrganisation._id};2;"Chèque";"200,00";"Reçu";;;`, ], query: 'startDate=2022-03-01T10:00:00.000Z&endDate=2022-04-20T10:00:00.000Z', diff --git a/tests/integration/seed/exportsSeed.js b/tests/integration/seed/exportsSeed.js index 8bebb63e35..fffe893851 100644 --- a/tests/integration/seed/exportsSeed.js +++ b/tests/integration/seed/exportsSeed.js @@ -97,6 +97,7 @@ const { PENDING, RECEIVED, XML_GENERATED, + CANCELLED, BANK_TRANSFER, PRESENT, MISSING, @@ -1462,7 +1463,7 @@ const courseFundingOrganisation = { const courseBillNumber = { _id: new ObjectId(), seq: 8 }; const courseCreditNoteNumber = { _id: new ObjectId(), seq: 2 }; const coursePaymentNumber = [ - { _id: new ObjectId(), seq: 6, nature: PAYMENT }, + { _id: new ObjectId(), seq: 7, nature: PAYMENT }, { _id: new ObjectId(), seq: 4, nature: REFUND }, ]; @@ -1664,6 +1665,16 @@ const coursePaymentList = [ type: DIRECT_DEBIT, status: PENDING, }, + { // 10 cancelled because of creditNote + number: 'REG-00007', + date: '2022-03-10T00:00:00.000Z', + companies: [authCompany._id], + courseBill: courseBillList[1]._id, + netInclTaxes: 1200, + nature: PAYMENT, + type: DIRECT_DEBIT, + status: CANCELLED, + }, ]; const xmlSEPAFileInfos = { diff --git a/tests/unit/helpers/vendorHistoryExport.test.js b/tests/unit/helpers/vendorHistoryExport.test.js index 00a762e12b..f35b4969d7 100644 --- a/tests/unit/helpers/vendorHistoryExport.test.js +++ b/tests/unit/helpers/vendorHistoryExport.test.js @@ -22,6 +22,7 @@ const { VENDOR_ADMIN, NO_DATA, CHECK, + DIRECT_DEBIT, REFUND, ESTIMATED_START_DATE_EDITION, WEBAPP, @@ -32,6 +33,7 @@ const { RECEIVED, PENDING, PAID, + CANCELLED, PRESENT, MISSING, DRAFT, @@ -2918,7 +2920,7 @@ describe('exportCoursePaymentHistory', () => { }); it('should return an array with the header and 3 rows', async () => { - const courseBillIds = [new ObjectId(), new ObjectId()]; + const courseBillIds = [new ObjectId(), new ObjectId(), new ObjectId()]; const payerId = new ObjectId(); const coursePaymentList = [ { @@ -2967,6 +2969,21 @@ describe('exportCoursePaymentHistory', () => { netInclTaxes: 200, status: RECEIVED, }, + { + _id: new ObjectId(), + nature: PAYMENT, + number: 'REG-5', + date: '2022-01-15T23:00:00.000Z', + courseBill: { + _id: courseBillIds[2], + number: 'FACT-3', + payer: { _id: payerId }, + course: { type: INTRA, trainees: [{ _id: new ObjectId(), identity: { firstname: 'Archie', lastname: 'Pelle' } }] }, + }, + type: DIRECT_DEBIT, + netInclTaxes: 50, + status: CANCELLED, + }, ]; findCoursePayment .onCall(0) @@ -2975,6 +2992,7 @@ describe('exportCoursePaymentHistory', () => { [ { _id: coursePaymentList[0], courseBill: courseBillIds[0] }, { _id: coursePaymentList[2], courseBill: courseBillIds[1] }, + { _id: coursePaymentList[3], courseBill: courseBillIds[2] }, ], ['setOptions', 'lean']) ); @@ -2986,6 +3004,7 @@ describe('exportCoursePaymentHistory', () => { ['Nature', 'Identifiant', 'Date', 'Facture associée', 'Id payeur facture', 'Numéro du paiement (parmi ceux de la même facture)', 'Moyen de paiement', 'Montant', 'Statut', 'Nom de lot fichier XML', 'Date d\'effet du prélèvement', 'Apprenant'], ['Remboursement', 'REG-2', '23/01/2022', 'FACT-2', payerId, 2, 'Chèque', '22,00', 'Reçu', 'LOT-002', '22/01/2022', 'Archie PELLE'], ['Remboursement', 'REG-4', '11/01/2022', 'FACT-1', payerId, 1, 'Chèque', '200,00', 'Reçu', '', '', ''], + ['Paiement', 'REG-5', '16/01/2022', 'FACT-3', payerId, 1, 'Prélèvement', '50,00', 'Annulé', '', '', ''], ]); SinonMongoose.calledWithExactly( findCoursePayment, From fe2b247b7c97ab3e5d486a7dc7863a575bf9c290 Mon Sep 17 00:00:00 2001 From: ulysse Date: Thu, 19 Nov 2026 10:49:03 +0100 Subject: [PATCH 52/53] COM-4331: display billed duration --- src/helpers/hourlyPaymentPlans.js | 4 ++-- tests/unit/helpers/hourlyPaymentPlans.test.js | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/helpers/hourlyPaymentPlans.js b/src/helpers/hourlyPaymentPlans.js index af1551021b..063f38fe2a 100644 --- a/src/helpers/hourlyPaymentPlans.js +++ b/src/helpers/hourlyPaymentPlans.js @@ -29,8 +29,8 @@ exports.getPricesFromDurations = ( billableELearningDuration = remainingDuration.isShorterThan(PT0S) ? CompaniDuration(PT0S) : remainingDuration; } } - const eLearning = hourlyPaymentPlan.elearningPrice && { - duration: eLearningMonthDuration, + const eLearning = hourlyPaymentPlan.elearningPrice && !billableELearningDuration.isEquivalentTo(PT0S) && { + duration: billableELearningDuration, price: NumbersHelper.multiply(billableELearningDuration.asHours(), hourlyPaymentPlan.elearningPrice), }; diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js index 4886a22480..38605b3e4d 100644 --- a/tests/unit/helpers/hourlyPaymentPlans.test.js +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -64,16 +64,16 @@ describe('getPricesFromDurations', () => { .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 8 })); expect(limitReachedThisMonth.elearning.price).toBe('40'); - expect(limitReachedThisMonth.elearning.duration.asHours()).toBe(3); + expect(limitReachedThisMonth.elearning.duration.asHours()).toBe(2); }); - it('should not bill e-learning if limit already reached', () => { + it('should not return e-learning line 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'); + expect(limitAlreadyReached.elearning).toBeUndefined(); }); it('should not return e-learning line if there is no e-learning price', () => { From 1f05524f265ed4a934af88ba88212bd645ad1d07 Mon Sep 17 00:00:00 2001 From: Manon Palin Date: Thu, 19 Nov 2026 11:52:20 +0100 Subject: [PATCH 53/53] COM-4329 - flag old archived courses to paid --- src/helpers/courses.js | 23 +++----- tests/unit/helpers/courses.test.js | 89 +++++++++++------------------- 2 files changed, 41 insertions(+), 71 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 7f6787cea5..2230f6611c 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -2330,9 +2330,9 @@ exports.getCourseTrainerSalary = (course) => { return salary ? NumbersHelper.toNumber(NumbersHelper.multiply(salary.price, salary.count)) : undefined; }; -// Trainer billing was not tracked in the app before October 1st, 2026: -// courses ended before this date are considered as paid -const TRAINER_PAYMENTS_START_DATE = '2026-09-30T22:00:00.000Z'; +// Trainer billing was not tracked in the app before September 1st, 2026: +// courses archived before this date are considered as paid +const TRAINER_PAYMENTS_START_DATE = '2026-08-31T22:00:00.000Z'; exports.listTrainersBilling = async (query) => { let courseIdsWithSlotsOrBillsInPeriod; @@ -2356,7 +2356,7 @@ exports.listTrainersBilling = async (query) => { ...(query.trainer ? { trainers: query.trainer } : { 'trainers.0': { $exists: true } }), type: { $nin: [SINGLE, INTER_B2C] }, }, - { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 } + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 } ) .populate({ path: 'companies', select: 'name' }) .populate({ path: 'subProgram', select: 'program', populate: { path: 'program', select: 'name' } }) @@ -2375,14 +2375,6 @@ exports.listTrainersBilling = async (query) => { .lean(); const billsByTrainerAndCourse = groupBy(trainerBills, bill => `${bill.trainer}-${bill.course}`); - const courseSlots = await CourseSlot - .find({ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }) - .lean(); - const isCourseEndedBeforePaymentsStart = mapValues( - groupBy(courseSlots, 'course'), - slots => slots.every(slot => slot.endDate && CompaniDate(slot.endDate).isBefore(TRAINER_PAYMENTS_START_DATE)) - ); - const trainers = query.trainer ? [courses[0].trainers.find(t => UtilsHelper.areObjectIdsEquals(t._id, query.trainer))] : uniqBy(courses.flatMap(c => c.trainers), t => t._id.toHexString()); @@ -2407,8 +2399,11 @@ exports.listTrainersBilling = async (query) => { invoicedAmount = NumbersHelper.toNumber(invoicedAmount); paidAmount = NumbersHelper.toNumber(paidAmount); + const isArchivedBeforePaymentsStart = !!course.archivedAt && + CompaniDate(course.archivedAt).isBefore(TRAINER_PAYMENTS_START_DATE); + let status = INVOICED; - if (isCourseEndedBeforePaymentsStart[course._id]) status = PAID; + if (isArchivedBeforePaymentsStart) status = PAID; else if (NumbersHelper.isEqualTo(invoicedAmount, 0)) status = NOT_INVOICED; else if (plannedSalary !== undefined && NumbersHelper.isLessThan(invoicedAmount, plannedSalary)) { status = PARTIALLY_INVOICED; @@ -2417,7 +2412,7 @@ exports.listTrainersBilling = async (query) => { } trainerCourses.push({ - ...omit(course, ['billingPurchaseList']), + ...omit(course, ['billingPurchaseList', 'archivedAt']), ...(plannedSalary !== undefined && { plannedSalary }), invoicedAmount, paidAmount, diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 4b7669a984..300d1d57e2 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -11487,7 +11487,6 @@ describe('listTrainersBilling', () => { courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); - courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11526,7 +11525,7 @@ describe('listTrainersBilling', () => { query: 'find', args: [ { trainers: trainerId, type: { $nin: ['single', 'inter_b2c'] } }, - { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, ], }, { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, @@ -11554,27 +11553,36 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); - SinonMongoose.calledOnceWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }], - }, - { query: 'lean' }, - ] - ); + sinon.assert.notCalled(courseSlotFind); }); - it('should consider courses ended before trainer payments start as paid', async () => { + it('should consider courses archived before trainer payments start as paid', async () => { const trainerId = new ObjectId(); const trainer = { _id: trainerId, identity: { firstname: 'Jean', lastname: 'Dupont' } }; const billingPurchaseList = [{ billingItem: { type: TRAINER_SALARY }, price: 100, count: 1 }]; const courses = [ - { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended before', billingPurchaseList }, - { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended after with bill', billingPurchaseList }, - { _id: new ObjectId(), trainers: [trainer], tradeName: 'ended after', billingPurchaseList }, - { _id: new ObjectId(), trainers: [trainer], tradeName: 'with slot to plan', billingPurchaseList }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'archived before', + billingPurchaseList, + archivedAt: '2026-08-31T21:00:00.000Z', + }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'archived after with bill', + billingPurchaseList, + archivedAt: '2026-09-01T08:00:00.000Z', + }, + { + _id: new ObjectId(), + trainers: [trainer], + tradeName: 'archived on september 1st', + billingPurchaseList, + archivedAt: '2026-08-31T22:00:00.000Z', + }, + { _id: new ObjectId(), trainers: [trainer], tradeName: 'not archived', billingPurchaseList }, ]; const trainerBills = [ { @@ -11585,19 +11593,9 @@ describe('listTrainersBilling', () => { submittedAt: '2024-01-01T08:00:00.000Z', }, ]; - const courseSlots = [ - { course: courses[0]._id, endDate: '2026-09-01T10:00:00.000Z' }, - { course: courses[0]._id, endDate: '2026-09-30T21:00:00.000Z' }, - { course: courses[1]._id, endDate: '2026-11-01T10:00:00.000Z' }, - { course: courses[2]._id, endDate: '2026-09-01T10:00:00.000Z' }, - { course: courses[2]._id, endDate: '2026-10-01T08:00:00.000Z' }, - { course: courses[3]._id, endDate: '2026-09-01T10:00:00.000Z' }, - { course: courses[3]._id }, - ]; courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); - courseSlotFind.returns(SinonMongoose.stubChainedQueries(courseSlots, ['lean'])); const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); @@ -11605,21 +11603,21 @@ describe('listTrainersBilling', () => { ...trainer, courses: [ { - ...omit(courses[0], ['billingPurchaseList']), + ...omit(courses[0], ['billingPurchaseList', 'archivedAt']), plannedSalary: 100, invoicedAmount: 0, paidAmount: 0, status: 'paid', }, { - ...omit(courses[1], ['billingPurchaseList']), + ...omit(courses[1], ['billingPurchaseList', 'archivedAt']), plannedSalary: 100, invoicedAmount: 40, paidAmount: 0, status: 'partially_invoiced', }, { - ...omit(courses[2], ['billingPurchaseList']), + ...omit(courses[2], ['billingPurchaseList', 'archivedAt']), plannedSalary: 100, invoicedAmount: 0, paidAmount: 0, @@ -11634,6 +11632,7 @@ describe('listTrainersBilling', () => { }, ], }]); + sinon.assert.notCalled(courseSlotFind); }); it('should only return courses with slots or trainer bills in period', async () => { @@ -11666,7 +11665,6 @@ describe('listTrainersBilling', () => { trainerBillFind.onCall(0).returns(SinonMongoose.stubChainedQueries(trainerBillsInPeriod, ['lean'])); courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); trainerBillFind.onCall(1).returns(SinonMongoose.stubChainedQueries([])); - courseSlotFind.onCall(1).returns(SinonMongoose.stubChainedQueries([], ['lean'])); const result = await CourseHelper.listTrainersBilling(query); @@ -11697,20 +11695,6 @@ describe('listTrainersBilling', () => { ], 0 ); - SinonMongoose.calledWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [ - { course: { $in: [courses[0]._id, courses[1]._id] } }, - { course: 1, endDate: 1 }, - ], - }, - { query: 'lean' }, - ], - 1 - ); SinonMongoose.calledWithExactly( trainerBillFind, [ @@ -11736,7 +11720,7 @@ describe('listTrainersBilling', () => { trainers: trainerId, type: { $nin: ['single', 'inter_b2c'] }, }, - { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, ], }, { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, @@ -11851,7 +11835,7 @@ describe('listTrainersBilling', () => { query: 'find', args: [ { 'trainers.0': { $exists: true }, type: { $nin: ['single', 'inter_b2c'] } }, - { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1 }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, ], }, { query: 'populate', args: [{ path: 'companies', select: 'name' }] }, @@ -11876,15 +11860,6 @@ describe('listTrainersBilling', () => { { query: 'lean' }, ] ); - SinonMongoose.calledOnceWithExactly( - courseSlotFind, - [ - { - query: 'find', - args: [{ course: { $in: courses.map(c => c._id) } }, { course: 1, endDate: 1 }], - }, - { query: 'lean' }, - ] - ); + sinon.assert.notCalled(courseSlotFind); }); });