tests fix

This commit is contained in:
Kavalar 2023-12-06 00:15:52 +03:00
parent d50f5e8031
commit 4046e71ffa
5 changed files with 84 additions and 17 deletions

View File

@ -54,7 +54,7 @@ class UserResponse extends ActiveRecord
public function rules() public function rules()
{ {
return [ return [
[['user_id', 'question_id'], 'integer'], [['user_id', 'question_id', 'answer_id'], 'integer'],
[['created_at', 'updated_at'], 'safe'], [['created_at', 'updated_at'], 'safe'],
[['answer_flag'], 'number'], [['answer_flag'], 'number'],
[['response_body'], 'string', 'max' => 255], [['response_body'], 'string', 'max' => 255],
@ -74,6 +74,7 @@ class UserResponse extends ActiveRecord
'id' => 'ID', 'id' => 'ID',
'user_id' => 'Пользователь', 'user_id' => 'Пользователь',
'question_id' => 'Вопрос', 'question_id' => 'Вопрос',
'answer_id' => 'Идентификатор ответа',
'response_body' => 'Ответ пользователя', 'response_body' => 'Ответ пользователя',
'created_at' => 'Created At', 'created_at' => 'Created At',
'updated_at' => 'Updated At', 'updated_at' => 'Updated At',
@ -98,6 +99,14 @@ class UserResponse extends ActiveRecord
return $this->hasOne(Question::className(), ['id' => 'question_id']); return $this->hasOne(Question::className(), ['id' => 'question_id']);
} }
/**
* @return ActiveQuery
*/
public function getAnswer(): ActiveQuery
{
return $this->hasOne(Answer::class, ['id' => 'answer_id']);
}
/** /**
* @return ActiveQuery * @return ActiveQuery
*/ */

View File

@ -0,0 +1,43 @@
<?php
use yii\db\Migration;
/**
* Class m231204_202917_add_answer_id_column_at_user_response_table
*/
class m231204_202917_add_answer_id_column_at_user_response_table extends Migration
{
private const TABLE_NAME = 'user_response';
private const TABLE_COLUMN = 'answer_id';
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->addColumn(self::TABLE_NAME, self::TABLE_COLUMN, $this->integer()->defaultValue(null)->after('question_id'));
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropColumn(self::TABLE_NAME, self::TABLE_COLUMN);
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m231204_202917_add_answer_id_column_at_user_response_table cannot be reverted.\n";
return false;
}
*/
}

View File

@ -2,6 +2,7 @@
namespace frontend\modules\api\controllers; namespace frontend\modules\api\controllers;
use common\classes\Debug;
use frontend\modules\api\models\questionnaire\UserQuestionnaire; use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use frontend\modules\api\services\UserQuestionnaireService; use frontend\modules\api\services\UserQuestionnaireService;
use frontend\modules\api\services\UserResponseService; use frontend\modules\api\services\UserResponseService;
@ -29,7 +30,11 @@ class UserResponseController extends ApiController
* @OA\Post(path="/user-response/set-responses", * @OA\Post(path="/user-response/set-responses",
* summary="Добавить массив ответов пользователя", * summary="Добавить массив ответов пользователя",
* description="Добавление массива ответов на вопросы от пользователя. При наличии лимита времени на выполнение теста, * description="Добавление массива ответов на вопросы от пользователя. При наличии лимита времени на выполнение теста,
будет проведена проверка. При превышении лимита времени на выполнение будет возвращена ошибка: Time's up!", будет проведена проверка. При превышении лимита времени на выполнение будет возвращена ошибка: Time's up!
<br>
Пример запроса <b>userResponses</b><br>
<code>[{'question_id': 1,'response_body':'Otvet','answer_id':3},{'question_id': 2,'response_body':'Otvet 2','answer_id':5}]</code>
",
* security={ * security={
* {"bearerAuth": {}} * {"bearerAuth": {}}
* }, * },
@ -38,7 +43,7 @@ class UserResponseController extends ApiController
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/x-www-form-urlencoded", * mediaType="application/x-www-form-urlencoded",
* @OA\Schema( * @OA\Schema(
* required={"request_id"}, * required={"user_id", "userResponses", "user_questionnaire_uuid"},
* @OA\Property( * @OA\Property(
* property="user_id", * property="user_id",
* type="integer", * type="integer",
@ -46,14 +51,10 @@ class UserResponseController extends ApiController
* nullable=false, * nullable=false,
* ), * ),
* @OA\Property( * @OA\Property(
* property="question_id", * property="userResponses",
* type="integer",
* description="Идентификатор вопроса",
* ),
* @OA\Property(
* property="response_body",
* type="string", * type="string",
* description="UUID анкеты назначенной пользователю", * description="Ответы пользователя",
* example="{}",
* ), * ),
* @OA\Property( * @OA\Property(
* property="user_questionnaire_uuid", * property="user_questionnaire_uuid",
@ -92,7 +93,7 @@ class UserResponseController extends ApiController
throw new BadRequestHttpException("Time's up!"); throw new BadRequestHttpException("Time's up!");
} }
$userResponseModels = UserResponseService::createUserResponses($userResponses, $uuid); $userResponseModels = UserResponseService::createUserResponses($userResponses, $userQuestionnaire);
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

@ -71,8 +71,8 @@ namespace frontend\modules\api\models;
* schema="UserResponseExampleArr", * schema="UserResponseExampleArr",
* type="array", * type="array",
* example={ * example={
* {"user_id": 23, "question_id": 22, "response_body": "Ответ 1", "user_questionnaire_uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5",}, * {"user_id": 23, "question_id": 22, "answer_id": 32, "response_body": "Ответ 1", "user_questionnaire_uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5",},
* {"user_id": 16, "question_id": 3, "response_body": "Ответ 22", "user_questionnaire_uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5",}, * {"user_id": 16, "question_id": 3, "answer_id": 44, "response_body": "Ответ 22", "user_questionnaire_uuid": "d222f858-60fd-47fb-8731-dc9d5fc384c5",},
* }, * },
* @OA\Items( * @OA\Items(
* type="object", * type="object",
@ -85,6 +85,10 @@ namespace frontend\modules\api\models;
* type="integer", * type="integer",
* ), * ),
* @OA\Property( * @OA\Property(
* property="answer_id",
* type="integer",
* ),
* @OA\Property(
* property="response_body", * property="response_body",
* type="string", * type="string",
* ), * ),
@ -103,6 +107,7 @@ class UserResponse extends \common\models\UserResponse
return [ return [
'user_id', 'user_id',
'question_id', 'question_id',
'answer_id',
'response_body', 'response_body',
'user_questionnaire_uuid', 'user_questionnaire_uuid',
]; ];

View File

@ -2,7 +2,9 @@
namespace frontend\modules\api\services; namespace frontend\modules\api\services;
use common\classes\Debug;
use common\services\ScoreCalculatorService; use common\services\ScoreCalculatorService;
use frontend\modules\api\models\questionnaire\UserQuestionnaire;
use frontend\modules\api\models\UserResponse; use frontend\modules\api\models\UserResponse;
use Yii; use Yii;
use yii\web\BadRequestHttpException; use yii\web\BadRequestHttpException;
@ -14,14 +16,21 @@ class UserResponseService
* @throws BadRequestHttpException * @throws BadRequestHttpException
* @throws ServerErrorHttpException * @throws ServerErrorHttpException
*/ */
public static function createUserResponses($userResponsesParams, $uuid): array public static function createUserResponses($userResponsesParams, UserQuestionnaire $userQuestionnaire): array
{ {
$userResponseModels = array(); $userResponseModels = array();
foreach ($userResponsesParams as $userResponse) { try {
$userResponsesParamsArray = json_decode($userResponsesParams, true);
}
catch (\Exception $ex) {
throw new BadRequestHttpException('userResponses is not json');
}
foreach ($userResponsesParamsArray as $userResponse) {
$model = new UserResponse(); $model = new UserResponse();
$model->load($userResponse, ''); $model->load($userResponse, '');
$model->user_questionnaire_uuid = $uuid; $model->user_id = $userQuestionnaire->user_id;
$model->user_questionnaire_uuid = $userQuestionnaire->uuid;
try { try {
self::validateResponseModel($model); self::validateResponseModel($model);
@ -30,7 +39,7 @@ class UserResponseService
} }
array_push($userResponseModels, $model); $userResponseModels[] = $model;
} }
foreach ($userResponseModels as $responseModel) { foreach ($userResponseModels as $responseModel) {