update api for test

This commit is contained in:
iIronside 2023-11-16 11:55:49 +03:00
parent b258eb7edf
commit 886ba1e656
15 changed files with 290 additions and 290 deletions

View File

@ -23,6 +23,15 @@ class UserQuestionnaireStatusHelper
]; ];
} }
public static function listCompleteStatuses(): array
{
return [
self::STATUS_COMPLETED,
self::STATUS_ON_INSPECTION
];
}
/** /**
* @throws Exception * @throws Exception
*/ */

View File

@ -89,11 +89,6 @@ class Answer extends \yii\db\ActiveRecord
->viaTable('question', ['id' => 'question_id']); ->viaTable('question', ['id' => 'question_id']);
} }
// public function getUserQuestionnaire()
// {
// return $this->hasOne(\backend\modules\questionnaire\models\UserQuestionnaire::className(), ['id'])
// }
static function numCorrectAnswers($question_id) static function numCorrectAnswers($question_id)
{ {
return Answer::find() return Answer::find()

View File

@ -133,7 +133,6 @@ class Question extends \yii\db\ActiveRecord
{ {
return self::find()->where(['questionnaire_id' => $questionnaire_id]) return self::find()->where(['questionnaire_id' => $questionnaire_id])
->andWhere(['status' => '1']) ->andWhere(['status' => '1'])
->AsArray()
->all(); ->all();
} }
} }

View File

@ -26,6 +26,8 @@ use \backend\modules\questionnaire\models\Answer;
* @property int $score * @property int $score
* @property int $status * @property int $status
* @property double $percent_correct_answers * @property double $percent_correct_answers
* @property string $testing_date
* @property string $start_testing
* *
* @property Questionnaire $questionnaire * @property Questionnaire $questionnaire
* @property User $user * @property User $user
@ -63,7 +65,7 @@ class UserQuestionnaire extends ActiveRecord
[['questionnaire_id', 'user_id', 'status'], 'required'], [['questionnaire_id', 'user_id', 'status'], 'required'],
[['questionnaire_id', 'user_id', 'score', 'status'], 'integer'], [['questionnaire_id', 'user_id', 'score', 'status'], 'integer'],
[['percent_correct_answers'], 'number'], [['percent_correct_answers'], 'number'],
[['created_at', 'updated_at', 'testing_date'], 'safe'], [['created_at', 'updated_at', 'testing_date', 'start_testing'], 'safe'],
[['uuid'], 'string', 'max' => 36], [['uuid'], 'string', 'max' => 36],
[['uuid'], 'unique'], [['uuid'], 'unique'],
[['questionnaire_id'], 'exist', 'skipOnError' => true, 'targetClass' => Questionnaire::className(), 'targetAttribute' => ['questionnaire_id' => 'id']], [['questionnaire_id'], 'exist', 'skipOnError' => true, 'targetClass' => Questionnaire::className(), 'targetAttribute' => ['questionnaire_id' => 'id']],
@ -98,6 +100,7 @@ class UserQuestionnaire extends ActiveRecord
'created_at' => 'Дата создания', 'created_at' => 'Дата создания',
'updated_at' => 'Дата обновления', 'updated_at' => 'Дата обновления',
'testing_date' => 'Дата тестирования', 'testing_date' => 'Дата тестирования',
'start_testing' => 'Дата начала тестирования',
'percent_correct_answers' => 'Процент правильных ответов', 'percent_correct_answers' => 'Процент правильных ответов',
]; ];
} }

View File

@ -0,0 +1,25 @@
<?php
use yii\db\Migration;
/**
* Class m231114_072752_add_column_start_testing_to_user_questionnaire
*/
class m231114_072752_add_column_start_testing_to_user_questionnaire extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->addColumn('user_questionnaire', 'start_testing', $this->dateTime());
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropColumn('user_questionnaire', 'start_testing');
}
}

View File

