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/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/controllers/trainerBillController.js b/src/controllers/trainerBillController.js index e17f574070..19c54f25f0 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.auth.credentials); + + 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/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/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/src/helpers/completionCertificates.js b/src/helpers/completionCertificates.js index b1ac314836..a6f7240c0f 100644 --- a/src/helpers/completionCertificates.js +++ b/src/helpers/completionCertificates.js @@ -1,17 +1,20 @@ 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 groupBy = require('lodash/groupBy'); 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 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 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'); +const HourlyPaymentPlansHelper = require('./hourlyPaymentPlans'); +const CourseSlotsHelper = require('./courseSlots'); const CoursesHelper = require('./courses'); const GCloudStorageHelper = require('./gCloudStorage'); @@ -66,12 +69,32 @@ 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 }) @@ -88,13 +111,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -127,57 +147,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,24 +229,85 @@ exports.generate = async (completionCertificateId) => { updatePayload.vaeSupportRemainingMinutes = newVAESupportRemainingMinutes; } await CompletionCertificate.updateOne({ _id: completionCertificateId }, { $set: updatePayload }); + + const billsToUpdate = await CourseBill + .find( + { + course: course._id, + maturityDate: { $gte: startOfMonth, $lte: endOfMonth }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 } + ) + .setOptions({ isVendorUser: true }) + .lean(); + + 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)); + 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); + 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 + .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 } } + ); + })); + } }; exports.create = async payload => CompletionCertificate.create(payload); exports.deleteFile = async (completionCertificateId) => { 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, trainee, vaeSupportRemainingMinutes: { $lt: vaeSupportRemainingMinutes } }) .setOptions({ isVendorUser: true }) .lean(); - const certificateToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; + certificatesToDelete = [completionCertificate, ...completionCertificateWithRemainingMinutes]; await CompletionCertificate.updateMany( - { _id: { $in: certificateToDelete.map(c => c._id) } }, + { _id: { $in: certificatesToDelete.map(c => c._id) } }, { $unset: { file: '', vaeSupportRemainingMinutes: '' } } ); - for (const certificate of certificateToDelete) { + for (const certificate of certificatesToDelete) { await GCloudStorageHelper.deleteCourseFile(certificate.file.publicId); } } else { @@ -286,4 +318,33 @@ exports.deleteFile = async (completionCertificateId) => { await GCloudStorageHelper.deleteCourseFile(completionCertificate.file.publicId); } + + for (const certificate of certificatesToDelete) { + 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 }, + }, + { '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/constants.js b/src/helpers/constants.js index 6cce8c8048..788bbe2b93 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -224,11 +224,13 @@ module.exports = { [this.RECEIVED]: 'Reçu', [this.XML_GENERATED]: 'Fichier XML associé', [this.PAID]: 'Réglé', + [this.CANCELLED]: 'Annulé', }; }, 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/courseBills.js b/src/helpers/courseBills.js index 08826c5f70..9d2d9148b4 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'); @@ -148,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(); @@ -167,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 }) @@ -185,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 @@ -246,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 = {}; @@ -302,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); @@ -310,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), @@ -323,9 +351,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', + options: { sort: { startDate: 1 } }, + populate: { path: 'step', select: 'durationCountedPerTrainer' }, + }) + .populate({ + path: 'subProgram', + select: 'steps hourlyPaymentPlans', + populate: { path: 'steps', select: 'name activities type theoreticalDuration' }, + }) + .lean(); + + const dates = { startDate: course.slots[0].startDate, endDate: CompaniDate().toISO() }; + const { slotsWithAttendance, eLearningDuration } = await CoursesHelper + .getTraineeDurations(course, course.trainees[0], dates); + + const durationPerStep = CourseSlotsHelper.getDurationPerStep(slotsWithAttendance); + const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans + .find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId)); + + 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) => { 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, certificateGenerationMode: 1 } + ) .populate({ path: 'trainees', select: 'identity' }) .populate({ path: 'trainers', select: 'identity' }) .populate({ path: 'subProgram', select: 'subjectToVat' }) @@ -338,7 +402,23 @@ exports.createBillList = async (payload) => { } if (payload.quantity === 1) { - const billCreated = await CourseBill.create({ ...omit(payload, 'quantity'), ...vat && { vat } }); + const isGlobalCertificationCourseWithPriceFromDurations = payload.hourlyPaymentPlanId && + course.certificateGenerationMode === GLOBAL; + 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({ + ...omit(payload, ['quantity', 'hourlyPaymentPlanId']), + mainFee: { ...mainFee, ...Array.isArray(mainFeePrice) && { price: mainFeePrice[0] } }, + ...payload.hourlyPaymentPlanId && { hourlyPaymentPlan: payload.hourlyPaymentPlanId }, + ...vat && { vat }, + }); if (payload.mainFee.percentage) { const trainerFees = (course.prices || []).reduce((acc, price) => { @@ -398,8 +478,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/helpers/coursePayments.js b/src/helpers/coursePayments.js index 720dc4a803..14650b9dff 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,38 @@ 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(); + + const formattedPayments = 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 } }; + }); + + return formattedPayments; +}; exports.updateList = async payload => CoursePayment .updateMany({ _id: { $in: payload._ids } }, { $set: { status: payload.status } }); 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 19844f26a5..8b3cc3e698 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'); @@ -88,8 +89,13 @@ const { SECOND, MONTH, TRAINER_SALARY, + PARTIALLY_INVOICED, + NOT_INVOICED, + INVOICED, + PAID, VAEI_COACH, ARCHITECT, + INTER_B2C, } = require('./constants'); const CompaniesHelper = require('./companies'); const CourseHistoriesHelper = require('./courseHistories'); @@ -105,6 +111,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'); @@ -580,15 +587,18 @@ const getCourseForOperations = async (courseId, credentials, origin) => { }, { path: 'subProgram', - select: origin === WEBAPP ? 'program steps paymentPlans' : 'program steps', + select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans archivedAt' : 'program steps', 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' }] ), ], @@ -634,7 +644,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 }, + }, ] : []), ] @@ -1406,6 +1420,50 @@ exports.getRealELearningDuration = (activityHistories) => { return eLearningDuration; }; +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; + + 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 eLearningDuration = await exports.getTraineeELearningDuration(course, traineeId, dates); + + return { slotsWithAttendance, eLearningDuration }; +}; + const getTraineeInformations = ( trainee, courseAttendances, @@ -2260,3 +2318,116 @@ exports.deleteBillingPurchase = async (courseId, billingPurchaseId) => Course.up { _id: courseId }, { $pull: { billingPurchaseList: { _id: billingPurchaseId } } } ); + +exports.getCourseTrainerSalary = (course) => { + if (course.trainers.length !== 1) return undefined; + + 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 salary ? NumbersHelper.toNumber(NumbersHelper.multiply(salary.price, salary.count)) : undefined; +}; + +// 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; + if (query.startDate) { + const slotsInPeriod = await CourseSlot + .find({ startDate: { $gte: query.startDate }, endDate: { $lte: query.endDate } }, { course: 1 }) + .lean(); + 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( + { + ...(courseIdsWithSlotsOrBillsInPeriod && { _id: { $in: courseIdsWithSlotsOrBillsInPeriod } }), + ...(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, archivedAt: 1 } + ) + .populate({ path: 'companies', 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 trainerBills = await TrainerBill + .find( + { course: { $in: courses.map(c => c._id) }, ...(query.trainer && { trainer: query.trainer }) }, + { course: 1, amount: 1, trainer: 1, submittedAt: 1 } + ) + .populate({ path: 'payment', select: 'status' }) + .lean(); + const billsByTrainerAndCourse = groupBy(trainerBills, bill => `${bill.trainer}-${bill.course}`); + + 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 filteredTrainerCourses = courses + .filter(course => UtilsHelper.doesArrayIncludeId(course.trainers.map(t => t._id), trainer._id)); + + const trainerCourses = []; + for (const course of filteredTrainerCourses) { + const plannedSalary = exports.getCourseTrainerSalary(course); + 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); + billsSubmissionDates.push(bill.submittedAt); + } + invoicedAmount = NumbersHelper.toNumber(invoicedAmount); + paidAmount = NumbersHelper.toNumber(paidAmount); + + const isArchivedBeforePaymentsStart = !!course.archivedAt && + CompaniDate(course.archivedAt).isBefore(TRAINER_PAYMENTS_START_DATE); + + let status = INVOICED; + if (isArchivedBeforePaymentsStart) 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)) { + status = PAID; + } + + trainerCourses.push({ + ...omit(course, ['billingPurchaseList', 'archivedAt']), + ...(plannedSalary !== undefined && { plannedSalary }), + invoicedAmount, + paidAmount, + status, + ...(status === INVOICED && { billsSubmissionDates }), + }); + } + + trainersBilling.push({ ...trainer, courses: trainerCourses }); + } + + return trainersBilling; +}; diff --git a/src/helpers/hourlyPaymentPlans.js b/src/helpers/hourlyPaymentPlans.js new file mode 100644 index 0000000000..063f38fe2a --- /dev/null +++ b/src/helpers/hourlyPaymentPlans.js @@ -0,0 +1,43 @@ +const NumbersHelper = require('./numbers'); +const UtilsHelper = require('./utils'); +const { CompaniDuration } = require('./dates/companiDurations'); +const { SHORT_DURATION_H_MM, PT0S } = require('./constants'); + +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; + + const { name: stepName } = steps.find(step => UtilsHelper.areObjectIdsEquals(step._id, stepId)); + + const price = NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount); + + 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 && !billableELearningDuration.isEquivalentTo(PT0S) && { + duration: billableELearningDuration, + price: NumbersHelper.multiply(billableELearningDuration.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/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/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 644b9d545e..d2dda4041f 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'); @@ -125,6 +126,45 @@ exports.updateSubProgram = async (subProgramId, payload) => { return SubProgram.updateOne({ _id: subProgramId }, { $push: { paymentPlans: { prices } } }); } + 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 = { + $set: { + 'hourlyPaymentPlans.$.prices': prices, + ...elearningPrice && { 'hourlyPaymentPlans.$.elearningPrice': elearningPrice }, + ...elearningLimit && { 'hourlyPaymentPlans.$.elearningLimit': elearningLimit }, + }, + ...!elearningLimit && { $unset: { 'hourlyPaymentPlans.$.elearningLimit': '' } }, + }; + + return SubProgram.updateOne({ _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, updateQuery); + } + + if (hourlyPaymentPlanId && !prices.length) { + return SubProgram.updateOne( + { _id: subProgramId }, + { $pull: { hourlyPaymentPlans: { _id: hourlyPaymentPlanId } } } + ); + } + + return SubProgram.updateOne( + { _id: subProgramId }, + { + $push: { + hourlyPaymentPlans: { + prices, + ...elearningPrice && { elearningPrice }, + ...elearningLimit && { elearningLimit }, + }, + }, + } + ); + } + const subProgram = await SubProgram .findOneAndUpdate({ _id: subProgramId }, { $set: { status: payload.status } }) .populate({ path: 'steps', select: 'activities type' }) @@ -138,6 +178,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); @@ -152,11 +193,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/src/helpers/trainerBills.js b/src/helpers/trainerBills.js index 71a790a7f0..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, @@ -94,3 +95,9 @@ exports.createBill = async (payload, credentials) => { return trainerBill; }; + +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/helpers/trainerPayments.js b/src/helpers/trainerPayments.js index 547094bcfd..fa5e8cc6ff 100644 --- a/src/helpers/trainerPayments.js +++ b/src/helpers/trainerPayments.js @@ -1,22 +1,89 @@ 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]; - return TrainerPayment + const trainerPayments = await TrainerPayment .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 subProgram', + populate: [ + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], }) .populate({ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }) .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; + + const formattedTrainer = { ...omit(trainer, ['bic', 'iban']), hasBankDetails: !!(trainer.bic && trainer.iban) }; + if (!course) return { ...payment, trainerBill: { ...payment.trainerBill, trainer: formattedTrainer } }; + + const plannedSalary = CoursesHelper.getCourseTrainerSalary(course); + const formattedCourse = { + _id: course._id, + ...(plannedSalary && { + plannedSalary, + totalPaymentsAmount: totalPaymentsAmounts[`${course._id}-${trainer._id}`] || 0, + }), + }; + + return { + ...payment, + trainerBill: { + ...payment.trainerBill, + trainer: formattedTrainer, + course: formattedCourse, + }, + }; + }); + + return formattedPayments; }; exports.update = async (trainerPaymentId, payload) => TrainerPayment diff --git a/src/helpers/translate.js b/src/helpers/translate.js index 9a706ccf0f..489b7f3215 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -105,6 +105,13 @@ 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.', + 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.', /* Steps */ stepUpdated: 'Step updated.', @@ -226,6 +233,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.', @@ -260,6 +269,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.', @@ -482,6 +492,13 @@ 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.', + 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à.', /* Steps */ stepsFound: 'Liste des étapes trouvée.', @@ -607,6 +624,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.', @@ -646,6 +665,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/helpers/users.js b/src/helpers/users.js index e2fe9f2ccf..20fd462120 100644 --- a/src/helpers/users.js +++ b/src/helpers/users.js @@ -102,10 +102,14 @@ 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' }) + .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({ @@ -244,14 +252,21 @@ 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); + 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/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/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/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/models/SubProgram.js b/src/models/SubProgram.js index 180428a686..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]; @@ -23,6 +29,18 @@ 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 }, + elearningLimit: { type: Number }, + }], + default: undefined, + }, paymentPlans: { type: [{ prices: { type: [Number], required: true } }], default: undefined }, subjectToVat: { type: Boolean }, sheetTemplateId: { type: String }, @@ -66,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/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/courseBills.js b/src/routes/courseBills.js index 0b2ac1f245..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() }), } ), @@ -92,6 +97,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/courses.js b/src/routes/courses.js index 872439861b..2811290771 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,30 @@ exports.plugin = { handler: list, }); + server.route({ + method: 'GET', + path: '/trainers-billing', + options: { + auth: { scope: ['trainerbills:edit', 'user:read-{query.trainer}'] }, + 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, + }); + server.route({ method: 'POST', path: '/', diff --git a/src/routes/preHandlers/courseBills.js b/src/routes/preHandlers/courseBills.js index 8504c7facd..5fda62de1d 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, @@ -13,6 +16,7 @@ const { BALANCE, INTRA, GROUP, + GLOBAL, TRAINEE, SINGLE, } = require('../../helpers/constants'); @@ -20,14 +24,64 @@ 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 }) + .findOne({ _id: courseId }, { + type: 1, + expectedBillsCount: 1, + companies: 1, + prices: 1, + interruptionDates: 1, + certificateGenerationMode: 1, + trainees: 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') || []; + const subProgramHppIds = hourlyPaymentPlans.map(hpp => hpp._id); + if (!UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId)) { + throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); + } + } + + if (quantity === 1 && !mainFee.price && !hourlyPaymentPlanId) throw Boom.badRequest(); + if (hourlyPaymentPlanId && mainFee.price) throw Boom.badRequest(); + + const shouldComputePriceFromDuration = hourlyPaymentPlanId && course.certificateGenerationMode === GLOBAL; + + 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/src/routes/preHandlers/courses.js b/src/routes/preHandlers/courses.js index 487836d3b2..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; }; @@ -1658,3 +1665,19 @@ exports.authorizeCourseBillingPurchaseEdition = async (req) => { return null; }; + +exports.authorizeTrainerBillsGet = async (req) => { + try { + const { trainer: trainerId } = req.query; + + if (trainerId) { + 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/subPrograms.js b/src/routes/preHandlers/subPrograms.js index 4a966263d4..449a122fe4 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, @@ -18,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; @@ -73,7 +75,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 +162,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 +178,50 @@ 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, elearningLimit } = req.payload.hourlyPaymentPlan; + if (hourlyPaymentPlanId) { + const subProgramHppIds = (subProgram.hourlyPaymentPlans || []).map(hpp => hpp._id); + const hourlyPaymentPlanExists = UtilsHelper.doesArrayIncludeId(subProgramHppIds, hourlyPaymentPlanId); + if (!hourlyPaymentPlanExists) throw Boom.notFound(translate[language].subProgramHourlyPaymentPlanNotFound); + + if (!prices.length) { + const isUsedByBill = await CourseBill.countDocuments({ hourlyPaymentPlan: hourlyPaymentPlanId }, { limit: 1 }); + if (isUsedByBill) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanUsed); + } + } + + 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.elearningLimit + ? !!elearningLimit && CompaniDuration(hpp.elearningLimit).isEquivalentTo(elearningLimit) + : !elearningLimit) && + hpp.prices.length === prices.length && + hpp.prices.every(hp => prices + .some(p => UtilsHelper.areObjectIdsEquals(p.step, hp.step) && p.hourlyAmount === hp.hourlyAmount))); + if (isDuplicate) throw Boom.forbidden(translate[language].subProgramHourlyPaymentPlanAlreadyExists); + } + + 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/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/subPrograms.js b/src/routes/subPrograms.js index b33b77871e..50f21e8984 100644 --- a/src/routes/subPrograms.js +++ b/src/routes/subPrograms.js @@ -12,6 +12,7 @@ const { authorizeStepReuse, getSubProgram, } = require('./preHandlers/subPrograms'); +const { durationStrictlyPositive } = require('./validations/utils'); const { update, remove, @@ -65,6 +66,28 @@ 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(), + elearningLimit: durationStrictlyPositive + .when('elearningPrice', { is: Joi.exist(), otherwise: Joi.forbidden() }), + }).required(), + }), Joi.object({ archivedAt: Joi.date().allow('') }) ), }, diff --git a/src/routes/trainerBills.js b/src/routes/trainerBills.js index 1128f65e25..32d0ac254d 100644 --- a/src/routes/trainerBills.js +++ b/src/routes/trainerBills.js @@ -1,6 +1,6 @@ const Joi = require('joi'); Joi.objectId = require('joi-objectid')(Joi); -const { create } = require('../controllers/trainerBillController'); +const { create, list } = require('../controllers/trainerBillController'); const { authorizeTrainerBillCreation } = require('./preHandlers/trainerBills'); const { formDataPayload, objectIdOrArray } = require('./validations/utils'); @@ -19,11 +19,21 @@ 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 }], }, handler: create, }); + + server.route({ + method: 'GET', + path: '/', + options: { + auth: { scope: ['trainerbills:create'] }, + }, + handler: list, + }); }, }; diff --git a/tests/integration/completionCertificates.test.js b/tests/integration/completionCertificates.test.js index 38dbb115d3..0dc01e57a8 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,24 @@ 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 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 () => { const payload = { action: GENERATION }; const response = await app.inject({ @@ -391,6 +415,19 @@ 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 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 () => { const response = await app.inject({ method: 'DELETE', diff --git a/tests/integration/courseBills.test.js b/tests/integration/courseBills.test.js index ae8abd1c39..9b686612b9 100644 --- a/tests/integration/courseBills.test.js +++ b/tests/integration/courseBills.test.js @@ -11,6 +11,7 @@ const { coursesList, courseFundingOrganisationList, billingItemList, + hourlyPaymentPlanId, } = require('./seed/courseBillsSeed'); const { authCompany, otherCompany, companyWithoutSubscription } = require('../seed/authCompaniesSeed'); @@ -538,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', @@ -800,6 +824,72 @@ 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', + 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 (GLOBAL)', 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 (GLOBAL)', 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', () => { @@ -884,6 +974,64 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => { expect(billsCountAfter).toBe(billsCountBefore + 2); }); + 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', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { ...singleCoursePayload, course: coursesList[17]._id, hourlyPaymentPlanId }, + }); + + expect(response.statusCode).toBe(200); + + 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 () => { + const response = await app.inject({ + method: 'POST', + url: '/coursebills/list-creation', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { + ...singleCoursePayload, + quantity: 2, + mainFee: omit(singleCoursePayload.mainFee, 'price'), + 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', + 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/courses.test.js b/tests/integration/courses.test.js index f6222106bb..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', @@ -10092,3 +10113,170 @@ describe('COURSES ROUTES - GET /{_id}/all-documents', () => { }); }); }); + +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', 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(); + }); + + 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); + const { trainers } = response.result.data; + expect(trainers.length).toEqual(1); + expect(trainers[0].courses.length).toEqual(15); + }); + + 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({ + method: 'GET', + url: `/courses/trainers-billing?startDate=${startDate}&endDate=${endDate}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + 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(trainerAndCoachCourses.length).toEqual(4); + const trainerCourseBilledInPeriod = trainerCourses + .find(c => UtilsHelper.areObjectIdsEquals(c._id, coursesList[7]._id)); + expect(CompaniDate(trainerCourseBilledInPeriod.billsSubmissionDates[0]).toISO()) + .toEqual('2020-03-02T10:00:00.000Z'); + }); + + 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', + 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'); + }); + + 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).toEqual(15); + expect(courses.every(c => c.type !== SINGLE)).toBeTruthy(); + const notInvoicedCourse = courses.find(c => UtilsHelper.areObjectIdsEquals(c._id, coursesList[4]._id)); + expect(notInvoicedCourse).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); + }); + + 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', () => { + 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/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/completionCertificatesSeed.js b/tests/integration/seed/completionCertificatesSeed.js index 1c26c0c418..17bbda5742 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 }, ]; @@ -275,6 +293,45 @@ 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, description: 'Facture test' }, + hourlyPaymentPlan: hourlyPaymentPlanId, + 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, + description: 'Facture test \r\n--- Détail ---\r\nautre étape - 4h - 200,00\u00a0€', + }, + hourlyPaymentPlan: hourlyPaymentPlanId, + maturityDate: '2020-01-20T10:00:00.000Z', + }, ]; const populateDB = async () => { @@ -288,6 +345,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 +354,4 @@ const populateDB = async () => { ]); }; -module.exports = { populateDB, courseList, completionCertificateList }; +module.exports = { populateDB, courseList, completionCertificateList, courseBillsList }; diff --git a/tests/integration/seed/courseBillsSeed.js b/tests/integration/seed/courseBillsSeed.js index db48837ae5..90a41637bb 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'); @@ -32,7 +36,20 @@ 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 }] }, + { _id: new ObjectId(), prices: [{ step: steps[0]._id, hourlyAmount: 60 }] }, + ], + }, +]; const programList = [{ _id: new ObjectId(), name: 'Program 1', subPrograms: [subProgramList[0]._id] }]; @@ -372,6 +389,59 @@ 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', }, ]; @@ -578,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 = [ @@ -601,12 +680,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), @@ -628,4 +768,6 @@ module.exports = { courseFundingOrganisationList, coursesList, billingItemList, + hourlyPaymentPlanId, + slotsList, }; diff --git a/tests/integration/seed/coursesSeed.js b/tests/integration/seed/coursesSeed.js index 5e2870a4ea..21c8aba662 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'); @@ -368,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 = [ @@ -831,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 = [ @@ -1537,6 +1554,28 @@ 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' }, + }, + { + _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 () => { await deleteNonAuthenticationSeeds(); @@ -1563,6 +1602,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 +1631,5 @@ module.exports = { traineeWithoutCompany, ROFAndCoach, slots, + trainerBillList, }; 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/integration/seed/seedsVerification.test.js b/tests/integration/seed/seedsVerification.test.js index a103b5cfb0..8329d0ae84 100644 --- a/tests/integration/seed/seedsVerification.test.js +++ b/tests/integration/seed/seedsVerification.test.js @@ -1253,7 +1253,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, 'hourlyPaymentPlan'))); expect(everyPriceIsValid).toBeTruthy(); }); @@ -2555,10 +2557,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', @@ -2607,6 +2615,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', () => { diff --git a/tests/integration/seed/subProgramsSeed.js b/tests/integration/seed/subProgramsSeed.js index 4cfc1fbdd8..d041f7d958 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 } = require('../../../src/helpers/constants'); +const { + WEBAPP, + INTRA, + PUBLISHED, + DRAFT, + GLOBAL, + PAID, + MONTHLY, + GROUP, +} = require('../../../src/helpers/constants'); const { authCompany } = require('../../seed/authCompaniesSeed'); const tester = { @@ -102,6 +112,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 +170,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(), @@ -179,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 = [ @@ -240,6 +258,31 @@ const coursesList = [ accessRules: [], tradeName: 'program 5', }, + { // course using the hourly payment plan of subProgram 13 + _id: new ObjectId(), + format: 'blended', + subProgram: subProgramsList[13]._id, + 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(); @@ -283,6 +326,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), @@ -301,4 +345,5 @@ module.exports = { cardsList, tester, paymentPlanId, + hourlyPaymentPlanId, }; 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/subPrograms.test.js b/tests/integration/subPrograms.test.js index cce94ff6fc..10cfe0aa7b 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,119 @@ 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 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 400 if the e-learning limit is sent without e-learning price', async () => { + const payload = { + hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }], elearningLimit: 'PT36000S' }, + }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[13]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(400); + }); + + it('should return 403 if the e-learning price is missing on a subProgram with an e-learning step', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 60 }] } }; + + const response = await app.inject({ + method: 'PUT', + url: `/subprograms/${subProgramsList[17]._id.toHexString()}`, + payload, + headers: { 'x-access-token': authToken }, + }); + + expect(response.statusCode).toBe(403); + }); + + it('should return 403 if an identical hourly payment plan already exists', async () => { + const payload = { hourlyPaymentPlan: { prices: [{ step: stepsList[0]._id, hourlyAmount: 40 }] } }; + + 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/integration/trainerBills.test.js b/tests/integration/trainerBills.test.js index 7f9bc54639..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 } = 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' }); @@ -265,3 +318,78 @@ 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', + 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); + }); + }); + + describe('Other trainer', () => { + it('should not get other trainer\'s bills', async () => { + authToken = await getTokenByCredentials(trainerAndCoach.local); + + const response = await app.inject({ + method: 'GET', + url: '/trainerbills', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(200); + expect(response.result.data.trainerBills.length).toBe(0); + }); + + 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', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + 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 }, + ]; + 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', + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(role.expectedCode); + }); + }); + }); +}); 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/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/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, diff --git a/tests/unit/helpers/completionCertificates.test.js b/tests/unit/helpers/completionCertificates.test.js index 242b65f089..028e1a10a5 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,16 @@ describe('generate', () => { let uploadCourseFile; let updateOne; let findActivityHistories; - let getTotalDuration; + let getDurationPerStep; let courseFind; let getELearningDuration; let getRealELearningDuration; + let findBills; + let updateOneBill; + let getPricesFromDurations; + let getPriceDetails; const PRI_SUBPROGRAM_IDS = new ObjectId(); + const stepId = new ObjectId(); const REAL_ELEARNING_DURATION_SUBPROGRAM_ID = new ObjectId(); beforeEach(() => { @@ -449,10 +458,14 @@ 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'); + 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; @@ -470,22 +483,32 @@ describe('generate', () => { updateOne.restore(); UtilsMock.unmockCurrentDate(); findActivityHistories.restore(); - getTotalDuration.restore(); + getDurationPerStep.restore(); courseFind.restore(); getELearningDuration.restore(); getRealELearningDuration.restore(); + findBills.restore(); + updateOneBill.restore(); + getPricesFromDurations.restore(); + getPriceDetails.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 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' }, @@ -530,7 +553,14 @@ describe('generate', () => { subProgram: { _id: subProgramIds[0], program: { subPrograms: subProgramIds }, + hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ + { + _id: stepId, + name: 'étape 1', + type: 'on_site', + theoreticalDuration: '1h', + }, { type: E_LEARNING, theoreticalDuration: '3h30', @@ -591,7 +621,13 @@ 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, hourlyPaymentPlan: hourlyPaymentPlan._id, mainFee: { description: 'Facture test' } }], + ['setOptions', 'lean'] + )); + getPricesFromDurations.returns(priceDetails); + getPriceDetails.returns('étape 1 - 6h30 - 260,00 €'); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); getELearningDuration.returns('PT3H30M'); @@ -620,13 +656,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -658,9 +691,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 +777,47 @@ 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(), + }, + hourlyPaymentPlan: { $exists: true }, + 'mainFee.price': { $in: [0, null] }, + }, + { hourlyPaymentPlan: 1, 'mainFee.description': 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + sinon.assert.calledOnceWithExactly( + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT3H30M', + completionCertificate.course.subProgram.steps, + undefined + ); + 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 €', + }, + } + ); }); it('should generate completion certificate (with real elearning duration)', async () => { @@ -753,6 +826,10 @@ describe('generate', () => { const companyId = new ObjectId(); const courseId = new ObjectId(); const month = '03-2025'; + 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 = [ { _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' }, @@ -785,6 +862,7 @@ describe('generate', () => { subProgram: { _id: subProgramIds[0], program: { subPrograms: subProgramIds }, + hourlyPaymentPlans: [hourlyPaymentPlan], steps: [ { type: E_LEARNING, @@ -843,10 +921,17 @@ 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(durationPerStep); courseFind.returns(SinonMongoose.stubChainedQueries(coursesWithSameProgram)); - findActivityHistories.returns(SinonMongoose.stubChainedQueries(activityHistories, ['lean'])); - getRealELearningDuration.returns('PT200S'); + 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.onCall(0).returns('PT200S'); + getRealELearningDuration.onCall(1).returns(previousELearningDuration); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); uploadCourseFile.returns({ publicId: '1234', link: 'tests/1234' }); @@ -872,13 +957,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -902,17 +984,25 @@ 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( - 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, @@ -944,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, @@ -987,6 +1078,38 @@ describe('generate', () => { ] ); sinon.assert.notCalled(findOneTrainingContract); + 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, 'mainFee.description': 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + sinon.assert.calledOnceWithExactly( + getPricesFromDurations, + hourlyPaymentPlan, + durationPerStep, + 'PT200S', + completionCertificate.course.subProgram.steps, + previousELearningDuration + ); + sinon.assert.notCalled(getPriceDetails); + sinon.assert.notCalled(updateOneBill); }); it('should generate completion certificate in VAE period (attendance within remaining budget)', async () => { @@ -1087,9 +1210,10 @@ 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'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1116,13 +1240,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -1195,9 +1316,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 +1378,31 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 330 } } ); sinon.assert.notCalled(getELearningDuration); + 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, 'mainFee.description': 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + 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 () => { @@ -1363,9 +1508,10 @@ 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'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1392,13 +1538,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -1471,9 +1614,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 +1676,31 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' }, vaeSupportRemainingMinutes: 0 } } ); sinon.assert.notCalled(getELearningDuration); + 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, 'mainFee.description': 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + 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 () => { @@ -1636,9 +1803,10 @@ 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'])); + findBills.returns(SinonMongoose.stubChainedQueries([], ['setOptions', 'lean'])); getRealELearningDuration.returns('PT200S'); formatIdentity.returns('Jean SAITRIEN'); getPdf.returns('pdf'); @@ -1665,13 +1833,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: 'name activities type theoreticalDuration' }, ], }, ], @@ -1744,9 +1909,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 +1970,31 @@ describe('generate', () => { { $set: { file: { publicId: '1234', link: 'tests/1234' } } } ); sinon.assert.notCalled(getELearningDuration); + 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, 'mainFee.description': 1 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ] + ); + sinon.assert.notCalled(updateOneBill); + sinon.assert.notCalled(getPricesFromDurations); + sinon.assert.notCalled(getPriceDetails); }); }); @@ -1835,12 +2024,16 @@ describe('deleteFile', () => { let updateOne; let updateMany; let deleteCourseFile; + 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'); + findBills = sinon.stub(CourseBill, 'find'); + updateOneBill = sinon.stub(CourseBill, 'updateOne'); }); afterEach(() => { findOne.restore(); @@ -1848,39 +2041,88 @@ describe('deleteFile', () => { updateOne.restore(); updateMany.restore(); deleteCourseFile.restore(); + findBills.restore(); + updateOneBill.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(), - 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.notCalled(find); - sinon.assert.notCalled(updateMany); - }); - - it('should remove the file of a completion certificat', async () => { + 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(), + course: courseId, + month: '03-2025', + file: { publicId: 'completionCertificateTest', link: 'test/completionCertificateTest' }, + }; + findOne.returns(SinonMongoose.stubChainedQueries(completionCertificate, ['lean'])); + findBills.returns(SinonMongoose.stubChainedQueries(bills, ['setOptions', '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'); + 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 }, + ], + }, + { 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.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); + }); + + 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 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, @@ -1899,6 +2141,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]); @@ -1906,7 +2150,6 @@ describe('deleteFile', () => { findOne, [{ query: 'findOne', args: [{ _id: completionCertificateIds[0] }] }, { query: 'lean' }] ); - SinonMongoose.calledOnceWithExactly( find, [ @@ -1922,6 +2165,64 @@ describe('deleteFile', () => { ); sinon.assert.calledWithExactly(deleteCourseFile.getCall(0), 'completionCertificateTest'); sinon.assert.calledWithExactly(deleteCourseFile.getCall(1), 'completionCertificateTest_2'); + 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 }, + ], + }, + { query: 'setOptions', args: [{ isVendorUser: true }] }, + { query: 'lean' }, + ], + 0 + ); + 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 }, + ], + }, + { 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, updateOneBill); sinon.assert.notCalled(updateOne); }); }); diff --git a/tests/unit/helpers/courseBills.test.js b/tests/unit/helpers/courseBills.test.js index c3b7b0aa08..36f373f0a0 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, @@ -465,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], @@ -519,6 +525,7 @@ describe('list', () => { companies: [companies[1]], mainFee: { price: 320, count: 1 }, payer: { name: 'Funder' }, + hourlyPaymentPlan, maturityDate: '2025-06-13T14:00:00.000Z', }, { @@ -621,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], @@ -708,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], @@ -855,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, + }, ], }, { @@ -1022,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', @@ -1128,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', @@ -1145,8 +1210,99 @@ describe('list', () => { }); }); +describe('computePriceFromDurations', () => { + let findOneCourse; + let getTraineeDurations; + let getDurationPerStep; + let getPricesFromDurations; + let getPriceDetails; + + beforeEach(() => { + findOneCourse = sinon.stub(Course, 'findOne'); + getTraineeDurations = sinon.stub(CoursesHelper, 'getTraineeDurations'); + getDurationPerStep = sinon.stub(CourseSlotsHelper, 'getDurationPerStep'); + getPricesFromDurations = sinon.stub(HourlyPaymentPlansHelper, 'getPricesFromDurations'); + getPriceDetails = sinon.stub(HourlyPaymentPlansHelper, 'getPriceDetails'); + }); + + afterEach(() => { + findOneCourse.restore(); + getTraineeDurations.restore(); + getDurationPerStep.restore(); + getPricesFromDurations.restore(); + getPriceDetails.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 priceDetails = { stepId: { stepName: 'étape', duration: CompaniDuration({ minutes: 120 }), price: '300' } }; + + const steps = [{ _id: new ObjectId(), name: 'étape' }]; + 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 }); + getDurationPerStep.returns(durationPerStep); + getPricesFromDurations.returns(priceDetails); + getPriceDetails.returns('étape - 2h - 300,00 €'); + + const result = await CourseBillHelper.computePriceFromDurations(courseId, hourlyPaymentPlans[1]._id); + + expect(result).toEqual({ price: 300, details: 'étape - 2h - 300,00 €' }); + SinonMongoose.calledOnceWithExactly( + findOneCourse, + [ + { query: 'findOne', args: [{ _id: courseId }, { subProgram: 1, slots: 1, trainees: 1 }] }, + { + query: 'populate', + args: [{ + path: 'slots', + select: 'startDate endDate trainers step', + options: { sort: { startDate: 1 } }, + populate: { path: 'step', select: 'durationCountedPerTrainer' }, + }], + }, + { + query: 'populate', + args: [{ + path: 'subProgram', + select: 'steps hourlyPaymentPlans', + populate: { path: 'steps', select: 'name activities type theoreticalDuration' }, + }], + }, + { query: 'lean' }, + ] + ); + 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, + hourlyPaymentPlans[1], + durationPerStep, + eLearningDuration, + steps + ); + sinon.assert.calledOnceWithExactly(getPriceDetails, priceDetails); + }); +}); + describe('createBillList', () => { let findOneCourse; + let computePriceFromDurations; let createCourseBill; let insertManyCourseBills; let addBillingPurchase; @@ -1155,6 +1311,7 @@ describe('createBillList', () => { beforeEach(() => { findOneCourse = sinon.stub(Course, 'findOne'); + computePriceFromDurations = sinon.stub(CourseBillHelper, 'computePriceFromDurations'); createCourseBill = sinon.stub(CourseBill, 'create'); insertManyCourseBills = sinon.stub(CourseBill, 'insertMany'); addBillingPurchase = sinon.stub(CourseBillHelper, 'addBillingPurchase'); @@ -1164,6 +1321,7 @@ describe('createBillList', () => { afterEach(() => { findOneCourse.restore(); + computePriceFromDurations.restore(); createCourseBill.restore(); insertManyCourseBills.restore(); addBillingPurchase.restore(); @@ -1171,31 +1329,43 @@ 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', + hourlyPaymentPlanId: new ObjectId(), }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); + computePriceFromDurations.returns({ price: 250, details: 'étape - 2h - 250,00 €' }); await CourseBillHelper.createBillList(payload); + sinon.assert.calledOnceWithExactly(computePriceFromDurations, payload.course, payload.hourlyPaymentPlanId); + sinon.assert.calledOnceWithExactly( createCourseBill, { course: payload.course, mainFee: { - price: 100, + 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, payer: payload.payer, maturityDate: payload.maturityDate, @@ -1427,6 +1597,7 @@ describe('createBillList', () => { companies: [companyId], payer: { fundingOrganisation: payerId }, maturityDate: '2025-04-29T22:00:00.000Z', + hourlyPaymentPlanId: new ObjectId(), }; findOneCourse.returns(SinonMongoose.stubChainedQueries(course)); @@ -1438,7 +1609,17 @@ 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, + certificateGenerationMode: 1, + }, + ], }, { query: 'populate', args: [{ path: 'trainees', select: 'identity' }] }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, @@ -1459,6 +1640,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', @@ -1477,6 +1659,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', @@ -1515,7 +1698,17 @@ 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, + certificateGenerationMode: 1, + }, + ], }, { query: 'populate', args: [{ path: 'trainees', select: 'identity' }] }, { query: 'populate', args: [{ path: 'trainers', select: 'identity' }] }, @@ -1650,6 +1843,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', () => { 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, 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 e75585aed0..1d42390f02 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -12,10 +12,12 @@ 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'); 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'); @@ -23,6 +25,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'); @@ -2886,7 +2889,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -2894,6 +2897,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -2931,7 +2935,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' }, @@ -3001,7 +3009,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3009,6 +3017,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -3109,7 +3118,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3117,6 +3126,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -3291,7 +3301,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3299,6 +3309,7 @@ describe('getCourse', () => { select: 'name type theoreticalDuration durationCountedPerTrainer', populate: { path: 'activities', select: 'name type' }, }, + { path: 'hourlyPaymentPlans.prices.step', select: 'name' }, ], }, { @@ -11252,3 +11263,603 @@ 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 + ); + }); +}); + +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(() => { + process.env.CONSULTING_PROGRAM_IDS = `${new ObjectId()},${consultingProgramId}`; + process.env.CONSULTING_BILLING_ITEM = consultingBillingItemId.toHexString(); + }); + + afterEach(() => { + process.env.CONSULTING_PROGRAM_IDS = ''; + process.env.CONSULTING_BILLING_ITEM = ''; + }); + + 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 = { + trainers: [{ _id: new ObjectId() }], + subProgram: { program: { _id: new ObjectId() } }, + billingPurchaseList: [trainerSalaryItem], + }; + + const result = CourseHelper.getCourseTrainerSalary(course); + + expect(result).toEqual(80); + }); + + it('should return consulting billing item if no trainer salary and program is consulting', () => { + const course = { + trainers: [{ _id: new ObjectId() }], + subProgram: { program: { _id: consultingProgramId } }, + billingPurchaseList: [consultingItem], + }; + + const result = CourseHelper.getCourseTrainerSalary(course); + + 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(); + }); +}); + +describe('listTrainersBilling', () => { + let courseFind; + let trainerBillFind; + let courseSlotFind; + + beforeEach(() => { + courseFind = sinon.stub(Course, 'find'); + trainerBillFind = sinon.stub(TrainerBill, 'find'); + courseSlotFind = sinon.stub(CourseSlot, 'find'); + }); + + afterEach(() => { + courseFind.restore(); + trainerBillFind.restore(); + courseSlotFind.restore(); + }); + + it('should return an empty array if no course found', async () => { + const trainerId = new ObjectId(); + courseFind.returns(SinonMongoose.stubChainedQueries([], ['populate', 'sort', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([]); + sinon.assert.notCalled(trainerBillFind); + sinon.assert.notCalled(courseSlotFind); + }); + + 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', + 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 = [ + { + 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'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([{ + ...trainer, + courses: [ + { ...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', + billsSubmissionDates: ['2024-01-01T08:00:00.000Z'], + }, + { + ...omit(courses[3], ['billingPurchaseList']), + plannedSalary: 80, + invoicedAmount: 100, + paidAmount: 100, + status: 'paid', + }, + ], + }]); + SinonMongoose.calledOnceWithExactly( + courseFind, + [ + { + query: 'find', + args: [ + { trainers: trainerId, type: { $nin: ['single', 'inter_b2c'] } }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, + ], + }, + { 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( + trainerBillFind, + [ + { + query: 'find', + args: [ + { course: { $in: courses.map(c => c._id) }, trainer: trainerId }, + { course: 1, amount: 1, trainer: 1, submittedAt: 1 }, + ], + }, + { query: 'populate', args: [{ path: 'payment', select: 'status' }] }, + { query: 'lean' }, + ] + ); + sinon.assert.notCalled(courseSlotFind); + }); + + 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: '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 = [ + { + course: courses[1]._id, + trainer: trainerId, + amount: 40, + payment: { status: 'pending' }, + submittedAt: '2024-01-01T08:00:00.000Z', + }, + ]; + + courseFind.returns(SinonMongoose.stubChainedQueries(courses, ['populate', 'sort', 'lean'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + + const result = await CourseHelper.listTrainersBilling({ trainer: trainerId }); + + expect(result).toEqual([{ + ...trainer, + courses: [ + { + ...omit(courses[0], ['billingPurchaseList', 'archivedAt']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'paid', + }, + { + ...omit(courses[1], ['billingPurchaseList', 'archivedAt']), + plannedSalary: 100, + invoicedAmount: 40, + paidAmount: 0, + status: 'partially_invoiced', + }, + { + ...omit(courses[2], ['billingPurchaseList', 'archivedAt']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }, + { + ...omit(courses[3], ['billingPurchaseList']), + plannedSalary: 100, + invoicedAmount: 0, + paidAmount: 0, + status: 'not_invoiced', + }, + ], + }]); + sinon.assert.notCalled(courseSlotFind); + }); + + 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' }; + 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[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.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([])); + + 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], invoicedAmount: 0, paidAmount: 0, status: 'not_invoiced' }, + ], + }]); + SinonMongoose.calledWithExactly( + courseSlotFind, + [ + { + query: 'find', + args: [ + { startDate: { $gte: query.startDate }, endDate: { $lte: query.endDate } }, + { course: 1 }, + ], + }, + { query: 'lean' }, + ], + 0 + ); + SinonMongoose.calledWithExactly( + trainerBillFind, + [ + { + query: 'find', + args: [ + { submittedAt: { $gte: query.startDate, $lte: query.endDate }, course: { $exists: true } }, + { course: 1 }, + ], + }, + { query: 'lean' }, + ], + 0 + ); + SinonMongoose.calledOnceWithExactly( + courseFind, + [ + { + query: 'find', + args: [ + { + _id: { $in: [courses[0]._id, courses[1]._id] }, + trainers: trainerId, + type: { $nin: ['single', 'inter_b2c'] }, + }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, + ], + }, + { 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.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 () => { + 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', + 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 }], + }, + ]; + const trainerBills = [ + { + 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'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills, ['populate', 'lean'])); + courseSlotFind.returns(SinonMongoose.stubChainedQueries([], ['lean'])); + + const result = await CourseHelper.listTrainersBilling({}); + + expect(result).toEqual([ + { + ...firstTrainer, + courses: [ + { ...omit(courses[0], ['billingPurchaseList']), invoicedAmount: 100, paidAmount: 100, status: 'paid' }, + ], + }, + { + ...secondTrainer, + courses: [ + { + ...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'], + }, + ], + }, + ]); + SinonMongoose.calledOnceWithExactly( + courseFind, + [ + { + query: 'find', + args: [ + { 'trainers.0': { $exists: true }, type: { $nin: ['single', 'inter_b2c'] } }, + { trainers: 1, createdAt: 1, billingPurchaseList: 1, type: 1, misc: 1, tradeName: 1, archivedAt: 1 }, + ], + }, + { 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( + trainerBillFind, + [ + { + 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' }, + ] + ); + sinon.assert.notCalled(courseSlotFind); + }); +}); diff --git a/tests/unit/helpers/hourlyPaymentPlans.test.js b/tests/unit/helpers/hourlyPaymentPlans.test.js new file mode 100644 index 0000000000..38605b3e4d --- /dev/null +++ b/tests/unit/helpers/hourlyPaymentPlans.test.js @@ -0,0 +1,118 @@ +const { expect } = require('expect'); +const { ObjectId } = require('mongodb'); +const HourlyPaymentPlansHelper = require('../../../src/helpers/hourlyPaymentPlans'); +const { CompaniDuration } = require('../../../src/helpers/dates/companiDurations'); + +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: steps[0]._id, hourlyAmount: 50 }, { step: steps[1]._id, hourlyAmount: 80 }], + elearningPrice: 20, + }; + const durationPerStep = { + [steps[0]._id]: CompaniDuration({ minutes: 210 }), + [steps[1]._id]: CompaniDuration({ minutes: 60 }), + }; + const eLearningDuration = CompaniDuration({ minutes: 90 }); + + const result = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, steps); + + 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 not cap the billed e-learning if no previous duration and duration is lower than limit', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const noPreviousDuration = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, []); + + expect(noPreviousDuration.elearning.price).toBe('60'); + }); + + it('should not cap the billed e-learning if previous and current duration sum is lower than limit ', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const limitNotReached = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 6 })); + + expect(limitNotReached.elearning.price).toBe('60'); + }); + + it('should cap the billed e-learning with the remaining allowed duration', () => { + const hourlyPaymentPlan = { prices: [], elearningPrice: 20, elearningLimit: 'PT36000S' }; + const eLearningDuration = CompaniDuration({ hours: 3 }); + + const limitReachedThisMonth = HourlyPaymentPlansHelper + .getPricesFromDurations(hourlyPaymentPlan, {}, eLearningDuration, [], CompaniDuration({ hours: 8 })); + + expect(limitReachedThisMonth.elearning.price).toBe('40'); + expect(limitReachedThisMonth.elearning.duration.asHours()).toBe(2); + }); + 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).toBeUndefined(); + }); + + 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 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 + .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( + 'étape A - 3h30 - 175,00\u00a0€\r\n' + + 'étape B - 1h - 80,00\u00a0€\r\n' + + 'E-learning - 1h30 - 30,00\u00a0€' + ); + }); +}); 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); }); }); diff --git a/tests/unit/helpers/subPrograms.test.js b/tests/unit/helpers/subPrograms.test.js index 52628bee2a..1c8a42934d 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); }); @@ -820,6 +836,74 @@ 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, + elearningLimit: 'PT72000S', + }, + }; + + await SubProgramHelper.updateSubProgram(subProgramId, payload); + + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: subProgramId }, + { + $push: { + hourlyPaymentPlans: { + prices: [{ step: stepId, hourlyAmount: 50 }], + elearningPrice: 30, + elearningLimit: 72000, + }, + }, + } + ); + 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, elearningPrice: 30 } }; + + await SubProgramHelper.updateSubProgram(subProgramId, payload); + + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: subProgramId, 'hourlyPaymentPlans._id': hourlyPaymentPlanId }, + { + $set: { 'hourlyPaymentPlans.$.prices': prices, 'hourlyPaymentPlans.$.elearningPrice': 30 }, + $unset: { 'hourlyPaymentPlans.$.elearningLimit': '' }, + } + ); + 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(); diff --git a/tests/unit/helpers/trainerBills.test.js b/tests/unit/helpers/trainerBills.test.js index 327ba49c6d..9fce059768 100644 --- a/tests/unit/helpers/trainerBills.test.js +++ b/tests/unit/helpers/trainerBills.test.js @@ -295,4 +295,70 @@ describe('createBill', () => { { 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(); + const payload = { number: 'FACT_0006', file: 'file', amount: 80, course: courseId }; + + 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', + course: courseId, + 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 } + ); + }); +}); + +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 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(credentials); + + expect(result).toEqual(trainerBills); + SinonMongoose.calledOnceWithExactly( + trainerBillFind, + [ + { 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' }, + ] + ); + }); }); diff --git a/tests/unit/helpers/trainerPayments.test.js b/tests/unit/helpers/trainerPayments.test.js index f6a7fbe7bb..3b777b48e0 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,31 +77,56 @@ 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(); }); - it('should return the trainer payments with the given status', async () => { - const trainerPayments = [{ _id: new ObjectId(), status: PAID }]; + 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'])); 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, [ { 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 subProgram', + populate: [ + { path: 'subProgram', select: 'program', populate: { path: 'program', select: '_id' } }, + { path: 'billingPurchaseList.billingItem', select: 'type' }, + ], + }, + ], + }], }, { query: 'populate', @@ -110,9 +136,114 @@ describe('list', () => { { query: 'lean' }, ] ); + sinon.assert.notCalled(getCourseTrainerSalary); + sinon.assert.notCalled(trainerBillFind); }); - it('should query every status when status is an array', 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 courseWithTrainerSalary = { + _id: new ObjectId(), + trainers: [trainerId], + billingPurchaseList: [{ billingItem: { type: TRAINER_SALARY }, price: 40, count: 1 }], + }; + const courseWithoutTrainerSalary = { _id: new ObjectId(), trainers: [trainerId, new ObjectId()] }; + const trainerPayments = [ + { + _id: new ObjectId(), + status: PAID, + trainerBill: { number: 'FACT_1', trainer, course: courseWithTrainerSalary }, + }, + { + _id: new ObjectId(), + status: PAID, + trainerBill: { number: 'FACT_2', trainer, course: courseWithoutTrainerSalary }, + }, + ]; + + 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'])); + trainerBillFind.returns(SinonMongoose.stubChainedQueries(trainerBills)); + getCourseTrainerSalary.withArgs(courseWithTrainerSalary).returns(40); + getCourseTrainerSalary.withArgs(courseWithoutTrainerSalary).returns(undefined); + + 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: courseWithTrainerSalary._id, plannedSalary: 40, totalPaymentsAmount: 50.1 }, + }, + }, + { + ...trainerPayments[1], + trainerBill: { number: 'FACT_2', trainer: formattedTrainer, course: { _id: courseWithoutTrainerSalary._id } }, + }, + ]); + + SinonMongoose.calledOnceWithExactly( + 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: 'populate', + args: [{ path: 'trainerPaymentsXmlFileInfos', select: 'name', options: { isVendorUser: true } }], + }, + { query: 'sort', args: [{ date: -1 }] }, + { query: 'lean' }, + ] + ); + 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.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 () => { const trainerPayments = [{ _id: new ObjectId(), status: PAID }, { _id: new ObjectId(), status: PENDING }]; trainerPaymentFind.returns(SinonMongoose.stubChainedQueries(trainerPayments, ['populate', 'sort', 'lean'])); @@ -120,6 +251,37 @@ describe('list', () => { 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); + sinon.assert.notCalled(trainerBillFind); }); }); diff --git a/tests/unit/helpers/users.test.js b/tests/unit/helpers/users.test.js index 3b2bbc0bd7..5deb765b97 100644 --- a/tests/unit/helpers/users.test.js +++ b/tests/unit/helpers/users.test.js @@ -386,12 +386,16 @@ 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' }] }, { 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 }] }, @@ -415,13 +419,17 @@ 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' }] }, { 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', }], }, @@ -991,6 +1003,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 }] }, ] ); @@ -1023,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', }], }, @@ -1041,6 +1058,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 }] }, ] ); @@ -1052,13 +1070,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, @@ -1068,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', }], }, @@ -1086,6 +1110,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 }] }, ] ); @@ -1109,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', }], }, @@ -1127,6 +1156,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 }] }, ] ); @@ -1155,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', }], }, @@ -1173,6 +1207,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 }] }, ] ); 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(); + }); +}); 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', () => { 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,