changing foreign key in user_response from id to uuid, completed add greedy loading, some refactoring

This commit is contained in:
iIronside 2021-11-09 17:41:44 +03:00
parent de90b3178e
commit 560de1c05e
29 changed files with 3539 additions and 202 deletions

View File

@ -81,7 +81,7 @@ return [
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
'baseUrl' => '/secure', // /secure
'baseUrl' => '', // /secure
'parsers' => [
'application/json' => 'yii\web\JsonParser',
'text/xml' => 'yii/web/XmlParser',

View File

@ -57,7 +57,7 @@ class QuestionnaireCategoryController extends Controller
$model = $this->findModel($id);
$questionnaireSearchModel = new QuestionnaireSearch();
$questionnaireDataProvider = new ActiveDataProvider([
'query' => $model->getQuestionnaires(),
'query' => $model->getQuestionnaires()->with('category'),
'pagination' => [
'pageSize' => 20,
],

View File

@ -58,7 +58,7 @@ class QuestionnaireController extends Controller
$model = $this->findModel($id);
$questionSearchModel = new QuestionSearch();
$questionDataProvider = new ActiveDataProvider([
'query' => $model->getQuestions(),
'query' => $model->getQuestions()->with('questionType'),
'pagination' => [
'pageSize' => 20,
],

View File

@ -60,7 +60,7 @@ class UserQuestionnaireController extends Controller
{
$model = $this->findModel($id);
$responseDataProvider = new ActiveDataProvider([
'query' => $model->getUserResponses(),
'query' => $model->getUserResponses()->with('question', 'questionType'),
'pagination' => [
'pageSize' => 20,
],

View File

@ -7,6 +7,7 @@ use backend\modules\questionnaire\models\UserQuestionnaire;
use Yii;
use backend\modules\questionnaire\models\UserResponse;
use backend\modules\questionnaire\models\UserResponseSearch;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
@ -37,18 +38,12 @@ class UserResponseController extends Controller
*/
public function actionIndex()
{
$questionnaire = new Questionnaire();
$model = new UserResponse();
$searchModel = new UserResponseSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
'questionnaire' => $questionnaire
]);
}
@ -90,16 +85,15 @@ class UserResponseController extends Controller
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate(int $id, $user_questionnaire_id = null)
public function actionUpdate($id, $user_questionnaire_uuid = null)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($user_questionnaire_id !== null)
if ($user_questionnaire_uuid !== null)
{
return $this->redirect(['user-questionnaire/view', 'id' => $user_questionnaire_id]);
return $this->redirect(['user-questionnaire/view', 'id' => $this->findQuestionnaireId($model),]);
}
return $this->redirect(['view', 'id' => $model->id]);
}
@ -115,8 +109,18 @@ class UserResponseController extends Controller
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
public function actionDelete($id, $user_questionnaire_uuid = null)
{
if ($user_questionnaire_uuid !== null)
{
$model = $this->findModel($id);
$questionnaireId = $this->findQuestionnaireId($model);
$model->delete();
return $this->redirect(['user-questionnaire/view', 'id' => $questionnaireId]);
}
$this->findModel($id)->delete();
return $this->redirect(['index']);
@ -138,27 +142,8 @@ class UserResponseController extends Controller
throw new NotFoundHttpException('The requested page does not exist.');
}
public function actionQuestionnaire()
protected function findQuestionnaireId($model)
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$user_id = $parents[0];
$questionnairesArr = UserQuestionnaire::getQuestionnaireByUser($user_id);
return ['output'=>$questionnairesArr, 'selected'=>''];
}
}
return ['output'=>'', 'selected'=>''];
}
public function actionTest()
{
return $this->render('update', [
'model' => new UserQuestionnaire(),
]);
return ArrayHelper::getValue($model, 'questionnaire.id');
}
}

View File

@ -41,7 +41,7 @@ class UserQuestionnaireSearch extends UserQuestionnaire
*/
public function search($params)
{
$query = UserQuestionnaire::find()->with('questionnaire')->joinWith('user');
$query = UserQuestionnaire::find()->with('questionnaire', 'user');
// add conditions that should always apply here

View File

@ -17,8 +17,8 @@ class UserResponseSearch extends UserResponse
public function rules()
{
return [
[['id', 'user_id', 'question_id', 'user_questionnaire_id'], 'integer'],
[['response_body', 'created_at', 'updated_at'], 'safe'],
[['id', 'user_id', 'question_id'], 'integer'],
[['response_body', 'created_at', 'updated_at', 'user_questionnaire_uuid'], 'safe'],
[['answer_flag'], 'number'],
];
}
@ -41,7 +41,7 @@ class UserResponseSearch extends UserResponse
*/
public function search($params)
{
$query = UserResponse::find()->with('user');
$query = UserResponse::find()->with(['user', 'question', 'questionnaire']);
// add conditions that should always apply here
@ -65,10 +65,10 @@ class UserResponseSearch extends UserResponse
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'answer_flag' => $this->answer_flag,
'user_questionnaire_id' => $this->user_questionnaire_id,
]);
$query->andFilterWhere(['like', 'response_body', $this->response_body]);
$query->andFilterWhere(['like', 'response_body', $this->response_body])
->andFilterWhere(['like', 'user_questionnaire_uuid', $this->user_questionnaire_uuid]);
return $dataProvider;
}

View File

@ -3,8 +3,10 @@
use backend\modules\questionnaire\models\Question;
use common\helpers\AnswerHelper;
use common\helpers\StatusHelper;
use kartik\select2\Select2;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\questionnaire\models\AnswerSearch */
@ -21,6 +23,20 @@ $this->params['breadcrumbs'][] = $this->title;
<?= Html::a('Создать новый ответ', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<!-- --><?php
//
// echo Select2::widget([
// 'model' => \backend\modules\questionnaire\models\Questionnaire::findOne()->where(['id'=>1]),
// 'attribute' => 'state_2',
// 'data' => 1,
// 'options' => ['placeholder' => 'Select a state ...'],
// 'pluginOptions' => [
// 'allowClear' => true
// ],
// ]);
//
// ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
@ -37,7 +53,7 @@ $this->params['breadcrumbs'][] = $this->title;
'format' => 'raw',
'filter' => AnswerHelper::answerFlagsList(),
'value' => function ($model) {
return AnswerHelper::answerStatusLabel($model->answer_flag);
return AnswerHelper::answerFlagLabel($model->answer_flag);
},
],
[

View File

@ -48,7 +48,7 @@ function cut_title($str)
'attribute' => 'answer_flag',
'format' => 'raw',
'filter' => AnswerHelper::answerFlagsList(),
'value' => AnswerHelper::answerStatusLabel($model->answer_flag),
'value' => AnswerHelper::answerFlagLabel($model->answer_flag),
],
[
'attribute' => 'status',

View File

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

View File

@ -41,9 +41,7 @@ YiiAsset::register($this);
'attribute' => 'status',
'format' => 'raw',
'filter' => StatusHelper::statusList(),
'value' => function($model) {
return StatusHelper::statusLabel($model->status);
},
'value' => StatusHelper::statusLabel($model->status),
],
'created_at',
'updated_at',

View File

@ -16,9 +16,9 @@ use yii\widgets\Pjax;
/* @var $responseDataProvider yii\data\ActiveDataProvider */
$user = $model->getUserName();
$questionnaire = $model->getQuestionnaireTitle();
$questionnaire_title = $model->getQuestionnaireTitle();
$this->title = $user . ": " . $questionnaire;
$this->title = $user . ": " . $questionnaire_title;
$this->params['breadcrumbs'][] = ['label' => 'User Questionnaires', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
YiiAsset::register($this);
@ -85,7 +85,7 @@ YiiAsset::register($this);
<?= Html::a('Проверить ответы', ['rate-responses', 'id' => $model->id], [
'class' => 'btn btn-primary',
'data' => [
'confirm' => 'Проверка ответов пользователя: ' . $user . ". Категория: " . $questionnaire,
'confirm' => 'Проверка ответов пользователя: ' . $user . ". Категория: " . $questionnaire_title,
// 'method' => 'post',
],
]) ?>
@ -135,15 +135,13 @@ YiiAsset::register($this);
],
[
'attribute' => 'Тип вопроса',
'value' => function($model) {
return $model->getQuestionType();
}
'value' => 'questionType.question_type',
],
[
'attribute' => 'answer_flag',
'format' => 'raw',
'value' => function ($model) {
return AnswerHelper::answerFlagLable($model->answer_flag);
return AnswerHelper::answerStatusLabel($model->answer_flag);
},
],
@ -156,7 +154,14 @@ YiiAsset::register($this);
'update' => function ($url,$model) {
return Html::a(
'<span class="glyphicon glyphicon-pencil"></span>',
['user-response/update', 'id' => $model['id'], 'user_questionnaire_id' => $model['user_questionnaire_id']]);
['user-response/update', 'id' => $model['id'], 'user_questionnaire_uuid' => $model['user_questionnaire_uuid']]);
},
'delete' => function ($url,$model) {
return Html::a(
'<span class="glyphicon glyphicon-trash"></span>',
['user-response/delete', 'id' => $model['id'], 'user_questionnaire_uuid' => $model['user_questionnaire_uuid']],
['data' => ['confirm' => 'Вы уверены, что хотите удалить этот вопрос?', 'method' => 'post']]
);
},
],
],

