Skip to content

Commit

Permalink
[FEATURE] Mettre à jour la route de récupération de stages dans orga …
Browse files Browse the repository at this point in the history
…(Revert)(PIX-8914) "
  • Loading branch information
pix-service-auto-merge authored Oct 18, 2023
2 parents 2e21ae7 + 71ec101 commit dd40b73
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 199 deletions.
Original file line number Diff line number Diff line change
@@ -1,62 +1,46 @@
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable import/no-restricted-paths */
import * as defaultStageRepository from '../../infrastructure/repositories/stage-repository.js';
import * as defaultStageAcquisitionRepository from '../../infrastructure/repositories/stage-acquisition-repository.js';
import * as stageCollectionRepository from '../../infrastructure/repositories/user-campaign-results/stage-collection-repository.js';
import { UserNotAuthorizedToAccessEntityError, NoStagesForCampaign } from '../errors.js';
import * as defaultStageAndStageAcquisitionComparisonService from '../services/stages/stage-and-stage-acquisition-comparison-service.js';

const getCampaignParticipationsCountByStage = async function ({
userId,
campaignId,
campaignRepository,
stageRepository = defaultStageRepository,
stageAndStageAcquisitionComparisonService = defaultStageAndStageAcquisitionComparisonService,
stageAcquisitionRepository = defaultStageAcquisitionRepository,
campaignParticipationRepository,
}) {
if (!(await campaignRepository.checkIfUserOrganizationHasAccessToCampaign(campaignId, userId))) {
throw new UserNotAuthorizedToAccessEntityError('User does not belong to the organization that owns the campaign');
}

const stages = await stageRepository.getByCampaignId(campaignId);
const stageCollection = await stageCollectionRepository.findStageCollection({ campaignId });

if (!stages.length) {
if (!stageCollection.hasStage) {
throw new NoStagesForCampaign();
}

const stageAcquisitions = await stageAcquisitionRepository.getByCampaignId(campaignId);
const participantsResults = await campaignParticipationRepository.getAllParticipationsByCampaignId(campaignId);

const uniqueCampaignParticipationIds = [
...new Set(stageAcquisitions.map((stageAcquisition) => stageAcquisition.campaignParticipationId)),
];

const stagesInfos = stages.map((stage, index) => ({
const participantsByStage = stageCollection.stages.map((stage, index) => ({
id: stage.id,
value: 0,
reachedStage: index + 1,
totalStage: stages.length,
totalStage: stageCollection.totalStages,
title: stage.prescriberTitle,
description: stage.prescriberDescription,
}));

uniqueCampaignParticipationIds.forEach((campaignParticipationId) => {
const stageAcquisitionForCampaignParticipation = stageAcquisitions.filter(
(stageAcquisition) => stageAcquisition.campaignParticipationId === campaignParticipationId,
);

const stagesInformation = stageAndStageAcquisitionComparisonService.compare(
stages,
stageAcquisitionForCampaignParticipation,
participantsResults.forEach((participantResult) => {
const stageReached = stageCollection.getReachedStage(
participantResult.validatedSkillsCount,
participantResult.masteryRate * 100,
);

const stageReached = stagesInformation.reachedStage;

if (!stageReached) return;

const stageIndex = stagesInfos.findIndex((data) => data.id === stageReached.id);
stagesInfos[stageIndex].value++;
const stageIndex = participantsByStage.findIndex((data) => data.id === stageReached.id);
participantsByStage[stageIndex].value++;
});

return stagesInfos;
return participantsByStage;
};

export { getCampaignParticipationsCountByStage };
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const toDomain = (stageAcquisitionData) =>

/**
* @param {Knex} knexConnection
* @param {string[]} selectedFields
*
* @returns {*}
*/
Expand Down Expand Up @@ -89,25 +90,6 @@ const getByCampaignIdAndUserId = async (campaignId, userId, knexConnection = kne
.orderBy(`${STAGE_ACQUISITIONS_TABLE_NAME}.id`),
);

/**
* @param {number} campaignId
* @param {Knex} knexConnection
*
* @returns {Promise<StageAcquisition[]>}
*/
const getByCampaignId = async (campaignId, knexConnection = knex) =>
toDomain(
await buildSelectAllQuery(knexConnection)
.join(
'campaign-participations',
'campaign-participations.id',
`${STAGE_ACQUISITIONS_TABLE_NAME}.${CAMPAIGN_PARTICIPATION_ID_COLUMN}`,
)
.join('campaigns', 'campaigns.id', 'campaign-participations.campaignId')
.where('campaigns.id', campaignId)
.orderBy(`${STAGE_ACQUISITIONS_TABLE_NAME}.id`),
);

/**
* @param {Stage[]} stages
* @param {number} userId
Expand All @@ -126,10 +108,9 @@ const saveStages = async (stages, userId, campaignParticipationId, knexConnectio
};

export {
getByCampaignId,
getByCampaignParticipations,
getByCampaignIdAndUserId,
saveStages,
getByCampaignParticipation,
getByCampaignParticipations,
getStageIdsByCampaignParticipation,
saveStages,
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('Acceptance | API | Campaign Stats Controller', function () {
});

describe('GET /api/campaigns/{id}/stats/participations-by-stage', function () {
it('should return the campaign with stages information', async function () {
it('should return the campaign by id', async function () {
// given
const learningContentObjects = learningContentBuilder.fromAreas([
{
Expand Down Expand Up @@ -58,32 +58,7 @@ describe('Acceptance | API | Campaign Stats Controller', function () {
databaseBuilder.factory.buildCampaignSkill({ campaignId: campaign.id, skillId: 'recSkillId1' });
databaseBuilder.factory.buildCampaignSkill({ campaignId: campaign.id, skillId: 'recSkillId2' });
const userId = databaseBuilder.factory.buildUser().id;
const anotherUserId = databaseBuilder.factory.buildUser().id;
databaseBuilder.factory.buildMembership({ organizationId: campaign.organizationId, userId });
databaseBuilder.factory.buildMembership({ organizationId: campaign.organizationId, userId: anotherUserId });
const campaignParticipation = databaseBuilder.factory.buildCampaignParticipation({
userId,
campaignId: campaign.id,
});
const anotherCampaignParticipation = databaseBuilder.factory.buildCampaignParticipation({
userId: anotherUserId,
campaignId: campaign.id,
});
databaseBuilder.factory.buildStageAcquisition({
stageId: stage1.id,
userId,
campaignParticipationId: campaignParticipation.id,
});
databaseBuilder.factory.buildStageAcquisition({
stageId: stage2.id,
userId,
campaignParticipationId: campaignParticipation.id,
});
databaseBuilder.factory.buildStageAcquisition({
stageId: stage1.id,
userId: anotherUserId,
campaignParticipationId: anotherCampaignParticipation.id,
});
await databaseBuilder.commit();

// when
Expand All @@ -99,20 +74,13 @@ describe('Acceptance | API | Campaign Stats Controller', function () {
expect(response.result.data.attributes.data).to.deep.equal([
{
id: stage1.id,
value: 1,
value: 0,
title: stage1.prescriberTitle,
description: stage1.prescriberDescription,
'reached-stage': 1,
'total-stage': 2,
},
{
id: stage2.id,
value: 1,
title: stage2.prescriberTitle,
description: stage2.prescriberDescription,
'reached-stage': 2,
'total-stage': 2,
},
{ id: stage2.id, value: 0, title: null, description: null, 'reached-stage': 2, 'total-stage': 2 },
]);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ describe('Integration | UseCase | get-campaign-participations-counts-by-stage',
let campaignId;
let userId;
let stage1, stage2, stage3;
let campaignParticipation1, campaignParticipation2, campaignParticipation3, campaignParticipation4;

beforeEach(async function () {
const learningContentObjects = learningContentBuilder.fromAreas([
Expand Down Expand Up @@ -59,12 +58,10 @@ describe('Integration | UseCase | get-campaign-participations-counts-by-stage',
stage2 = databaseBuilder.factory.buildStage({ targetProfileId, threshold: 30 });
stage3 = databaseBuilder.factory.buildStage({ targetProfileId, threshold: 70 });
campaignId = databaseBuilder.factory.buildCampaign({ organizationId, targetProfileId }).id;
campaignParticipation1 = databaseBuilder.factory.buildCampaignParticipation({ campaignId });
campaignParticipation2 = databaseBuilder.factory.buildCampaignParticipation({ campaignId });
campaignParticipation3 = databaseBuilder.factory.buildCampaignParticipation({ campaignId });
campaignParticipation4 = databaseBuilder.factory.buildCampaignParticipation({ campaignId });

await databaseBuilder.commit();
databaseBuilder.factory.buildCampaignSkill({ campaignId, skillId: 'recSkillId1' });
databaseBuilder.factory.buildCampaignSkill({ campaignId, skillId: 'recSkillId2' });
databaseBuilder.factory.buildCampaignSkill({ campaignId, skillId: 'recSkillId3' });
databaseBuilder.factory.buildCampaignSkill({ campaignId, skillId: 'recSkillId4' });
});

context('when requesting user is not allowed to access campaign informations', function () {
Expand All @@ -84,9 +81,8 @@ describe('Integration | UseCase | get-campaign-participations-counts-by-stage',
});
});

context('when the campaign has no stages', function () {
context('when the campaign doesnt manage stages', function () {
it('should throw a NoStagesForCampaign error', async function () {
// given
const campaign2 = databaseBuilder.factory.buildCampaign({ organizationId });
databaseBuilder.factory.buildCampaignSkill({ campaignId: campaign2.id, skillId: 'recSkillId1' });
await databaseBuilder.commit();
Expand All @@ -103,48 +99,11 @@ describe('Integration | UseCase | get-campaign-participations-counts-by-stage',
});
});

context('when the campaign has stages', function () {
it('should return acquisitions counts by stages', async function () {
// given
[
// campaignParticipation1
{
stageId: stage1.id,
campaignParticipationId: campaignParticipation1.id,
},
{
stageId: stage2.id,
campaignParticipationId: campaignParticipation1.id,
},
{
stageId: stage3.id,
campaignParticipationId: campaignParticipation1.id,
},
// campaignParticipation2
{
stageId: stage1.id,
campaignParticipationId: campaignParticipation2.id,
},
{
stageId: stage2.id,
campaignParticipationId: campaignParticipation2.id,
},
// campaignParticipation3
{
stageId: stage1.id,
campaignParticipationId: campaignParticipation3.id,
},
// campaignParticipation4
{
stageId: stage1.id,
campaignParticipationId: campaignParticipation4.id,
},
{
stageId: stage2.id,
campaignParticipationId: campaignParticipation4.id,
},
].map(databaseBuilder.factory.buildStageAcquisition);

context('when the campaign manage stages', function () {
it('should return participations counts by stages', async function () {
databaseBuilder.factory.buildCampaignParticipation({ campaignId, masteryRate: 0 });
databaseBuilder.factory.buildCampaignParticipation({ campaignId, masteryRate: 0.31 });
databaseBuilder.factory.buildCampaignParticipation({ campaignId, masteryRate: 0.72 });
await databaseBuilder.commit();

// when
Expand All @@ -160,12 +119,14 @@ describe('Integration | UseCase | get-campaign-participations-counts-by-stage',
reachedStage: 1,
totalStage: 3,
},
{ id: stage2.id, value: 2, title: null, description: null, reachedStage: 2, totalStage: 3 },
{ id: stage2.id, value: 1, title: null, description: null, reachedStage: 2, totalStage: 3 },
{ id: stage3.id, value: 1, title: null, description: null, reachedStage: 3, totalStage: 3 },
]);
});

it('should set to 0 all participation counts when no stage acquisitions', async function () {
it('should set to 0 all participation counts when no participations', async function () {
await databaseBuilder.commit();

// when
const result = await usecases.getCampaignParticipationsCountByStage({ userId, campaignId });

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { expect, databaseBuilder, knex } from '../../../test-helper.js';
import {
getByCampaignId,
getByCampaignIdAndUserId,
getByCampaignParticipation,
getByCampaignParticipations,
Expand Down Expand Up @@ -109,8 +108,6 @@ describe('Integration | Repository | Stage Acquisition', function () {

// then
expect(result.length).to.deep.equal(2);
expect(result[0].campaignParticipationId).to.equal(firstStage.campaignParticipationId);
expect(result[1].campaignParticipationId).to.equal(secondStage.campaignParticipationId);
});
});

Expand Down Expand Up @@ -159,62 +156,6 @@ describe('Integration | Repository | Stage Acquisition', function () {
});
});

describe('getByCampaignId', function () {
let stage;
let campaign;
let campaignParticipation, campaignParticipation2, campaignParticipation3;
let targetProfile;

beforeEach(async function () {
// given
targetProfile = databaseBuilder.factory.buildTargetProfile();
databaseBuilder.factory.buildStage({ targetProfileId: targetProfile.id });
campaign = databaseBuilder.factory.buildCampaign({ targetProfileId: targetProfile.id });
stage = databaseBuilder.factory.buildStage({ campaignId: campaign.id });
campaignParticipation = databaseBuilder.factory.buildCampaignParticipation({ campaignId: campaign.id });
campaignParticipation2 = databaseBuilder.factory.buildCampaignParticipation({ campaignId: campaign.id });
campaignParticipation3 = databaseBuilder.factory.buildCampaignParticipation({ campaignId: campaign.id });
databaseBuilder.factory.buildStageAcquisition({
campaignParticipationId: campaignParticipation.id,
stageId: stage.id,
});
databaseBuilder.factory.buildStageAcquisition({
campaignParticipationId: campaignParticipation2.id,
stageId: stage.id,
});
databaseBuilder.factory.buildStageAcquisition({
campaignParticipationId: campaignParticipation3.id,
stageId: stage.id,
});

await databaseBuilder.commit();
});

afterEach(async function () {
await knex('stage-acquisitions').delete();
});

it('should return StageAcquisition instances', async function () {
// when
const stageAcquisitions = await getByCampaignId(campaign.id);

// then
expect(stageAcquisitions[0]).to.be.instanceof(StageAcquisition);
expect(stageAcquisitions.length).to.equal(3);
expect(stageAcquisitions[0].campaignParticipationId).to.equal(campaignParticipation.id);
expect(stageAcquisitions[1].campaignParticipationId).to.equal(campaignParticipation2.id);
expect(stageAcquisitions[2].campaignParticipationId).to.equal(campaignParticipation3.id);
});

it('should return the expected stages', async function () {
// when
const result = await getByCampaignId(campaign.id);

// then
expect(result[0].stageId).to.deep.equal(stage.id);
});
});

describe('saveStages', function () {
let targetProfile;
let stages;
Expand Down

0 comments on commit dd40b73

Please sign in to comment.