Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 48 additions & 16 deletions src/helpers/completionCertificates.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const { CompaniDate } = require('./dates/companiDates');
const { CompaniDuration } = require('./dates/companiDurations');
const { MM_YYYY, MONTH, DD_MM_YYYY, SHORT_DURATION_H_MM, OFFICIAL } = require('./constants');
const UtilsHelper = require('./utils');
const NumbersHelper = require('./numbers');
const HourlyPaymentPlansHelper = require('./hourlyPaymentPlans');
const CourseSlotsHelper = require('./courseSlots');
const CoursesHelper = require('./courses');
Expand Down Expand Up @@ -112,7 +113,7 @@ exports.generate = async (completionCertificateId) => {
select: 'program steps hourlyPaymentPlans',
populate: [
{ path: 'program', select: 'subPrograms' },
{ path: 'steps', select: 'activities type theoreticalDuration' },
{ path: 'steps', select: 'name activities type theoreticalDuration' },
],
},
],
Expand Down Expand Up @@ -236,7 +237,7 @@ exports.generate = async (completionCertificateId) => {
hourlyPaymentPlan: { $exists: true },
'mainFee.price': { $in: [0, null] },
},
{ hourlyPaymentPlan: 1 }
{ hourlyPaymentPlan: 1, 'mainFee.description': 1 }
)
.setOptions({ isVendorUser: true })
.lean();
Expand All @@ -245,9 +246,26 @@ exports.generate = async (completionCertificateId) => {
for (const [planId, bills] of Object.entries(billsGroupedByPlan)) {
const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans
.find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, planId));
const price = HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration);

await CourseBill.updateMany({ _id: { $in: bills.map(b => b._id) } }, { $set: { 'mainFee.price': price } });
const priceDetails = HourlyPaymentPlansHelper
.getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps);
const hasPricedStep = Object.values(priceDetails).some(line => line.stepId);
if (!hasPricedStep && CompaniDuration(eLearningDuration).isShorterThan('PT900S')) continue;

const descriptionDetails = HourlyPaymentPlansHelper.getPriceDetails(priceDetails);
const price = NumbersHelper
.toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price)));

await Promise.all(bills.map((bill) => {
const base = (get(bill, 'mainFee.description') || '').split('--- Détail ---')[0].trimEnd();
const description = descriptionDetails
? `${base ? `${base}\r\n` : ''}--- Détail ---\r\n${descriptionDetails}`
: base;

return CourseBill.updateOne(
{ _id: bill._id },
{ $set: { 'mainFee.price': price, 'mainFee.description': description } }
);
}));
}
};

Expand Down Expand Up @@ -281,17 +299,31 @@ exports.deleteFile = async (completionCertificateId) => {
}

for (const certificate of certificatesToDelete) {
await CourseBill.updateMany(
{
course: certificate.course,
maturityDate: {
$gte: CompaniDate(certificate.month, MM_YYYY).startOf(MONTH).toISO(),
$lte: CompaniDate(certificate.month, MM_YYYY).endOf(MONTH).toISO(),
const bills = await CourseBill
.find(
{
course: certificate.course,
maturityDate: {
$gte: CompaniDate(certificate.month, MM_YYYY).startOf(MONTH).toISO(),
$lte: CompaniDate(certificate.month, MM_YYYY).endOf(MONTH).toISO(),
},
hourlyPaymentPlan: { $exists: true },
billedAt: { $exists: false },
},
hourlyPaymentPlan: { $exists: true },
billedAt: { $exists: false },
},
{ $set: { 'mainFee.price': 0 } }
);
{ 'mainFee.description': 1 }
)
.setOptions({ isVendorUser: true })
.lean();

await Promise.all(bills.map((bill) => {
const base = (get(bill, 'mainFee.description') || '').split('--- Détail ---')[0].trimEnd();

return CourseBill.updateOne(
{ _id: bill._id },
base
? { $set: { 'mainFee.price': 0, 'mainFee.description': base } }
: { $set: { 'mainFee.price': 0 }, $unset: { 'mainFee.description': '' } }
);
}));
}
};
20 changes: 15 additions & 5 deletions src/helpers/courseBills.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => {
.populate({
path: 'subProgram',
select: 'steps hourlyPaymentPlans',
populate: { path: 'steps', select: 'activities type theoreticalDuration' },
populate: { path: 'steps', select: 'name activities type theoreticalDuration' },
})
.lean();

Expand All @@ -349,7 +349,13 @@ exports.computePriceFromDurations = async (courseId, hourlyPaymentPlanId) => {
const hourlyPaymentPlan = course.subProgram.hourlyPaymentPlans
.find(hpp => UtilsHelper.areObjectIdsEquals(hpp._id, hourlyPaymentPlanId));

return HourlyPaymentPlansHelper.getPriceFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration);
const priceDetails = HourlyPaymentPlansHelper
.getPricesFromDurations(hourlyPaymentPlan, durationPerStep, eLearningDuration, course.subProgram.steps);

return {
price: NumbersHelper.toFixedToFloat(NumbersHelper.add(...Object.values(priceDetails).map(line => line.price))),
details: HourlyPaymentPlansHelper.getPriceDetails(priceDetails),
};
};

