From 41f936051df8e527dbbcfeddc8aff3bf34d06a29 Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 16 Nov 2026 11:12:22 +0100 Subject: [PATCH 1/4] COM-4328 : notifications --- src/helpers/notifications.js | 25 ++++++++------ tests/unit/helpers/notifications.test.js | 43 ++++++++++++------------ 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/src/helpers/notifications.js b/src/helpers/notifications.js index 31dc77d083..1a8c2cc4b2 100644 --- a/src/helpers/notifications.js +++ b/src/helpers/notifications.js @@ -11,6 +11,7 @@ const { TRAINER_ATTENDANCE_REMINDER, } = require('./constants'); +const EXPO_BATCH_SIZE = 100; const EXPO_NOTIFICATION_API_URL = 'https://exp.host/--/api/v2/push/send/'; exports.sendNotificationToAPI = async payload => axios.post(`${EXPO_NOTIFICATION_API_URL}`, payload); @@ -54,21 +55,25 @@ exports.sendNewElearningCourseNotification = async (courseId, query) => { const courseName = getCourseName(course); - const notifications = []; + const messages = []; for (const trainee of trainees) { for (const expoToken of trainee.formationExpoTokenList) { - notifications.push( - this.sendNotificationToUser({ - title: 'Une nouvelle formation est disponible', - body: `Découvrez notre nouvelle formation : ${courseName}.`, - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken, - }) - ); + messages.push({ + to: expoToken, + title: 'Une nouvelle formation est disponible', + body: `Découvrez notre nouvelle formation : ${courseName}.`, + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }); } } - await Promise.all(notifications); + for (let i = 0; i < messages.length; i += EXPO_BATCH_SIZE) { + try { + await this.sendNotificationToAPI(messages.slice(i, i + EXPO_BATCH_SIZE)); + } catch (e) { + console.error(e); + } + } }; exports.sendAttendanceSheetSignatureRequestNotification = diff --git a/tests/unit/helpers/notifications.test.js b/tests/unit/helpers/notifications.test.js index 5203aa8f64..d7d148e8a6 100644 --- a/tests/unit/helpers/notifications.test.js +++ b/tests/unit/helpers/notifications.test.js @@ -153,23 +153,23 @@ describe('sendBlendedCourseRegistrationNotification', () => { }); describe('sendNewElearningCourseNotification', () => { - let sendNotificationToUser; + let sendNotificationToAPI; let courseFindOne; let userFind; beforeEach(() => { - sendNotificationToUser = sinon.stub(NotificationHelper, 'sendNotificationToUser'); + sendNotificationToAPI = sinon.stub(NotificationHelper, 'sendNotificationToAPI'); courseFindOne = sinon.stub(Course, 'findOne'); userFind = sinon.stub(User, 'find'); }); afterEach(() => { - sendNotificationToUser.restore(); + sendNotificationToAPI.restore(); courseFindOne.restore(); userFind.restore(); }); - it('should format payload and call sendNotificationToUser', async () => { + it('should format payload and call sendNotificationToAPI', async () => { const trainees = [{ formationExpoTokenList: ['ExponentPushToken[jeSuisUnTokenExpo]', 'ExponentPushToken[jeSuisUnAutreTokenExpo]'], }]; @@ -212,23 +212,22 @@ describe('sendNewElearningCourseNotification', () => { { query: 'lean', args: [] }, ] ); - sinon.assert.calledWithExactly( - sendNotificationToUser.getCall(0), - { - title: 'Une nouvelle formation est disponible', - body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken: 'ExponentPushToken[jeSuisUnTokenExpo]', - } - ); - sinon.assert.calledWithExactly( - sendNotificationToUser.getCall(1), - { - title: 'Une nouvelle formation est disponible', - body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', - data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, - expoToken: 'ExponentPushToken[jeSuisUnAutreTokenExpo]', - } + sinon.assert.calledOnceWithExactly( + sendNotificationToAPI, + [ + { + to: 'ExponentPushToken[jeSuisUnTokenExpo]', + title: 'Une nouvelle formation est disponible', + body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }, + { + to: 'ExponentPushToken[jeSuisUnAutreTokenExpo]', + title: 'Une nouvelle formation est disponible', + body: 'Découvrez notre nouvelle formation : La communication avec Patrick - skusku.', + data: { _id: course.subProgram.program._id, type: NEW_ELEARNING_COURSE }, + }, + ] ); }); @@ -271,7 +270,7 @@ describe('sendNewElearningCourseNotification', () => { { query: 'lean', args: [] }, ] ); - sinon.assert.notCalled(sendNotificationToUser); + sinon.assert.notCalled(sendNotificationToAPI); }); }); From f04d855ff6dc4cb6f393a363748fa6288dab1eac Mon Sep 17 00:00:00 2001 From: ulysse Date: Mon, 16 Nov 2026 11:12:36 +0100 Subject: [PATCH 2/4] COM-4328 : access rules --- src/helpers/subPrograms.js | 5 +++-- tests/unit/helpers/subPrograms.test.js | 22 +++++++++++++++++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/helpers/subPrograms.js b/src/helpers/subPrograms.js index 394ee4e411..c16dd3a3ad 100644 --- a/src/helpers/subPrograms.js +++ b/src/helpers/subPrograms.js @@ -162,6 +162,7 @@ exports.updateSubProgram = async (subProgramId, payload) => { .findOne({ subProgram: { $in: otherSubProgramList }, type: INTER_B2C, format: STRICTLY_E_LEARNING }) .lean(); let courseId; + const accessCompanies = existingCourse ? existingCourse.accessRules : payload.accessCompanies; if (existingCourse) { courseId = existingCourse._id; await updateExistingElearningCourse(existingCourse._id, subProgramId); @@ -176,11 +177,11 @@ exports.updateSubProgram = async (subProgramId, payload) => { courseId = course._id; } query = { formationExpoTokenList: { $exists: true, $not: { $size: 0 } } }; - if (payload.accessCompanies) { + if (accessCompanies && accessCompanies.length) { const userCompanies = await UserCompany .find( { - company: { $in: payload.accessCompanies }, + company: { $in: accessCompanies }, $or: [{ endDate: { $gt: CompaniDate().toISO() } }, { endDate: { $exists: false } }], }, { user: 1 } diff --git a/tests/unit/helpers/subPrograms.test.js b/tests/unit/helpers/subPrograms.test.js index aa82ae32dc..84b3000e9d 100644 --- a/tests/unit/helpers/subPrograms.test.js +++ b/tests/unit/helpers/subPrograms.test.js @@ -472,11 +472,13 @@ describe('updateSubProgram', () => { ], program: { name: 'nom', subPrograms: programSubPrograms }, }; + const userId = new ObjectId(); const existingCourse = { _id: new ObjectId(), subProgram: otherSubProgramId, accessRules: [new ObjectId()] }; findOneAndUpdate.returns(SinonMongoose.stubChainedQueries(updatedSubProgram)); stepUpdateManyStub.returns({ activities }); courseFindOne.returns(SinonMongoose.stubChainedQueries(existingCourse, ['lean'])); + userCompanyFind.returns(SinonMongoose.stubChainedQueries([{ user: userId }], ['lean'])); await SubProgramHelper.updateSubProgram(subProgram._id, payload); @@ -496,14 +498,28 @@ describe('updateSubProgram', () => { { $set: { subProgram: subProgram._id } } ); sinon.assert.notCalled(courseCreateStub); - sinon.assert.notCalled(find); sinon.assert.notCalled(updateOne); + SinonMongoose.calledOnceWithExactly( + userCompanyFind, + [ + { + query: 'find', + args: [ + { + company: { $in: existingCourse.accessRules }, + $or: [{ endDate: { $gt: '2025-03-31T14:00:00.000Z' } }, { endDate: { $exists: false } }], + }, + { user: 1 }, + ], + }, + { query: 'lean' }, + ] + ); sinon.assert.calledWithExactly( sendNewElearningCourseNotification, existingCourse._id, - { formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } + { _id: { $in: [userId] }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); - sinon.assert.notCalled(userCompanyFind); sinon.assert.notCalled(getLastVersion); sinon.assert.notCalled(findOne); }); From e7c41909aaca54c11a046cb13a4a470407bfea73 Mon Sep 17 00:00:00 2001 From: ulysse Date: Tue, 17 Nov 2026 17:52:53 +0100 Subject: [PATCH 3/4] COM-4328: fix bug --- src/helpers/courses.js | 10 +++++++- tests/unit/helpers/courses.test.js | 38 ++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 6d428c5496..cf258b2661 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -1869,7 +1869,15 @@ exports.generateCompletionCertificates = async (courseId, credentials, query) => }; exports.addAccessRule = async (courseId, payload) => { - await Course.updateOne({ _id: courseId }, { $addToSet: { accessRules: payload.companies } }); + const course = await Course + .findOneAndUpdate( + { _id: courseId }, + { $addToSet: { accessRules: payload.companies } }, + { projection: { subProgram: 1 } } + ) + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); + if (course.subProgram.archivedAt) return; const userCompanies = await UserCompany .find( diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 0ce3540e33..ac25274421 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -9003,17 +9003,17 @@ describe('generateCompletionCertificates', () => { }); describe('addAccessRule', () => { - let updateOne; + let findOneAndUpdate; let userCompanyFind; let sendNewElearningCourseNotification; beforeEach(() => { - updateOne = sinon.stub(Course, 'updateOne'); + findOneAndUpdate = sinon.stub(Course, 'findOneAndUpdate'); userCompanyFind = sinon.stub(UserCompany, 'find'); sendNewElearningCourseNotification = sinon.stub(NotificationHelper, 'sendNewElearningCourseNotification'); }); afterEach(() => { - updateOne.restore(); + findOneAndUpdate.restore(); userCompanyFind.restore(); sendNewElearningCourseNotification.restore(); }); @@ -9026,10 +9026,25 @@ describe('addAccessRule', () => { { user: userIds[0], company: payload.companies[0] }, { user: userIds[1], company: payload.companies[1] }, ]; + findOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId() } })); userCompanyFind.returns(SinonMongoose.stubChainedQueries(userCompanies, ['lean'])); await CourseHelper.addAccessRule(courseId, payload); - sinon.assert.calledOnceWithExactly(updateOne, { _id: courseId }, { $addToSet: { accessRules: payload.companies } }); + SinonMongoose.calledOnceWithExactly( + findOneAndUpdate, + [ + { + query: 'findOneAndUpdate', + args: [ + { _id: courseId }, + { $addToSet: { accessRules: payload.companies } }, + { projection: { subProgram: 1 } }, + ], + }, + { query: 'populate', args: [{ path: 'subProgram', select: 'archivedAt' }] }, + { query: 'lean' }, + ] + ); SinonMongoose.calledOnceWithExactly( userCompanyFind, [ @@ -9051,6 +9066,21 @@ describe('addAccessRule', () => { { _id: { $in: userIds }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); }); + + it('should add access rule but not notify if subProgram is archived', async () => { + const courseId = new ObjectId(); + const payload = { companies: [new ObjectId()] }; + findOneAndUpdate.returns( + SinonMongoose + .stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId(), archivedAt: '2025-01-01T12:30:00' } }) + ); + + await CourseHelper.addAccessRule(courseId, payload); + + sinon.assert.calledOnce(findOneAndUpdate); + sinon.assert.notCalled(userCompanyFind); + sinon.assert.notCalled(sendNewElearningCourseNotification); + }); }); describe('deleteAccessRule', () => { From 137dbfb47dc777239e23d6bcebc6f4902eb3c763 Mon Sep 17 00:00:00 2001 From: ulysse Date: Wed, 18 Nov 2026 14:22:01 +0100 Subject: [PATCH 4/4] COM-4328: review --- src/helpers/courses.js | 12 ++----- src/routes/preHandlers/courses.js | 11 +++++-- tests/integration/courses.test.js | 23 +++++++++++++- tests/integration/seed/coursesSeed.js | 16 ++++++++++ tests/unit/helpers/courses.test.js | 46 +++++---------------------- 5 files changed, 57 insertions(+), 51 deletions(-) diff --git a/src/helpers/courses.js b/src/helpers/courses.js index cf258b2661..7725dcca36 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -587,7 +587,7 @@ const getCourseForOperations = async (courseId, credentials, origin) => { }, { path: 'subProgram', - select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans' : 'program steps', + select: origin === WEBAPP ? 'program steps paymentPlans hourlyPaymentPlans archivedAt' : 'program steps', populate: [ { path: 'program', select: 'learningGoals' }, ...(origin === WEBAPP @@ -1869,15 +1869,7 @@ exports.generateCompletionCertificates = async (courseId, credentials, query) => }; exports.addAccessRule = async (courseId, payload) => { - const course = await Course - .findOneAndUpdate( - { _id: courseId }, - { $addToSet: { accessRules: payload.companies } }, - { projection: { subProgram: 1 } } - ) - .populate({ path: 'subProgram', select: 'archivedAt' }) - .lean(); - if (course.subProgram.archivedAt) return; + await Course.updateOne({ _id: courseId }, { $addToSet: { accessRules: payload.companies } }); const userCompanies = await UserCompany .find( diff --git a/src/routes/preHandlers/courses.js b/src/routes/preHandlers/courses.js index dc4cb9ed84..a892245220 100644 --- a/src/routes/preHandlers/courses.js +++ b/src/routes/preHandlers/courses.js @@ -601,8 +601,11 @@ exports.authorizeGetCourse = async (req) => { }; exports.authorizeAccessRuleAddition = async (req) => { - const course = await Course.findById(req.params._id, 'accessRules').lean(); + const course = await Course.findById(req.params._id, 'accessRules subProgram') + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); if (!course) throw Boom.notFound(); + if (course.subProgram.archivedAt) throw Boom.forbidden(); const accessRuleAlreadyExist = req.payload.companies .some(companyId => UtilsHelper.doesArrayIncludeId(course.accessRules, companyId)); @@ -615,9 +618,13 @@ exports.authorizeAccessRuleAddition = async (req) => { }; exports.authorizeAccessRuleDeletion = async (req) => { - const course = await Course.countDocuments({ _id: req.params._id, accessRules: req.params.accessRuleId }); + const course = await Course + .findOne({ _id: req.params._id, accessRules: req.params.accessRuleId }, 'subProgram') + .populate({ path: 'subProgram', select: 'archivedAt' }) + .lean(); if (!course) throw Boom.notFound(); + if (course.subProgram.archivedAt) throw Boom.forbidden(); return null; }; diff --git a/tests/integration/courses.test.js b/tests/integration/courses.test.js index 29c24e7d43..06ab7d2f6c 100644 --- a/tests/integration/courses.test.js +++ b/tests/integration/courses.test.js @@ -1020,7 +1020,7 @@ describe('COURSES ROUTES - GET /courses', () => { }); expect(response.statusCode).toBe(200); - expect(response.result.data.courses.length).toEqual(4); + expect(response.result.data.courses.length).toEqual(5); }); it('should get all trainee courses (pedagogy webapp)', async () => { @@ -5092,6 +5092,17 @@ describe('COURSES ROUTES - POST /:_id/accessrules', () => { expect(response.statusCode).toBe(409); }); + it('should return 403 if subProgram is archived', async () => { + const response = await app.inject({ + method: 'POST', + url: `/courses/${coursesList[28]._id}/accessrules`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + payload: { companies: [otherCompany._id] }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 404 if company does not exist', async () => { const response = await app.inject({ method: 'POST', @@ -5172,6 +5183,16 @@ describe('COURSES ROUTES - DELETE /:_id/accessrules/:accessRuleId', () => { expect(response.statusCode).toBe(404); }); + it('should return 403 if subProgram is archived', async () => { + const response = await app.inject({ + method: 'DELETE', + url: `/courses/${coursesList[28]._id}/accessrules/${authCompany._id}`, + headers: { Cookie: `${process.env.ALENVI_TOKEN}=${authToken}` }, + }); + + expect(response.statusCode).toBe(403); + }); + it('should return 404 if accessRules doesn\'t exist', async () => { const response = await app.inject({ method: 'DELETE', diff --git a/tests/integration/seed/coursesSeed.js b/tests/integration/seed/coursesSeed.js index c6ba003827..21c8aba662 100644 --- a/tests/integration/seed/coursesSeed.js +++ b/tests/integration/seed/coursesSeed.js @@ -369,6 +369,13 @@ const subProgramsList = [ sheetTemplateId: 'templateId', folderId: 'parent_folderId', }, + { + _id: new ObjectId(), + name: 'sous-programme archivé', + steps: [stepList[1]._id], + status: PUBLISHED, + archivedAt: '2021-01-01T00:00:00.000Z', + }, ]; const programsList = [ @@ -832,6 +839,15 @@ const coursesList = [ }, ], }, + { // 28 eLearning course with archived subProgram + _id: new ObjectId(), + subProgram: subProgramsList[5]._id, + type: INTER_B2C, + format: STRICTLY_E_LEARNING, + trainees: [], + accessRules: [authCompany._id], + tradeName: 'nom', + }, ]; const courseBillsList = [ diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index ac25274421..50827cb716 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -2889,7 +2889,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3009,7 +3009,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3118,7 +3118,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -3301,7 +3301,7 @@ describe('getCourse', () => { }, { path: 'subProgram', - select: 'program steps paymentPlans hourlyPaymentPlans', + select: 'program steps paymentPlans hourlyPaymentPlans archivedAt', populate: [ { path: 'program', select: 'learningGoals' }, { @@ -9003,17 +9003,17 @@ describe('generateCompletionCertificates', () => { }); describe('addAccessRule', () => { - let findOneAndUpdate; + let updateOne; let userCompanyFind; let sendNewElearningCourseNotification; beforeEach(() => { - findOneAndUpdate = sinon.stub(Course, 'findOneAndUpdate'); + updateOne = sinon.stub(Course, 'updateOne'); userCompanyFind = sinon.stub(UserCompany, 'find'); sendNewElearningCourseNotification = sinon.stub(NotificationHelper, 'sendNewElearningCourseNotification'); }); afterEach(() => { - findOneAndUpdate.restore(); + updateOne.restore(); userCompanyFind.restore(); sendNewElearningCourseNotification.restore(); }); @@ -9026,25 +9026,10 @@ describe('addAccessRule', () => { { user: userIds[0], company: payload.companies[0] }, { user: userIds[1], company: payload.companies[1] }, ]; - findOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId() } })); userCompanyFind.returns(SinonMongoose.stubChainedQueries(userCompanies, ['lean'])); await CourseHelper.addAccessRule(courseId, payload); - SinonMongoose.calledOnceWithExactly( - findOneAndUpdate, - [ - { - query: 'findOneAndUpdate', - args: [ - { _id: courseId }, - { $addToSet: { accessRules: payload.companies } }, - { projection: { subProgram: 1 } }, - ], - }, - { query: 'populate', args: [{ path: 'subProgram', select: 'archivedAt' }] }, - { query: 'lean' }, - ] - ); + sinon.assert.calledOnceWithExactly(updateOne, { _id: courseId }, { $addToSet: { accessRules: payload.companies } }); SinonMongoose.calledOnceWithExactly( userCompanyFind, [ @@ -9066,21 +9051,6 @@ describe('addAccessRule', () => { { _id: { $in: userIds }, formationExpoTokenList: { $exists: true, $not: { $size: 0 } } } ); }); - - it('should add access rule but not notify if subProgram is archived', async () => { - const courseId = new ObjectId(); - const payload = { companies: [new ObjectId()] }; - findOneAndUpdate.returns( - SinonMongoose - .stubChainedQueries({ _id: courseId, subProgram: { _id: new ObjectId(), archivedAt: '2025-01-01T12:30:00' } }) - ); - - await CourseHelper.addAccessRule(courseId, payload); - - sinon.assert.calledOnce(findOneAndUpdate); - sinon.assert.notCalled(userCompanyFind); - sinon.assert.notCalled(sendNewElearningCourseNotification); - }); }); describe('deleteAccessRule', () => {