Merge pull request #92 from apuc/update_user_answers

Update user answers
This commit is contained in:
kavalar 2022-03-16 14:50:48 +03:00 committed by GitHub
commit 120cf406c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 209 additions and 188 deletions

View File

@ -33,11 +33,11 @@ $this->params['breadcrumbs'][] = $this->title;
'id',
[
'attribute' => 'field_id',
'value' => ArrayHelper::getValue($model, 'field.title') // AnswerHelper::answerFlagLabel($model->answer_flag),
'value' => ArrayHelper::getValue($model, 'field.title')
],
[
'attribute' => 'document_id',
'value' => ArrayHelper::getValue($model, 'document.title') // AnswerHelper::answerFlagLabel($model->answer_flag),
'value' => ArrayHelper::getValue($model, 'document.title')
],
'value',
],

View File

@ -4,7 +4,7 @@ namespace backend\modules\questionnaire\controllers;
use backend\modules\questionnaire\models\Questionnaire;
use backend\modules\questionnaire\models\QuestionnaireCategory;
use common\helpers\ScoreCalculatorHelper;
use common\services\ScoreCalculatorService;
use Yii;
use backend\modules\questionnaire\models\UserQuestionnaire;
use backend\modules\questionnaire\models\UserQuestionnaireSearch;
@ -169,7 +169,7 @@ class UserQuestionnaireController extends Controller
public function actionRateResponses($id)
{
$user_questionnaire = $this->findModel($id);
ScoreCalculatorHelper::rateResponses($user_questionnaire);
ScoreCalculatorService::rateResponses($user_questionnaire);
return $this->actionView($id);
}
@ -177,7 +177,7 @@ class UserQuestionnaireController extends Controller
public function actionCalculateScore($id)
{
$user_questionnaire = $this->findModel($id);
ScoreCalculatorHelper::calculateScore($user_questionnaire);
ScoreCalculatorService::calculateScore($user_questionnaire);
return $this->actionView($id);
}

View File

@ -47,7 +47,7 @@ $this->params['breadcrumbs'][] = $this->title;
'format' => 'raw',
'filter' => AnswerHelper::answerFlagsList(),
'value' => function ($model) {
return AnswerHelper::answerFlagLabel($model->answer_flag);
return AnswerHelper:: answerFlagLabel($model->answer_flag);
},
],
[

View File

@ -1,6 +1,6 @@
<?php
use common\helpers\ScoreCalculatorHelper;
use common\services\ScoreCalculatorService;
use common\helpers\AnswerHelper;
use common\helpers\StatusHelper;
use yii\bootstrap\Modal;
@ -23,20 +23,8 @@ $this->params['breadcrumbs'][] = ['label' => 'User Questionnaires', 'url' => ['i
$this->params['breadcrumbs'][] = $this->title;
YiiAsset::register($this);
?>
<?php
//$this->registerJs(
// '$("document").ready(function(){
// $("#new_note").on("pjax:end", function() {
// $.pjax.reload({container:"#user_responses"}); //Reload GridView
// });
// });'
//);
?>
<div class="user-questionnaire-view">
<!-- --><?php //var_dump($model->setPercentCorrectAnswers(4)); die();?>
<p>
<?= Html::a('Список', ['index'], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Изменить', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
@ -98,7 +86,7 @@ YiiAsset::register($this);
'class' => 'btn btn-success',
],
]);
if(ScoreCalculatorHelper::checkAnswerFlagsForNull($model))
if(ScoreCalculatorService::checkAnswerFlagsForNull($model))
{
echo 'Ответы проверены. Посчитать баллы?';
echo Html::a('Посчитать баллы', ['calculate-score', 'id' => $model->id], [
@ -141,7 +129,7 @@ YiiAsset::register($this);
'attribute' => 'answer_flag',
'format' => 'raw',
'value' => function ($model) {
return AnswerHelper::answerStatusLabel($model->answer_flag);
return AnswerHelper::userResponseLabel($model->answer_flag);
},
],
@ -169,5 +157,4 @@ YiiAsset::register($this);
]);
?>
<?php Pjax::end(); ?>
</div>

View File

@ -38,12 +38,19 @@ use yii\widgets\ActiveForm;
<?= $form->field($model, 'response_body')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'answer_flag')->dropDownList(
AnswerHelper::answerFlagsList(),
[
'prompt' => 'Выберите'
]
) ?>
<?= $form->field($model, 'answer_flag')->dropDownList([
'0.0' => 'Ошибочный',
'0.1' => '10%',
'0.2' => '20%',
'0.3' => '30%',
'0.4' => '40%',
'0.5' => '50%',
'0.6' => '60%',
'0.7' => '70%',
'0.8' => '80%',
'0.9' => '90%',
'1' => '100%',
]); ?>
<?= $form->field($model, 'user_questionnaire_uuid')->textInput(['maxlength' => true]) ?>

