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
2 changes: 1 addition & 1 deletion src/helpers/courses.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 15 additions & 10 deletions src/helpers/notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pourquoi ne plus utiliser sendNotificationToUser ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parce que sendNotificationToUser n'envoie qu'une notif là où sendNotificationToAPI accepte un tableau et permet d'envoyer plusieurs notifs groupé, c'est le fait d'envoyer les notifs une par une à chaque apprenant qui retournait une 429

} catch (e) {
console.error(e);
}
}
};

exports.sendAttendanceSheetSignatureRequestNotification =
Expand Down
5 changes: 3 additions & 2 deletions src/helpers/subPrograms.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 }
Expand Down
11 changes: 9 additions & 2 deletions src/routes/preHandlers/courses.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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;
};
Expand Down
23 changes: 22 additions & 1 deletion tests/integration/courses.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down
16 changes: 16 additions & 0 deletions tests/integration/seed/coursesSeed.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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 = [
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/helpers/courses.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2889,7 +2889,7 @@ describe('getCourse', () => {
},
{
path: 'subProgram',
select: 'program steps paymentPlans hourlyPaymentPlans',
select: 'program steps paymentPlans hourlyPaymentPlans archivedAt',
populate: [
{ path: 'program', select: 'learningGoals' },
{
Expand Down Expand Up @@ -3009,7 +3009,7 @@ describe('getCourse', () => {
},
{
path: 'subProgram',
select: 'program steps paymentPlans hourlyPaymentPlans',
select: 'program steps paymentPlans hourlyPaymentPlans archivedAt',
populate: [
{ path: 'program', select: 'learningGoals' },
{
Expand Down Expand Up @@ -3118,7 +3118,7 @@ describe('getCourse', () => {
},
{
path: 'subProgram',
select: 'program steps paymentPlans hourlyPaymentPlans',
select: 'program steps paymentPlans hourlyPaymentPlans archivedAt',
populate: [
{ path: 'program', select: 'learningGoals' },
{
Expand Down Expand Up @@ -3301,7 +3301,7 @@ describe('getCourse', () => {
},
{
path: 'subProgram',
select: 'program steps paymentPlans hourlyPaymentPlans',
select: 'program steps paymentPlans hourlyPaymentPlans archivedAt',
populate: [
{ path: 'program', select: 'learningGoals' },
{
Expand Down
43 changes: 21 additions & 22 deletions tests/unit/helpers/notifications.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]'],
}];
Expand Down Expand Up @@ -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 },
},
]
);
});

Expand Down Expand Up @@ -271,7 +270,7 @@ describe('sendNewElearningCourseNotification', () => {
{ query: 'lean', args: [] },
]
);
sinon.assert.notCalled(sendNotificationToUser);
sinon.assert.notCalled(sendNotificationToAPI);
});
});

Expand Down
22 changes: 19 additions & 3 deletions tests/unit/helpers/subPrograms.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);
});
Expand Down
Loading