@ -1,85 +0,0 @@
<?php
namespace frontend\modules\api\controllers;
use common\models\Answer;
use Yii;
use yii\filters\auth\HttpBearerAuth;
use yii\web\NotFoundHttpException;
use yii\rest\Controller;
class AnswerController extends ApiController
{
// public function behaviors(): array
// {
// $behaviors = parent::behaviors();
//
// $behaviors['authenticator']['authMethods'] = [
// HttpBearerAuth::className(),
// ];
//
// return $behaviors;
// }
public function verbs(): array
{
return [
'get-answers' => ['get'],
];
}
/**
* @OA\Get(path="/answer/get-answers",
* summary="Список ответов на вопрос",
* description="Получение списка ответов",
* security={
* {"bearerAuth": {}}
* },
* tags={"Tests"},
* @OA\Parameter(
* name="question_id",
* in="query",
* required=true,
* description="id вопроса",
* @OA\Schema(
* type="integer",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает масив вопросов",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/AnswerExampleArr"),
* ),
*
* ),
* )
*
* @throws NotFoundHttpException
*/
public function actionGetAnswers(): array
{
$question_id = Yii::$app->request->get('question_id');
if(empty($question_id) or !is_numeric($question_id))
{
throw new NotFoundHttpException('Incorrect question ID');
}
$answers = Answer::activeAnswers($question_id);
if(empty($answers)) {
throw new NotFoundHttpException('Answers not found or question inactive');
}
array_walk( $answers, function(&$arr){
unset(
$arr['created_at'],
$arr['updated_at'],
$arr['answer_flag'],
$arr['status']
);
});
return $answers;
}
}

View File

@ -2,36 +2,35 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use common\helpers\UUIDHelper; use Exception;
use common\models\Question; use frontend\modules\api\models\questionnaire\forms\QuestionnaireUuidForm;
use common\models\UserQuestionnaire; use frontend\modules\api\models\questionnaire\Question;
use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use frontend\modules\api\services\UserQuestionnaireService;
use Yii; use Yii;
use yii\filters\auth\HttpBearerAuth; use yii\web\BadRequestHttpException;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;
class QuestionController extends ApiController class QuestionController extends ApiController
{ {
public function behaviors() private UserQuestionnaireService $userQuestionnaireService;
{
$behaviors = parent::behaviors();
$behaviors['authenticator']['authMethods'] = [
HttpBearerAuth::className(),
];
return $behaviors;
}
public function verbs() public function __construct(
$id,
$module,
UserQuestionnaireService $userQuestionnaireService,
$config = []
)
{ {
return [ $this->userQuestionnaireService = $userQuestionnaireService;
'get-questions' => ['get'], parent::__construct($id, $module, $config);
];
} }
/** /**
* @OA\Get(path="/question/get-questions", * @OA\Get(path="/question/get-questions",
* summary="Список вопросов", * summary="Список вопросов",
* description="Получение списка вопросов", * description="Получение списка вопросов и возможные варианты ответа. Сохраняет временную метку начала тестирования,
от которой будет отсчитываться временной интервал на выполнение теста. При наличии лимита времени на выполнение теста.
При превышении лимита времени на выполнение будет возвращена ошибка: Time's up!",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
@ -53,40 +52,28 @@ class QuestionController extends ApiController
* @OA\Schema(ref="#/components/schemas/QuestionExampleArr"), * @OA\Schema(ref="#/components/schemas/QuestionExampleArr"),
* ), * ),
* *
*
* ), * ),
* ) * )
* *
* @throws NotFoundHttpException * @throws BadRequestHttpException
* @throws \Exception * @throws Exception
*/ */
public function actionGetQuestions(): array public function actionGetQuestions(): array
{ {
$uuid = Yii::$app->request->get('uuid'); $form = new QuestionnaireUuidForm();
if(empty($uuid) or !UUIDHelper::is_valid($uuid)) if ($form->load(Yii::$app->request->get()) && !$form->validate()) {
{ $errors = $form->errors;
throw new NotFoundHttpException('Incorrect questionnaire UUID'); throw new BadRequestHttpException(array_shift($errors)[0]);
} }
$questionnaire_id = UserQuestionnaire::getQuestionnaireId($uuid); $userQuestionnaire = UserQuestionnaire::findOne(['uuid' => $form->uuid]);
$questions = Question::activeQuestions($questionnaire_id); if (!$this->userQuestionnaireService->checkTimeLimit($userQuestionnaire)) {
if(empty($questions)) { UserQuestionnaireService::calculateScore($userQuestionnaire->uuid);
throw new NotFoundHttpException('Questions not found'); throw new BadRequestHttpException("Time's up!");
} }
array_walk( $questions, function(&$arr){ return Question::activeQuestions($userQuestionnaire->questionnaire_id);
unset(
$arr['score'],
$arr['created_at'],
$arr['updated_at'],
$arr['status'],
$arr['questionnaire_id']
);
});
return $questions;
} }
} }