View File

@ -20,13 +20,6 @@ $this->params['breadcrumbs'][] = $this->title;
<?= Html::a('Новый ответ пользователя', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php
//echo $this->render('_search_by_questionnaire', [
// 'model' => $searchModel,
// ])
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
@ -50,7 +43,7 @@ $this->params['breadcrumbs'][] = $this->title;
'format' => 'raw',
'filter' => AnswerHelper::answerFlagsList(),
'value' => function ($model) {
return AnswerHelper::answerStatusLabel($model->answer_flag);
return AnswerHelper::userResponseLabel($model->answer_flag);
},
],
[

View File

@ -44,7 +44,7 @@ YiiAsset::register($this);
[
'attribute' => 'answer_flag',
'format' => 'raw',
'value' => AnswerHelper::answerFlagLabel($model->answer_flag),
'value' => AnswerHelper::userResponseLabel($model->answer_flag),
],
'user_questionnaire_uuid',
],

View File

@ -40,7 +40,7 @@ class AnswerHelper
]);
}
public static function answerStatusLabel($answer_flag): string
public static function userResponseLabel($answer_flag): string
{
$class = 'label label-warning';
$content = 'Не проверен';

View File

@ -150,8 +150,8 @@ class UserQuestionnaire extends ActiveRecord
*/
public function numCorrectAnswersWithoutOpenQuestions()
{
return $this->hasMany(Answer::className(), ['question_id' => 'question_id'])
->viaTable('user_response', ['user_questionnaire_uuid' => 'uuid'])
return $this->hasMany(Answer::className(), ['question_id' => 'id'])
->viaTable('question', ['questionnaire_id' => 'questionnaire_id'])
->where(['answer_flag' => '1'])
->andWhere(['status' => '1'])
->count();
@ -162,9 +162,10 @@ class UserQuestionnaire extends ActiveRecord
*/
public function numOpenQuestionsAnswers()
{
return $this->hasMany(Question::className(), ['id' => 'question_id'])
->viaTable('user_response', ['user_questionnaire_uuid' => 'uuid'])
return $this->hasMany(Question::className(), ['questionnaire_id' => 'id'])
->viaTable('questionnaire', ['id' => 'questionnaire_id'])
->where(['question_type_id' => '1'])
->andWhere(['status' => '1'])
->count();
}

View File

@ -1,14 +1,14 @@
<?php
namespace common\helpers;
namespace common\services;
use backend\modules\questionnaire\models\Answer;
//use backend\modules\questionnaire\models\UserQuestionnaire;
use common\models\UserQuestionnaire;
use common\models\UserResponse;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
class ScoreCalculatorHelper
class ScoreCalculatorService
{
public static function rateResponses(UserQuestionnaire $user_questionnaire)
{
@ -45,6 +45,9 @@ class ScoreCalculatorHelper
return true;
}
/**
* @throws InvalidConfigException
*/
public static function calculateScore(UserQuestionnaire $userQuestionnaire)
{
$responses_questions = $userQuestionnaire->hasMany(UserResponse::className(), ['user_questionnaire_uuid' => 'uuid'])
@ -72,11 +75,9 @@ class ScoreCalculatorHelper
}
}
// if($score !== null) {
self::setPercentCorrectAnswers($user_correct_answers_num, $userQuestionnaire);
$userQuestionnaire->score = round($score);
$userQuestionnaire->save();
// }
self::setPercentCorrectAnswers($user_correct_answers_num, $userQuestionnaire);
$userQuestionnaire->score = round($score);
$userQuestionnaire->save();
}
protected static function isCorrect($answer_flag): bool
@ -92,6 +93,9 @@ class ScoreCalculatorHelper
return Answer::numCorrectAnswers($question_id);
}
/**
* @throws InvalidConfigException
*/
protected static function setPercentCorrectAnswers($user_correct_answers_num, UserQuestionnaire $userQuestionnaire)
{
if($user_correct_answers_num !== null) {

View File

@ -19,11 +19,7 @@ class TemplateService
public static function getTemplateWithFields($template_id): array
{
return Template::find()
// ->select('title')
->joinWith('templateDocumentFields.field')
// ->with([
// 'fields' => function ($query) { $query->select(['id', 'title', 'field_template']); }
// ])
->where(['template.id' => $template_id])
->asArray()
->one();

View File

@ -0,0 +1,37 @@
<?php
namespace common\services;
use common\models\UserQuestionnaire;
use yii\web\NotFoundHttpException;
class UserQuestionnaireService
{
public static function getQuestionnaireList($user_id): array
{
$userQuestionnaireModels = UserQuestionnaire::findActiveUserQuestionnaires($user_id);
array_walk($userQuestionnaireModels, function (&$arr) {
unset(
$arr['questionnaire_id'],
$arr['created_at'],
$arr['updated_at'],
$arr['id'],
);
});
return $userQuestionnaireModels;
}
/**
* @throws NotFoundHttpException
*/
public static function calculateScore($user_questionnaire_uuid)
{
$userQuestionnaireModel = UserQuestionnaire::findOne(['uuid' => $user_questionnaire_uuid]);
if(empty($userQuestionnaireModel)) {
throw new NotFoundHttpException('The questionnaire with this uuid does not exist');
}
ScoreCalculatorService::rateResponses($userQuestionnaireModel);
ScoreCalculatorService::calculateScore($userQuestionnaireModel);
return $userQuestionnaireModel;
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace common\services;
use common\models\UserResponse;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
class UserResponseService
{
/**
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
*/
public static function createUserResponse($userResponseParams): UserResponse
{
$userResponse = new UserResponse();
$userResponse->load($userResponseParams, '');
(new UserResponseService)->validateResponseModel($userResponse);
(new UserResponseService)->saveModel($userResponse);
return $userResponse;
}
/**
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
*/
public static function createUserResponses($userResponsesParams): array
{
$userResponseModels = array();
foreach ($userResponsesParams['userResponses'] as $userResponseParams) {
$model = new UserResponse();
$model->load($userResponseParams, '');
(new UserResponseService)->validateResponseModel($model);
array_push($userResponseModels, $model);
}
foreach ($userResponseModels as $responseModel) {
(new UserResponseService)->saveModel($responseModel);
}
return $userResponseModels;
}
/**
* @throws BadRequestHttpException
*/
protected function validateResponseModel($model)
{
if (!$model->validate()) {
throw new BadRequestHttpException(json_encode($model->errors));
}
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!'));
}
}
/**
* @throws ServerErrorHttpException
*/
protected function saveModel($model)
{
if ($model->save()) {
ScoreCalculatorService::rateOneResponse($model);
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
} elseif (!$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
}
}
}

View File

@ -1083,7 +1083,7 @@
answer_flag
</td>
<td>
Флаг ответа(1 - верно, 0 - ложно)
Флаг ответа(1 - верно, 0 - ложно). Если отправлен ответ на открытый вопрос, флаг ответа не будет возвращаться до момента проверки в админ панели.
</td>
</tr>
</table>

View File

@ -97005,3 +97005,29 @@
127.0.0.1 - - [11/Mar/2022:10:48:38 +0300] "GET /reports/ajax/get-reports-for-day-by-date?date=2022-01-31 HTTP/1.1" 200 456 "http://backend.guild.loc/reports/reports" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [11/Mar/2022:10:48:38 +0300] "GET /reports/ajax/get-reports-for-month-by-id-year-month?&month=01&year=2022 HTTP/1.1" 200 12 "http://backend.guild.loc/reports/reports" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [11/Mar/2022:10:48:38 +0300] "GET /reports/ajax/get-reports-for-day-by-date?date=2022-01-31 HTTP/1.1" 200 456 "http://backend.guild.loc/reports/reports" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:51 +0300] "GET /questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5 HTTP/1.1" 200 13709 "http://backend.guild.loc/questionnaire/user-questionnaire/view?id=1" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/39b83f70/css/select2.css HTTP/1.1" 200 17358 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/71772193/css/bootstrap.css HTTP/1.1" 200 145933 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/5b57ee2f/css/select2-addl.css HTTP/1.1" 200 994 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/5b57ee2f/css/select2-krajee.css HTTP/1.1" 200 20817 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/bae3a4f/css/kv-widgets.css HTTP/1.1" 200 813 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /css/site.css HTTP/1.1" 200 805 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/ccdf1f3a/css/font-awesome.min.css HTTP/1.1" 200 31000 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/cd83ad4b/css/AdminLTE.min.css HTTP/1.1" 200 106548 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/cd83ad4b/css/skins/_all-skins.min.css HTTP/1.1" 200 41635 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/cd83ad4b/img/user2-160x160.jpg HTTP/1.1" 200 7070 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/5aa3f20b/jquery.js HTTP/1.1" 200 288580 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/27128343/yii.js HTTP/1.1" 200 20934 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/39b83f70/js/i18n/ru.js HTTP/1.1" 200 1171 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/39b83f70/js/select2.full.js HTTP/1.1" 200 173566 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/5b57ee2f/js/select2-krajee.js HTTP/1.1" 200 7344 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/bae3a4f/js/kv-widgets.js HTTP/1.1" 200 1061 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/27128343/yii.validation.js HTTP/1.1" 200 16405 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/27128343/yii.activeForm.js HTTP/1.1" 200 36765 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /js/site.js HTTP/1.1" 200 1214 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/71772193/js/bootstrap.js HTTP/1.1" 200 75484 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/cd83ad4b/js/adminlte.min.js HTTP/1.1" 200 13611 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /debug/default/toolbar?tag=6231a1a376864 HTTP/1.1" 200 3426 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/bae3a4f/img/loading-plugin.gif HTTP/1.1" 200 847 "http://backend.guild.loc/assets/bae3a4f/css/kv-widgets.css" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:52 +0300] "GET /assets/ccdf1f3a/fonts/fontawesome-webfont.woff2?v=4.7.0 HTTP/1.1" 200 77160 "http://backend.guild.loc/assets/ccdf1f3a/css/font-awesome.min.css" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"
127.0.0.1 - - [16/Mar/2022:11:36:53 +0300] "GET /favicon.ico HTTP/1.1" 200 318 "http://backend.guild.loc/questionnaire/user-response/update?id=218&user_questionnaire_uuid=d222f858-60fd-47fb-8731-dc9d5fc384c5" "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0"

View File

@ -2,26 +2,12 @@
namespace frontend\modules\api\controllers;
use common\helpers\ScoreCalculatorHelper;
use common\models\UserQuestionnaire;
use Yii;
use yii\filters\auth\HttpBearerAuth;
use yii\rest\Controller;
use common\services\UserQuestionnaireService;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
class UserQuestionnaireController extends ApiController
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator']['authMethods'] = [
HttpBearerAuth::className(),
];
return $behaviors;
}
public function verbs()
{
return [
@ -33,51 +19,28 @@ class UserQuestionnaireController extends ApiController
/**
* @throws NotFoundHttpException
*/
public function actionQuestionnairesList()//: array
public function actionQuestionnairesList($user_id): array
{
$user_id = Yii::$app->request->get('user_id');
if(empty($user_id) or !is_numeric($user_id))
{
if (empty($user_id) or !is_numeric($user_id)) {
throw new NotFoundHttpException('Incorrect user ID');
}
$userQuestionnaireModels = UserQuestionnaire::findActiveUserQuestionnaires($user_id);
$userQuestionnaireModels = UserQuestionnaireService::getQuestionnaireList($user_id);
if(empty($userQuestionnaireModels)) {
throw new NotFoundHttpException('Active questionnaire not found');
}
array_walk( $userQuestionnaireModels, function(&$arr){
unset(
$arr['questionnaire_id'],
// $arr['created_at'],
// $arr['updated_at'],
$arr['id'],
);
});
return $userQuestionnaireModels;
return $userQuestionnaireModels;
}
public function actionQuestionnaireCompleted()
/**
* @throws NotFoundHttpException
* @throws ServerErrorHttpException
*/
public function actionQuestionnaireCompleted($user_questionnaire_uuid)
{
// return Yii::$app->request;
$user_questionnaire_uuid = Yii::$app->request->get('user_questionnaire_uuid');
if(empty($user_questionnaire_uuid))
{
throw new NotFoundHttpException('Incorrect user ID');
$userQuestionnaireModel = UserQuestionnaireService::calculateScore($user_questionnaire_uuid);
if ($userQuestionnaireModel->errors) {
throw new ServerErrorHttpException(json_encode($userQuestionnaireModel->errors));
}
$userQuestionnaireModel = UserQuestionnaire::findOne(['uuid' => $user_questionnaire_uuid]);
if(empty($userQuestionnaireModel)) {
throw new NotFoundHttpException('Active questionnaire not found');
}
ScoreCalculatorHelper::rateResponses($userQuestionnaireModel);
ScoreCalculatorHelper::calculateScore($userQuestionnaireModel);
return $userQuestionnaireModel;
}
}

View File

@ -2,31 +2,15 @@
namespace frontend\modules\api\controllers;
use common\helpers\ScoreCalculatorHelper;
use common\models\UserResponse;
use Exception;
use common\services\UserResponseService;
use Yii;
use yii\base\InvalidConfigException;
use yii\filters\auth\HttpBearerAuth;
use yii\rest\ActiveController;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
class UserResponseController extends ApiController
{
public $modelClass = 'common\models\UserResponse';
// public function behaviors(): array
// {
// $behaviors = parent::behaviors();
//
// $behaviors['authenticator']['authMethods'] = [
// HttpBearerAuth::className(),
// ];
//
// return $behaviors;
// }
public function verbs(): array
{
return [
@ -35,82 +19,31 @@ class UserResponseController extends ApiController
];
}
// public function actions()
// {
// $actions = parent::actions();
// unset($actions['create']);
// return $actions;
// }
/**
* @throws InvalidConfigException
* @throws BadRequestHttpException
* @throws ServerErrorHttpException
* @throws ServerErrorHttpException|BadRequestHttpException
*/
public function actionSetResponse()
public function actionSetResponse(): UserResponse
{
$request = Yii::$app->getRequest()->getBodyParams();
$model = new UserResponse();
$model->load($request, '');
$this->validateResponseModel($model);
$this->saveModel($model);
return $model;
$userResponseModel = UserResponseService::createUserResponse(Yii::$app->getRequest()->getBodyParams());
if ($userResponseModel->errors) {
throw new ServerErrorHttpException(json_encode($userResponseModel->errors));
}
return $userResponseModel;
}
/**
* @throws InvalidConfigException
* @throws ServerErrorHttpException
* @throws BadRequestHttpException
* @throws ServerErrorHttpException|BadRequestHttpException
*/
public function actionSetResponses(): array
{
$requests = Yii::$app->getRequest()->getBodyParams();
$responseModels = array();
foreach ($requests['userResponses'] as $request) {
$model = new UserResponse();
$model->load($request, '');
$this->validateResponseModel($model);
array_push($responseModels, $model);
}
foreach ($responseModels as $responseModel) {
$this->saveModel($responseModel);
}
return $responseModels;
}
/**
* @throws BadRequestHttpException
*/
protected function validateResponseModel($model)
{
if(!$model->validate()) {
throw new BadRequestHttpException(json_encode($model->errors));
}
if (empty($model->user_id) or empty($model->question_id) or empty($model->user_questionnaire_uuid)) {
throw new BadRequestHttpException(json_encode($model->errors));
}
}
/**
* @throws ServerErrorHttpException
*/
protected function saveModel($model)
{
if ($model->save()) {
ScoreCalculatorHelper::rateOneResponse($model);
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
} elseif (!$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
$userResponseModels = UserResponseService::createUserResponses(Yii::$app->getRequest()->getBodyParams());
foreach ($userResponseModels as $model) {
if ($model->errors) {
throw new ServerErrorHttpException(json_encode($model->errors));
}
}
return $userResponseModels;
}
}