diff --git a/src/helpers/courses.js b/src/helpers/courses.js index 6d428c5496..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 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 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/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 0ce3540e33..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' }, { 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 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); });