View File

@ -2,8 +2,9 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use frontend\modules\api\models\UserQuestionnaire; use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use frontend\modules\api\services\UserQuestionnaireService; use frontend\modules\api\services\UserQuestionnaireService;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException; use yii\web\ServerErrorHttpException;
@ -14,14 +15,11 @@ class UserQuestionnaireController extends ApiController
public function behaviors(): array public function behaviors(): array
{ {
return ArrayHelper::merge(parent::behaviors(), [ return ArrayHelper::merge(parent::behaviors(), [
'verbs' => [ 'verbs' => [
'class' => \yii\filters\VerbFilter::class, 'class' => \yii\filters\VerbFilter::class,
'actions' => [ 'actions' => [
'questionnaires-list' => ['get'], 'questionnaires-list' => ['get'],
'questionnaire-completed' => ['get'], 'questionnaire-completed' => ['get'],
'get-points-number' => ['get'],
'get-question-number' => ['get'],
], ],
] ]
]); ]);
@ -73,7 +71,7 @@ class UserQuestionnaireController extends ApiController
/** /**
* @OA\Get(path="/user-questionnaire/questionnaire-completed", * @OA\Get(path="/user-questionnaire/questionnaire-completed",
* summary="Проверка теста", * summary="Проверка теста",
* description="Выполнения проверки теста", * description="Выполнение проверки теста",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
@ -98,7 +96,7 @@ class UserQuestionnaireController extends ApiController
* ) * )
* *
* @throws NotFoundHttpException * @throws NotFoundHttpException
* @throws ServerErrorHttpException * @throws ServerErrorHttpException|InvalidConfigException
*/ */
public function actionQuestionnaireCompleted($user_questionnaire_uuid): UserQuestionnaire public function actionQuestionnaireCompleted($user_questionnaire_uuid): UserQuestionnaire
{ {
@ -108,90 +106,4 @@ class UserQuestionnaireController extends ApiController
} }
return $userQuestionnaireModel; return $userQuestionnaireModel;
} }
/**
* @OA\Get(path="/user-questionnaire/get-points-number",
* summary="Количество балов в тесте",
* description="Возвращает максимальное количество балов за тест",
* security={
* {"bearerAuth": {}}
* },
* tags={"Tests"},
* @OA\Parameter(
* name="user_questionnaire_uuid",
* in="query",
* required=true,
* @OA\Schema(
* type="string",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает максимально возможное количество балов за тест",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* @OA\Property(
* property="sum_point",
* type="integer",
* example="61",
* ),
* ),
* ),
*
* ),
* )
* @throws ServerErrorHttpException
*/
public function actionGetPointsNumber($user_questionnaire_uuid): array
{
$questionPointsNumber = UserQuestionnaireService::getPointsNumber($user_questionnaire_uuid);
if (empty($questionPointsNumber)) {
throw new ServerErrorHttpException('Question points not found!');
}
return $questionPointsNumber;
}
/**
* @OA\Get(path="/user-questionnaire/get-question-number",
* summary="Число вопросов в тесте",
* description="Возвращает число вопросов в тесте",
* security={
* {"bearerAuth": {}}
* },
* tags={"Tests"},
* @OA\Parameter(
* name="user_questionnaire_uuid",
* in="query",
* required=true,
* @OA\Schema(
* type="string",
* )
* ),
* @OA\Response(
* response=200,
* description="Возвращает число вопросов в тесте",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* @OA\Property(
* property="question_number",
* type="integer",
* example="61",
* ),
* ),
* ),
*
* ),
* )
* @throws ServerErrorHttpException
*/
public function actionGetQuestionNumber($user_questionnaire_uuid): array
{
$questionNumber = UserQuestionnaireService::getQuestionNumber($user_questionnaire_uuid);
if (empty($questionNumber)) {
throw new ServerErrorHttpException('Question number not found!');
}
return $questionNumber;
}
} }

