diff --git a/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index ddb512d448..cb11d50a1c 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' }, ], }, ], @@ -236,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(); @@ -245,9 +246,26 @@ 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); - - await CourseBill.updateMany({ _id: { $in: bills.map(b => b._id) } }, { $set: { 'mainFee.price': price } }); + 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))); + + 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 } } + ); + })); } }; @@ -281,17 +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(), + 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 }, }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - { $set: { 'mainFee.price': 0 } } - ); + { '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/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..cbe7a43941 100644 --- a/tests/unit/helpers/completionCertificates.test.js +++ b/tests/unit/helpers/completionCertificates.test.js @@ -440,8 +440,9 @@ describe('generate', () => { let getELearningDuration; let getRealELearningDuration; let findBills; - let updateManyBills; - let getPriceFromDurations; + let updateOneBill; + let getPricesFromDurations; + let getPriceDetails; const PRI_SUBPROGRAM_IDS = new ObjectId(); const stepId = new ObjectId(); const REAL_ELEARNING_DURATION_SUBPROGRAM_ID = new ObjectId(); @@ -462,8 +463,9 @@ describe('generate', () => { 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'); + 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; process.env.PRI_SUBPROGRAM_IDS = PRI_SUBPROGRAM_IDS; process.env.REAL_ELEARNING_DURATION_SUBPROGRAM_IDS = REAL_ELEARNING_DURATION_SUBPROGRAM_ID; @@ -486,8 +488,9 @@ describe('generate', () => { getELearningDuration.restore(); getRealELearningDuration.restore(); findBills.restore(); - updateManyBills.restore(); - getPriceFromDurations.restore(); + updateOneBill.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', @@ -611,10 +623,11 @@ 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'] )); - 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' }, ], }, ], @@ -779,18 +792,30 @@ 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.calledOnceWithExactly(getPriceFromDurations, hourlyPaymentPlan, durationPerStep, 'PT3H30M'); sinon.assert.calledOnceWithExactly( - updateManyBills, - { _id: { $in: [billId] } }, - { $set: { 'mainFee.price': 260 } } + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT3H30M', + completionCertificate.course.subProgram.steps + ); + sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); + sinon.assert.calledOnceWithExactly( + updateOneBill, + { _id: billId }, + { + $set: { + 'mainFee.price': 260, + 'mainFee.description': 'Facture test\r\n--- Détail ---\r\nétape 1 - 6h30 - 260,00 €', + }, + } ); }); @@ -800,6 +825,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' }, @@ -832,6 +860,7 @@ describe('generate', () => { subProgram: { _id: subProgramIds[0], program: { subPrograms: subProgramIds }, + hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ { type: E_LEARNING, @@ -890,10 +919,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'); @@ -923,7 +956,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' }, ], }, ], @@ -1046,15 +1079,22 @@ 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(getPriceFromDurations); + sinon.assert.calledOnceWithExactly( + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT200S', + completionCertificate.course.subProgram.steps + ); + sinon.assert.notCalled(getPriceDetails); + sinon.assert.notCalled(updateOneBill); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { @@ -1188,7 +1228,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' }, ], }, ], @@ -1338,15 +1378,16 @@ 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(getPriceFromDurations); + sinon.assert.notCalled(updateOneBill); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); it('should generate completion certificate in VAE period (attendance exceeds remaining budget)', async () => { @@ -1485,7 +1526,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' }, ], }, ], @@ -1635,15 +1676,16 @@ 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(getPriceFromDurations); + sinon.assert.notCalled(updateOneBill); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); it('should generate completion certificate normally when VAE period budget is exhausted', async () => { @@ -1779,7 +1821,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' }, ], }, ], @@ -1928,15 +1970,16 @@ 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(getPriceFromDurations); + sinon.assert.notCalled(updateOneBill); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); }); @@ -1966,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(); @@ -1981,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(), @@ -1996,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); @@ -2009,20 +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(), + 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(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, + { 'mainFee.description': 1 }, + ], }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - { $set: { 'mainFee.price': 0 } } + { 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); }); @@ -2031,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, @@ -2049,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]); @@ -2071,34 +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(), + 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(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, + { 'mainFee.description': 1 }, + ], }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - { $set: { 'mainFee.price': 0 } } + { 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(), + 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(), + }, + hourlyPaymentPlan: { $exists: true }, + billedAt: { $exists: false }, + }, + { 'mainFee.description': 1 }, + ], }, - hourlyPaymentPlan: { $exists: true }, - billedAt: { $exists: false }, - }, - { $set: { 'mainFee.price': 0 } } + { 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); }); }); 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€' + ); }); });