From 1b5e1e33a5957231e0c3cce58c1606b8edc792ed Mon Sep 17 00:00:00 2001 From: Bastien Seree Date: Tue, 24 Sep 2024 16:20:54 +0200 Subject: [PATCH] Cyberleague:[#114] Add isActionAllowed to manage nextQuestion action --- .../web/server/plugins/cyberleague/actions.js | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/backend/web/server/plugins/cyberleague/actions.js b/backend/web/server/plugins/cyberleague/actions.js index f1b63d1247..e4056defdc 100644 --- a/backend/web/server/plugins/cyberleague/actions.js +++ b/backend/web/server/plugins/cyberleague/actions.js @@ -1,10 +1,10 @@ -const { addAction } = require('../../utils/studio/actions') +const { addAction, setAllowActionFn } = require('../../utils/studio/actions') const Score = require("../../models/Score") const lodash = require('lodash') const { idEqual } = require('../../utils/database') -const { NotFoundError } = require('../../utils/errors') +const { NotFoundError, ForbiddenError } = require('../../utils/errors') const { createScore } = require('./score') -const { SCORE_LEVEL_1 } = require('./consts') +const { SCORE_LEVEL_1, ANSWERS } = require('./consts') // const startSurvey = async (_, user) => { @@ -33,4 +33,23 @@ const nextQuestion = async ({ value }, user) => { return score.answers[answerIndex +1] } //TODO rename action to next_question -addAction('smartdiet_next_question', nextQuestion) \ No newline at end of file +addAction('smartdiet_next_question', nextQuestion) + +const isActionAllowed = async ({action, dataId, user, ...rest}) => { + if (action == 'smartdiet_next_question') { + const score = await Score.findOne({answers: dataId}).populate('answers') + const answerIndex = lodash.findIndex(score.answers, (a)=> idEqual(a._id, dataId)) + + //if answer without answer + if (!lodash.includes(ANSWERS,score.answers[answerIndex])) { + throw new ForbiddenError(`Il faut répondre à la question avant de pouvoir passer à la suivante`) + } + + //si pas d'autres questions -> throw error + if (answerIndex + 1 == score.answers.length) { + throw new NotFoundError(`Il n'y a pas de question suivante`) + } + } +} + +setAllowActionFn(isActionAllowed) \ No newline at end of file