View File

@ -2,6 +2,8 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use frontend\modules\api\services\UserQuestionnaireService;
use frontend\modules\api\services\UserResponseService; use frontend\modules\api\services\UserResponseService;
use Yii; use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
@ -10,18 +12,24 @@ use yii\web\ServerErrorHttpException;
class UserResponseController extends ApiController class UserResponseController extends ApiController
{ {
public function verbs(): array private UserQuestionnaireService $userQuestionnaireService;
public function __construct(
$id,
$module,
UserQuestionnaireService $userQuestionnaireService,
$config = []
)
{ {
return [ $this->userQuestionnaireService = $userQuestionnaireService;
'set-response' => ['post'], parent::__construct($id, $module, $config);
'set-responses' => ['post'],
];
} }
/** /**
* @OA\Post(path="/user-response/set-responses", * @OA\Post(path="/user-response/set-responses",
* summary="Добавить массив ответов пользователя", * summary="Добавить массив ответов пользователя",
* description="Добавление массива ответов на вопросы от пользователя", * description="Добавление массива ответов на вопросы от пользователя. При наличии лимита времени на выполнение теста,
будет проведена проверка. При превышении лимита времени на выполнение будет возвращена ошибка: Time's up!",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
@ -58,7 +66,7 @@ class UserResponseController extends ApiController
* *
* @OA\Response( * @OA\Response(
* response=200, * response=200,
* description="Возвращает объект Запроса", * description="Возвращает масив ответов",
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/UserResponseExampleArr"), * @OA\Schema(ref="#/components/schemas/UserResponseExampleArr"),
@ -66,12 +74,25 @@ class UserResponseController extends ApiController
* ), * ),
* ) * )
* *
* @return array
* @throws BadRequestHttpException
* @throws InvalidConfigException * @throws InvalidConfigException
* @throws ServerErrorHttpException|BadRequestHttpException * @throws ServerErrorHttpException
* @throws \yii\web\NotFoundHttpException
*/ */
public function actionSetResponses(): array public function actionSetResponses(): array
{ {
$userResponseModels = UserResponseService::createUserResponses(Yii::$app->getRequest()->getBodyParams()); $uuid = Yii::$app->request->post('user_questionnaire_uuid');
$userResponses = Yii::$app->request->post('userResponses');
$userQuestionnaire = UserQuestionnaire::findOne(['uuid' => $uuid]);
if (!$this->userQuestionnaireService->checkTimeLimit($userQuestionnaire)) {
UserQuestionnaireService::calculateScore($userQuestionnaire->uuid);
throw new BadRequestHttpException("Time's up!");
}
$userResponseModels = UserResponseService::createUserResponses($userResponses, $uuid);
foreach ($userResponseModels as $model) { foreach ($userResponseModels as $model) {
if ($model->errors) { if ($model->errors) {
throw new ServerErrorHttpException(json_encode($model->errors)); throw new ServerErrorHttpException(json_encode($model->errors));

View File

@ -1,6 +1,6 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\questionnaire;
/** /**
@ -20,7 +20,7 @@ namespace frontend\modules\api\models;
* description="Идентификатор вопроса" * description="Идентификатор вопроса"
* ), * ),
* @OA\Property( * @OA\Property(
* property="question_body", * property="answer_body",
* type="string", * type="string",
* example="Вопрос №1", * example="Вопрос №1",
* description="Тело вопроса" * description="Тело вопроса"
@ -32,8 +32,8 @@ namespace frontend\modules\api\models;
* schema="AnswerExampleArr", * schema="AnswerExampleArr",
* type="array", * type="array",
* example={ * example={
* {"id": "1", "question_id": 2, "question_body": "Ответ 1",}, * {"id": "1", "question_id": 2, "answer_body": "Ответ 1",},
* {"id": "4", "question_id": 3, "question_body": "Ответ 22",}, * {"id": "4", "question_id": 3, "answer_body": "Ответ 22",},
* }, * },
* @OA\Items( * @OA\Items(
* type="object", * type="object",
@ -46,7 +46,7 @@ namespace frontend\modules\api\models;
* type="integer", * type="integer",
* ), * ),
* @OA\Property( * @OA\Property(
* property="question_body", * property="answer_body",
* type="string", * type="string",
* ), * ),
* ), * ),
@ -55,5 +55,24 @@ namespace frontend\modules\api\models;
*/ */
class Answer extends \common\models\Answer class Answer extends \common\models\Answer
{ {
/**
* @return string[]
*/
public function fields(): array
{
return [
'id',
'question_id',
'answer_body',
];
}
/**
* @return string[]
*/
public function extraFields(): array
{
return [];
}
} }

View File

@ -1,7 +1,8 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\questionnaire;
use yii\db\ActiveQuery;
/** /**
* *
@ -43,16 +44,16 @@ namespace frontend\modules\api\models;
* example="00:22:00", * example="00:22:00",
* description="Лимит времени на ответ" * description="Лимит времени на ответ"
* ), * ),
* @OA\Property(
* property="result_profiles",
* ref="#/components/schemas/AnswerExampleArr",
* ),
*) *)
* *
* *
* @OA\Schema( * @OA\Schema(
* schema="QuestionExampleArr", * schema="QuestionExampleArr",
* type="array", * type="array",
* example={
* {"id": "1", "question_type_id": 2, "question_body": "Вопрос 1", "question_priority": 1, "next_question": 2, "time_limit": "00:10:00",},
* {"id": "4", "question_type_id": 3, "question_body": "Вопрос 22", "question_priority": 4, "next_question": 5, "time_limit": "00:10:00",},
* },
* @OA\Items( * @OA\Items(
* type="object", * type="object",
* @OA\Property( * @OA\Property(
@ -79,11 +80,48 @@ namespace frontend\modules\api\models;
* property="time_limit", * property="time_limit",
* type="string", * type="string",
* ), * ),
* @OA\Property(
* property="result_profiles",
* ref="#/components/schemas/AnswerExampleArr",
* ),
* ), * ),
*) *)
* *
* @property Answer[] $answers
*/ */
class Question extends \common\models\Question class Question extends \common\models\Question
{ {
/**
* @return string[]
*/
public function fields(): array
{
return [
'id',
'question_type_id',
'question_body',
'question_priority',
'next_question',
'time_limit',
'answers' => function () {
return $this->answers;
}
];
}
/**
* @return string[]
*/
public function extraFields(): array
{
return [];
}
/**
* @return ActiveQuery
*/
public function getAnswers(): ActiveQuery
{
return $this->hasMany(Answer::class, ['question_id' => 'id']);
}
} }

View File

@ -1,6 +1,6 @@
<?php <?php
namespace frontend\modules\api\models; namespace frontend\modules\api\models\questionnaire;
/** /**
@ -49,6 +49,30 @@ namespace frontend\modules\api\models;
* example="Анкета 1", * example="Анкета 1",
* description="Название анкеты" * description="Название анкеты"
* ), * ),
* @OA\Property(
* property="description",
* type="string",
* example="Анкета 1",
* description="Описание теста"
* ),
* @OA\Property(
* property="points_number",
* type="int",
* example="80",
* description="Количество балов"
* ),
* @OA\Property(
* property="number_questions",
* type="int",
* example="21",
* description="Количество вопросов"
* ),
* @OA\Property(
* property="time_limit",
* type="string",
* example="00:50:00",
* description="Лимит времени на выполнение"
* ),
*) *)
* *
* @OA\Schema( * @OA\Schema(
@ -64,8 +88,8 @@ namespace frontend\modules\api\models;
* schema="UserQuestionnaireArrExample", * schema="UserQuestionnaireArrExample",
* type="array", * type="array",
* example={ * example={
* {"uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5", "score": 11, "status": 2, "percent_correct_answers": 0.25, "testing_date": "2022-04-03 09:23:45", "questionnaire_title": "Тест 2"}, * {"uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5", "score": 11, "status": 2, "percent_correct_answers": 0.25, "testing_date": "2022-04-03 09:23:45", "questionnaire_title": "Тест 2", "description": "Описание", "points_number": "22", "number_questions": "15", "time_limit": "00:50:00"},
* {"uuid": "gcjs77d9-vtyd-02jh-9467-dc8fbb6s6jdb", "score": 20, "status": 2, "percent_correct_answers": 0.85, "testing_date": "2022-03-17 11:14:22", "questionnaire_title": "Тест 1"}, * {"uuid": "gcjs77d9-vtyd-02jh-9467-dc8fbb6s6jdb", "score": 20, "status": 2, "percent_correct_answers": 0.85, "testing_date": "2022-03-17 11:14:22", "questionnaire_title": "Тест 1", "description": "Описание", "points_number": "80", "number_questions": "35", "time_limit": "01:10:00"},
* }, * },
* @OA\Items( * @OA\Items(
* type="object", * type="object",
@ -93,6 +117,22 @@ namespace frontend\modules\api\models;
* property="questionnaire_title", * property="questionnaire_title",
* type="string", * type="string",
* ), * ),
* @OA\Property(
* property="description",
* type="string",
* ),
* @OA\Property(
* property="points_number",
* type="int",
* ),
* @OA\Property(
* property="number_questions",
* type="int",
* ),
* @OA\Property(
* property="time_limit",
* type="string",
* ),
* ), * ),
*) *)
* *
@ -114,6 +154,21 @@ class UserQuestionnaire extends \common\models\UserQuestionnaire
'description' => function () { 'description' => function () {
return $this->questionnaire->description; return $this->questionnaire->description;
}, },
'points_number' => function () {
return Question::find()
->where(['questionnaire_id' => $this->questionnaire_id])
->andWhere(['status' => 1])
->sum('score');
},
'number_questions' => function () {
return Question::find()
->where(['questionnaire_id' => $this->questionnaire_id])
->andWhere(['status' => 1])
->count();
},
'time_limit' => function () {
return $this->questionnaire->time_limit;
}
]; ];
} }

View File

@ -0,0 +1,32 @@
<?php
namespace frontend\modules\api\models\questionnaire\forms;
use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use yii\base\Model;
class QuestionnaireUuidForm extends Model
{
public $uuid;
/**
* @return array
*/
public function rules()
{
return [
[['uuid'], 'string'],
[['uuid'], 'required'],
[['uuid'], 'exist', 'skipOnError' => false, 'targetClass' => UserQuestionnaire::class, 'targetAttribute' => ['uuid' => 'uuid']],
];
}
/**
* @return string
*/
public function formName(): string
{
return '';
}
}

View File

@ -2,12 +2,12 @@
namespace frontend\modules\api\services; namespace frontend\modules\api\services;
use common\models\Question; use common\helpers\UserQuestionnaireStatusHelper;
use common\services\ScoreCalculatorService; use common\services\ScoreCalculatorService;
use frontend\modules\api\models\UserQuestionnaire; use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
class UserQuestionnaireService class UserQuestionnaireService
{ {
@ -26,6 +26,8 @@ class UserQuestionnaireService
if (empty($userQuestionnaireModel)) { if (empty($userQuestionnaireModel)) {
throw new NotFoundHttpException('The questionnaire with this uuid does not exist'); throw new NotFoundHttpException('The questionnaire with this uuid does not exist');
} }
if (!in_array($userQuestionnaireModel->status, UserQuestionnaireStatusHelper::listCompleteStatuses() )) {
ScoreCalculatorService::rateResponses($userQuestionnaireModel); ScoreCalculatorService::rateResponses($userQuestionnaireModel);
if (ScoreCalculatorService::checkAnswerFlagsForNull($userQuestionnaireModel)) { if (ScoreCalculatorService::checkAnswerFlagsForNull($userQuestionnaireModel)) {
ScoreCalculatorService::calculateScore($userQuestionnaireModel); ScoreCalculatorService::calculateScore($userQuestionnaireModel);
@ -33,38 +35,24 @@ class UserQuestionnaireService
$userQuestionnaireModel->status = 3; $userQuestionnaireModel->status = 3;
$userQuestionnaireModel->save(); $userQuestionnaireModel->save();
} }
}
return $userQuestionnaireModel; return $userQuestionnaireModel;
} }
/** public function checkTimeLimit(UserQuestionnaire $userQuestionnaire): bool
* @throws ServerErrorHttpException
*/
public static function getQuestionNumber($user_questionnaire_uuid): array
{ {
$userQuestionnaireModel = UserQuestionnaire::findOne(['uuid' => $user_questionnaire_uuid]); if (!$userQuestionnaire->start_testing) {
if (empty($userQuestionnaireModel)) { $userQuestionnaire->start_testing = date('Y:m:d H:i:s');
throw new ServerErrorHttpException('Not found UserQuestionnaire'); $userQuestionnaire->save();
} } elseif ($userQuestionnaire->questionnaire->time_limit) {
$count = Question::find() $limitTime = strtotime($userQuestionnaire->questionnaire->time_limit) - strtotime("00:00:00");
->where(['questionnaire_id' => $userQuestionnaireModel->questionnaire_id]) $currentTime = strtotime(date('Y-m-d H:i:s'));
->andWhere(['status' => 1]) $startTesting = strtotime($userQuestionnaire->start_testing);
->count();
return array('question_number' => $count);
}
/** if ($currentTime - $startTesting > $limitTime) {
* @throws ServerErrorHttpException return false;
*/ }
public static function getPointsNumber($user_questionnaire_uuid) }
{ return true;
$userQuestionnaireModel = UserQuestionnaire::findOne(['uuid' => $user_questionnaire_uuid]);
if (empty($userQuestionnaireModel)) {
throw new ServerErrorHttpException('Not found UserQuestionnaire');
}
$pointSum = Question::find()
->where(['questionnaire_id' => $userQuestionnaireModel->questionnaire_id])
->andWhere(['status' => 1])
->sum('score');
return array('sum_point' => $pointSum);
} }
} }

View File

@ -14,17 +14,19 @@ class UserResponseService
* @throws BadRequestHttpException * @throws BadRequestHttpException
* @throws ServerErrorHttpException * @throws ServerErrorHttpException
*/ */
public static function createUserResponses($userResponsesParams): array public static function createUserResponses($userResponsesParams, $uuid): array
{ {
$userResponseModels = array(); $userResponseModels = array();
foreach ($userResponsesParams as $userResponse) { foreach ($userResponsesParams as $userResponse) {
$model = new UserResponse(); $model = new UserResponse();
$model->load($userResponse, ''); $model->load($userResponse, '');
$model->user_questionnaire_uuid = $uuid;
try { try {
self::validateResponseModel($model); self::validateResponseModel($model);
} catch (\Exception $ex) { } catch (\Exception $ex) {
throw new BadRequestHttpException(json_encode('One of the parameters is empty!')); throw new BadRequestHttpException($ex->getMessage());
} }
@ -48,7 +50,7 @@ class UserResponseService
} }
if (empty($model->user_id) or empty($model->question_id) or empty($model->user_questionnaire_uuid)) { if (empty($model->user_id) or empty($model->question_id) or empty($model->user_questionnaire_uuid)) {
throw new BadRequestHttpException(json_encode('One of the parameters is empty!')); throw new BadRequestHttpException(json_encode('One of t222he parameters is empty!'));
} }
} }