exports.createBillList = async (payload) => {
Expand All @@ -372,9 +378,13 @@ exports.createBillList = async (payload) => {
if (payload.quantity === 1) {
const isGlobalCertificationCourseWithPriceFromDurations = payload.hourlyPaymentPlanId &&
course.certificateGenerationMode === GLOBAL;
const mainFee = isGlobalCertificationCourseWithPriceFromDurations
? { ...payload.mainFee, price: await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId) }
: payload.mainFee;
let { mainFee } = payload;
if (isGlobalCertificationCourseWithPriceFromDurations) {
const { price, details } = await exports.computePriceFromDurations(course._id, payload.hourlyPaymentPlanId);
const descriptionDetails = details && `--- Détail ---\r\n${details}`;
const description = [payload.mainFee.description, descriptionDetails].filter(Boolean).join('\r\n');
mainFee = { ...payload.mainFee, price, ...description && { description } };
}
const { price: mainFeePrice } = mainFee;

const billCreated = await CourseBill.create({
Expand Down
27 changes: 19 additions & 8 deletions src/helpers/hourlyPaymentPlans.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
const NumbersHelper = require('./numbers');
const UtilsHelper = require('./utils');
const { CompaniDuration } = require('./dates/companiDurations');
const { SHORT_DURATION_H_MM } = require('./constants');

exports.getPriceFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration) => {
const stepsPrice = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => {
exports.getPricesFromDurations = (hourlyPaymentPlan, durationPerStep, eLearningDuration, steps) => {
const stepsPrices = Object.entries(durationPerStep).reduce((acc, [stepId, duration]) => {
const stepPrice = hourlyPaymentPlan.prices.find(p => UtilsHelper.areObjectIdsEquals(p.step, stepId));
if (!stepPrice) return acc;

return NumbersHelper.add(acc, NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount));
}, 0);
const { name: stepName } = steps.find(step => UtilsHelper.areObjectIdsEquals(step._id, stepId));

const eLearningPrice = hourlyPaymentPlan.elearningPrice
? NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice)
: 0;
const price = NumbersHelper.multiply(duration.asHours(), stepPrice.hourlyAmount);

return NumbersHelper.toFixedToFloat(NumbersHelper.add(stepsPrice, eLearningPrice));
return { ...acc, [stepId]: { stepId, stepName, duration, price } };
}, {});

const eLearning = hourlyPaymentPlan.elearningPrice && {
duration: CompaniDuration(eLearningDuration),
price: NumbersHelper.multiply(CompaniDuration(eLearningDuration).asHours(), hourlyPaymentPlan.elearningPrice),
};

return { ...stepsPrices, ...eLearning && { elearning: eLearning } };
};

exports.getPriceDetails = priceDetails => Object.values(priceDetails)
.map(line => `${line.stepName || 'E-learning'} - ${line.duration.format(SHORT_DURATION_H_MM)}`
+ ` - ${UtilsHelper.formatPrice(line.price)}`)
.join('\r\n');
11 changes: 7 additions & 4 deletions tests/integration/completionCertificates.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,10 @@ describe('COMPLETION CERTIFICATES ROUTES - PUT /completioncertificates/{_id}', (
});

expect(response.statusCode).toBe(200);
const billCount = await CourseBill.countDocuments({ _id: courseBillsList[0]._id, 'mainFee.price': 200 });
expect(billCount).toBe(1);
const bill = await CourseBill.findOne({ _id: courseBillsList[0]._id }).setOptions({ isVendorUser: true }).lean();
expect(bill.mainFee.price).toBe(200);
expect(bill.mainFee.description)
.toBe('Facture test\r\n--- Détail ---\r\nautre étape - 4h - 200,00\u00a0€');
});