View File

@ -1,7 +1,8 @@
<?php
use backend\modules\questionnaire\models\Question;
use backend\modules\questionnaire\models\UserQuestionnaire;
use common\helpers\AnswerHelper;
use common\models\User;
use kartik\select2\Select2;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
@ -15,48 +16,37 @@ use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'answer_flag')->dropDownList(
<?= $form->field($model, 'user_id')->widget(Select2::className(),
[
'' => 'Не задано',
'0.1' => '10%',
'0.2' => '20%',
'0.3' => '30%',
'0.5' => '50%',
'0.7' => '70%',
'0.8' => '80%',
'0.85' => '85%',
'0.9' => '90%',
'1' => '100%',
]
) ?>
<?= $form->field($model, 'user_id')->widget(Select2::class, [
'data' => \common\models\User::find()->select(['username','id'] )->indexBy('id')->column(),
'options' => ['placeholder' => '...','class' => 'form-control'],
'data' => User::find()->select(['username', 'id'])->indexBy('id')->column(),
'options' => ['placeholder' => 'Выберите пользователя','class' => 'form-control'],
'pluginOptions' => [
'placeholder' => 'Выберите',
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'question_id')->widget(Select2::class,[
'data' => Question::find()->select(['question_body', 'id'])->indexBy('id')->column(),
'pluginOptions' => [
'allowClear' => true // 'id != :id', ['id'=>1]
],
]) ?>
<?= $form->field($model, 'user_questionnaire_id')->widget(Select2::class,[
'data' => UserQuestionnaire::find()->select(['id', 'id'])->indexBy('id')->column(),
'options' => ['placeholder' => '...','class' => 'form-control'],
<?= $form->field($model, 'question_id')->widget(Select2::className(),
[
'data' => Question::find()->select(['question_body', 'id'])->indexBy('id')->column(),
'options' => ['placeholder' => 'Выберите пользователя','class' => 'form-control'],
'pluginOptions' => [
'placeholder' => 'Выберите',
'allowClear' => true
],
]) ?>
<?= $form->field($model, 'response_body')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'answer_flag')->dropDownList(
AnswerHelper::answerFlagsList(),
[
'prompt' => 'Выберите'
]
) ?>
<?= $form->field($model, 'user_questionnaire_uuid')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>

View File

@ -25,11 +25,11 @@ use yii\widgets\ActiveForm;
<?= $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'answer_flag') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<?php // echo $form->field($model, 'user_questionnaire_id') ?>
<?php // echo $form->field($model, 'answer_flag') ?>
<?php // echo $form->field($model, 'user_questionnaire_uuid') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>

View File

@ -5,7 +5,7 @@ use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model backend\modules\questionnaire\models\UserResponse */
$this->title = 'Создать ответ пользователя';
$this->title = 'Новый ответ пользователя';
$this->params['breadcrumbs'][] = ['label' => 'User Responses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

View File

@ -1,29 +1,23 @@
<?php
use backend\modules\questionnaire\models\Questionnaire;
use backend\modules\questionnaire\models\Question;
use backend\modules\questionnaire\models\UserQuestionnaire;
use common\helpers\AnswerHelper;
use common\models\User;
use kartik\depdrop\DepDrop;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\questionnaire\models\UserResponseSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $model backend\modules\questionnaire\models\UserResponse */
/* @var $questionnaire backend\modules\questionnaire\models\Questionnaire */
$this->title = 'Ответы пользователей';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-responses-index">
<div class="user-response-index">
<p>
<?= Html::a('Создать новый ответ пользователя', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Новый ответ пользователя', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
@ -31,39 +25,34 @@ $this->params['breadcrumbs'][] = $this->title;
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'user_questionnaire_id',
'filter' => Questionnaire::find()->select(['title', 'id'])->indexBy('id')->column(),
'value' => function($model){
return $model->getQuestionnaireTitle();
}
],
[
'attribute' => 'user_id',
'filter' => User::find()->select(['username', 'id'])->indexBy('id')->column(),
'value' => 'user.username',
],
[
'attribute' => 'question_id',
'filter' => Question::find()->select(['question_body', 'id'])->indexBy('id')->column(),
'value' => 'question.question_body',
],
'response_body',
[
'attribute' => 'Тип вопроса',
'value' => function($model){
return $model->getQuestionType();
}
],
'created_at',
'updated_at',
[
'attribute' =>'answer_flag',
'filter' => AnswerHelper::answerFlagsList(),
'format' => 'raw',
'filter' => AnswerHelper::answerFlagsList(),
'value' => function ($model) {
return AnswerHelper::answerFlagLable($model->answer_flag);
return AnswerHelper::answerStatusLabel($model->answer_flag);
},
],
[
'attribute' => 'user_questionnaire_uuid',
'filter' => UserQuestionnaire::find()->select(['uuid', 'id'])->indexBy('id')->column(),
'value' => 'questionnaire.title',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>

View File

@ -5,7 +5,7 @@ use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model backend\modules\questionnaire\models\UserResponse */
$this->title = 'Изменение ответа: ' . $model->response_body;
$this->title = 'Изменение ответа пользователя';
$this->params['breadcrumbs'][] = ['label' => 'User Responses', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';

View File

@ -8,20 +8,11 @@ use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model backend\modules\questionnaire\models\UserResponse */
/* @var $responseDataProvider yii\data\ActiveDataProvider */
$this->title =cut_title($model->response_body);
$this->title = $model->response_body;
$this->params['breadcrumbs'][] = ['label' => 'User Responses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
YiiAsset::register($this);
function cut_title($str)
{
if(strlen($str) > 40){
return mb_substr($str, 0, 40, 'UTF-8') . '...';
}
return $str;
}
?>
<div class="user-response-view">
@ -42,22 +33,20 @@ function cut_title($str)
'attributes' => [
'id',
[
'attribute' => 'Пользователь',
'attribute' => 'user_id',
'value' => ArrayHelper::getValue($model, 'user.username'),
],
[
'attribute' => 'Вопрос',
'attribute' => 'question_id',
'value' => ArrayHelper::getValue($model, 'question.question_body'),
],
'response_body',
'created_at',
'updated_at',
[
'attribute' => 'answer_flag',
'format' => 'raw',
'value' => AnswerHelper::answerFlagLable($model->answer_flag),
'value' => AnswerHelper::answerFlagLabel($model->answer_flag),
],
'user_questionnaires_uuid',
'user_questionnaire_uuid',
],
]) ?>

View File

@ -22,7 +22,7 @@ class AnswerHelper
/**
* @throws Exception
*/
public static function answerStatusLabel($status): string
public static function answerFlagLabel($status): string
{
switch ($status) {
case self::FLAG_FALSE:
@ -40,7 +40,7 @@ class AnswerHelper
]);
}
public static function answerFlagLable($answer_flag)
public static function answerStatusLabel($answer_flag): string
{
$class = 'label label-warning';
$content = 'Не проверен';

View File

@ -51,7 +51,7 @@ class ScoreCalculatorHelper
public static function calculateScore(UserQuestionnaire $userQuestionnaire)
{
$responses_questions = $userQuestionnaire->hasMany(UserResponse::className(), ['user_questionnaire_id' => 'id'])
$responses_questions = $userQuestionnaire->hasMany(UserResponse::className(), ['user_questionnaire_uuid' => 'uuid'])
->joinWith('question')->asArray()->all();
$score = null;

View File

@ -0,0 +1,113 @@
<?php
namespace common\helpers;
class UUIDHelper
{
public static function v3($namespace, $name) {
if(!self::is_valid($namespace)) return false;
// Get hexadecimal components of namespace
$nhex = str_replace(array('-','{','}'), '', $namespace);
// Binary Value
$nstr = '';
// Convert Namespace UUID to bits
for($i = 0; $i < strlen($nhex); $i+=2) {
$nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
}
// Calculate hash value
$hash = md5($nstr . $name);
return sprintf('%08s-%04s-%04x-%04x-%12s',
// 32 bits for "time_low"
substr($hash, 0, 8),
// 16 bits for "time_mid"
substr($hash, 8, 4),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 3
(hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
// 48 bits for "node"
substr($hash, 20, 12)
);
}
public static function v4() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
public static function v5($namespace, $name) {
if(!self::is_valid($namespace)) return false;
// Get hexadecimal components of namespace
$nhex = str_replace(array('-','{','}'), '', $namespace);
// Binary Value
$nstr = '';
// Convert Namespace UUID to bits
for($i = 0; $i < strlen($nhex); $i+=2) {
$nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
}
// Calculate hash value
$hash = sha1($nstr . $name);
return sprintf('%08s-%04s-%04x-%04x-%12s',
// 32 bits for "time_low"
substr($hash, 0, 8),
// 16 bits for "time_mid"
substr($hash, 8, 4),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 5
(hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
// 48 bits for "node"
substr($hash, 20, 12)
);
}
public static function is_valid($uuid) {
return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
'[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
}
}

View File

@ -21,12 +21,6 @@ use yii\db\Expression;
*/
class Answer extends \yii\db\ActiveRecord
{
const STATUS_PASSIVE = 0;
const STATUS_ACTIVE = 1;
const FLAG_TRUE = 1;
const FLAG_FALSE = 0;
/**
* {@inheritdoc}
*/

View File

@ -27,9 +27,6 @@ use yii\db\Expression;
*/
class Question extends \yii\db\ActiveRecord
{
const STATUS_PASSIVE = 0;
const STATUS_ACTIVE = 1;
/**
* {@inheritdoc}
*/

View File

@ -25,9 +25,6 @@ use yii\helpers\ArrayHelper;
*/
class Questionnaire extends ActiveRecord
{
const STATUS_PASSIVE = 0;
const STATUS_ACTIVE = 1;
/**
* {@inheritdoc}
*/
@ -59,7 +56,7 @@ class Questionnaire extends ActiveRecord
[['created_at', 'updated_at', 'time_limit'], 'safe'],
['title', 'unique'],
[['title'], 'string', 'max' => 255],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'default', 'value' => true],
[['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => QuestionnaireCategory::className(), 'targetAttribute' => ['category_id' => 'id']],
];
}
@ -129,7 +126,6 @@ class Questionnaire extends ActiveRecord
public static function questionnairesOfCategoryArr($category_id): array
{
$categories = self::find()->where(['category_id' => $category_id, 'status' => '1'])->all();
return ArrayHelper::map($categories, 'id', 'title');
}
}

View File

@ -20,9 +20,6 @@ use yii\helpers\ArrayHelper;
*/
class QuestionnaireCategory extends \yii\db\ActiveRecord
{
const STATUS_PASSIVE = 0;
const STATUS_ACTIVE = 1;
/**
* {@inheritdoc}
*/
@ -53,7 +50,7 @@ class QuestionnaireCategory extends \yii\db\ActiveRecord
[['status'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
[['title'], 'string', 'max' => 255],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'default', 'value' => true],
];
}

View File

@ -2,9 +2,10 @@
namespace common\models;
//use Ramsey\Uuid\Uuid;
use common\helpers\UUIDHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use backend\modules\questionnaire\models\Question;
@ -28,11 +29,8 @@ use \backend\modules\questionnaire\models\Answer;
* @property User $user
* @property UserResponse[] $userResponses
*/
class UserQuestionnaire extends \yii\db\ActiveRecord
class UserQuestionnaire extends ActiveRecord
{
const STATUS_PASSIVE = 0;
const STATUS_ACTIVE = 1;
/**
* {@inheritdoc}
*/
@ -71,15 +69,18 @@ class UserQuestionnaire extends \yii\db\ActiveRecord
];
}
// public function beforeSave($insert)
// {
// if (parent::beforeSave($insert)) {
// $this->uuid = Uuid::uuid4()->toString();
// return true;
// } else {
// return false;
// }
// }
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if (empty($this->uuid))
{
$this->uuid = UUIDHelper::v4();
}
return true;
} else {
return false;
}
}
/**
* {@inheritdoc}
@ -120,7 +121,7 @@ class UserQuestionnaire extends \yii\db\ActiveRecord
*/
public function getUserResponses(): ActiveQuery
{
return $this->hasMany(UserResponse::className(), ['user_questionnaire_id' => 'id']);
return $this->hasMany(UserResponse::className(), ['user_questionnaire_uuid' => 'uuid']);
}
public function getQuestionnaireTitle()
@ -147,16 +148,16 @@ class UserQuestionnaire extends \yii\db\ActiveRecord
return $formatQuestionnaireArr;
}
public function getQuestions(): ActiveQuery
public function getQuestions()
{
return $this->hasMany(Question::className(), ['id' => 'question_id'])
->viaTable('user_response', ['user_questionnaire_id' => 'id']);
->viaTable('user_response', ['user_questionnaire_uuid' => 'uuid']);
}
public function numCorrectAnswersWithoutOpenQuestions()
{
return $this->hasMany(Answer::className(), ['question_id' => 'question_id'])
->viaTable('user_response', ['user_questionnaire_id' => 'id'])
->viaTable('user_response', ['user_questionnaire_uuid' => 'uuid'])
->where(['answer_flag' => '1'])
->andWhere(['status' => '1'])
->count();
@ -165,7 +166,7 @@ class UserQuestionnaire extends \yii\db\ActiveRecord
public function numOpenQuestionsAnswers()
{
return $this->hasMany(Question::className(), ['id' => 'question_id'])
->viaTable('user_response', ['user_questionnaire_id' => 'id'])
->viaTable('user_response', ['user_questionnaire_uuid' => 'uuid'])
->where(['question_type_id' => '1'])
->count();
}

View File

@ -2,6 +2,7 @@
namespace common\models;
use yii\base\InvalidConfigException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
@ -18,8 +19,8 @@ use \backend\modules\questionnaire\models\UserQuestionnaire;
* @property string $response_body
* @property string $created_at
* @property string $updated_at
* @property int $user_questionnaire_id
* @property double $answer_flag
* @property string $user_questionnaire_uuid
*
* @property UserQuestionnaire $userQuestionnaire
* @property Question $question
@ -53,11 +54,12 @@ class UserResponse extends ActiveRecord
public function rules()
{
return [
[['user_id', 'question_id', 'user_questionnaire_id'], 'integer'],
[['user_id', 'question_id'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
[['answer_flag'], 'number'],
[['response_body'], 'string', 'max' => 255],
[['user_questionnaire_id'], 'exist', 'skipOnError' => true, 'targetClass' => UserQuestionnaire::className(), 'targetAttribute' => ['user_questionnaire_id' => 'id']],
[['user_questionnaire_uuid'], 'string', 'max' => 36],
[['user_questionnaire_uuid'], 'exist', 'skipOnError' => true, 'targetClass' => UserQuestionnaire::className(), 'targetAttribute' => ['user_questionnaire_uuid' => 'uuid']],
[['question_id'], 'exist', 'skipOnError' => true, 'targetClass' => Question::className(), 'targetAttribute' => ['question_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
@ -76,7 +78,7 @@ class UserResponse extends ActiveRecord
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'answer_flag' => 'Корректность',
'user_questionnaire_id' => 'Анкеты',
'user_questionnaire_uuid' => 'UUID анкеты',
];
}
@ -85,7 +87,7 @@ class UserResponse extends ActiveRecord
*/
public function getUserQuestionnaire()
{
return $this->hasOne(UserQuestionnaire::className(), ['id' => 'user_questionnaire_id']);
return $this->hasOne(UserQuestionnaire::className(), ['uuid' => 'user_questionnaire_uuid']);
}
/**
@ -104,25 +106,30 @@ class UserResponse extends ActiveRecord
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* @throws InvalidConfigException
*/
public function getQuestionnaire()
{
return $this->hasOne(Questionnaire::className(), ['id' => 'questionnaire_id'])
->viaTable('user_questionnaire', ['uuid' => 'user_questionnaire_uuid']);
}
/**
* @throws InvalidConfigException
*/
public function getQuestionType()
{
return $this->hasOne(QuestionType::class, ['id' => 'question_type_id'])
->viaTable('question', ['id' => 'question_id']);
}
public function getCorrectAnswers()
{
return $this->hasMany(Answer::class, ['question_id' => 'question_id'])
->where(['answer_flag' => '1'])->all();
}
public function getQuestionnaireTitle()
{
$tmp = $this->hasOne(Questionnaire::className(), ['id' => 'questionnaire_id'])
->viaTable('user_questionnaire', ['id' => 'user_questionnaire_id'])->one();
return ArrayHelper::getValue($tmp, 'title');
}
public function getQuestionType()
{
return ArrayHelper::getValue($this->hasOne(QuestionType::class, ['id' => 'question_type_id'])
->viaTable('question', ['id' => 'question_id'])->one(), 'question_type');
}
public function getQuestionTypeValue()
{
$qType = $this->getQuestion()->one();

View File

@ -0,0 +1,43 @@
<?php
use yii\db\Migration;
/**
* Class m211109_084732_changing_foreign_key_in_user_response_from_user_questionnaire_id_to_user_questionnaire_uuid
*/
class m211109_084732_changing_foreign_key_in_user_response_from_user_questionnaire_id_to_user_questionnaire_uuid extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->dropForeignKey('questionnaire_response', 'user_response');
$this->renameColumn('user_response', 'user_questionnaire_id', 'user_questionnaire_uuid');
$this->alterColumn('user_response', 'user_questionnaire_uuid', 'varchar(36)');
$this->addForeignKey(
'questionnaire_response',
'user_response',
'user_questionnaire_uuid',
'user_questionnaire',
'uuid'
);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropForeignKey('questionnaire_response', 'user_response');
$this->alterColumn('user_response', 'user_questionnaire_uuid', 'int');
$this->renameColumn('user_response', 'user_questionnaire_uuid', 'user_questionnaire_id');
$this->addForeignKey(
'questionnaire_response',
'user_response',
'user_questionnaire_id',
'user_questionnaire',
'id'
);
}
}

File diff suppressed because it is too large Load Diff