it('should return 404 if completion certificate does not exist', async () => {
Expand Down Expand Up @@ -421,8 +423,9 @@ describe('COMPLETION CERTIFICATES ROUTES - DELETE /completioncertificates/{_id}/
});

expect(response.statusCode).toBe(200);
const billCount = await CourseBill.countDocuments({ _id: courseBillsList[1]._id, 'mainFee.price': 0 });
expect(billCount).toBe(1);
const bill = await CourseBill.findOne({ _id: courseBillsList[1]._id }).setOptions({ isVendorUser: true }).lean();
expect(bill.mainFee.price).toBe(0);
expect(bill.mainFee.description).toBe('Facture test');
});

it('should return 404 if completion certificate does not exist', async () => {
Expand Down
23 changes: 23 additions & 0 deletions tests/integration/courseBills.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,29 @@ describe('COURSE BILL ROUTES - POST /coursebills/list-creation', () => {
expect(response.statusCode).toBe(409);
});

it('should create a bill with the price and the details of the hourly payment plan (GLOBAL)', async () => {
const response = await app.inject({
method: 'POST',
url: '/coursebills/list-creation',
headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` },
payload: {
...singleCoursePayload,
mainFee: omit(singleCoursePayload.mainFee, 'price'),
hourlyPaymentPlanId,
},
});

expect(response.statusCode).toBe(200);

const createdBill = await CourseBill
.findOne({ course: coursesList[12]._id, hourlyPaymentPlan: hourlyPaymentPlanId })
.setOptions({ isVendorUser: true })
.lean();
expect(createdBill.mainFee.price).toBe(150);
expect(createdBill.mainFee.description)
.toBe('test\r\n--- Détail ---\r\nétape - 3h - 150,00\u00a0€');
});

it('should return 400 if price sent with an hourly payment plan', async () => {
const response = await app.inject({
method: 'POST',
Expand Down
9 changes: 7 additions & 2 deletions tests/integration/seed/completionCertificatesSeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ const courseBillsList = [
course: courseList[2]._id,
companies: [authCompany._id],
payer: { company: authCompany._id },
mainFee: { price: 0, count: 1, countUnit: GROUP },
mainFee: { price: 0, count: 1, countUnit: GROUP, description: 'Facture test' },
hourlyPaymentPlan: hourlyPaymentPlanId,
maturityDate: '2020-01-15T10:00:00.000Z',
},
Expand All @@ -323,7 +323,12 @@ const courseBillsList = [
course: courseList[2]._id,
companies: [authCompany._id],
payer: { company: authCompany._id },
mainFee: { price: 200, count: 1, countUnit: GROUP },
mainFee: {
price: 200,
count: 1,
countUnit: GROUP,
description: 'Facture test \r\n--- Détail ---\r\nautre étape - 4h - 200,00\u00a0€',
},
hourlyPaymentPlan: hourlyPaymentPlanId,
maturityDate: '2020-01-20T10:00:00.000Z',
},
Expand Down
Loading
Loading